1 /*-------------------------------------------------------------------------
3 * initdb --- initialize a PostgreSQL installation
5 * initdb creates (initializes) a PostgreSQL database cluster (site,
6 * instance, installation, whatever). A database cluster is a
7 * collection of PostgreSQL databases all managed by the same postmaster.
9 * To create the database cluster, we create the directory that contains
10 * all its data, create the files that hold the global tables, create
11 * a few other control files for it, and create two databases: the
12 * template0 and template1 databases.
14 * The template databases are ordinary PostgreSQL databases. template0
15 * is never supposed to change after initdb, whereas template1 can be
16 * changed to add site-local standard data. Either one can be copied
17 * to produce a new database.
19 * To create template1, we run the postgres (backend) program in bootstrap
20 * mode and feed it data from the postgres.bki library file. After this
21 * initial bootstrap phase, some additional stuff is created by normal
22 * SQL commands fed to a standalone backend. Some of those commands are
23 * just embedded into this program (yeah, it's ugly), but larger chunks
24 * are taken from script files.
26 * template0 is made just by copying the completed template1.
30 * - clean up find_postgres code and return values
33 * The program has some memory leakage - it isn't worth cleaning it up.
36 * This is a C implementation of the previous shell script for setting up a
37 * PostgreSQL cluster location, and should be highly compatible with it.
38 * author of C translation: Andrew Dunstan mailto:andrew@dunslane.net
40 * This code is released under the terms of the PostgreSQL License.
42 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
43 * Portions Copyright (c) 1994, Regents of the University of California
44 * Portions taken from FreeBSD.
46 * $PostgreSQL: pgsql/src/bin/initdb/initdb.c,v 1.21 2004/01/31 22:10:00 neilc Exp $
48 *-------------------------------------------------------------------------
51 #include "postgres_fe.h"
61 #include "libpq/pqsignal.h"
62 #include "mb/pg_wchar.h"
63 #include "getopt_long.h"
70 #define _(x) gettext((x))
72 /* version string we expect back from postgres */
73 #define PG_VERSIONSTR "postgres (PostgreSQL) " PG_VERSION "\n"
76 * these values are passed in by makefile defines
78 * Note that "datadir" is not the directory we're going to initialize,
79 * it's merely how Autoconf names PREFIX/share.
81 char *bindir = PGBINDIR;
82 char *datadir = PGDATADIR;
84 /* values to be obtained from arguments */
88 char *lc_collate = "";
90 char *lc_monetary = "";
91 char *lc_numeric = "";
93 char *lc_messages = "";
95 bool pwprompt = false;
98 bool show_setting = false;
105 char *encodingid = "0";
111 char *conversion_file;
112 char *info_schema_file;
114 char *system_views_file;
115 char *effective_user;
116 bool testpath = true;
117 bool made_new_pgdata = false;
118 bool found_existing_pgdata = false;
119 char infoversion[100];
120 bool caught_signal = false;
121 bool output_failed = false;
124 int n_connections = 10;
128 * Centralized knowledge of switches to pass to backend
130 * Note: in the shell-script version, we also passed PGDATA as a -D switch,
131 * but here it is more convenient to pass it as an environment variable
132 * (no quoting to worry about).
134 static const char *boot_options = "-F";
135 static const char *backend_options = "-F -O -c search_path=pg_catalog -c exit_on_error=true";
138 /* platform specific path stuff */
139 #if defined(__CYGWIN__) || defined(WIN32)
141 #define DEVNULL "nul"
144 #define DEVNULL "/dev/null"
153 /* detected path to postgres and (we assume) friends */
156 /* forward declare all our functions */
157 static bool rmtree(char *, bool);
158 static void exit_nicely(void);
159 static void canonicalize_path(char *);
161 static char *expanded_path(char *);
163 #define expanded_path(x) (x)
165 static char **readfile(char *);
166 static void writefile(char *, char **);
167 static void pclose_check(FILE *stream);
168 static char *get_id(void);
169 static char *get_encoding_id(char *);
170 static char *get_short_version(void);
171 static int mkdir_p(char *, mode_t);
172 static int check_data_dir(void);
173 static bool mkdatadir(char *);
174 static bool chklocale(const char *);
175 static void setlocales(void);
176 static void set_input(char **, char *);
177 static void check_input(char *path);
178 static int find_postgres(char *);
179 static int set_paths(void);
180 static char **replace_token(char **, char *, char *);
181 static void set_short_version(char *, char *);
182 static void set_null_conf(void);
183 static void test_buffers(void);
184 static void test_connections(void);
185 static void setup_config(void);
186 static void bootstrap_template1(char *);
187 static void setup_shadow(void);
188 static void get_set_pwd(void);
189 static void unlimit_systables(void);
190 static void setup_depend(void);
191 static void setup_sysviews(void);
192 static void setup_description(void);
193 static void setup_conversion(void);
194 static void setup_privileges(void);
195 static void set_info_version(void);
196 static void setup_schema(void);
197 static void vacuum_db(void);
198 static void make_template0(void);
199 static void usage(const char *);
200 static void trapsig(int);
201 static void check_ok(void);
202 static char *xstrdup(const char *);
203 static void *xmalloc(size_t);
204 static void init_nls(void);
207 * macros for running pipes to postgres
209 #define PG_CMD_DECL char cmd[MAXPGPATH]; char ** line ; FILE * pg
210 #define PG_CMD_DECL_NOLINE char cmd[MAXPGPATH]; FILE * pg
212 #define PG_CMD_OPEN \
216 pg = popen(cmd, "w"); \
221 #define PG_CMD_CLOSE \
226 #define PG_CMD_PUTLINE \
228 if (fputs(*line, pg) < 0 || fflush(pg) < 0) \
229 output_failed = true; \
233 #define QUOTE_PATH ""
235 #define QUOTE_PATH "\""
239 * routines to check mem allocations and fail noisily.
241 * Note that we can't call exit_nicely() on a memory failure, as it calls
242 * rmtree() which needs memory allocation. So we just exit with a bang.
249 result = malloc(size);
252 fprintf(stderr, _("%s: out of memory\n"), progname);
259 xstrdup(const char *s)
266 fprintf(stderr, _("%s: out of memory\n"), progname);
273 * delete a directory tree recursively
274 * assumes path points to a valid directory
275 * deletes everything under path
276 * if rmtopdir is true deletes the directory too
279 rmtree(char *path, bool rmtopdir)
281 char buf[MAXPGPATH + 64];
284 /* doesn't handle .* files, but we don't make any... */
285 snprintf(buf, sizeof(buf), "rm -rf \"%s\"%s", path,
286 rmtopdir ? "" : "/*");
288 snprintf(buf, sizeof(buf), "%s /s /q \"%s\"",
289 rmtopdir ? "rmdir" : "del", path);
297 * make all paths look like unix, with forward slashes
298 * also strip any trailing slash.
300 * The Windows command processor will accept suitably quoted paths
301 * with forward slashes, but barfs badly with mixed forward and back
302 * slashes. Removing the trailing slash on a path means we never get
303 * ugly double slashes. Don't remove a leading slash, though.
306 canonicalize_path(char *path)
310 for (p = path; *p; p++)
317 if (p > path+1 && *--p == '/')
322 * make a copy of the array of lines, with token replaced by replacement
323 * the first time it occurs on each line.
325 * This does most of what sed was used for in the shell script, but
326 * doesn't need any regexp stuff.
329 replace_token(char **lines, char *token, char *replacement)
338 for (i = 0; lines[i]; i++)
341 result = (char **) xmalloc(numlines * sizeof(char *));
343 toklen = strlen(token);
344 replen = strlen(replacement);
345 diff = replen - toklen;
347 for (i = 0; i < numlines; i++)
353 /* just copy pointer if NULL or no change needed */
355 if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
357 result[i] = lines[i];
361 /* if we get here a change is needed - set up new line */
363 newline = (char *) xmalloc(strlen(lines[i]) + diff + 1);
365 pre = where - lines[i];
367 strncpy(newline, lines[i], pre);
369 strcpy(newline + pre, replacement);
371 strcpy(newline + pre + replen, lines[i] + pre + toklen);
382 * get the lines from a text file
395 if ((infile = fopen(path, "r")) == NULL)
397 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
398 progname, path, strerror(errno));
402 /* pass over the file twice - the first time to size the result */
404 while ((c = fgetc(infile)) != EOF)
410 if (linelen > maxlength)
416 /* handle last line without a terminating newline (yuck) */
420 if (linelen > maxlength)
423 /* set up the result and the line buffer */
425 result = (char **) xmalloc((nlines + 2) * sizeof(char *));
426 buffer = (char *) xmalloc(maxlength + 2);
428 /* now reprocess the file and store the lines */
432 while (fgets(buffer, maxlength + 1, infile) != NULL)
434 result[nlines] = xstrdup(buffer);
439 result[nlines] = NULL;
445 * write an array of lines to a file
448 writefile(char *path, char **lines)
453 if ((out_file = fopen(path, PG_BINARY_W)) == NULL)
455 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
456 progname, path, strerror(errno));
459 for (line = lines; *line != NULL; line++)
461 if (fputs(*line, out_file) < 0)
465 if (fclose(out_file))
469 /* pclose() plus useful error reporting */
471 pclose_check(FILE *stream)
475 exitstatus = pclose(stream);
478 return; /* all is well */
480 if (exitstatus == -1)
482 /* pclose() itself failed, and hopefully set errno */
483 perror("pclose failed");
485 else if (WIFEXITED(exitstatus))
487 fprintf(stderr, _("%s: child process exited with exit code %d\n"),
488 progname, WEXITSTATUS(exitstatus));
490 else if (WIFSIGNALED(exitstatus))
492 fprintf(stderr, _("%s: child process was terminated by signal %d\n"),
493 progname, WTERMSIG(exitstatus));
497 fprintf(stderr, _("%s: child process exited with unrecognized status %d\n"),
498 progname, exitstatus);
504 /* source stolen from FreeBSD /src/bin/mkdir/mkdir.c and adapted */
507 * this tries to build all the elements of a path to a directory a la mkdir -p
508 * we assume the path is in canonical form, i.e. uses / as the separator
509 * we also assume it isn't null.
512 mkdir_p(char *path, mode_t omode)
527 /* skip network and drive specifiers for win32 */
530 if (p[0] == '/' && p[1] == '/')
533 p = strstr(p + 2, "/");
537 else if (p[1] == ':' &&
538 ((p[0] >= 'a' && p[0] <= 'z') ||
539 (p[0] >= 'A' && p[0] <= 'Z')))
547 if (p[0] == '/') /* Skip leading '/'. */
549 for (first = 1, last = 0; !last; ++p)
553 else if (p[0] != '/')
556 if (!last && p[1] == '\0')
561 * POSIX 1003.2: For each dir operand that does not name an
562 * existing directory, effects equivalent to those cased by
563 * the following command shall occcur:
565 * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode]
568 * We change the user's umask and then restore it, instead of
572 numask = oumask & ~(S_IWUSR | S_IXUSR);
573 (void) umask(numask);
577 (void) umask(oumask);
578 if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
580 if (errno == EEXIST || errno == EISDIR)
582 if (stat(path, &sb) < 0)
587 else if (!S_ISDIR(sb.st_mode))
607 (void) umask(oumask);
612 * clean up any files we created on failure
613 * if we created the data directory remove it too
618 fprintf(stderr, _("%s: failed\n"), progname);
624 fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
626 if (!rmtree(pg_data, true))
627 fprintf(stderr, _("%s: failed\n"), progname);
629 else if (found_existing_pgdata)
632 _("%s: removing contents of data directory \"%s\"\n"),
634 if (!rmtree(pg_data, false))
635 fprintf(stderr, _("%s: failed\n"), progname);
637 /* otherwise died during startup, do nothing! */
641 if (made_new_pgdata || found_existing_pgdata)
643 _("%s: data directory \"%s\" not removed at user's request\n"),
651 * find the current user
653 * on unix make sure it isn't really root
662 pw = getpwuid(getuid());
664 #ifndef __BEOS__ /* no root check on BEOS */
666 if (!geteuid()) /* 0 is root's uid */
669 _("%s: cannot be run as root\n"
670 "Please log in (using, e.g., \"su\") as the "
671 "(unprivileged) user that will\n"
672 "own the server process.\n"),
678 #else /* the windows code */
685 struct passwd_win32 *pw = &pass_win32;
686 DWORD pwname_size = sizeof(pass_win32.pw_name) - 1;
689 GetUserName(pw->pw_name, &pwname_size);
692 return xstrdup(pw->pw_name);
696 * get the encoding id for a given encoding name
699 get_encoding_id(char *encoding_name)
704 if (encoding_name && *encoding_name)
706 if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
707 pg_valid_server_encoding(encoding_name) >= 0)
709 sprintf(result, "%d", enc);
710 return xstrdup(result);
713 fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
714 progname, encoding_name ? encoding_name : "(null)");
719 * get short version of VERSION
722 get_short_version(void)
728 vr = xstrdup(PG_VERSION);
730 for (end = 0; vr[end] != '\0'; end++)
741 else if (vr[end] < '0' || vr[end] > '9')
743 /* gone past digits and dots */
747 if (end == 0 || vr[end - 1] == '.' || !gotdot)
755 * make sure the data directory either doesn't exist or is empty
757 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
758 * or -1 if trouble accessing directory
769 chkdir = opendir(pg_data);
772 return (errno == ENOENT) ? 0 : -1;
774 while ((file = readdir(chkdir)) != NULL)
776 if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
778 /* skip this and parent directory */
783 result = 2; /* not empty */
791 result = -1; /* some kind of I/O error? */
797 * make the data directory (or one of its subdirectories if subdir is not NULL)
800 mkdatadir(char *subdir)
804 path = xmalloc(strlen(pg_data) + 2 +
805 (subdir == NULL ? 0 : strlen(subdir)));
808 sprintf(path, "%s/%s", pg_data, subdir);
810 strcpy(path, pg_data);
812 return (mkdir_p(path, 0700) == 0);
817 * set name of given input file variable under data directory
820 set_input(char **dest, char *filename)
822 *dest = xmalloc(strlen(datadir) + strlen(filename) + 2);
823 sprintf(*dest, "%s/%s", datadir, filename);
827 * check that given input file exists
830 check_input(char *path)
834 if (stat(path, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
837 _("%s: file \"%s\" does not exist\n"
838 "This means you have a corrupted installation or identified\n"
839 "the wrong directory with the invocation option -L.\n"),
847 * TODO - clean this up and handle the errors properly
850 #define FIND_SUCCESS 0
851 #define FIND_NOT_FOUND 1
852 #define FIND_STAT_ERR 2
853 #define FIND_NOT_REGFILE 3
854 #define FIND_BAD_PERM 4
855 #define FIND_EXEC_ERR 5
856 #define FIND_WRONG_VERSION 6
859 * see if there is a postgres executable in the given path, and giving the
860 * right version number
863 find_postgres(char *path)
870 int permmask = S_IROTH | S_IXOTH;
875 int plen = strlen(path);
877 if (plen > 0 && path[plen - 1] != '/')
878 snprintf(fn, sizeof(fn), "%s/postgres%s", path, EXE);
880 snprintf(fn, sizeof(fn), "%spostgres%s", path, EXE);
882 if (stat(fn, &statbuf) != 0)
885 return FIND_NOT_FOUND;
887 return FIND_STAT_ERR;
889 if (!S_ISREG(statbuf.st_mode))
890 return FIND_NOT_REGFILE;
895 * Only unix requires this test, on WIN32 an .exe file should be
898 if ((statbuf.st_mode & permmask) != permmask)
899 return FIND_BAD_PERM;
902 snprintf(cmd, sizeof(cmd), "\"%s/postgres\" -V 2>%s", path, DEVNULL);
904 /* flush output buffers in case popen does not... */
908 if ((pgver = popen(cmd, "r")) == NULL)
909 return FIND_EXEC_ERR;
911 if (fgets(line, sizeof(line), pgver) == NULL)
912 perror("fgets failure");
916 if (strcmp(line, PG_VERSIONSTR) != 0)
917 return FIND_WRONG_VERSION;
923 * Windows doesn't like relative paths to executables (other things work fine)
924 * so we call its builtin function to expand them. Elsewhere this is a NOOP
928 expanded_path(char *path)
930 char abspath[MAXPGPATH];
932 if (_fullpath(abspath, path, sizeof(abspath)) == NULL)
934 perror("expanded path");
937 canonicalize_path(abspath);
938 return xstrdup(abspath);
943 * set the paths pointing to postgres
945 * look for it in the same place we found this program, or in the environment
946 * path, or in the configured bindir.
947 * We do it in this order because during upgrades users might move
948 * their trees to backup places, so the hard-wired bindir might be inaccurate.
950 * XXX this needs work, as its error handling is vastly inferior to the
951 * shell-script version, in particular the case where a postgres executable
957 if (testpath && !self_path)
968 path = xstrdup(getenv("PATH"));
969 pathlen = strlen(path);
971 for (i = 0, pathsegs = 1; i < pathlen; i++)
973 if (path[i] == PATHSEP)
977 pathbits = (char **) xmalloc(pathsegs * sizeof(char *));
978 for (i = 0, pathsegs = 0, cursor = path; i <= pathlen; i++)
980 if (path[i] == PATHSEP || path[i] == 0)
983 if (strlen(cursor) == 0)
985 /* empty path segment means current directory */
986 pathbits[pathsegs] = xstrdup(".");
990 canonicalize_path(cursor);
991 pathbits[pathsegs] = cursor;
994 cursor = path + i + 1;
998 for (i = 0; i < pathsegs; i++)
1000 snprintf(buf, sizeof(buf), "%s/%s%s", pathbits[i], progname, EXE);
1001 if (stat(buf, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1003 self_path = pathbits[i];
1009 if (testpath && self_path &&
1010 (find_postgres(expanded_path(self_path)) == 0))
1012 /* we found postgres on out own path */
1013 pgpath = expanded_path(self_path);
1017 /* look in the hardcoded bindir */
1021 cbindir = xstrdup(bindir);
1022 canonicalize_path(cbindir);
1023 res = find_postgres(expanded_path(cbindir));
1025 pgpath = expanded_path(cbindir);
1034 * write out the PG_VERSION file in the data dir, or its subdirectory
1035 * if extrapath is not NULL
1038 set_short_version(char *short_version, char *extrapath)
1043 if (extrapath == NULL)
1045 path = xmalloc(strlen(pg_data) + 12);
1046 sprintf(path, "%s/PG_VERSION", pg_data);
1050 path = xmalloc(strlen(pg_data) + strlen(extrapath) + 13);
1051 sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
1053 version_file = fopen(path, PG_BINARY_W);
1054 if (version_file == NULL)
1056 fprintf(version_file, "%s\n", short_version);
1057 if (fclose(version_file))
1062 * set up an empty config file so we can check buffers and connections
1070 path = xmalloc(strlen(pg_data) + 17);
1071 sprintf(path, "%s/postgresql.conf", pg_data);
1072 conf_file = fopen(path, PG_BINARY_W);
1073 if (conf_file == NULL || fclose(conf_file))
1078 * check how many connections we can sustain
1081 test_connections(void)
1083 char cmd[MAXPGPATH];
1084 static const int conns[] = {100, 50, 40, 30, 20, 10};
1085 static const int len = sizeof(conns) / sizeof(int);
1089 printf(_("selecting default max_connections ... "));
1092 for (i = 0; i < len; i++)
1094 snprintf(cmd, sizeof(cmd),
1095 "\"%s/postgres\" -boot -x0 %s "
1096 "-c shared_buffers=%d -c max_connections=%d template1 "
1098 pgpath, boot_options,
1099 conns[i] * 5, conns[i],
1101 status = system(cmd);
1107 n_connections = conns[i];
1109 printf("%d\n", n_connections);
1113 * check how many buffers we can run with
1118 char cmd[MAXPGPATH];
1119 static const int bufs[] = {1000, 900, 800, 700, 600, 500,
1120 400, 300, 200, 100, 50};
1121 static const int len = sizeof(bufs) / sizeof(int);
1125 printf(_("selecting default shared_buffers ... "));
1128 for (i = 0; i < len; i++)
1130 snprintf(cmd, sizeof(cmd),
1131 "\"%s/postgres\" -boot -x0 %s "
1132 "-c shared_buffers=%d -c max_connections=%d template1 "
1134 pgpath, boot_options,
1135 bufs[i], n_connections,
1137 status = system(cmd);
1143 n_buffers = bufs[i];
1145 printf("%d\n", n_buffers);
1149 * set up all the config files
1156 char path[MAXPGPATH];
1158 fputs(_("creating configuration files ... "), stdout);
1161 /* postgresql.conf */
1163 conflines = readfile(conf_file);
1165 snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1166 conflines = replace_token(conflines, "#max_connections = 100", repltok);
1168 snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
1169 conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);
1171 snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
1172 conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1174 snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
1175 conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1177 snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);
1179 conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1181 snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
1182 conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1184 snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1186 writefile(path, conflines);
1194 conflines = readfile(hba_file);
1197 conflines = replace_token(conflines,
1199 "#host all all ::1");
1202 snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1204 writefile(path, conflines);
1211 conflines = readfile(ident_file);
1213 snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1215 writefile(path, conflines);
1225 * run the BKI script in bootstrap mode to create template1
1228 bootstrap_template1(char *short_version)
1230 char *talkargs = "";
1232 char headerline[MAXPGPATH];
1236 printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1242 bki_lines = readfile(bki_file);
1244 /* Check that bki file appears to be of the right version */
1246 snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1249 if (strcmp(headerline, *bki_lines) != 0)
1252 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1253 "Check your installation or specify the correct path "
1254 "using the option -L.\n"),
1255 progname, bki_file, PG_VERSION);
1260 bki_lines = replace_token(bki_lines, "POSTGRES", effective_user);
1262 bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1265 * Pass correct LC_xxx environment to bootstrap.
1267 * The shell script arranged to restore the LC settings afterwards,
1268 * but there doesn't seem to be any compelling reason to do that.
1270 snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1271 putenv(xstrdup(cmd));
1273 snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1274 putenv(xstrdup(cmd));
1278 snprintf(cmd, sizeof(cmd),
1279 "\"%s/postgres\" -boot -x1 %s %s template1",
1280 pgpath, boot_options, talkargs);
1284 for (line = bki_lines; *line != NULL; line++)
1298 * set up the shadow password table
1303 char *pg_shadow_setup[] = {
1305 * Create a trigger so that direct updates to pg_shadow will be
1306 * written to the flat password/group files pg_pwd and pg_group
1308 "CREATE TRIGGER pg_sync_pg_pwd "
1309 " AFTER INSERT OR UPDATE OR DELETE ON pg_shadow "
1310 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1311 "CREATE TRIGGER pg_sync_pg_group "
1312 " AFTER INSERT OR UPDATE OR DELETE ON pg_group "
1313 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1316 * needs to be done before alter user, because alter user checks
1317 * that pg_shadow is secure ...
1319 "REVOKE ALL on pg_shadow FROM public;\n",
1325 fputs(_("initializing pg_shadow ... "), stdout);
1328 snprintf(cmd, sizeof(cmd),
1329 "\"%s/postgres\" %s template1 >%s",
1330 pgpath, backend_options,
1335 for (line = pg_shadow_setup; *line != NULL; line++)
1344 * get the superuser password if required, and call postgres to set it
1353 char pwdpath[MAXPGPATH];
1354 struct stat statbuf;
1356 pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1357 pwd2 = simple_prompt("Enter it again: ", 100, false);
1358 if (strcmp(pwd1, pwd2) != 0)
1360 fprintf(stderr, _("Passwords didn't match.\n"));
1365 printf(_("setting password ... "));
1368 snprintf(cmd, sizeof(cmd),
1369 "\"%s/postgres\" %s template1 >%s",
1370 pgpath, backend_options,
1376 "ALTER USER \"%s\" WITH PASSWORD '%s';\n", username, pwd1) < 0)
1385 snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1386 if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1389 _("%s: The password file was not generated. "
1390 "Please report this problem.\n"),
1402 unlimit_systables(void)
1404 char *systables_setup[] = {
1405 "ALTER TABLE pg_attrdef CREATE TOAST TABLE;\n",
1406 "ALTER TABLE pg_constraint CREATE TOAST TABLE;\n",
1407 "ALTER TABLE pg_database CREATE TOAST TABLE;\n",
1408 "ALTER TABLE pg_description CREATE TOAST TABLE;\n",
1409 "ALTER TABLE pg_group CREATE TOAST TABLE;\n",
1410 "ALTER TABLE pg_proc CREATE TOAST TABLE;\n",
1411 "ALTER TABLE pg_rewrite CREATE TOAST TABLE;\n",
1412 "ALTER TABLE pg_shadow CREATE TOAST TABLE;\n",
1413 "ALTER TABLE pg_statistic CREATE TOAST TABLE;\n",
1419 fputs(_("enabling unlimited row size for system tables ... "), stdout);
1422 snprintf(cmd, sizeof(cmd),
1423 "\"%s/postgres\" %s template1 >%s",
1424 pgpath, backend_options,
1429 for (line = systables_setup; *line != NULL; line++)
1443 char *pg_depend_setup[] = {
1445 * Make PIN entries in pg_depend for all objects made so far in
1446 * the tables that the dependency code handles. This is overkill
1447 * (the system doesn't really depend on having every last weird
1448 * datatype, for instance) but generating only the minimum
1449 * required set of dependencies seems hard.
1451 * Note that we deliberately do not pin the system views, which
1452 * haven't been created yet.
1454 * First delete any already-made entries; PINs override all else, and
1455 * must be the only entries for their objects.
1457 "DELETE FROM pg_depend;\n",
1458 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1459 " FROM pg_class;\n",
1460 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1462 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1464 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1466 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1467 " FROM pg_constraint;\n",
1468 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1469 " FROM pg_attrdef;\n",
1470 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1471 " FROM pg_language;\n",
1472 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1473 " FROM pg_operator;\n",
1474 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1475 " FROM pg_opclass;\n",
1476 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1477 " FROM pg_rewrite;\n",
1478 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1479 " FROM pg_trigger;\n",
1482 * restriction here to avoid pinning the public namespace
1484 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1485 " FROM pg_namespace "
1486 " WHERE nspname LIKE 'pg%';\n",
1492 fputs(_("initializing pg_depend ... "), stdout);
1495 snprintf(cmd, sizeof(cmd),
1496 "\"%s/postgres\" %s template1 >%s",
1497 pgpath, backend_options,
1502 for (line = pg_depend_setup; *line != NULL; line++)
1511 * set up system views
1514 setup_sysviews(void)
1518 char **sysviews_setup;
1520 fputs(_("creating system views ... "), stdout);
1523 sysviews_setup = readfile(system_views_file);
1526 * We use -N here to avoid backslashing stuff in system_views.sql
1528 snprintf(cmd, sizeof(cmd),
1529 "\"%s/postgres\" %s -N template1 >%s",
1530 pgpath, backend_options,
1535 for (line = sysviews_setup; *line != NULL; line++)
1543 free(sysviews_setup);
1549 * load description data
1552 setup_description(void)
1557 fputs(_("loading pg_description ... "), stdout);
1560 snprintf(cmd, sizeof(cmd),
1561 "\"%s/postgres\" %s template1 >%s",
1562 pgpath, backend_options,
1568 "CREATE TEMP TABLE tmp_pg_description ( "
1572 " description text) WITHOUT OIDS;\n");
1577 "COPY tmp_pg_description FROM '%s';\n",
1583 "INSERT INTO pg_description "
1584 " SELECT t.objoid, c.oid, t.objsubid, t.description "
1585 " FROM tmp_pg_description t, pg_class c "
1586 " WHERE c.relname = t.classname;\n");
1596 * load conversion functions
1599 setup_conversion(void)
1605 fputs(_("creating conversions ... "), stdout);
1608 snprintf(cmd, sizeof(cmd),
1609 "\"%s/postgres\" %s template1 >%s",
1610 pgpath, backend_options,
1615 conv_lines = readfile(conversion_file);
1616 for (line = conv_lines; *line != NULL; line++)
1618 if (strstr(*line, "DROP CONVERSION") != *line)
1634 * We set most system catalogs and built-in functions as world-accessible.
1635 * Some objects may require different permissions by default, so we
1636 * make sure we don't overwrite privilege sets that have already been
1640 setup_privileges(void)
1642 char *privileges_setup[] = {
1644 " SET relacl = '{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1645 " WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;\n",
1647 " SET proacl = '{\"=X/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1648 " WHERE proacl IS NULL;\n",
1649 "UPDATE pg_language "
1650 " SET lanacl = '{\"=U/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1651 " WHERE lanpltrusted;\n",
1652 "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
1653 "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
1661 fputs(_("setting privileges on built-in objects ... "), stdout);
1664 snprintf(cmd, sizeof(cmd),
1665 "\"%s/postgres\" %s template1 >%s",
1666 pgpath, backend_options,
1671 priv_lines = replace_token(privileges_setup,
1672 "$POSTGRES_SUPERUSERNAME", username);
1673 for (line = priv_lines; *line != NULL; line++)
1682 * extract the strange version of version required for information schema
1686 set_info_version(void)
1688 char *letterversion;
1693 char *vstr = xstrdup(PG_VERSION);
1696 ptr = vstr + (strlen(vstr) - 1);
1697 while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1699 letterversion = ptr + 1;
1700 major = strtol(vstr, &endptr, 10);
1702 minor = strtol(endptr + 1, &endptr, 10);
1704 micro = strtol(endptr + 1, &endptr, 10);
1705 snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1706 major, minor, micro, letterversion);
1710 * load info schema and populate from features file
1719 fputs(_("creating information schema ... "), stdout);
1722 lines = readfile(info_schema_file);
1725 * We use -N here to avoid backslashing stuff in information_schema.sql
1727 snprintf(cmd, sizeof(cmd),
1728 "\"%s/postgres\" %s -N template1 >%s",
1729 pgpath, backend_options,
1734 for (line = lines; *line != NULL; line++)
1744 snprintf(cmd, sizeof(cmd),
1745 "\"%s/postgres\" %s template1 >%s",
1746 pgpath, backend_options,
1752 "UPDATE information_schema.sql_implementation_info "
1753 " SET character_value = '%s' "
1754 " WHERE implementation_info_name = 'DBMS VERSION';\n",
1760 "COPY information_schema.sql_features "
1761 " (feature_id, feature_name, sub_feature_id, "
1762 " sub_feature_name, is_supported, comments) "
1774 * clean everything up in template1
1781 fputs(_("vacuuming database template1 ... "), stdout);
1784 snprintf(cmd, sizeof(cmd),
1785 "\"%s/postgres\" %s template1 >%s",
1786 pgpath, backend_options,
1791 if (fputs("ANALYZE;\nVACUUM FULL FREEZE;\n", pg) < 0)
1801 * copy template1 to template0
1804 make_template0(void)
1806 char *template0_setup[] = {
1807 "CREATE DATABASE template0;\n",
1808 "UPDATE pg_database SET "
1809 " datistemplate = 't', "
1810 " datallowconn = 'f' "
1811 " WHERE datname = 'template0';\n",
1814 * We use the OID of template0 to determine lastsysoid
1816 "UPDATE pg_database SET datlastsysoid = "
1817 " (SELECT oid::int4 - 1 FROM pg_database "
1818 " WHERE datname = 'template0');\n",
1821 * Explicitly revoke public create-schema and create-temp-table
1822 * privileges in template1 and template0; else the latter would be
1825 "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
1826 "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
1829 * Finally vacuum to clean up dead rows in pg_database
1831 "VACUUM FULL pg_database;\n",
1837 fputs(_("copying template1 to template0 ... "), stdout);
1840 snprintf(cmd, sizeof(cmd),
1841 "\"%s/postgres\" %s template1 >%s",
1842 pgpath, backend_options,
1847 for (line = template0_setup; *line; line++)
1857 * signal handler in case we are interrupted.
1859 * The Windows runtime docs at
1860 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
1861 * specifically forbid a number of things being done from a signal handler,
1862 * including IO, memory allocation and system calls, and only allow jmpbuf
1863 * if you are handling SIGFPE.
1865 * I avoided doing the forbidden things by setting a flag instead of calling
1866 * exit_nicely() directly.
1868 * Also note the behaviour of Windows with SIGINT, which says this:
1869 * Note SIGINT is not supported for any Win32 application, including
1870 * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
1871 * Win32 operating systems generate a new thread to specifically handle
1872 * that interrupt. This can cause a single-thread application such as UNIX,
1873 * to become multithreaded, resulting in unexpected behavior.
1875 * I have no idea how to handle this. (Strange they call UNIX an application!)
1876 * So this will need some testing on Windows.
1881 /* handle systems that reset the handler, like Windows (grr) */
1882 pqsignal(signum, trapsig);
1883 caught_signal = true;
1887 * call exit_nicely() if we got a signal, or else output "ok".
1894 printf(_("caught signal\n"));
1897 else if (output_failed)
1899 printf(_("could not write to child process\n"));
1904 /* all seems well */
1911 * check if given string is a valid locale specifier
1912 * based on some code given to me by Peter Eisentraut
1913 * (but I take responsibility for it :-)
1916 chklocale(const char *locale)
1919 int category = LC_CTYPE;
1922 save = setlocale(category, NULL);
1924 return false; /* should not happen; */
1926 save = xstrdup(save);
1928 ret = (setlocale(category, locale) != NULL);
1930 setlocale(category, save);
1933 /* should we exit here? */
1935 fprintf(stderr, _("%s: invalid locale name \"%s\"\n"), progname, locale);
1941 * set up the locale variables
1943 * assumes we have called setlocale(LC_ALL,"")
1948 /* set empty lc_* values to locale config if set */
1950 if (strlen(locale) > 0)
1952 if (strlen(lc_ctype) == 0)
1954 if (strlen(lc_collate) == 0)
1955 lc_collate = locale;
1956 if (strlen(lc_numeric) == 0)
1957 lc_numeric = locale;
1958 if (strlen(lc_time) == 0)
1960 if (strlen(lc_monetary) == 0)
1961 lc_monetary = locale;
1962 if (strlen(lc_messages) == 0)
1963 lc_messages = locale;
1967 * override absent/invalid config settings from initdb's locale
1971 if (strlen(lc_ctype) == 0 || !chklocale(lc_ctype))
1972 lc_ctype = xstrdup(setlocale(LC_CTYPE, NULL));
1973 if (strlen(lc_collate) == 0 || !chklocale(lc_collate))
1974 lc_collate = xstrdup(setlocale(LC_COLLATE, NULL));
1975 if (strlen(lc_numeric) == 0 || !chklocale(lc_numeric))
1976 lc_numeric = xstrdup(setlocale(LC_NUMERIC, NULL));
1977 if (strlen(lc_time) == 0 || !chklocale(lc_time))
1978 lc_time = xstrdup(setlocale(LC_TIME, NULL));
1979 if (strlen(lc_monetary) == 0 || !chklocale(lc_monetary))
1980 lc_monetary = xstrdup(setlocale(LC_MONETARY, NULL));
1981 if (strlen(lc_messages) == 0 || !chklocale(lc_messages))
1984 /* when available get the current locale setting */
1985 lc_messages = xstrdup(setlocale(LC_MESSAGES, NULL));
1989 /* when not available, get the CTYPE setting */
1990 lc_messages = xstrdup(setlocale(LC_CTYPE, NULL));
2000 usage(const char *progname)
2002 printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2003 printf(_("Usage:\n"));
2004 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2005 printf(_("\nOptions:\n"));
2006 printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2007 printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2008 printf(_(" --locale=LOCALE initialize database cluster with given locale\n"));
2009 printf(_(" --lc-collate, --lc-ctype, --lc-messages=LOCALE\n"
2010 " --lc-monetary, --lc-numeric, --lc-time=LOCALE\n"
2011 " initialize database cluster with given locale\n"
2012 " in the respective category (default taken from\n"
2013 " environment)\n"));
2014 printf(_(" --no-locale equivalent to --locale=C\n"));
2015 printf(_(" -U, --username=NAME database superuser name\n"));
2016 printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2017 printf(_(" -?, --help show this help, then exit\n"));
2018 printf(_(" -V, --version output version information, then exit\n"));
2019 printf(_("\nLess commonly used options:\n"));
2020 printf(_(" -d, --debug generate lots of debugging output\n"));
2021 printf(_(" -s, --show show internal settings\n"));
2022 printf(_(" -L DIRECTORY where to find the input files\n"));
2023 printf(_(" -n, --noclean do not clean up after errors\n"));
2024 printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2026 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2030 * Initialized NLS if enabled.
2036 setlocale(LC_ALL, "");
2037 bindtextdomain("initdb", LOCALEDIR);
2038 textdomain("initdb");
2044 main(int argc, char *argv[])
2047 * options with no short version return a low integer, the rest return
2048 * their short version value
2050 static struct option long_options[] = {
2051 {"pgdata", required_argument, NULL, 'D'},
2052 {"encoding", required_argument, NULL, 'E'},
2053 {"locale", required_argument, NULL, 1},
2054 {"lc-collate", required_argument, NULL, 2},
2055 {"lc-ctype", required_argument, NULL, 3},
2056 {"lc-monetary", required_argument, NULL, 4},
2057 {"lc-numeric", required_argument, NULL, 5},
2058 {"lc-time", required_argument, NULL, 6},
2059 {"lc-messages", required_argument, NULL, 7},
2060 {"no-locale", no_argument, NULL, 8},
2061 {"pwprompt", no_argument, NULL, 'W'},
2062 {"username", required_argument, NULL, 'U'},
2063 {"help", no_argument, NULL, '?'},
2064 {"version", no_argument, NULL, 'V'},
2065 {"debug", no_argument, NULL, 'd'},
2066 {"show", no_argument, NULL, 's'},
2067 {"noclean", no_argument, NULL, 'n'},
2074 char *short_version;
2075 char *pgdenv; /* PGDATA value got from sent to
2078 {"global", "pg_xlog", "pg_clog", "base", "base/1"};
2081 #if defined(__CYGWIN__) || defined(WIN32)
2082 char *exe; /* location of exe suffix in progname */
2087 /* parse argv[0] - detect explicit path if there was one */
2088 carg0 = xstrdup(argv[0]);
2089 canonicalize_path(carg0);
2091 lastsep = strrchr(carg0, '/');
2092 progname = lastsep ? xstrdup(lastsep + 1) : carg0;
2094 #if defined(__CYGWIN__) || defined(WIN32)
2095 if (strlen(progname) > 4 &&
2096 (exe = progname + (strlen(progname) - 4)) &&
2097 stricmp(exe, EXE) == 0)
2099 /* strip .exe suffix, regardless of case */
2111 /* no path known to ourselves from argv[0] */
2117 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2122 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2124 puts("initdb (PostgreSQL) " PG_VERSION);
2129 /* process command-line options */
2131 while ((c = getopt_long(argc, argv, "dD:E:L:nU:W", long_options, &option_index)) != -1)
2136 pg_data = xstrdup(optarg);
2139 encoding = xstrdup(optarg);
2145 username = xstrdup(optarg);
2149 printf(_("Running in debug mode.\n"));
2153 printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
2156 datadir = xstrdup(optarg);
2159 locale = xstrdup(optarg);
2162 lc_collate = xstrdup(optarg);
2165 lc_ctype = xstrdup(optarg);
2168 lc_monetary = xstrdup(optarg);
2171 lc_numeric = xstrdup(optarg);
2174 lc_time = xstrdup(optarg);
2177 lc_messages = xstrdup(optarg);
2183 show_setting = true;
2186 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2192 /* Non-option argument specifies data directory */
2195 pg_data = xstrdup(argv[optind]);
2201 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
2202 progname, argv[optind + 1]);
2203 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2207 if (strlen(pg_data) == 0)
2209 pgdenv = getenv("PGDATA");
2210 if (pgdenv && strlen(pgdenv))
2213 pg_data = xstrdup(pgdenv);
2218 _("%s: no data directory specified\n"
2219 "You must identify the directory where the data for this database system\n"
2220 "will reside. Do this with either the invocation option -D or the\n"
2221 "environment variable PGDATA.\n"),
2227 canonicalize_path(pg_data);
2230 * we have to set PGDATA for postgres rather than pass it on the
2231 * commnd line to avoid dumb quoting problems on Windows, and we would
2232 * expecially need quotes otherwise on Windows because paths there are
2233 * most likely to have embedded spaces.
2235 pgdenv = xmalloc(8 + strlen(pg_data));
2236 sprintf(pgdenv, "PGDATA=%s", pg_data);
2239 if (set_paths() != 0)
2242 _("The program \"postgres\" is needed by %s "
2243 "but was not found in \n"
2244 "the directory \"%s\". Check your installation.\n"),
2249 if ((short_version = get_short_version()) == NULL)
2251 fprintf(stderr, _("%s: could not determine valid short version string\n"), progname);
2255 effective_user = get_id();
2256 if (!strlen(username))
2257 username = effective_user;
2259 if (strlen(encoding))
2260 encodingid = get_encoding_id(encoding);
2262 set_input(&bki_file, "postgres.bki");
2263 set_input(&desc_file, "postgres.description");
2264 set_input(&hba_file, "pg_hba.conf.sample");
2265 set_input(&ident_file, "pg_ident.conf.sample");
2266 set_input(&conf_file, "postgresql.conf.sample");
2267 set_input(&conversion_file, "conversion_create.sql");
2268 set_input(&info_schema_file, "information_schema.sql");
2269 set_input(&features_file, "sql_features.txt");
2270 set_input(&system_views_file, "system_views.sql");
2274 if (show_setting || debug)
2278 "PGDATA=%s\ndatadir=%s\nPGPATH=%s\n"
2279 "ENCODING=%s\nENCODINGID=%s\n"
2280 "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2281 "POSTGRES_DESCR=%s\nPOSTGRESQL_CONF_SAMPLE=%s\n"
2282 "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2284 pg_data, datadir, pgpath,
2285 encoding, encodingid,
2287 desc_file, conf_file,
2288 hba_file, ident_file);
2293 check_input(bki_file);
2294 check_input(desc_file);
2295 check_input(hba_file);
2296 check_input(ident_file);
2297 check_input(conf_file);
2298 check_input(conversion_file);
2299 check_input(info_schema_file);
2300 check_input(features_file);
2301 check_input(system_views_file);
2303 printf(_("The files belonging to this database system will be owned "
2305 "This user must also own the server process.\n\n"),
2310 if (strcmp(lc_ctype, lc_collate) == 0 &&
2311 strcmp(lc_ctype, lc_time) == 0 &&
2312 strcmp(lc_ctype, lc_numeric) == 0 &&
2313 strcmp(lc_ctype, lc_monetary) == 0 &&
2314 strcmp(lc_ctype, lc_messages) == 0)
2316 printf(_("The database cluster will be initialized with locale %s.\n\n"),
2321 printf(_("The database cluster will be initialized with locales\n"
2339 * now we are starting to do real work, trap signals so we can clean
2343 /* some of these are not valid on Windows */
2345 pqsignal(SIGHUP, trapsig);
2348 pqsignal(SIGINT, trapsig);
2351 pqsignal(SIGQUIT, trapsig);
2354 pqsignal(SIGTERM, trapsig);
2357 /* Ignore SIGPIPE when writing to backend, so we can clean up */
2359 pqsignal(SIGPIPE, SIG_IGN);
2362 switch (check_data_dir())
2365 /* PGDATA not there, must create it */
2366 printf(_("creating directory %s ... "),
2370 if (!mkdatadir(NULL))
2375 made_new_pgdata = true;
2379 /* Present but empty, fix permissions and use it */
2380 printf(_("fixing permissions on existing directory %s ... "),
2384 if (chmod(pg_data, 0700) != 0)
2392 found_existing_pgdata = true;
2396 /* Present and not empty */
2398 _("%s: directory \"%s\" exists but is not empty\n"
2399 "If you want to create a new database system, either remove or empty\n"
2400 "the directory \"%s\" or run %s\n"
2401 "with an argument other than \"%s\".\n"),
2402 progname, pg_data, pg_data, progname, pg_data);
2403 exit(1); /* no further message needed */
2406 /* Trouble accessing directory */
2411 /* Create required subdirectories */
2413 for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
2415 printf(_("creating directory %s/%s ... "), pg_data, subdirs[i]);
2418 if (!mkdatadir(subdirs[i]))
2424 /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2425 set_short_version(short_version, NULL);
2428 * Determine platform-specific config settings
2430 * Use reasonable values if kernel will let us, else scale back. Probe for
2431 * max_connections first since it is subject to more constraints than
2440 /* Now create all the text config files */
2443 /* Bootstrap template1 */
2444 bootstrap_template1(short_version);
2446 /* Make the per-database PGVERSION for template1 only after init'ing it */
2447 set_short_version(short_version, "base/1");
2449 /* Create the stuff we don't need to use bootstrap mode for */
2455 unlimit_systables();
2461 setup_description();
2473 printf(_("\nSuccess. You can now start the database server using:\n\n"
2474 " %s%s%s/postmaster -D %s%s%s\n"
2476 " %s%s%s/pg_ctl -D %s%s%s -l logfile start\n\n"),
2477 QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH,
2478 QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH);