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.19 2004/01/26 22:35:32 tgl 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)
454 if ((out_file = fopen(path, PG_BINARY_W)) == NULL)
456 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
457 progname, path, strerror(errno));
460 for (line = lines; *line != NULL; line++)
462 if (fputs(*line, out_file) < 0)
466 if (fclose(out_file))
470 /* pclose() plus useful error reporting */
472 pclose_check(FILE *stream)
476 exitstatus = pclose(stream);
479 return; /* all is well */
481 if (exitstatus == -1)
483 /* pclose() itself failed, and hopefully set errno */
484 perror("pclose failed");
486 else if (WIFEXITED(exitstatus))
488 fprintf(stderr, _("%s: child process exited with exit code %d\n"),
489 progname, WEXITSTATUS(exitstatus));
491 else if (WIFSIGNALED(exitstatus))
493 fprintf(stderr, _("%s: child process was terminated by signal %d\n"),
494 progname, WTERMSIG(exitstatus));
498 fprintf(stderr, _("%s: child process exited with unrecognized status %d\n"),
499 progname, exitstatus);
505 /* source stolen from FreeBSD /src/bin/mkdir/mkdir.c and adapted */
508 * this tries to build all the elements of a path to a directory a la mkdir -p
509 * we assume the path is in canonical form, i.e. uses / as the separator
510 * we also assume it isn't null.
513 mkdir_p(char *path, mode_t omode)
528 /* skip network and drive specifiers for win32 */
531 if (p[0] == '/' && p[1] == '/')
534 p = strstr(p + 2, "/");
538 else if (p[1] == ':' &&
539 ((p[0] >= 'a' && p[0] <= 'z') ||
540 (p[0] >= 'A' && p[0] <= 'Z')))
548 if (p[0] == '/') /* Skip leading '/'. */
550 for (first = 1, last = 0; !last; ++p)
554 else if (p[0] != '/')
562 * POSIX 1003.2: For each dir operand that does not name an
563 * existing directory, effects equivalent to those cased by
564 * the following command shall occcur:
566 * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode]
569 * We change the user's umask and then restore it, instead of
573 numask = oumask & ~(S_IWUSR | S_IXUSR);
574 (void) umask(numask);
578 (void) umask(oumask);
579 if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
581 if (errno == EEXIST || errno == EISDIR)
583 if (stat(path, &sb) < 0)
588 else if (!S_ISDIR(sb.st_mode))
608 (void) umask(oumask);
613 * clean up any files we created on failure
614 * if we created the data directory remove it too
619 fprintf(stderr, _("%s: failed\n"), progname);
625 fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
627 if (!rmtree(pg_data, true))
628 fprintf(stderr, _("%s: failed\n"), progname);
630 else if (found_existing_pgdata)
633 _("%s: removing contents of data directory \"%s\"\n"),
635 if (!rmtree(pg_data, false))
636 fprintf(stderr, _("%s: failed\n"), progname);
638 /* otherwise died during startup, do nothing! */
642 if (made_new_pgdata || found_existing_pgdata)
644 _("%s: data directory \"%s\" not removed at user's request\n"),
652 * find the current user
654 * on unix make sure it isn't really root
663 pw = getpwuid(getuid());
665 #ifndef __BEOS__ /* no root check on BEOS */
667 if (!geteuid()) /* 0 is root's uid */
670 _("%s: cannot be run as root\n"
671 "Please log in (using, e.g., \"su\") as the "
672 "(unprivileged) user that will\n"
673 "own the server process.\n"),
679 #else /* the windows code */
686 struct passwd_win32 *pw = &pass_win32;
687 DWORD pwname_size = sizeof(pass_win32.pw_name) - 1;
690 GetUserName(pw->pw_name, &pwname_size);
693 return xstrdup(pw->pw_name);
697 * get the encoding id for a given encoding name
700 get_encoding_id(char *encoding_name)
705 if (encoding_name && *encoding_name)
707 if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
708 pg_valid_server_encoding(encoding_name) >= 0)
710 sprintf(result, "%d", enc);
711 return xstrdup(result);
714 fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
715 progname, encoding_name ? encoding_name : "(null)");
720 * get short version of VERSION
723 get_short_version(void)
729 vr = xstrdup(PG_VERSION);
731 for (end = 0; vr[end] != '\0'; end++)
742 else if (vr[end] < '0' || vr[end] > '9')
744 /* gone past digits and dots */
748 if (end == 0 || vr[end - 1] == '.' || !gotdot)
756 * make sure the data directory either doesn't exist or is empty
758 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
759 * or -1 if trouble accessing directory
770 chkdir = opendir(pg_data);
773 return (errno == ENOENT) ? 0 : -1;
775 while ((file = readdir(chkdir)) != NULL)
777 if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
779 /* skip this and parent directory */
784 result = 2; /* not empty */
792 result = -1; /* some kind of I/O error? */
798 * make the data directory (or one of its subdirectories if subdir is not NULL)
801 mkdatadir(char *subdir)
805 path = xmalloc(strlen(pg_data) + 2 +
806 (subdir == NULL ? 0 : strlen(subdir)));
809 sprintf(path, "%s/%s", pg_data, subdir);
811 strcpy(path, pg_data);
813 return (mkdir_p(path, 0700) == 0);
818 * set name of given input file variable under data directory
821 set_input(char **dest, char *filename)
823 *dest = xmalloc(strlen(datadir) + strlen(filename) + 2);
824 sprintf(*dest, "%s/%s", datadir, filename);
828 * check that given input file exists
831 check_input(char *path)
835 if (stat(path, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
838 _("%s: file \"%s\" does not exist\n"
839 "This means you have a corrupted installation or identified\n"
840 "the wrong directory with the invocation option -L.\n"),
848 * TODO - clean this up and handle the errors properly
851 #define FIND_SUCCESS 0
852 #define FIND_NOT_FOUND 1
853 #define FIND_STAT_ERR 2
854 #define FIND_NOT_REGFILE 3
855 #define FIND_BAD_PERM 4
856 #define FIND_EXEC_ERR 5
857 #define FIND_WRONG_VERSION 6
860 * see if there is a postgres executable in the given path, and giving the
861 * right version number
864 find_postgres(char *path)
871 int permmask = S_IROTH | S_IXOTH;
876 int plen = strlen(path);
878 if (plen > 0 && path[plen - 1] != '/')
879 snprintf(fn, sizeof(fn), "%s/postgres%s", path, EXE);
881 snprintf(fn, sizeof(fn), "%spostgres%s", path, EXE);
883 if (stat(fn, &statbuf) != 0)
886 return FIND_NOT_FOUND;
888 return FIND_STAT_ERR;
890 if (!S_ISREG(statbuf.st_mode))
891 return FIND_NOT_REGFILE;
896 * Only unix requires this test, on WIN32 an .exe file should be
899 if ((statbuf.st_mode & permmask) != permmask)
900 return FIND_BAD_PERM;
903 snprintf(cmd, sizeof(cmd), "\"%s/postgres\" -V 2>%s", path, DEVNULL);
905 /* flush output buffers in case popen does not... */
909 if ((pgver = popen(cmd, "r")) == NULL)
910 return FIND_EXEC_ERR;
912 if (fgets(line, sizeof(line), pgver) == NULL)
913 perror("fgets failure");
917 if (strcmp(line, PG_VERSIONSTR) != 0)
918 return FIND_WRONG_VERSION;
924 * Windows doesn't like relative paths to executables (other things work fine)
925 * so we call its builtin function to expand them. Elsewhere this is a NOOP
929 expanded_path(char *path)
931 char abspath[MAXPGPATH];
933 if (_fullpath(abspath, path, sizeof(abspath)) == NULL)
935 perror("expanded path");
938 canonicalize_path(abspath);
939 return xstrdup(abspath);
944 * set the paths pointing to postgres
946 * look for it in the same place we found this program, or in the environment
947 * path, or in the configured bindir.
948 * We do it in this order because during upgrades users might move
949 * their trees to backup places, so the hard-wired bindir might be inaccurate.
951 * XXX this needs work, as its error handling is vastly inferior to the
952 * shell-script version, in particular the case where a postgres executable
958 if (testpath && !self_path)
969 path = xstrdup(getenv("PATH"));
970 pathlen = strlen(path);
972 for (i = 0, pathsegs = 1; i < pathlen; i++)
974 if (path[i] == PATHSEP)
978 pathbits = (char **) xmalloc(pathsegs * sizeof(char *));
979 for (i = 0, pathsegs = 0, cursor = path; i <= pathlen; i++)
981 if (path[i] == PATHSEP || path[i] == 0)
984 if (strlen(cursor) == 0)
986 /* empty path segment means current directory */
987 pathbits[pathsegs] = xstrdup(".");
991 canonicalize_path(cursor);
992 pathbits[pathsegs] = cursor;
995 cursor = path + i + 1;
999 for (i = 0; i < pathsegs; i++)
1001 snprintf(buf, sizeof(buf), "%s/%s%s", pathbits[i], progname, EXE);
1002 if (stat(buf, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1004 self_path = pathbits[i];
1010 if (testpath && self_path &&
1011 (find_postgres(expanded_path(self_path)) == 0))
1013 /* we found postgres on out own path */
1014 pgpath = expanded_path(self_path);
1018 /* look in the hardcoded bindir */
1022 cbindir = xstrdup(bindir);
1023 canonicalize_path(cbindir);
1024 res = find_postgres(expanded_path(cbindir));
1026 pgpath = expanded_path(cbindir);
1035 * write out the PG_VERSION file in the data dir, or its subdirectory
1036 * if extrapath is not NULL
1039 set_short_version(char *short_version, char *extrapath)
1044 if (extrapath == NULL)
1046 path = xmalloc(strlen(pg_data) + 12);
1047 sprintf(path, "%s/PG_VERSION", pg_data);
1051 path = xmalloc(strlen(pg_data) + strlen(extrapath) + 13);
1052 sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
1054 version_file = fopen(path, PG_BINARY_W);
1055 if (version_file == NULL)
1057 fprintf(version_file, "%s\n", short_version);
1058 if (fclose(version_file))
1063 * set up an empty config file so we can check buffers and connections
1071 path = xmalloc(strlen(pg_data) + 17);
1072 sprintf(path, "%s/postgresql.conf", pg_data);
1073 conf_file = fopen(path, PG_BINARY_W);
1074 if (conf_file == NULL || fclose(conf_file))
1079 * check how many connections we can sustain
1082 test_connections(void)
1084 char cmd[MAXPGPATH];
1085 static const int conns[] = {100, 50, 40, 30, 20, 10};
1086 static const int len = sizeof(conns) / sizeof(int);
1090 printf(_("selecting default max_connections ... "));
1093 for (i = 0; i < len; i++)
1095 snprintf(cmd, sizeof(cmd),
1096 "\"%s/postgres\" -boot -x0 %s "
1097 "-c shared_buffers=%d -c max_connections=%d template1 "
1099 pgpath, boot_options,
1100 conns[i] * 5, conns[i],
1102 status = system(cmd);
1108 n_connections = conns[i];
1110 printf("%d\n", n_connections);
1114 * check how many buffers we can run with
1119 char cmd[MAXPGPATH];
1120 static const int bufs[] = {1000, 900, 800, 700, 600, 500,
1121 400, 300, 200, 100, 50};
1122 static const int len = sizeof(bufs) / sizeof(int);
1126 printf(_("selecting default shared_buffers ... "));
1129 for (i = 0; i < len; i++)
1131 snprintf(cmd, sizeof(cmd),
1132 "\"%s/postgres\" -boot -x0 %s "
1133 "-c shared_buffers=%d -c max_connections=%d template1 "
1135 pgpath, boot_options,
1136 bufs[i], n_connections,
1138 status = system(cmd);
1144 n_buffers = bufs[i];
1146 printf("%d\n", n_buffers);
1150 * set up all the config files
1157 char path[MAXPGPATH];
1159 fputs(_("creating configuration files ... "), stdout);
1162 /* postgresql.conf */
1164 conflines = readfile(conf_file);
1166 snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1167 conflines = replace_token(conflines, "#max_connections = 100", repltok);
1169 snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
1170 conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);
1172 snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
1173 conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1175 snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
1176 conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1178 snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);
1180 conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1182 snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
1183 conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1185 snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1187 writefile(path, conflines);
1195 conflines = readfile(hba_file);
1198 conflines = replace_token(conflines,
1200 "#host all all ::1");
1203 snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1205 writefile(path, conflines);
1212 conflines = readfile(ident_file);
1214 snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1216 writefile(path, conflines);
1226 * run the BKI script in bootstrap mode to create template1
1229 bootstrap_template1(char *short_version)
1231 char *talkargs = "";
1233 char headerline[MAXPGPATH];
1237 printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1243 bki_lines = readfile(bki_file);
1245 /* Check that bki file appears to be of the right version */
1247 snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1250 if (strcmp(headerline, *bki_lines) != 0)
1253 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1254 "Check your installation or specify the correct path "
1255 "using the option -L.\n"),
1256 progname, bki_file, PG_VERSION);
1261 bki_lines = replace_token(bki_lines, "POSTGRES", effective_user);
1263 bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1266 * Pass correct LC_xxx environment to bootstrap.
1268 * The shell script arranged to restore the LC settings afterwards,
1269 * but there doesn't seem to be any compelling reason to do that.
1271 snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1272 putenv(xstrdup(cmd));
1274 snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1275 putenv(xstrdup(cmd));
1279 snprintf(cmd, sizeof(cmd),
1280 "\"%s/postgres\" -boot -x1 %s %s template1",
1281 pgpath, boot_options, talkargs);
1285 for (line = bki_lines; *line != NULL; line++)
1299 * set up the shadow password table
1304 char *pg_shadow_setup[] = {
1306 * Create a trigger so that direct updates to pg_shadow will be
1307 * written to the flat password/group files pg_pwd and pg_group
1309 "CREATE TRIGGER pg_sync_pg_pwd "
1310 " AFTER INSERT OR UPDATE OR DELETE ON pg_shadow "
1311 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1312 "CREATE TRIGGER pg_sync_pg_group "
1313 " AFTER INSERT OR UPDATE OR DELETE ON pg_group "
1314 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1317 * needs to be done before alter user, because alter user checks
1318 * that pg_shadow is secure ...
1320 "REVOKE ALL on pg_shadow FROM public;\n",
1326 fputs(_("initializing pg_shadow ... "), stdout);
1329 snprintf(cmd, sizeof(cmd),
1330 "\"%s/postgres\" %s template1 >%s",
1331 pgpath, backend_options,
1336 for (line = pg_shadow_setup; *line != NULL; line++)
1345 * get the superuser password if required, and call postgres to set it
1354 char pwdpath[MAXPGPATH];
1355 struct stat statbuf;
1357 pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1358 pwd2 = simple_prompt("Enter it again: ", 100, false);
1359 if (strcmp(pwd1, pwd2) != 0)
1361 fprintf(stderr, _("Passwords didn't match.\n"));
1366 printf(_("setting password ... "));
1369 snprintf(cmd, sizeof(cmd),
1370 "\"%s/postgres\" %s template1 >%s",
1371 pgpath, backend_options,
1377 "ALTER USER \"%s\" WITH PASSWORD '%s';\n", username, pwd1) < 0)
1386 snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1387 if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1390 _("%s: The password file was not generated. "
1391 "Please report this problem.\n"),
1403 unlimit_systables(void)
1405 char *systables_setup[] = {
1406 "ALTER TABLE pg_attrdef CREATE TOAST TABLE;\n",
1407 "ALTER TABLE pg_constraint CREATE TOAST TABLE;\n",
1408 "ALTER TABLE pg_database CREATE TOAST TABLE;\n",
1409 "ALTER TABLE pg_description CREATE TOAST TABLE;\n",
1410 "ALTER TABLE pg_group CREATE TOAST TABLE;\n",
1411 "ALTER TABLE pg_proc CREATE TOAST TABLE;\n",
1412 "ALTER TABLE pg_rewrite CREATE TOAST TABLE;\n",
1413 "ALTER TABLE pg_shadow CREATE TOAST TABLE;\n",
1414 "ALTER TABLE pg_statistic CREATE TOAST TABLE;\n",
1420 fputs(_("enabling unlimited row size for system tables ... "), stdout);
1423 snprintf(cmd, sizeof(cmd),
1424 "\"%s/postgres\" %s template1 >%s",
1425 pgpath, backend_options,
1430 for (line = systables_setup; *line != NULL; line++)
1444 char *pg_depend_setup[] = {
1446 * Make PIN entries in pg_depend for all objects made so far in
1447 * the tables that the dependency code handles. This is overkill
1448 * (the system doesn't really depend on having every last weird
1449 * datatype, for instance) but generating only the minimum
1450 * required set of dependencies seems hard.
1452 * Note that we deliberately do not pin the system views, which
1453 * haven't been created yet.
1455 * First delete any already-made entries; PINs override all else, and
1456 * must be the only entries for their objects.
1458 "DELETE FROM pg_depend;\n",
1459 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1460 " FROM pg_class;\n",
1461 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1463 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1465 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1467 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1468 " FROM pg_constraint;\n",
1469 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1470 " FROM pg_attrdef;\n",
1471 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1472 " FROM pg_language;\n",
1473 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1474 " FROM pg_operator;\n",
1475 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1476 " FROM pg_opclass;\n",
1477 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1478 " FROM pg_rewrite;\n",
1479 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1480 " FROM pg_trigger;\n",
1483 * restriction here to avoid pinning the public namespace
1485 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1486 " FROM pg_namespace "
1487 " WHERE nspname LIKE 'pg%';\n",
1493 fputs(_("initializing pg_depend ... "), stdout);
1496 snprintf(cmd, sizeof(cmd),
1497 "\"%s/postgres\" %s template1 >%s",
1498 pgpath, backend_options,
1503 for (line = pg_depend_setup; *line != NULL; line++)
1512 * set up system views
1515 setup_sysviews(void)
1519 char **sysviews_setup;
1521 fputs(_("creating system views ... "), stdout);
1524 sysviews_setup = readfile(system_views_file);
1527 * We use -N here to avoid backslashing stuff in system_views.sql
1529 snprintf(cmd, sizeof(cmd),
1530 "\"%s/postgres\" %s -N template1 >%s",
1531 pgpath, backend_options,
1536 for (line = sysviews_setup; *line != NULL; line++)
1544 free(sysviews_setup);
1550 * load description data
1553 setup_description(void)
1558 fputs(_("loading pg_description ... "), stdout);
1561 snprintf(cmd, sizeof(cmd),
1562 "\"%s/postgres\" %s template1 >%s",
1563 pgpath, backend_options,
1569 "CREATE TEMP TABLE tmp_pg_description ( "
1573 " description text) WITHOUT OIDS;\n");
1578 "COPY tmp_pg_description FROM '%s';\n",
1584 "INSERT INTO pg_description "
1585 " SELECT t.objoid, c.oid, t.objsubid, t.description "
1586 " FROM tmp_pg_description t, pg_class c "
1587 " WHERE c.relname = t.classname;\n");
1597 * load conversion functions
1600 setup_conversion(void)
1606 fputs(_("creating conversions ... "), stdout);
1609 snprintf(cmd, sizeof(cmd),
1610 "\"%s/postgres\" %s template1 >%s",
1611 pgpath, backend_options,
1616 conv_lines = readfile(conversion_file);
1617 for (line = conv_lines; *line != NULL; line++)
1619 if (strstr(*line, "DROP CONVERSION") != *line)
1635 * We set most system catalogs and built-in functions as world-accessible.
1636 * Some objects may require different permissions by default, so we
1637 * make sure we don't overwrite privilege sets that have already been
1641 setup_privileges(void)
1643 char *privileges_setup[] = {
1645 " SET relacl = '{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1646 " WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;\n",
1648 " SET proacl = '{\"=X/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1649 " WHERE proacl IS NULL;\n",
1650 "UPDATE pg_language "
1651 " SET lanacl = '{\"=U/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1652 " WHERE lanpltrusted;\n",
1653 "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
1654 "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
1662 fputs(_("setting privileges on built-in objects ... "), stdout);
1665 snprintf(cmd, sizeof(cmd),
1666 "\"%s/postgres\" %s template1 >%s",
1667 pgpath, backend_options,
1672 priv_lines = replace_token(privileges_setup,
1673 "$POSTGRES_SUPERUSERNAME", username);
1674 for (line = priv_lines; *line != NULL; line++)
1683 * extract the strange version of version required for information schema
1687 set_info_version(void)
1689 char *letterversion;
1694 char *vstr = xstrdup(PG_VERSION);
1697 ptr = vstr + (strlen(vstr) - 1);
1698 while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1700 letterversion = ptr + 1;
1701 major = strtol(vstr, &endptr, 10);
1703 minor = strtol(endptr + 1, &endptr, 10);
1705 micro = strtol(endptr + 1, &endptr, 10);
1706 snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1707 major, minor, micro, letterversion);
1711 * load info schema and populate from features file
1720 fputs(_("creating information schema ... "), stdout);
1723 lines = readfile(info_schema_file);
1726 * We use -N here to avoid backslashing stuff in information_schema.sql
1728 snprintf(cmd, sizeof(cmd),
1729 "\"%s/postgres\" %s -N template1 >%s",
1730 pgpath, backend_options,
1735 for (line = lines; *line != NULL; line++)
1745 snprintf(cmd, sizeof(cmd),
1746 "\"%s/postgres\" %s template1 >%s",
1747 pgpath, backend_options,
1753 "UPDATE information_schema.sql_implementation_info "
1754 " SET character_value = '%s' "
1755 " WHERE implementation_info_name = 'DBMS VERSION';\n",
1761 "COPY information_schema.sql_features "
1762 " (feature_id, feature_name, sub_feature_id, "
1763 " sub_feature_name, is_supported, comments) "
1775 * clean everything up in template1
1782 fputs(_("vacuuming database template1 ... "), stdout);
1785 snprintf(cmd, sizeof(cmd),
1786 "\"%s/postgres\" %s template1 >%s",
1787 pgpath, backend_options,
1792 if (fputs("ANALYZE;\nVACUUM FULL FREEZE;\n", pg) < 0)
1802 * copy template1 to template0
1805 make_template0(void)
1807 char *template0_setup[] = {
1808 "CREATE DATABASE template0;\n",
1809 "UPDATE pg_database SET "
1810 " datistemplate = 't', "
1811 " datallowconn = 'f' "
1812 " WHERE datname = 'template0';\n",
1815 * We use the OID of template0 to determine lastsysoid
1817 "UPDATE pg_database SET datlastsysoid = "
1818 " (SELECT oid::int4 - 1 FROM pg_database "
1819 " WHERE datname = 'template0');\n",
1822 * Explicitly revoke public create-schema and create-temp-table
1823 * privileges in template1 and template0; else the latter would be
1826 "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
1827 "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
1830 * Finally vacuum to clean up dead rows in pg_database
1832 "VACUUM FULL pg_database;\n",
1838 fputs(_("copying template1 to template0 ... "), stdout);
1841 snprintf(cmd, sizeof(cmd),
1842 "\"%s/postgres\" %s template1 >%s",
1843 pgpath, backend_options,
1848 for (line = template0_setup; *line; line++)
1858 * signal handler in case we are interrupted.
1860 * The Windows runtime docs at
1861 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
1862 * specifically forbid a number of things being done from a signal handler,
1863 * including IO, memory allocation and system calls, and only allow jmpbuf
1864 * if you are handling SIGFPE.
1866 * I avoided doing the forbidden things by setting a flag instead of calling
1867 * exit_nicely() directly.
1869 * Also note the behaviour of Windows with SIGINT, which says this:
1870 * Note SIGINT is not supported for any Win32 application, including
1871 * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
1872 * Win32 operating systems generate a new thread to specifically handle
1873 * that interrupt. This can cause a single-thread application such as UNIX,
1874 * to become multithreaded, resulting in unexpected behavior.
1876 * I have no idea how to handle this. (Strange they call UNIX an application!)
1877 * So this will need some testing on Windows.
1882 /* handle systems that reset the handler, like Windows (grr) */
1883 pqsignal(signum, trapsig);
1884 caught_signal = true;
1888 * call exit_nicely() if we got a signal, or else output "ok".
1895 printf(_("caught signal\n"));
1898 else if (output_failed)
1900 printf(_("could not write to child process\n"));
1905 /* all seems well */
1912 * check if given string is a valid locale specifier
1913 * based on some code given to me by Peter Eisentraut
1914 * (but I take responsibility for it :-)
1917 chklocale(const char *locale)
1920 int category = LC_CTYPE;
1923 save = setlocale(category, NULL);
1925 return false; /* should not happen; */
1927 save = xstrdup(save);
1929 ret = (setlocale(category, locale) != NULL);
1931 setlocale(category, save);
1934 /* should we exit here? */
1936 fprintf(stderr, _("%s: invalid locale name \"%s\"\n"), progname, locale);
1942 * set up the locale variables
1944 * assumes we have called setlocale(LC_ALL,"")
1949 /* set empty lc_* values to locale config if set */
1951 if (strlen(locale) > 0)
1953 if (strlen(lc_ctype) == 0)
1955 if (strlen(lc_collate) == 0)
1956 lc_collate = locale;
1957 if (strlen(lc_numeric) == 0)
1958 lc_numeric = locale;
1959 if (strlen(lc_time) == 0)
1961 if (strlen(lc_monetary) == 0)
1962 lc_monetary = locale;
1963 if (strlen(lc_messages) == 0)
1964 lc_messages = locale;
1968 * override absent/invalid config settings from initdb's locale
1972 if (strlen(lc_ctype) == 0 || !chklocale(lc_ctype))
1973 lc_ctype = xstrdup(setlocale(LC_CTYPE, NULL));
1974 if (strlen(lc_collate) == 0 || !chklocale(lc_collate))
1975 lc_collate = xstrdup(setlocale(LC_COLLATE, NULL));
1976 if (strlen(lc_numeric) == 0 || !chklocale(lc_numeric))
1977 lc_numeric = xstrdup(setlocale(LC_NUMERIC, NULL));
1978 if (strlen(lc_time) == 0 || !chklocale(lc_time))
1979 lc_time = xstrdup(setlocale(LC_TIME, NULL));
1980 if (strlen(lc_monetary) == 0 || !chklocale(lc_monetary))
1981 lc_monetary = xstrdup(setlocale(LC_MONETARY, NULL));
1982 if (strlen(lc_messages) == 0 || !chklocale(lc_messages))
1985 /* when available get the current locale setting */
1986 lc_messages = xstrdup(setlocale(LC_MESSAGES, NULL));
1990 /* when not available, get the CTYPE setting */
1991 lc_messages = xstrdup(setlocale(LC_CTYPE, NULL));
2001 usage(const char *progname)
2003 printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2004 printf(_("Usage:\n"));
2005 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2006 printf(_("\nOptions:\n"));
2007 printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2008 printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2009 printf(_(" --locale=LOCALE initialize database cluster with given locale\n"));
2010 printf(_(" --lc-collate, --lc-ctype, --lc-messages=LOCALE\n"
2011 " --lc-monetary, --lc-numeric, --lc-time=LOCALE\n"
2012 " initialize database cluster with given locale\n"
2013 " in the respective category (default taken from\n"
2014 " environment)\n"));
2015 printf(_(" --no-locale equivalent to --locale=C\n"));
2016 printf(_(" -U, --username=NAME database superuser name\n"));
2017 printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2018 printf(_(" -?, --help show this help, then exit\n"));
2019 printf(_(" -V, --version output version information, then exit\n"));
2020 printf(_("\nLess commonly used options:\n"));
2021 printf(_(" -d, --debug generate lots of debugging output\n"));
2022 printf(_(" -s, --show show internal settings\n"));
2023 printf(_(" -L DIRECTORY where to find the input files\n"));
2024 printf(_(" -n, --noclean do not clean up after errors\n"));
2025 printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2027 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2031 * Initialized NLS if enabled.
2037 setlocale(LC_ALL, "");
2038 bindtextdomain("initdb", LOCALEDIR);
2039 textdomain("initdb");
2045 main(int argc, char *argv[])
2048 * options with no short version return a low integer, the rest return
2049 * their short version value
2051 static struct option long_options[] = {
2052 {"pgdata", required_argument, NULL, 'D'},
2053 {"encoding", required_argument, NULL, 'E'},
2054 {"locale", required_argument, NULL, 1},
2055 {"lc-collate", required_argument, NULL, 2},
2056 {"lc-ctype", required_argument, NULL, 3},
2057 {"lc-monetary", required_argument, NULL, 4},
2058 {"lc-numeric", required_argument, NULL, 5},
2059 {"lc-time", required_argument, NULL, 6},
2060 {"lc-messages", required_argument, NULL, 7},
2061 {"no-locale", no_argument, NULL, 8},
2062 {"pwprompt", no_argument, NULL, 'W'},
2063 {"username", required_argument, NULL, 'U'},
2064 {"help", no_argument, NULL, '?'},
2065 {"version", no_argument, NULL, 'V'},
2066 {"debug", no_argument, NULL, 'd'},
2067 {"show", no_argument, NULL, 's'},
2068 {"noclean", no_argument, NULL, 'n'},
2075 char *short_version;
2076 char *pgdenv; /* PGDATA value got from sent to
2079 {"global", "pg_xlog", "pg_clog", "base", "base/1"};
2082 #if defined(__CYGWIN__) || defined(WIN32)
2083 char *exe; /* location of exe suffix in progname */
2088 /* parse argv[0] - detect explicit path if there was one */
2089 carg0 = xstrdup(argv[0]);
2090 canonicalize_path(carg0);
2092 lastsep = strrchr(carg0, '/');
2093 progname = lastsep ? xstrdup(lastsep + 1) : carg0;
2095 #if defined(__CYGWIN__) || defined(WIN32)
2096 if (strlen(progname) > 4 &&
2097 (exe = progname + (strlen(progname) - 4)) &&
2098 stricmp(exe, EXE) == 0)
2100 /* strip .exe suffix, regardless of case */
2112 /* no path known to ourselves from argv[0] */
2118 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2123 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2125 puts("initdb (PostgreSQL) " PG_VERSION);
2130 /* process command-line options */
2132 while ((c = getopt_long(argc, argv, "dD:E:L:nU:W", long_options, &option_index)) != -1)
2137 pg_data = xstrdup(optarg);
2140 encoding = xstrdup(optarg);
2146 username = xstrdup(optarg);
2150 printf(_("Running in debug mode.\n"));
2154 printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
2157 datadir = xstrdup(optarg);
2160 locale = xstrdup(optarg);
2163 lc_collate = xstrdup(optarg);
2166 lc_ctype = xstrdup(optarg);
2169 lc_monetary = xstrdup(optarg);
2172 lc_numeric = xstrdup(optarg);
2175 lc_time = xstrdup(optarg);
2178 lc_messages = xstrdup(optarg);
2184 show_setting = true;
2187 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2193 /* Non-option argument specifies data directory */
2196 pg_data = xstrdup(argv[optind]);
2202 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
2203 progname, argv[optind + 1]);
2204 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2208 if (strlen(pg_data) == 0)
2210 pgdenv = getenv("PGDATA");
2211 if (pgdenv && strlen(pgdenv))
2214 pg_data = xstrdup(pgdenv);
2219 _("%s: no data directory specified\n"
2220 "You must identify the directory where the data for this database system\n"
2221 "will reside. Do this with either the invocation option -D or the\n"
2222 "environment variable PGDATA.\n"),
2228 canonicalize_path(pg_data);
2231 * we have to set PGDATA for postgres rather than pass it on the
2232 * commnd line to avoid dumb quoting problems on Windows, and we would
2233 * expecially need quotes otherwise on Windows because paths there are
2234 * most likely to have embedded spaces.
2236 pgdenv = xmalloc(8 + strlen(pg_data));
2237 sprintf(pgdenv, "PGDATA=%s", pg_data);
2240 if (set_paths() != 0)
2243 _("The program \"postgres\" is needed by %s "
2244 "but was not found in \n"
2245 "the directory \"%s\". Check your installation.\n"),
2250 if ((short_version = get_short_version()) == NULL)
2252 fprintf(stderr, _("%s: could not determine valid short version string\n"), progname);
2256 effective_user = get_id();
2257 if (!strlen(username))
2258 username = effective_user;
2260 if (strlen(encoding))
2261 encodingid = get_encoding_id(encoding);
2263 set_input(&bki_file, "postgres.bki");
2264 set_input(&desc_file, "postgres.description");
2265 set_input(&hba_file, "pg_hba.conf.sample");
2266 set_input(&ident_file, "pg_ident.conf.sample");
2267 set_input(&conf_file, "postgresql.conf.sample");
2268 set_input(&conversion_file, "conversion_create.sql");
2269 set_input(&info_schema_file, "information_schema.sql");
2270 set_input(&features_file, "sql_features.txt");
2271 set_input(&system_views_file, "system_views.sql");
2275 if (show_setting || debug)
2279 "PGDATA=%s\ndatadir=%s\nPGPATH=%s\n"
2280 "ENCODING=%s\nENCODINGID=%s\n"
2281 "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2282 "POSTGRES_DESCR=%s\nPOSTGRESQL_CONF_SAMPLE=%s\n"
2283 "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2285 pg_data, datadir, pgpath,
2286 encoding, encodingid,
2288 desc_file, conf_file,
2289 hba_file, ident_file);
2294 check_input(bki_file);
2295 check_input(desc_file);
2296 check_input(hba_file);
2297 check_input(ident_file);
2298 check_input(conf_file);
2299 check_input(conversion_file);
2300 check_input(info_schema_file);
2301 check_input(features_file);
2302 check_input(system_views_file);
2304 printf(_("The files belonging to this database system will be owned "
2306 "This user must also own the server process.\n\n"),
2311 if (strcmp(lc_ctype, lc_collate) == 0 &&
2312 strcmp(lc_ctype, lc_time) == 0 &&
2313 strcmp(lc_ctype, lc_numeric) == 0 &&
2314 strcmp(lc_ctype, lc_monetary) == 0 &&
2315 strcmp(lc_ctype, lc_messages) == 0)
2317 printf(_("The database cluster will be initialized with locale %s.\n\n"),
2322 printf(_("The database cluster will be initialized with locales\n"
2340 * now we are starting to do real work, trap signals so we can clean
2344 /* some of these are not valid on Windows */
2346 pqsignal(SIGHUP, trapsig);
2349 pqsignal(SIGINT, trapsig);
2352 pqsignal(SIGQUIT, trapsig);
2355 pqsignal(SIGTERM, trapsig);
2358 /* Ignore SIGPIPE when writing to backend, so we can clean up */
2360 pqsignal(SIGPIPE, SIG_IGN);
2363 switch (check_data_dir())
2366 /* PGDATA not there, must create it */
2367 printf(_("creating directory %s ... "),
2371 if (!mkdatadir(NULL))
2376 made_new_pgdata = true;
2380 /* Present but empty, fix permissions and use it */
2381 printf(_("fixing permissions on existing directory %s ... "),
2385 if (chmod(pg_data, 0700) != 0)
2393 found_existing_pgdata = true;
2397 /* Present and not empty */
2399 _("%s: directory \"%s\" exists but is not empty\n"
2400 "If you want to create a new database system, either remove or empty\n"
2401 "the directory \"%s\" or run %s\n"
2402 "with an argument other than \"%s\".\n"),
2403 progname, pg_data, pg_data, progname, pg_data);
2404 exit(1); /* no further message needed */
2407 /* Trouble accessing directory */
2412 /* Create required subdirectories */
2414 for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
2416 printf(_("creating directory %s/%s ... "), pg_data, subdirs[i]);
2419 if (!mkdatadir(subdirs[i]))
2425 /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2426 set_short_version(short_version, NULL);
2429 * Determine platform-specific config settings
2431 * Use reasonable values if kernel will let us, else scale back. Probe for
2432 * max_connections first since it is subject to more constraints than
2441 /* Now create all the text config files */
2444 /* Bootstrap template1 */
2445 bootstrap_template1(short_version);
2447 /* Make the per-database PGVERSION for template1 only after init'ing it */
2448 set_short_version(short_version, "base/1");
2450 /* Create the stuff we don't need to use bootstrap mode for */
2456 unlimit_systables();
2462 setup_description();
2474 printf(_("\nSuccess. You can now start the database server using:\n\n"
2475 " %s%s%s/postmaster -D %s%s%s\n"
2477 " %s%s%s/pg_ctl -D %s%s%s -l logfile start\n\n"),
2478 QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH,
2479 QUOTE_PATH, pgpath, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH);