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.
29 * The program has some memory leakage - it isn't worth cleaning it up.
32 * This is a C implementation of the previous shell script for setting up a
33 * PostgreSQL cluster location, and should be highly compatible with it.
34 * author of C translation: Andrew Dunstan mailto:andrew@dunslane.net
36 * This code is released under the terms of the PostgreSQL License.
38 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
39 * Portions Copyright (c) 1994, Regents of the University of California
40 * Portions taken from FreeBSD.
42 * $PostgreSQL: pgsql/src/bin/initdb/initdb.c,v 1.44 2004/07/19 02:47:12 tgl Exp $
44 *-------------------------------------------------------------------------
47 #include "postgres_fe.h"
55 #ifdef HAVE_LANGINFO_H
56 # include <langinfo.h>
59 #include "libpq/pqsignal.h"
60 #include "mb/pg_wchar.h"
61 #include "getopt_long.h"
68 #define _(x) gettext((x))
70 /* version string we expect back from postgres */
71 #define PG_VERSIONSTR "postgres (PostgreSQL) " PG_VERSION "\n"
74 * these values are passed in by makefile defines
76 char *share_path = NULL;
78 /* values to be obtained from arguments */
82 char *lc_collate = "";
84 char *lc_monetary = "";
85 char *lc_numeric = "";
87 char *lc_messages = "";
89 bool pwprompt = false;
90 char *pwfilename = NULL;
93 bool show_setting = false;
99 char *encodingid = "0";
105 char *conversion_file;
106 char *info_schema_file;
108 char *system_views_file;
109 char *effective_user;
110 bool testpath = true;
111 bool made_new_pgdata = false;
112 bool found_existing_pgdata = false;
113 char infoversion[100];
114 bool caught_signal = false;
115 bool output_failed = false;
118 int n_connections = 10;
122 * Centralized knowledge of switches to pass to backend
124 * Note: in the shell-script version, we also passed PGDATA as a -D switch,
125 * but here it is more convenient to pass it as an environment variable
126 * (no quoting to worry about).
128 static const char *boot_options = "-F";
129 static const char *backend_options = "-F -O -c search_path=pg_catalog -c exit_on_error=true";
132 /* path to 'initdb' binary directory */
133 char bin_path[MAXPGPATH];
134 char backend_exec[MAXPGPATH];
136 static void *xmalloc(size_t size);
137 static char *xstrdup(const char *s);
138 static bool rmtree(char *path, bool rmtopdir);
139 static char **replace_token(char **lines, char *token, char *replacement);
140 static char **readfile(char *path);
141 static void writefile(char *path, char **lines);
142 static int mkdir_p(char *path, mode_t omode);
143 static void exit_nicely(void);
144 static char *get_id(void);
145 static char *get_encoding_id(char *encoding_name);
146 static char *get_short_version(void);
147 static int check_data_dir(void);
148 static bool mkdatadir(const char *subdir);
149 static void set_input(char **dest, char *filename);
150 static void check_input(char *path);
151 static void set_short_version(char *short_version, char *extrapath);
152 static void set_null_conf(void);
153 static void test_connections(void);
154 static void test_buffers(void);
155 static void setup_config(void);
156 static void bootstrap_template1(char *short_version);
157 static void setup_shadow(void);
158 static void get_set_pwd(void);
159 static void unlimit_systables(void);
160 static void setup_depend(void);
161 static void setup_sysviews(void);
162 static void setup_description(void);
163 static void setup_conversion(void);
164 static void setup_privileges(void);
165 static void set_info_version(void);
166 static void setup_schema(void);
167 static void vacuum_db(void);
168 static void make_template0(void);
169 static void trapsig(int signum);
170 static void check_ok(void);
171 static bool chklocale(const char *locale);
172 static void setlocales(void);
173 static void usage(const char *progname);
177 * macros for running pipes to postgres
179 #define PG_CMD_DECL char cmd[MAXPGPATH]; char ** line ; FILE * pg
180 #define PG_CMD_DECL_NOLINE char cmd[MAXPGPATH]; FILE * pg
182 #define PG_CMD_OPEN \
186 pg = popen(cmd, "w"); \
191 #define PG_CMD_CLOSE \
193 if (pclose_check(pg)) \
197 #define PG_CMD_PUTLINE \
199 if (fputs(*line, pg) < 0 || fflush(pg) < 0) \
200 output_failed = true; \
204 #define QUOTE_PATH ""
206 #define QUOTE_PATH "\""
210 * routines to check mem allocations and fail noisily.
212 * Note that we can't call exit_nicely() on a memory failure, as it calls
213 * rmtree() which needs memory allocation. So we just exit with a bang.
220 result = malloc(size);
223 fprintf(stderr, _("%s: out of memory\n"), progname);
230 xstrdup(const char *s)
237 fprintf(stderr, _("%s: out of memory\n"), progname);
244 * delete a directory tree recursively
245 * assumes path points to a valid directory
246 * deletes everything under path
247 * if rmtopdir is true deletes the directory too
250 rmtree(char *path, bool rmtopdir)
252 char buf[MAXPGPATH + 64];
255 /* doesn't handle .* files, but we don't make any... */
256 snprintf(buf, sizeof(buf), "rm -rf \"%s\"%s", path,
257 rmtopdir ? "" : "/*");
259 snprintf(buf, sizeof(buf), "%s /s /q \"%s\"",
260 rmtopdir ? "rmdir" : "del", path);
268 * make a copy of the array of lines, with token replaced by replacement
269 * the first time it occurs on each line.
271 * This does most of what sed was used for in the shell script, but
272 * doesn't need any regexp stuff.
275 replace_token(char **lines, char *token, char *replacement)
284 for (i = 0; lines[i]; i++)
287 result = (char **) xmalloc(numlines * sizeof(char *));
289 toklen = strlen(token);
290 replen = strlen(replacement);
291 diff = replen - toklen;
293 for (i = 0; i < numlines; i++)
299 /* just copy pointer if NULL or no change needed */
301 if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
303 result[i] = lines[i];
307 /* if we get here a change is needed - set up new line */
309 newline = (char *) xmalloc(strlen(lines[i]) + diff + 1);
311 pre = where - lines[i];
313 strncpy(newline, lines[i], pre);
315 strcpy(newline + pre, replacement);
317 strcpy(newline + pre + replen, lines[i] + pre + toklen);
328 * get the lines from a text file
341 if ((infile = fopen(path, "r")) == NULL)
343 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
344 progname, path, strerror(errno));
348 /* pass over the file twice - the first time to size the result */
350 while ((c = fgetc(infile)) != EOF)
356 if (linelen > maxlength)
362 /* handle last line without a terminating newline (yuck) */
366 if (linelen > maxlength)
369 /* set up the result and the line buffer */
371 result = (char **) xmalloc((nlines + 2) * sizeof(char *));
372 buffer = (char *) xmalloc(maxlength + 2);
374 /* now reprocess the file and store the lines */
378 while (fgets(buffer, maxlength + 1, infile) != NULL)
380 result[nlines] = xstrdup(buffer);
385 result[nlines] = NULL;
391 * write an array of lines to a file
394 writefile(char *path, char **lines)
399 if ((out_file = fopen(path, PG_BINARY_W)) == NULL)
401 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
402 progname, path, strerror(errno));
405 for (line = lines; *line != NULL; line++)
407 if (fputs(*line, out_file) < 0)
411 if (fclose(out_file))
415 /* source stolen from FreeBSD /src/bin/mkdir/mkdir.c and adapted */
418 * this tries to build all the elements of a path to a directory a la mkdir -p
419 * we assume the path is in canonical form, i.e. uses / as the separator
420 * we also assume it isn't null.
423 mkdir_p(char *path, mode_t omode)
438 /* skip network and drive specifiers for win32 */
441 if (p[0] == '/' && p[1] == '/')
444 p = strstr(p + 2, "/");
448 else if (p[1] == ':' &&
449 ((p[0] >= 'a' && p[0] <= 'z') ||
450 (p[0] >= 'A' && p[0] <= 'Z')))
458 if (p[0] == '/') /* Skip leading '/'. */
460 for (first = 1, last = 0; !last; ++p)
464 else if (p[0] != '/')
467 if (!last && p[1] == '\0')
472 * POSIX 1003.2: For each dir operand that does not name an
473 * existing directory, effects equivalent to those cased by
474 * the following command shall occcur:
476 * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode]
479 * We change the user's umask and then restore it, instead of
483 numask = oumask & ~(S_IWUSR | S_IXUSR);
484 (void) umask(numask);
488 (void) umask(oumask);
489 if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
491 if (errno == EEXIST || errno == EISDIR)
493 if (stat(path, &sb) < 0)
498 else if (!S_ISDIR(sb.st_mode))
518 (void) umask(oumask);
523 * clean up any files we created on failure
524 * if we created the data directory remove it too
529 fprintf(stderr, _("%s: failed\n"), progname);
535 fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
537 if (!rmtree(pg_data, true))
538 fprintf(stderr, _("%s: failed\n"), progname);
540 else if (found_existing_pgdata)
543 _("%s: removing contents of data directory \"%s\"\n"),
545 if (!rmtree(pg_data, false))
546 fprintf(stderr, _("%s: failed\n"), progname);
548 /* otherwise died during startup, do nothing! */
552 if (made_new_pgdata || found_existing_pgdata)
554 _("%s: data directory \"%s\" not removed at user's request\n"),
562 * find the current user
564 * on unix make sure it isn't really root
573 pw = getpwuid(getuid());
575 #ifndef __BEOS__ /* no root check on BEOS */
577 if (!geteuid()) /* 0 is root's uid */
580 _("%s: cannot be run as root\n"
581 "Please log in (using, e.g., \"su\") as the "
582 "(unprivileged) user that will\n"
583 "own the server process.\n"),
589 #else /* the windows code */
596 struct passwd_win32 *pw = &pass_win32;
597 DWORD pwname_size = sizeof(pass_win32.pw_name) - 1;
600 GetUserName(pw->pw_name, &pwname_size);
603 return xstrdup(pw->pw_name);
607 encodingid_to_string(int enc)
611 sprintf(result, "%d", enc);
612 return xstrdup(result);
616 * get the encoding id for a given encoding name
619 get_encoding_id(char *encoding_name)
623 if (encoding_name && *encoding_name)
625 if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
626 pg_valid_server_encoding(encoding_name) >= 0)
628 return encodingid_to_string(enc);
631 fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
632 progname, encoding_name ? encoding_name : "(null)");
636 #ifdef HAVE_LANGINFO_H
638 * Checks whether the encoding selected for PostgreSQL and the
639 * encoding used by the system locale match.
642 struct encoding_match
644 enum pg_enc pg_enc_code;
645 char *system_enc_name;
648 struct encoding_match encoding_match_list[] = {
649 { PG_EUC_JP, "EUC-JP" },
650 { PG_EUC_JP, "eucJP" },
651 { PG_EUC_JP, "IBM-eucJP" },
652 { PG_EUC_JP, "sdeckanji" },
654 { PG_EUC_CN, "EUC-CN" },
655 { PG_EUC_CN, "eucCN" },
656 { PG_EUC_CN, "IBM-eucCN" },
657 { PG_EUC_CN, "GB2312" },
658 { PG_EUC_CN, "dechanzi" },
660 { PG_EUC_KR, "EUC-KR" },
661 { PG_EUC_KR, "eucKR" },
662 { PG_EUC_KR, "IBM-eucKR" },
663 { PG_EUC_KR, "deckorean" },
664 { PG_EUC_KR, "5601" },
666 { PG_EUC_TW, "EUC-TW" },
667 { PG_EUC_TW, "eucTW" },
668 { PG_EUC_TW, "IBM-eucTW" },
669 { PG_EUC_TW, "cns11643" },
675 { PG_UTF8, "UTF-8" },
678 { PG_LATIN1, "ISO-8859-1" },
679 { PG_LATIN1, "ISO8859-1" },
680 { PG_LATIN1, "iso88591" },
682 { PG_LATIN2, "ISO-8859-2" },
683 { PG_LATIN2, "ISO8859-2" },
684 { PG_LATIN2, "iso88592" },
686 { PG_LATIN3, "ISO-8859-3" },
687 { PG_LATIN3, "ISO8859-3" },
688 { PG_LATIN3, "iso88593" },
690 { PG_LATIN4, "ISO-8859-4" },
691 { PG_LATIN4, "ISO8859-4" },
692 { PG_LATIN4, "iso88594" },
694 { PG_LATIN5, "ISO-8859-9" },
695 { PG_LATIN5, "ISO8859-9" },
696 { PG_LATIN5, "iso88599" },
698 { PG_LATIN6, "ISO-8859-10" },
699 { PG_LATIN6, "ISO8859-10" },
700 { PG_LATIN6, "iso885910" },
702 { PG_LATIN7, "ISO-8859-13" },
703 { PG_LATIN7, "ISO8859-13" },
704 { PG_LATIN7, "iso885913" },
706 { PG_LATIN8, "ISO-8859-14" },
707 { PG_LATIN8, "ISO8859-14" },
708 { PG_LATIN8, "iso885914" },
710 { PG_LATIN9, "ISO-8859-15" },
711 { PG_LATIN9, "ISO8859-15" },
712 { PG_LATIN9, "iso885915" },
714 { PG_LATIN10, "ISO-8859-16" },
715 { PG_LATIN10, "ISO8859-16" },
716 { PG_LATIN10, "iso885916" },
718 { PG_WIN1256, "CP1256" },
719 { PG_TCVN, "CP1258" },
721 { PG_WIN874, "???" },
723 { PG_KOI8R, "KOI8-R" },
724 { PG_WIN1251, "CP1251" },
727 { PG_ISO_8859_5, "ISO-8859-5" },
728 { PG_ISO_8859_5, "ISO8859-5" },
729 { PG_ISO_8859_5, "iso88595" },
731 { PG_ISO_8859_6, "ISO-8859-6" },
732 { PG_ISO_8859_6, "ISO8859-6" },
733 { PG_ISO_8859_6, "iso88596" },
735 { PG_ISO_8859_7, "ISO-8859-7" },
736 { PG_ISO_8859_7, "ISO8859-7" },
737 { PG_ISO_8859_7, "iso88597" },
739 { PG_ISO_8859_8, "ISO-8859-8" },
740 { PG_ISO_8859_8, "ISO8859-8" },
741 { PG_ISO_8859_8, "iso88598" },
743 { PG_SQL_ASCII, NULL } /* end marker */
747 get_encoding_from_locale(const char *ctype)
752 save = setlocale(LC_CTYPE, NULL);
755 save = xstrdup(save);
757 setlocale(LC_CTYPE, ctype);
758 sys = nl_langinfo(CODESET);
761 setlocale(LC_CTYPE, save);
768 check_encodings_match(int pg_enc, const char *ctype)
773 sys = get_encoding_from_locale(ctype);
775 for (i = 0; encoding_match_list[i].system_enc_name; i++)
777 if (pg_enc == encoding_match_list[i].pg_enc_code
778 && strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
786 _("%s: warning: encoding mismatch\n"), progname);
788 _("The encoding you selected (%s) and the encoding that the selected\n"
789 "locale uses (%s) are not known to match. This may lead to\n"
790 "misbehavior in various character string processing functions. To fix\n"
791 "this situation, rerun %s and either do not specify an encoding\n"
792 "explicitly, or choose a matching combination.\n"),
793 pg_encoding_to_char(pg_enc), sys, progname);
800 find_matching_encoding(const char *ctype)
805 sys = get_encoding_from_locale(ctype);
807 for (i = 0; encoding_match_list[i].system_enc_name; i++)
809 if (strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
812 return encoding_match_list[i].pg_enc_code;
819 #endif /* HAVE_LANGINFO_H */
822 * get short version of VERSION
825 get_short_version(void)
831 vr = xstrdup(PG_VERSION);
833 for (end = 0; vr[end] != '\0'; end++)
844 else if (vr[end] < '0' || vr[end] > '9')
846 /* gone past digits and dots */
850 if (end == 0 || vr[end - 1] == '.' || !gotdot)
858 * make sure the data directory either doesn't exist or is empty
860 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
861 * or -1 if trouble accessing directory
872 chkdir = opendir(pg_data);
875 return (errno == ENOENT) ? 0 : -1;
877 while ((file = readdir(chkdir)) != NULL)
879 if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
881 /* skip this and parent directory */
886 result = 2; /* not empty */
894 result = -1; /* some kind of I/O error? */
900 * make the data directory (or one of its subdirectories if subdir is not NULL)
903 mkdatadir(const char *subdir)
907 path = xmalloc(strlen(pg_data) + 2 +
908 (subdir == NULL ? 0 : strlen(subdir)));
911 sprintf(path, "%s/%s", pg_data, subdir);
913 strcpy(path, pg_data);
915 return (mkdir_p(path, 0700) == 0);
920 * set name of given input file variable under data directory
923 set_input(char **dest, char *filename)
925 *dest = xmalloc(strlen(share_path) + strlen(filename) + 2);
926 sprintf(*dest, "%s/%s", share_path, filename);
930 * check that given input file exists
933 check_input(char *path)
937 if (stat(path, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
940 _("%s: file \"%s\" does not exist\n"
941 "This means you have a corrupted installation or identified\n"
942 "the wrong directory with the invocation option -L.\n"),
950 * write out the PG_VERSION file in the data dir, or its subdirectory
951 * if extrapath is not NULL
954 set_short_version(char *short_version, char *extrapath)
959 if (extrapath == NULL)
961 path = xmalloc(strlen(pg_data) + 12);
962 sprintf(path, "%s/PG_VERSION", pg_data);
966 path = xmalloc(strlen(pg_data) + strlen(extrapath) + 13);
967 sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
969 version_file = fopen(path, PG_BINARY_W);
970 if (version_file == NULL)
972 fprintf(version_file, "%s\n", short_version);
973 if (fclose(version_file))
978 * set up an empty config file so we can check buffers and connections
986 path = xmalloc(strlen(pg_data) + 17);
987 sprintf(path, "%s/postgresql.conf", pg_data);
988 conf_file = fopen(path, PG_BINARY_W);
989 if (conf_file == NULL || fclose(conf_file))
994 * check how many connections we can sustain
997 test_connections(void)
1000 static const int conns[] = {100, 50, 40, 30, 20, 10};
1001 static const int len = sizeof(conns) / sizeof(int);
1005 printf(_("selecting default max_connections ... "));
1008 for (i = 0; i < len; i++)
1010 snprintf(cmd, sizeof(cmd),
1011 "%s\"%s\" -boot -x0 %s "
1012 "-c shared_buffers=%d -c max_connections=%d template1 "
1013 "< \"%s\" > \"%s\" 2>&1%s",
1014 SYSTEMQUOTE, backend_exec, boot_options,
1015 conns[i] * 5, conns[i],
1016 DEVNULL, DEVNULL, SYSTEMQUOTE);
1017 status = system(cmd);
1023 n_connections = conns[i];
1025 printf("%d\n", n_connections);
1029 * check how many buffers we can run with
1034 char cmd[MAXPGPATH];
1035 static const int bufs[] = {1000, 900, 800, 700, 600, 500,
1036 400, 300, 200, 100, 50};
1037 static const int len = sizeof(bufs) / sizeof(int);
1041 printf(_("selecting default shared_buffers ... "));
1044 for (i = 0; i < len; i++)
1046 snprintf(cmd, sizeof(cmd),
1047 "%s\"%s\" -boot -x0 %s "
1048 "-c shared_buffers=%d -c max_connections=%d template1 "
1049 "< \"%s\" > \"%s\" 2>&1%s",
1050 SYSTEMQUOTE, backend_exec, boot_options,
1051 bufs[i], n_connections,
1052 DEVNULL, DEVNULL, SYSTEMQUOTE);
1053 status = system(cmd);
1059 n_buffers = bufs[i];
1061 printf("%d\n", n_buffers);
1065 * set up all the config files
1072 char path[MAXPGPATH];
1074 fputs(_("creating configuration files ... "), stdout);
1077 /* postgresql.conf */
1079 conflines = readfile(conf_file);
1081 snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1082 conflines = replace_token(conflines, "#max_connections = 100", repltok);
1084 snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
1085 conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);
1087 snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
1088 conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1090 snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
1091 conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1093 snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);
1095 conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1097 snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
1098 conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1100 snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1102 writefile(path, conflines);
1110 conflines = readfile(hba_file);
1113 conflines = replace_token(conflines,
1115 "#host all all ::1");
1118 snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1120 writefile(path, conflines);
1127 conflines = readfile(ident_file);
1129 snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1131 writefile(path, conflines);
1141 * run the BKI script in bootstrap mode to create template1
1144 bootstrap_template1(char *short_version)
1146 char *talkargs = "";
1148 char headerline[MAXPGPATH];
1152 printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1158 bki_lines = readfile(bki_file);
1160 /* Check that bki file appears to be of the right version */
1162 snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1165 if (strcmp(headerline, *bki_lines) != 0)
1168 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1169 "Check your installation or specify the correct path "
1170 "using the option -L.\n"),
1171 progname, bki_file, PG_VERSION);
1176 bki_lines = replace_token(bki_lines, "POSTGRES", effective_user);
1178 bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1181 * Pass correct LC_xxx environment to bootstrap.
1183 * The shell script arranged to restore the LC settings afterwards,
1184 * but there doesn't seem to be any compelling reason to do that.
1186 snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1187 putenv(xstrdup(cmd));
1189 snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1190 putenv(xstrdup(cmd));
1194 /* Also ensure backend isn't confused by this environment var: */
1195 unsetenv("PGCLIENTENCODING");
1197 snprintf(cmd, sizeof(cmd),
1198 "\"%s\" -boot -x1 %s %s template1",
1199 backend_exec, boot_options, talkargs);
1203 for (line = bki_lines; *line != NULL; line++)
1217 * set up the shadow password table
1222 char *pg_shadow_setup[] = {
1224 * Create a trigger so that direct updates to pg_shadow will be
1225 * written to the flat password/group files pg_pwd and pg_group
1227 "CREATE TRIGGER pg_sync_pg_pwd "
1228 " AFTER INSERT OR UPDATE OR DELETE ON pg_shadow "
1229 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1230 "CREATE TRIGGER pg_sync_pg_group "
1231 " AFTER INSERT OR UPDATE OR DELETE ON pg_group "
1232 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1235 * needs to be done before alter user, because alter user checks
1236 * that pg_shadow is secure ...
1238 "REVOKE ALL on pg_shadow FROM public;\n",
1244 fputs(_("initializing pg_shadow ... "), stdout);
1247 snprintf(cmd, sizeof(cmd),
1248 "\"%s\" %s template1 >%s",
1249 backend_exec, backend_options,
1254 for (line = pg_shadow_setup; *line != NULL; line++)
1263 * get the superuser password if required, and call postgres to set it
1272 char pwdpath[MAXPGPATH];
1273 struct stat statbuf;
1278 * Read password from terminal
1280 pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1281 pwd2 = simple_prompt("Enter it again: ", 100, false);
1282 if (strcmp(pwd1, pwd2) != 0)
1284 fprintf(stderr, _("Passwords didn't match.\n"));
1292 * Read password from file
1294 * Ideally this should insist that the file not be world-readable.
1295 * However, this option is mainly intended for use on Windows where
1296 * file permissions may not exist at all, so we'll skip the paranoia
1299 FILE *pwf = fopen(pwfilename,"r");
1300 char pwdbuf[MAXPGPATH];
1305 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1306 progname, pwfilename, strerror(errno));
1309 if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
1311 fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
1312 progname, pwfilename, strerror(errno));
1318 while (i > 0 && (pwdbuf[i-1] == '\r' || pwdbuf[i-1] == '\n'))
1321 pwd1 = xstrdup(pwdbuf);
1324 printf(_("setting password ... "));
1327 snprintf(cmd, sizeof(cmd),
1328 "\"%s\" %s template1 >%s",
1329 backend_exec, backend_options,
1335 "ALTER USER \"%s\" WITH PASSWORD '%s';\n", effective_user, pwd1) < 0)
1344 snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1345 if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1348 _("%s: The password file was not generated. "
1349 "Please report this problem.\n"),
1361 unlimit_systables(void)
1363 char *systables_setup[] = {
1364 "ALTER TABLE pg_attrdef CREATE TOAST TABLE;\n",
1365 "ALTER TABLE pg_constraint CREATE TOAST TABLE;\n",
1366 "ALTER TABLE pg_database CREATE TOAST TABLE;\n",
1367 "ALTER TABLE pg_description CREATE TOAST TABLE;\n",
1368 "ALTER TABLE pg_group CREATE TOAST TABLE;\n",
1369 "ALTER TABLE pg_proc CREATE TOAST TABLE;\n",
1370 "ALTER TABLE pg_rewrite CREATE TOAST TABLE;\n",
1371 "ALTER TABLE pg_shadow CREATE TOAST TABLE;\n",
1372 "ALTER TABLE pg_statistic CREATE TOAST TABLE;\n",
1378 fputs(_("enabling unlimited row size for system tables ... "), stdout);
1381 snprintf(cmd, sizeof(cmd),
1382 "\"%s\" %s template1 >%s",
1383 backend_exec, backend_options,
1388 for (line = systables_setup; *line != NULL; line++)
1402 char *pg_depend_setup[] = {
1404 * Make PIN entries in pg_depend for all objects made so far in
1405 * the tables that the dependency code handles. This is overkill
1406 * (the system doesn't really depend on having every last weird
1407 * datatype, for instance) but generating only the minimum
1408 * required set of dependencies seems hard.
1410 * Note that we deliberately do not pin the system views, which
1411 * haven't been created yet.
1413 * First delete any already-made entries; PINs override all else, and
1414 * must be the only entries for their objects.
1416 "DELETE FROM pg_depend;\n",
1417 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1418 " FROM pg_class;\n",
1419 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1421 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1423 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1425 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1426 " FROM pg_constraint;\n",
1427 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1428 " FROM pg_attrdef;\n",
1429 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1430 " FROM pg_language;\n",
1431 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1432 " FROM pg_operator;\n",
1433 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1434 " FROM pg_opclass;\n",
1435 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1436 " FROM pg_rewrite;\n",
1437 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1438 " FROM pg_trigger;\n",
1441 * restriction here to avoid pinning the public namespace
1443 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1444 " FROM pg_namespace "
1445 " WHERE nspname LIKE 'pg%';\n",
1451 fputs(_("initializing pg_depend ... "), stdout);
1454 snprintf(cmd, sizeof(cmd),
1455 "\"%s\" %s template1 >%s",
1456 backend_exec, backend_options,
1461 for (line = pg_depend_setup; *line != NULL; line++)
1470 * set up system views
1473 setup_sysviews(void)
1477 char **sysviews_setup;
1479 fputs(_("creating system views ... "), stdout);
1482 sysviews_setup = readfile(system_views_file);
1485 * We use -N here to avoid backslashing stuff in system_views.sql
1487 snprintf(cmd, sizeof(cmd),
1488 "\"%s\" %s -N template1 >%s",
1489 backend_exec, backend_options,
1494 for (line = sysviews_setup; *line != NULL; line++)
1502 free(sysviews_setup);
1508 * load description data
1511 setup_description(void)
1516 fputs(_("loading pg_description ... "), stdout);
1519 snprintf(cmd, sizeof(cmd),
1520 "\"%s\" %s template1 >%s",
1521 backend_exec, backend_options,
1527 "CREATE TEMP TABLE tmp_pg_description ( "
1531 " description text) WITHOUT OIDS;\n");
1536 "COPY tmp_pg_description FROM '%s';\n",
1542 "INSERT INTO pg_description "
1543 " SELECT t.objoid, c.oid, t.objsubid, t.description "
1544 " FROM tmp_pg_description t, pg_class c "
1545 " WHERE c.relname = t.classname;\n");
1555 * load conversion functions
1558 setup_conversion(void)
1564 fputs(_("creating conversions ... "), stdout);
1567 snprintf(cmd, sizeof(cmd),
1568 "\"%s\" %s template1 >%s",
1569 backend_exec, backend_options,
1574 conv_lines = readfile(conversion_file);
1575 for (line = conv_lines; *line != NULL; line++)
1577 if (strstr(*line, "DROP CONVERSION") != *line)
1593 * We set most system catalogs and built-in functions as world-accessible.
1594 * Some objects may require different permissions by default, so we
1595 * make sure we don't overwrite privilege sets that have already been
1599 setup_privileges(void)
1601 char *privileges_setup[] = {
1603 " SET relacl = '{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1604 " WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;\n",
1606 " SET proacl = '{\"=X/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1607 " WHERE proacl IS NULL;\n",
1608 "UPDATE pg_language "
1609 " SET lanacl = '{\"=U/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1610 " WHERE lanpltrusted;\n",
1611 "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
1612 "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
1620 fputs(_("setting privileges on built-in objects ... "), stdout);
1623 snprintf(cmd, sizeof(cmd),
1624 "\"%s\" %s template1 >%s",
1625 backend_exec, backend_options,
1630 priv_lines = replace_token(privileges_setup,
1631 "$POSTGRES_SUPERUSERNAME", effective_user);
1632 for (line = priv_lines; *line != NULL; line++)
1641 * extract the strange version of version required for information schema
1645 set_info_version(void)
1647 char *letterversion;
1652 char *vstr = xstrdup(PG_VERSION);
1655 ptr = vstr + (strlen(vstr) - 1);
1656 while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1658 letterversion = ptr + 1;
1659 major = strtol(vstr, &endptr, 10);
1661 minor = strtol(endptr + 1, &endptr, 10);
1663 micro = strtol(endptr + 1, &endptr, 10);
1664 snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1665 major, minor, micro, letterversion);
1669 * load info schema and populate from features file
1678 fputs(_("creating information schema ... "), stdout);
1681 lines = readfile(info_schema_file);
1684 * We use -N here to avoid backslashing stuff in information_schema.sql
1686 snprintf(cmd, sizeof(cmd),
1687 "\"%s\" %s -N template1 >%s",
1688 backend_exec, backend_options,
1693 for (line = lines; *line != NULL; line++)
1703 snprintf(cmd, sizeof(cmd),
1704 "\"%s\" %s template1 >%s",
1705 backend_exec, backend_options,
1711 "UPDATE information_schema.sql_implementation_info "
1712 " SET character_value = '%s' "
1713 " WHERE implementation_info_name = 'DBMS VERSION';\n",
1719 "COPY information_schema.sql_features "
1720 " (feature_id, feature_name, sub_feature_id, "
1721 " sub_feature_name, is_supported, comments) "
1733 * clean everything up in template1
1740 fputs(_("vacuuming database template1 ... "), stdout);
1743 snprintf(cmd, sizeof(cmd),
1744 "\"%s\" %s template1 >%s",
1745 backend_exec, backend_options,
1750 if (fputs("ANALYZE;\nVACUUM FULL FREEZE;\n", pg) < 0)
1760 * copy template1 to template0
1763 make_template0(void)
1765 char *template0_setup[] = {
1766 "CREATE DATABASE template0;\n",
1767 "UPDATE pg_database SET "
1768 " datistemplate = 't', "
1769 " datallowconn = 'f' "
1770 " WHERE datname = 'template0';\n",
1773 * We use the OID of template0 to determine lastsysoid
1775 "UPDATE pg_database SET datlastsysoid = "
1776 " (SELECT oid::int4 - 1 FROM pg_database "
1777 " WHERE datname = 'template0');\n",
1780 * Explicitly revoke public create-schema and create-temp-table
1781 * privileges in template1 and template0; else the latter would be
1784 "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
1785 "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
1788 * Finally vacuum to clean up dead rows in pg_database
1790 "VACUUM FULL pg_database;\n",
1796 fputs(_("copying template1 to template0 ... "), stdout);
1799 snprintf(cmd, sizeof(cmd),
1800 "\"%s\" %s template1 >%s",
1801 backend_exec, backend_options,
1806 for (line = template0_setup; *line; line++)
1816 * signal handler in case we are interrupted.
1818 * The Windows runtime docs at
1819 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
1820 * specifically forbid a number of things being done from a signal handler,
1821 * including IO, memory allocation and system calls, and only allow jmpbuf
1822 * if you are handling SIGFPE.
1824 * I avoided doing the forbidden things by setting a flag instead of calling
1825 * exit_nicely() directly.
1827 * Also note the behaviour of Windows with SIGINT, which says this:
1828 * Note SIGINT is not supported for any Win32 application, including
1829 * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
1830 * Win32 operating systems generate a new thread to specifically handle
1831 * that interrupt. This can cause a single-thread application such as UNIX,
1832 * to become multithreaded, resulting in unexpected behavior.
1834 * I have no idea how to handle this. (Strange they call UNIX an application!)
1835 * So this will need some testing on Windows.
1840 /* handle systems that reset the handler, like Windows (grr) */
1841 pqsignal(signum, trapsig);
1842 caught_signal = true;
1846 * call exit_nicely() if we got a signal, or else output "ok".
1853 printf(_("caught signal\n"));
1856 else if (output_failed)
1858 printf(_("could not write to child process\n"));
1863 /* all seems well */
1870 * check if given string is a valid locale specifier
1871 * based on some code given to me by Peter Eisentraut
1872 * (but I take responsibility for it :-)
1875 chklocale(const char *locale)
1878 int category = LC_CTYPE;
1881 save = setlocale(category, NULL);
1883 return false; /* should not happen; */
1885 save = xstrdup(save);
1887 ret = (setlocale(category, locale) != NULL);
1889 setlocale(category, save);
1892 /* should we exit here? */
1894 fprintf(stderr, _("%s: invalid locale name \"%s\"\n"), progname, locale);
1900 * set up the locale variables
1902 * assumes we have called setlocale(LC_ALL,"")
1907 /* set empty lc_* values to locale config if set */
1909 if (strlen(locale) > 0)
1911 if (strlen(lc_ctype) == 0)
1913 if (strlen(lc_collate) == 0)
1914 lc_collate = locale;
1915 if (strlen(lc_numeric) == 0)
1916 lc_numeric = locale;
1917 if (strlen(lc_time) == 0)
1919 if (strlen(lc_monetary) == 0)
1920 lc_monetary = locale;
1921 if (strlen(lc_messages) == 0)
1922 lc_messages = locale;
1926 * override absent/invalid config settings from initdb's locale
1930 if (strlen(lc_ctype) == 0 || !chklocale(lc_ctype))
1931 lc_ctype = xstrdup(setlocale(LC_CTYPE, NULL));
1932 if (strlen(lc_collate) == 0 || !chklocale(lc_collate))
1933 lc_collate = xstrdup(setlocale(LC_COLLATE, NULL));
1934 if (strlen(lc_numeric) == 0 || !chklocale(lc_numeric))
1935 lc_numeric = xstrdup(setlocale(LC_NUMERIC, NULL));
1936 if (strlen(lc_time) == 0 || !chklocale(lc_time))
1937 lc_time = xstrdup(setlocale(LC_TIME, NULL));
1938 if (strlen(lc_monetary) == 0 || !chklocale(lc_monetary))
1939 lc_monetary = xstrdup(setlocale(LC_MONETARY, NULL));
1940 if (strlen(lc_messages) == 0 || !chklocale(lc_messages))
1943 /* when available get the current locale setting */
1944 lc_messages = xstrdup(setlocale(LC_MESSAGES, NULL));
1948 /* when not available, get the CTYPE setting */
1949 lc_messages = xstrdup(setlocale(LC_CTYPE, NULL));
1959 usage(const char *progname)
1961 printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
1962 printf(_("Usage:\n"));
1963 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
1964 printf(_("\nOptions:\n"));
1965 printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
1966 printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
1967 printf(_(" --locale=LOCALE initialize database cluster with given locale\n"));
1968 printf(_(" --lc-collate, --lc-ctype, --lc-messages=LOCALE\n"
1969 " --lc-monetary, --lc-numeric, --lc-time=LOCALE\n"
1970 " initialize database cluster with given locale\n"
1971 " in the respective category (default taken from\n"
1972 " environment)\n"));
1973 printf(_(" --no-locale equivalent to --locale=C\n"));
1974 printf(_(" -U, --username=NAME database superuser name\n"));
1975 printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
1976 printf(_(" --pwfile=filename read password for the new superuser from file\n"));
1977 printf(_(" -?, --help show this help, then exit\n"));
1978 printf(_(" -V, --version output version information, then exit\n"));
1979 printf(_("\nLess commonly used options:\n"));
1980 printf(_(" -d, --debug generate lots of debugging output\n"));
1981 printf(_(" -s, --show show internal settings\n"));
1982 printf(_(" -L DIRECTORY where to find the input files\n"));
1983 printf(_(" -n, --noclean do not clean up after errors\n"));
1984 printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
1986 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1990 main(int argc, char *argv[])
1993 * options with no short version return a low integer, the rest return
1994 * their short version value
1996 static struct option long_options[] = {
1997 {"pgdata", required_argument, NULL, 'D'},
1998 {"encoding", required_argument, NULL, 'E'},
1999 {"locale", required_argument, NULL, 1},
2000 {"lc-collate", required_argument, NULL, 2},
2001 {"lc-ctype", required_argument, NULL, 3},
2002 {"lc-monetary", required_argument, NULL, 4},
2003 {"lc-numeric", required_argument, NULL, 5},
2004 {"lc-time", required_argument, NULL, 6},
2005 {"lc-messages", required_argument, NULL, 7},
2006 {"no-locale", no_argument, NULL, 8},
2007 {"pwprompt", no_argument, NULL, 'W'},
2008 {"pwfile", required_argument, NULL, 9},
2009 {"username", required_argument, NULL, 'U'},
2010 {"help", no_argument, NULL, '?'},
2011 {"version", no_argument, NULL, 'V'},
2012 {"debug", no_argument, NULL, 'd'},
2013 {"show", no_argument, NULL, 's'},
2014 {"noclean", no_argument, NULL, 'n'},
2022 char *short_version;
2023 char *pgdenv; /* PGDATA value got from sent to
2025 static const char *subdirs[] = {
2028 "pg_xlog/archive_status",
2036 progname = get_progname(argv[0]);
2037 set_pglocale_pgservice(argv[0], "initdb");
2041 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2046 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2048 puts("initdb (PostgreSQL) " PG_VERSION);
2053 /* process command-line options */
2055 while ((c = getopt_long(argc, argv, "dD:E:L:nU:W", long_options, &option_index)) != -1)
2060 pg_data = xstrdup(optarg);
2063 encoding = xstrdup(optarg);
2069 username = xstrdup(optarg);
2073 printf(_("Running in debug mode.\n"));
2077 printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
2080 share_path = xstrdup(optarg);
2083 locale = xstrdup(optarg);
2086 lc_collate = xstrdup(optarg);
2089 lc_ctype = xstrdup(optarg);
2092 lc_monetary = xstrdup(optarg);
2095 lc_numeric = xstrdup(optarg);
2098 lc_time = xstrdup(optarg);
2101 lc_messages = xstrdup(optarg);
2107 pwfilename = xstrdup(optarg);
2110 show_setting = true;
2113 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2119 /* Non-option argument specifies data directory */
2122 pg_data = xstrdup(argv[optind]);
2128 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
2129 progname, argv[optind + 1]);
2130 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2134 if (pwprompt && pwfilename)
2136 fprintf(stderr, _("%s: you cannot specify both password prompt and password file\n"), progname);
2140 if (strlen(pg_data) == 0)
2142 pgdenv = getenv("PGDATA");
2143 if (pgdenv && strlen(pgdenv))
2146 pg_data = xstrdup(pgdenv);
2151 _("%s: no data directory specified\n"
2152 "You must identify the directory where the data for this database system\n"
2153 "will reside. Do this with either the invocation option -D or the\n"
2154 "environment variable PGDATA.\n"),
2160 canonicalize_path(pg_data);
2163 * we have to set PGDATA for postgres rather than pass it on the
2164 * commnd line to avoid dumb quoting problems on Windows, and we would
2165 * expecially need quotes otherwise on Windows because paths there are
2166 * most likely to have embedded spaces.
2168 pgdenv = xmalloc(8 + strlen(pg_data));
2169 sprintf(pgdenv, "PGDATA=%s", pg_data);
2172 if ((ret = find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
2177 _("The program \"postgres\" is needed by %s "
2178 "but was not found in the same directory as \"%s\".\n"
2179 "Check your installation.\n"),
2180 progname, progname);
2183 _("The program \"postgres\" was found by %s "
2184 "but was not the same version as \"%s\".\n"
2185 "Check your installation.\n"),
2186 progname, progname);
2190 /* store binary directory */
2191 strcpy(bin_path, backend_exec);
2192 *last_dir_separator(bin_path) = '\0';
2196 share_path = xmalloc(MAXPGPATH);
2197 get_share_path(backend_exec, share_path);
2200 canonicalize_path(share_path);
2202 if ((short_version = get_short_version()) == NULL)
2204 fprintf(stderr, _("%s: could not determine valid short version string\n"), progname);
2208 if (strlen(username))
2209 effective_user = username;
2211 effective_user = get_id();
2213 if (strlen(encoding))
2214 encodingid = get_encoding_id(encoding);
2216 set_input(&bki_file, "postgres.bki");
2217 set_input(&desc_file, "postgres.description");
2218 set_input(&hba_file, "pg_hba.conf.sample");
2219 set_input(&ident_file, "pg_ident.conf.sample");
2220 set_input(&conf_file, "postgresql.conf.sample");
2221 set_input(&conversion_file, "conversion_create.sql");
2222 set_input(&info_schema_file, "information_schema.sql");
2223 set_input(&features_file, "sql_features.txt");
2224 set_input(&system_views_file, "system_views.sql");
2228 if (show_setting || debug)
2232 "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2233 "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2234 "POSTGRES_DESCR=%s\nPOSTGRESQL_CONF_SAMPLE=%s\n"
2235 "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2237 pg_data, share_path, bin_path,
2238 effective_user, bki_file,
2239 desc_file, conf_file,
2240 hba_file, ident_file);
2245 check_input(bki_file);
2246 check_input(desc_file);
2247 check_input(hba_file);
2248 check_input(ident_file);
2249 check_input(conf_file);
2250 check_input(conversion_file);
2251 check_input(info_schema_file);
2252 check_input(features_file);
2253 check_input(system_views_file);
2257 printf(_("The files belonging to this database system will be owned "
2259 "This user must also own the server process.\n\n"),
2262 if (strcmp(lc_ctype, lc_collate) == 0 &&
2263 strcmp(lc_ctype, lc_time) == 0 &&
2264 strcmp(lc_ctype, lc_numeric) == 0 &&
2265 strcmp(lc_ctype, lc_monetary) == 0 &&
2266 strcmp(lc_ctype, lc_messages) == 0)
2268 printf(_("The database cluster will be initialized with locale %s.\n"), lc_ctype);
2272 printf(_("The database cluster will be initialized with locales\n"
2287 #ifdef HAVE_LANGINFO_H
2288 if (strcmp(lc_ctype, "C") != 0 && strcmp(lc_ctype, "POSIX") != 0)
2290 if (strlen(encoding) == 0)
2293 tmp = find_matching_encoding(lc_ctype);
2296 fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"), progname, lc_ctype);
2297 fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2298 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
2303 encodingid = encodingid_to_string(tmp);
2304 printf(_("The default database encoding has accordingly been set to %s.\n"),
2305 pg_encoding_to_char(tmp));
2309 check_encodings_match(atoi(encodingid), lc_ctype);
2311 #endif /* HAVE_LANGINFO_H */
2318 * now we are starting to do real work, trap signals so we can clean
2322 /* some of these are not valid on Windows */
2324 pqsignal(SIGHUP, trapsig);
2327 pqsignal(SIGINT, trapsig);
2330 pqsignal(SIGQUIT, trapsig);
2333 pqsignal(SIGTERM, trapsig);
2336 /* Ignore SIGPIPE when writing to backend, so we can clean up */
2338 pqsignal(SIGPIPE, SIG_IGN);
2341 switch (check_data_dir())
2344 /* PGDATA not there, must create it */
2345 printf(_("creating directory %s ... "),
2349 if (!mkdatadir(NULL))
2354 made_new_pgdata = true;
2358 /* Present but empty, fix permissions and use it */
2359 printf(_("fixing permissions on existing directory %s ... "),
2363 if (chmod(pg_data, 0700) != 0)
2371 found_existing_pgdata = true;
2375 /* Present and not empty */
2377 _("%s: directory \"%s\" exists but is not empty\n"
2378 "If you want to create a new database system, either remove or empty\n"
2379 "the directory \"%s\" or run %s\n"
2380 "with an argument other than \"%s\".\n"),
2381 progname, pg_data, pg_data, progname, pg_data);
2382 exit(1); /* no further message needed */
2385 /* Trouble accessing directory */
2390 /* Create required subdirectories */
2392 for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
2394 printf(_("creating directory %s/%s ... "), pg_data, subdirs[i]);
2397 if (!mkdatadir(subdirs[i]))
2403 /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2404 set_short_version(short_version, NULL);
2407 * Determine platform-specific config settings
2409 * Use reasonable values if kernel will let us, else scale back. Probe for
2410 * max_connections first since it is subject to more constraints than
2419 /* Now create all the text config files */
2422 /* Bootstrap template1 */
2423 bootstrap_template1(short_version);
2425 /* Make the per-database PG_VERSION for template1 only after init'ing it */
2426 set_short_version(short_version, "base/1");
2428 /* Create the stuff we don't need to use bootstrap mode for */
2431 if (pwprompt || pwfilename)
2434 unlimit_systables();
2440 setup_description();
2452 printf(_("\nSuccess. You can now start the database server using:\n\n"
2453 " %s%s%s/postmaster -D %s%s%s\n"
2455 " %s%s%s/pg_ctl -D %s%s%s -l logfile start\n\n"),
2456 QUOTE_PATH, bin_path, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH,
2457 QUOTE_PATH, bin_path, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH);