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-2004, 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.66 2004/11/09 15:57:52 petere Exp $
44 *-------------------------------------------------------------------------
47 #include "postgres_fe.h"
55 #ifdef HAVE_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;
91 char *authmethod = "";
94 bool show_setting = false;
100 char *encodingid = "0";
106 char *conversion_file;
107 char *info_schema_file;
109 char *system_views_file;
110 char *effective_user;
111 bool testpath = true;
112 bool made_new_pgdata = false;
113 bool found_existing_pgdata = false;
114 char infoversion[100];
115 bool caught_signal = false;
116 bool output_failed = false;
119 int n_connections = 10;
123 * Warning messages for authentication methods
125 char *authtrust_warning = \
126 "# CAUTION: Configuring the system for local \"trust\" authentication allows\n"
127 "# any local user to connect as any PostgreSQL user, including the database\n"
128 "# superuser. If you do not trust all your local users, use another\n"
129 "# authentication method.\n";
130 char *authwarning = NULL;
133 * Centralized knowledge of switches to pass to backend
135 * Note: in the shell-script version, we also passed PGDATA as a -D switch,
136 * but here it is more convenient to pass it as an environment variable
137 * (no quoting to worry about).
139 static const char *boot_options = "-F";
140 static const char *backend_options = "-F -O -c search_path=pg_catalog -c exit_on_error=true";
143 /* path to 'initdb' binary directory */
144 char bin_path[MAXPGPATH];
145 char backend_exec[MAXPGPATH];
147 static void *xmalloc(size_t size);
148 static char *xstrdup(const char *s);
149 static char **replace_token(char **lines, char *token, char *replacement);
150 #ifndef HAVE_UNIX_SOCKETS
151 static char **filter_lines_with_token(char **lines, char *token);
153 static char **readfile(char *path);
154 static void writefile(char *path, char **lines);
155 static int mkdir_p(char *path, mode_t omode);
156 static void exit_nicely(void);
157 static char *get_id(void);
158 static char *get_encoding_id(char *encoding_name);
159 static char *get_short_version(void);
160 static int check_data_dir(void);
161 static bool mkdatadir(const char *subdir);
162 static void set_input(char **dest, char *filename);
163 static void check_input(char *path);
164 static void set_short_version(char *short_version, char *extrapath);
165 static void set_null_conf(void);
166 static void test_connections(void);
167 static void test_buffers(void);
168 static void setup_config(void);
169 static void bootstrap_template1(char *short_version);
170 static void setup_shadow(void);
171 static void get_set_pwd(void);
172 static void unlimit_systables(void);
173 static void setup_depend(void);
174 static void setup_sysviews(void);
175 static void setup_description(void);
176 static void setup_conversion(void);
177 static void setup_privileges(void);
178 static void set_info_version(void);
179 static void setup_schema(void);
180 static void vacuum_db(void);
181 static void make_template0(void);
182 static void trapsig(int signum);
183 static void check_ok(void);
184 static char *escape_quotes(const char *src);
185 static bool chklocale(const char *locale);
186 static void setlocales(void);
187 static void usage(const char *progname);
191 * macros for running pipes to postgres
193 #define PG_CMD_DECL char cmd[MAXPGPATH]; char ** line ; FILE * pg
194 #define PG_CMD_DECL_NOLINE char cmd[MAXPGPATH]; FILE * pg
196 #define PG_CMD_OPEN \
200 pg = popen(cmd, "w"); \
205 #define PG_CMD_CLOSE \
207 if (pclose_check(pg)) \
211 #define PG_CMD_PUTLINE \
213 if (fputs(*line, pg) < 0 || fflush(pg) < 0) \
214 output_failed = true; \
218 #define QUOTE_PATH ""
220 #define QUOTE_PATH "\""
224 * routines to check mem allocations and fail noisily.
226 * Note that we can't call exit_nicely() on a memory failure, as it calls
227 * rmtree() which needs memory allocation. So we just exit with a bang.
234 result = malloc(size);
237 fprintf(stderr, _("%s: out of memory\n"), progname);
244 xstrdup(const char *s)
251 fprintf(stderr, _("%s: out of memory\n"), progname);
258 * make a copy of the array of lines, with token replaced by replacement
259 * the first time it occurs on each line.
261 * This does most of what sed was used for in the shell script, but
262 * doesn't need any regexp stuff.
265 replace_token(char **lines, char *token, char *replacement)
274 for (i = 0; lines[i]; i++)
277 result = (char **) xmalloc(numlines * sizeof(char *));
279 toklen = strlen(token);
280 replen = strlen(replacement);
281 diff = replen - toklen;
283 for (i = 0; i < numlines; i++)
289 /* just copy pointer if NULL or no change needed */
291 if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
293 result[i] = lines[i];
297 /* if we get here a change is needed - set up new line */
299 newline = (char *) xmalloc(strlen(lines[i]) + diff + 1);
301 pre = where - lines[i];
303 strncpy(newline, lines[i], pre);
305 strcpy(newline + pre, replacement);
307 strcpy(newline + pre + replen, lines[i] + pre + toklen);
318 * make a copy of lines without any that contain the token
319 * a sort of poor man's grep -v
322 #ifndef HAVE_UNIX_SOCKETS
324 filter_lines_with_token(char **lines, char *token)
330 for (i = 0; lines[i]; i++)
333 result = (char **) xmalloc(numlines * sizeof(char *));
335 for (src = 0, dst = 0; src < numlines; src++)
337 if (lines[src] == NULL || strstr(lines[src], token) == NULL)
338 result[dst++] = lines[src];
346 * get the lines from a text file
359 if ((infile = fopen(path, "r")) == NULL)
361 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
362 progname, path, strerror(errno));
366 /* pass over the file twice - the first time to size the result */
368 while ((c = fgetc(infile)) != EOF)
374 if (linelen > maxlength)
380 /* handle last line without a terminating newline (yuck) */
384 if (linelen > maxlength)
387 /* set up the result and the line buffer */
389 result = (char **) xmalloc((nlines + 2) * sizeof(char *));
390 buffer = (char *) xmalloc(maxlength + 2);
392 /* now reprocess the file and store the lines */
396 while (fgets(buffer, maxlength + 1, infile) != NULL)
398 result[nlines] = xstrdup(buffer);
403 result[nlines] = NULL;
409 * write an array of lines to a file
411 * This is only used to write text files. Use fopen "w" not PG_BINARY_W
412 * so that the resulting configuration files are nicely editable on Windows.
415 writefile(char *path, char **lines)
420 if ((out_file = fopen(path, "w")) == NULL)
422 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
423 progname, path, strerror(errno));
426 for (line = lines; *line != NULL; line++)
428 if (fputs(*line, out_file) < 0)
432 if (fclose(out_file))
436 /* source stolen from FreeBSD /src/bin/mkdir/mkdir.c and adapted */
439 * this tries to build all the elements of a path to a directory a la mkdir -p
440 * we assume the path is in canonical form, i.e. uses / as the separator
441 * we also assume it isn't null.
444 mkdir_p(char *path, mode_t omode)
459 /* skip network and drive specifiers for win32 */
462 if (p[0] == '/' && p[1] == '/')
465 p = strstr(p + 2, "/");
469 else if (p[1] == ':' &&
470 ((p[0] >= 'a' && p[0] <= 'z') ||
471 (p[0] >= 'A' && p[0] <= 'Z')))
479 if (p[0] == '/') /* Skip leading '/'. */
481 for (first = 1, last = 0; !last; ++p)
485 else if (p[0] != '/')
488 if (!last && p[1] == '\0')
493 * POSIX 1003.2: For each dir operand that does not name an
494 * existing directory, effects equivalent to those cased by
495 * the following command shall occcur:
497 * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode]
500 * We change the user's umask and then restore it, instead of
504 numask = oumask & ~(S_IWUSR | S_IXUSR);
505 (void) umask(numask);
509 (void) umask(oumask);
510 if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
512 if (errno == EEXIST || errno == EISDIR)
514 if (stat(path, &sb) < 0)
519 else if (!S_ISDIR(sb.st_mode))
539 (void) umask(oumask);
544 * clean up any files we created on failure
545 * if we created the data directory remove it too
550 fprintf(stderr, _("%s: failed\n"), progname);
556 fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
558 if (!rmtree(pg_data, true))
559 fprintf(stderr, _("%s: failed\n"), progname);
561 else if (found_existing_pgdata)
564 _("%s: removing contents of data directory \"%s\"\n"),
566 if (!rmtree(pg_data, false))
567 fprintf(stderr, _("%s: failed\n"), progname);
569 /* otherwise died during startup, do nothing! */
573 if (made_new_pgdata || found_existing_pgdata)
575 _("%s: data directory \"%s\" not removed at user's request\n"),
583 * find the current user
585 * on unix make sure it isn't really root
594 pw = getpwuid(getuid());
596 #ifndef __BEOS__ /* no root check on BEOS */
598 if (!geteuid()) /* 0 is root's uid */
601 _("%s: cannot be run as root\n"
602 "Please log in (using, e.g., \"su\") as the "
603 "(unprivileged) user that will\n"
604 "own the server process.\n"),
610 #else /* the windows code */
617 struct passwd_win32 *pw = &pass_win32;
618 DWORD pwname_size = sizeof(pass_win32.pw_name) - 1;
621 GetUserName(pw->pw_name, &pwname_size);
624 return xstrdup(pw->pw_name);
628 encodingid_to_string(int enc)
632 sprintf(result, "%d", enc);
633 return xstrdup(result);
637 * get the encoding id for a given encoding name
640 get_encoding_id(char *encoding_name)
644 if (encoding_name && *encoding_name)
646 if ((enc = pg_char_to_encoding(encoding_name)) >= 0 &&
647 pg_valid_server_encoding(encoding_name) >= 0)
648 return encodingid_to_string(enc);
650 fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
651 progname, encoding_name ? encoding_name : "(null)");
655 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
657 * Checks whether the encoding selected for PostgreSQL and the
658 * encoding used by the system locale match.
661 struct encoding_match
663 enum pg_enc pg_enc_code;
664 char *system_enc_name;
667 struct encoding_match encoding_match_list[] = {
668 {PG_EUC_JP, "EUC-JP"},
669 {PG_EUC_JP, "eucJP"},
670 {PG_EUC_JP, "IBM-eucJP"},
671 {PG_EUC_JP, "sdeckanji"},
673 {PG_EUC_CN, "EUC-CN"},
674 {PG_EUC_CN, "eucCN"},
675 {PG_EUC_CN, "IBM-eucCN"},
676 {PG_EUC_CN, "GB2312"},
677 {PG_EUC_CN, "dechanzi"},
679 {PG_EUC_KR, "EUC-KR"},
680 {PG_EUC_KR, "eucKR"},
681 {PG_EUC_KR, "IBM-eucKR"},
682 {PG_EUC_KR, "deckorean"},
685 {PG_EUC_TW, "EUC-TW"},
686 {PG_EUC_TW, "eucTW"},
687 {PG_EUC_TW, "IBM-eucTW"},
688 {PG_EUC_TW, "cns11643"},
697 {PG_LATIN1, "ISO-8859-1"},
698 {PG_LATIN1, "ISO8859-1"},
699 {PG_LATIN1, "iso88591"},
701 {PG_LATIN2, "ISO-8859-2"},
702 {PG_LATIN2, "ISO8859-2"},
703 {PG_LATIN2, "iso88592"},
705 {PG_LATIN3, "ISO-8859-3"},
706 {PG_LATIN3, "ISO8859-3"},
707 {PG_LATIN3, "iso88593"},
709 {PG_LATIN4, "ISO-8859-4"},
710 {PG_LATIN4, "ISO8859-4"},
711 {PG_LATIN4, "iso88594"},
713 {PG_LATIN5, "ISO-8859-9"},
714 {PG_LATIN5, "ISO8859-9"},
715 {PG_LATIN5, "iso88599"},
717 {PG_LATIN6, "ISO-8859-10"},
718 {PG_LATIN6, "ISO8859-10"},
719 {PG_LATIN6, "iso885910"},
721 {PG_LATIN7, "ISO-8859-13"},
722 {PG_LATIN7, "ISO8859-13"},
723 {PG_LATIN7, "iso885913"},
725 {PG_LATIN8, "ISO-8859-14"},
726 {PG_LATIN8, "ISO8859-14"},
727 {PG_LATIN8, "iso885914"},
729 {PG_LATIN9, "ISO-8859-15"},
730 {PG_LATIN9, "ISO8859-15"},
731 {PG_LATIN9, "iso885915"},
733 {PG_LATIN10, "ISO-8859-16"},
734 {PG_LATIN10, "ISO8859-16"},
735 {PG_LATIN10, "iso885916"},
737 {PG_WIN1256, "CP1256"},
742 {PG_KOI8R, "KOI8-R"},
743 {PG_WIN1251, "CP1251"},
746 {PG_ISO_8859_5, "ISO-8859-5"},
747 {PG_ISO_8859_5, "ISO8859-5"},
748 {PG_ISO_8859_5, "iso88595"},
750 {PG_ISO_8859_6, "ISO-8859-6"},
751 {PG_ISO_8859_6, "ISO8859-6"},
752 {PG_ISO_8859_6, "iso88596"},
754 {PG_ISO_8859_7, "ISO-8859-7"},
755 {PG_ISO_8859_7, "ISO8859-7"},
756 {PG_ISO_8859_7, "iso88597"},
758 {PG_ISO_8859_8, "ISO-8859-8"},
759 {PG_ISO_8859_8, "ISO8859-8"},
760 {PG_ISO_8859_8, "iso88598"},
762 {PG_SQL_ASCII, NULL} /* end marker */
766 get_encoding_from_locale(const char *ctype)
771 save = setlocale(LC_CTYPE, NULL);
774 save = xstrdup(save);
776 setlocale(LC_CTYPE, ctype);
777 sys = nl_langinfo(CODESET);
780 setlocale(LC_CTYPE, save);
787 check_encodings_match(int pg_enc, const char *ctype)
792 sys = get_encoding_from_locale(ctype);
794 for (i = 0; encoding_match_list[i].system_enc_name; i++)
796 if (pg_enc == encoding_match_list[i].pg_enc_code
797 && strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
805 _("%s: warning: encoding mismatch\n"), progname);
807 _("The encoding you selected (%s) and the encoding that the selected\n"
808 "locale uses (%s) are not known to match. This may lead to\n"
809 "misbehavior in various character string processing functions. To fix\n"
810 "this situation, rerun %s and either do not specify an encoding\n"
811 "explicitly, or choose a matching combination.\n"),
812 pg_encoding_to_char(pg_enc), sys, progname);
819 find_matching_encoding(const char *ctype)
824 sys = get_encoding_from_locale(ctype);
826 for (i = 0; encoding_match_list[i].system_enc_name; i++)
828 if (strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
831 return encoding_match_list[i].pg_enc_code;
838 #endif /* HAVE_LANGINFO_H && CODESET */
841 * get short version of VERSION
844 get_short_version(void)
850 vr = xstrdup(PG_VERSION);
852 for (end = 0; vr[end] != '\0'; end++)
863 else if (vr[end] < '0' || vr[end] > '9')
865 /* gone past digits and dots */
869 if (end == 0 || vr[end - 1] == '.' || !gotdot)
877 * make sure the data directory either doesn't exist or is empty
879 * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty,
880 * or -1 if trouble accessing directory
891 chkdir = opendir(pg_data);
894 return (errno == ENOENT) ? 0 : -1;
896 while ((file = readdir(chkdir)) != NULL)
898 if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0)
900 /* skip this and parent directory */
905 result = 2; /* not empty */
913 result = -1; /* some kind of I/O error? */
919 * make the data directory (or one of its subdirectories if subdir is not NULL)
922 mkdatadir(const char *subdir)
926 path = xmalloc(strlen(pg_data) + 2 +
927 (subdir == NULL ? 0 : strlen(subdir)));
930 sprintf(path, "%s/%s", pg_data, subdir);
932 strcpy(path, pg_data);
934 return (mkdir_p(path, 0700) == 0);
939 * set name of given input file variable under data directory
942 set_input(char **dest, char *filename)
944 *dest = xmalloc(strlen(share_path) + strlen(filename) + 2);
945 sprintf(*dest, "%s/%s", share_path, filename);
949 * check that given input file exists
952 check_input(char *path)
956 if (stat(path, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
959 _("%s: file \"%s\" does not exist\n"
960 "This means you have a corrupted installation or identified\n"
961 "the wrong directory with the invocation option -L.\n"),
969 * write out the PG_VERSION file in the data dir, or its subdirectory
970 * if extrapath is not NULL
973 set_short_version(char *short_version, char *extrapath)
978 if (extrapath == NULL)
980 path = xmalloc(strlen(pg_data) + 12);
981 sprintf(path, "%s/PG_VERSION", pg_data);
985 path = xmalloc(strlen(pg_data) + strlen(extrapath) + 13);
986 sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
988 version_file = fopen(path, PG_BINARY_W);
989 if (version_file == NULL)
991 fprintf(version_file, "%s\n", short_version);
992 if (fclose(version_file))
997 * set up an empty config file so we can check buffers and connections
1005 path = xmalloc(strlen(pg_data) + 17);
1006 sprintf(path, "%s/postgresql.conf", pg_data);
1007 conf_file = fopen(path, PG_BINARY_W);
1008 if (conf_file == NULL || fclose(conf_file))
1013 * check how many connections we can sustain
1016 test_connections(void)
1018 char cmd[MAXPGPATH];
1019 static const int conns[] = {100, 50, 40, 30, 20, 10};
1020 static const int len = sizeof(conns) / sizeof(int);
1024 printf(_("selecting default max_connections ... "));
1027 for (i = 0; i < len; i++)
1029 snprintf(cmd, sizeof(cmd),
1030 "%s\"%s\" -boot -x0 %s "
1031 "-c shared_buffers=%d -c max_connections=%d template1 "
1032 "< \"%s\" > \"%s\" 2>&1%s",
1033 SYSTEMQUOTE, backend_exec, boot_options,
1034 conns[i] * 5, conns[i],
1035 DEVNULL, DEVNULL, SYSTEMQUOTE);
1036 status = system(cmd);
1042 n_connections = conns[i];
1044 printf("%d\n", n_connections);
1048 * check how many buffers we can run with
1053 char cmd[MAXPGPATH];
1054 static const int bufs[] = {1000, 900, 800, 700, 600, 500,
1055 400, 300, 200, 100, 50};
1056 static const int len = sizeof(bufs) / sizeof(int);
1060 printf(_("selecting default shared_buffers ... "));
1063 for (i = 0; i < len; i++)
1065 snprintf(cmd, sizeof(cmd),
1066 "%s\"%s\" -boot -x0 %s "
1067 "-c shared_buffers=%d -c max_connections=%d template1 "
1068 "< \"%s\" > \"%s\" 2>&1%s",
1069 SYSTEMQUOTE, backend_exec, boot_options,
1070 bufs[i], n_connections,
1071 DEVNULL, DEVNULL, SYSTEMQUOTE);
1072 status = system(cmd);
1078 n_buffers = bufs[i];
1080 printf("%d\n", n_buffers);
1084 * set up all the config files
1091 char path[MAXPGPATH];
1093 fputs(_("creating configuration files ... "), stdout);
1096 /* postgresql.conf */
1098 conflines = readfile(conf_file);
1100 snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1101 conflines = replace_token(conflines, "#max_connections = 100", repltok);
1103 snprintf(repltok, sizeof(repltok), "shared_buffers = %d", n_buffers);
1104 conflines = replace_token(conflines, "#shared_buffers = 1000", repltok);
1106 lc_messages = escape_quotes(lc_messages);
1107 snprintf(repltok, sizeof(repltok), "lc_messages = '%s'", lc_messages);
1108 conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1110 lc_monetary = escape_quotes(lc_monetary);
1111 snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'", lc_monetary);
1112 conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1114 lc_numeric = escape_quotes(lc_numeric);
1115 snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'", lc_numeric);
1116 conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1118 lc_time = escape_quotes(lc_time);
1119 snprintf(repltok, sizeof(repltok), "lc_time = '%s'", lc_time);
1120 conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1122 snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1124 writefile(path, conflines);
1132 conflines = readfile(hba_file);
1134 #ifndef HAVE_UNIX_SOCKETS
1135 conflines = filter_lines_with_token(conflines,"@remove-line-for-nolocal@");
1137 conflines = replace_token(conflines,"@remove-line-for-nolocal@","");
1141 conflines = replace_token(conflines,
1143 "#host all all ::1");
1146 /* Replace default authentication methods */
1147 conflines = replace_token(conflines,
1151 conflines = replace_token(conflines,
1153 strcmp(authmethod, "trust") ? "" : authtrust_warning);
1155 snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1157 writefile(path, conflines);
1164 conflines = readfile(ident_file);
1166 snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1168 writefile(path, conflines);
1178 * run the BKI script in bootstrap mode to create template1
1181 bootstrap_template1(char *short_version)
1183 char *talkargs = "";
1185 char headerline[MAXPGPATH];
1189 printf(_("creating template1 database in %s/base/1 ... "), pg_data);
1195 bki_lines = readfile(bki_file);
1197 /* Check that bki file appears to be of the right version */
1199 snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1202 if (strcmp(headerline, *bki_lines) != 0)
1205 _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
1206 "Check your installation or specify the correct path "
1207 "using the option -L.\n"),
1208 progname, bki_file, PG_VERSION);
1213 bki_lines = replace_token(bki_lines, "POSTGRES", effective_user);
1215 bki_lines = replace_token(bki_lines, "ENCODING", encodingid);
1218 * Pass correct LC_xxx environment to bootstrap.
1220 * The shell script arranged to restore the LC settings afterwards, but
1221 * there doesn't seem to be any compelling reason to do that.
1223 snprintf(cmd, sizeof(cmd), "LC_COLLATE=%s", lc_collate);
1224 putenv(xstrdup(cmd));
1226 snprintf(cmd, sizeof(cmd), "LC_CTYPE=%s", lc_ctype);
1227 putenv(xstrdup(cmd));
1231 /* Also ensure backend isn't confused by this environment var: */
1232 unsetenv("PGCLIENTENCODING");
1234 snprintf(cmd, sizeof(cmd),
1235 "\"%s\" -boot -x1 %s %s template1",
1236 backend_exec, boot_options, talkargs);
1240 for (line = bki_lines; *line != NULL; line++)
1254 * set up the shadow password table
1259 char *pg_shadow_setup[] = {
1261 * Create a trigger so that direct updates to pg_shadow will be
1262 * written to the flat password/group files pg_pwd and pg_group
1264 "CREATE TRIGGER pg_sync_pg_pwd "
1265 " AFTER INSERT OR UPDATE OR DELETE ON pg_shadow "
1266 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1267 "CREATE TRIGGER pg_sync_pg_group "
1268 " AFTER INSERT OR UPDATE OR DELETE ON pg_group "
1269 " FOR EACH ROW EXECUTE PROCEDURE update_pg_pwd_and_pg_group();\n",
1272 * needs to be done before alter user, because alter user checks
1273 * that pg_shadow is secure ...
1275 "REVOKE ALL on pg_shadow FROM public;\n",
1281 fputs(_("initializing pg_shadow ... "), stdout);
1284 snprintf(cmd, sizeof(cmd),
1285 "\"%s\" %s template1 >%s",
1286 backend_exec, backend_options,
1291 for (line = pg_shadow_setup; *line != NULL; line++)
1300 * get the superuser password if required, and call postgres to set it
1309 char pwdpath[MAXPGPATH];
1310 struct stat statbuf;
1315 * Read password from terminal
1317 pwd1 = simple_prompt("Enter new superuser password: ", 100, false);
1318 pwd2 = simple_prompt("Enter it again: ", 100, false);
1319 if (strcmp(pwd1, pwd2) != 0)
1321 fprintf(stderr, _("Passwords didn't match.\n"));
1329 * Read password from file
1331 * Ideally this should insist that the file not be world-readable.
1332 * However, this option is mainly intended for use on Windows
1333 * where file permissions may not exist at all, so we'll skip the
1336 FILE *pwf = fopen(pwfilename, "r");
1337 char pwdbuf[MAXPGPATH];
1342 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1343 progname, pwfilename, strerror(errno));
1346 if (!fgets(pwdbuf, sizeof(pwdbuf), pwf))
1348 fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
1349 progname, pwfilename, strerror(errno));
1355 while (i > 0 && (pwdbuf[i - 1] == '\r' || pwdbuf[i - 1] == '\n'))
1358 pwd1 = xstrdup(pwdbuf);
1361 printf(_("setting password ... "));
1364 snprintf(cmd, sizeof(cmd),
1365 "\"%s\" %s template1 >%s",
1366 backend_exec, backend_options,
1372 "ALTER USER \"%s\" WITH PASSWORD '%s';\n", effective_user, pwd1) < 0)
1381 snprintf(pwdpath, sizeof(pwdpath), "%s/global/pg_pwd", pg_data);
1382 if (stat(pwdpath, &statbuf) != 0 || !S_ISREG(statbuf.st_mode))
1385 _("%s: The password file was not generated. "
1386 "Please report this problem.\n"),
1398 unlimit_systables(void)
1400 char *systables_setup[] = {
1401 "ALTER TABLE pg_attrdef CREATE TOAST TABLE;\n",
1402 "ALTER TABLE pg_constraint CREATE TOAST TABLE;\n",
1403 "ALTER TABLE pg_database CREATE TOAST TABLE;\n",
1404 "ALTER TABLE pg_description CREATE TOAST TABLE;\n",
1405 "ALTER TABLE pg_group CREATE TOAST TABLE;\n",
1406 "ALTER TABLE pg_proc CREATE TOAST TABLE;\n",
1407 "ALTER TABLE pg_rewrite CREATE TOAST TABLE;\n",
1408 "ALTER TABLE pg_shadow CREATE TOAST TABLE;\n",
1409 "ALTER TABLE pg_statistic CREATE TOAST TABLE;\n",
1415 fputs(_("enabling unlimited row size for system tables ... "), stdout);
1418 snprintf(cmd, sizeof(cmd),
1419 "\"%s\" %s template1 >%s",
1420 backend_exec, backend_options,
1425 for (line = systables_setup; *line != NULL; line++)
1439 char *pg_depend_setup[] = {
1441 * Make PIN entries in pg_depend for all objects made so far in
1442 * the tables that the dependency code handles. This is overkill
1443 * (the system doesn't really depend on having every last weird
1444 * datatype, for instance) but generating only the minimum
1445 * required set of dependencies seems hard.
1447 * Note that we deliberately do not pin the system views, which
1448 * haven't been created yet.
1450 * First delete any already-made entries; PINs override all else, and
1451 * must be the only entries for their objects.
1453 "DELETE FROM pg_depend;\n",
1454 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1455 " FROM pg_class;\n",
1456 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1458 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
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' "
1463 " FROM pg_constraint;\n",
1464 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1465 " FROM pg_attrdef;\n",
1466 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1467 " FROM pg_language;\n",
1468 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1469 " FROM pg_operator;\n",
1470 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1471 " FROM pg_opclass;\n",
1472 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1473 " FROM pg_rewrite;\n",
1474 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1475 " FROM pg_trigger;\n",
1478 * restriction here to avoid pinning the public namespace
1480 "INSERT INTO pg_depend SELECT 0,0,0, tableoid,oid,0, 'p' "
1481 " FROM pg_namespace "
1482 " WHERE nspname LIKE 'pg%';\n",
1488 fputs(_("initializing pg_depend ... "), stdout);
1491 snprintf(cmd, sizeof(cmd),
1492 "\"%s\" %s template1 >%s",
1493 backend_exec, backend_options,
1498 for (line = pg_depend_setup; *line != NULL; line++)
1507 * set up system views
1510 setup_sysviews(void)
1514 char **sysviews_setup;
1516 fputs(_("creating system views ... "), stdout);
1519 sysviews_setup = readfile(system_views_file);
1522 * We use -N here to avoid backslashing stuff in system_views.sql
1524 snprintf(cmd, sizeof(cmd),
1525 "\"%s\" %s -N template1 >%s",
1526 backend_exec, backend_options,
1531 for (line = sysviews_setup; *line != NULL; line++)
1539 free(sysviews_setup);
1545 * load description data
1548 setup_description(void)
1553 fputs(_("loading pg_description ... "), stdout);
1556 snprintf(cmd, sizeof(cmd),
1557 "\"%s\" %s template1 >%s",
1558 backend_exec, backend_options,
1564 "CREATE TEMP TABLE tmp_pg_description ( "
1568 " description text) WITHOUT OIDS;\n");
1573 "COPY tmp_pg_description FROM '%s';\n",
1579 "INSERT INTO pg_description "
1580 " SELECT t.objoid, c.oid, t.objsubid, t.description "
1581 " FROM tmp_pg_description t, pg_class c "
1582 " WHERE c.relname = t.classname;\n");
1592 * load conversion functions
1595 setup_conversion(void)
1601 fputs(_("creating conversions ... "), stdout);
1604 snprintf(cmd, sizeof(cmd),
1605 "\"%s\" %s template1 >%s",
1606 backend_exec, backend_options,
1611 conv_lines = readfile(conversion_file);
1612 for (line = conv_lines; *line != NULL; line++)
1614 if (strstr(*line, "DROP CONVERSION") != *line)
1630 * We set most system catalogs and built-in functions as world-accessible.
1631 * Some objects may require different permissions by default, so we
1632 * make sure we don't overwrite privilege sets that have already been
1636 setup_privileges(void)
1638 char *privileges_setup[] = {
1640 " SET relacl = '{\"=r/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1641 " WHERE relkind IN ('r', 'v', 'S') AND relacl IS NULL;\n",
1643 " SET proacl = '{\"=X/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1644 " WHERE proacl IS NULL;\n",
1645 "UPDATE pg_language "
1646 " SET lanacl = '{\"=U/\\\\\"$POSTGRES_SUPERUSERNAME\\\\\"\"}' "
1647 " WHERE lanpltrusted;\n",
1648 "GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;\n",
1649 "GRANT CREATE, USAGE ON SCHEMA public TO PUBLIC;\n",
1657 fputs(_("setting privileges on built-in objects ... "), stdout);
1660 snprintf(cmd, sizeof(cmd),
1661 "\"%s\" %s template1 >%s",
1662 backend_exec, backend_options,
1667 priv_lines = replace_token(privileges_setup,
1668 "$POSTGRES_SUPERUSERNAME", effective_user);
1669 for (line = priv_lines; *line != NULL; line++)
1678 * extract the strange version of version required for information schema
1682 set_info_version(void)
1684 char *letterversion;
1689 char *vstr = xstrdup(PG_VERSION);
1692 ptr = vstr + (strlen(vstr) - 1);
1693 while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1695 letterversion = ptr + 1;
1696 major = strtol(vstr, &endptr, 10);
1698 minor = strtol(endptr + 1, &endptr, 10);
1700 micro = strtol(endptr + 1, &endptr, 10);
1701 snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1702 major, minor, micro, letterversion);
1706 * load info schema and populate from features file
1715 fputs(_("creating information schema ... "), stdout);
1718 lines = readfile(info_schema_file);
1721 * We use -N here to avoid backslashing stuff in
1722 * information_schema.sql
1724 snprintf(cmd, sizeof(cmd),
1725 "\"%s\" %s -N template1 >%s",
1726 backend_exec, backend_options,
1731 for (line = lines; *line != NULL; line++)
1741 snprintf(cmd, sizeof(cmd),
1742 "\"%s\" %s template1 >%s",
1743 backend_exec, backend_options,
1749 "UPDATE information_schema.sql_implementation_info "
1750 " SET character_value = '%s' "
1751 " WHERE implementation_info_name = 'DBMS VERSION';\n",
1757 "COPY information_schema.sql_features "
1758 " (feature_id, feature_name, sub_feature_id, "
1759 " sub_feature_name, is_supported, comments) "
1771 * clean everything up in template1
1778 fputs(_("vacuuming database template1 ... "), stdout);
1781 snprintf(cmd, sizeof(cmd),
1782 "\"%s\" %s template1 >%s",
1783 backend_exec, backend_options,
1788 if (fputs("ANALYZE;\nVACUUM FULL FREEZE;\n", pg) < 0)
1798 * copy template1 to template0
1801 make_template0(void)
1803 char *template0_setup[] = {
1804 "CREATE DATABASE template0;\n",
1805 "UPDATE pg_database SET "
1806 " datistemplate = 't', "
1807 " datallowconn = 'f' "
1808 " WHERE datname = 'template0';\n",
1811 * We use the OID of template0 to determine lastsysoid
1813 "UPDATE pg_database SET datlastsysoid = "
1814 " (SELECT oid::int4 - 1 FROM pg_database "
1815 " WHERE datname = 'template0');\n",
1818 * Explicitly revoke public create-schema and create-temp-table
1819 * privileges in template1 and template0; else the latter would be
1822 "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n",
1823 "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n",
1826 * Finally vacuum to clean up dead rows in pg_database
1828 "VACUUM FULL pg_database;\n",
1834 fputs(_("copying template1 to template0 ... "), stdout);
1837 snprintf(cmd, sizeof(cmd),
1838 "\"%s\" %s template1 >%s",
1839 backend_exec, backend_options,
1844 for (line = template0_setup; *line; line++)
1854 * signal handler in case we are interrupted.
1856 * The Windows runtime docs at
1857 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_signal.asp
1858 * specifically forbid a number of things being done from a signal handler,
1859 * including IO, memory allocation and system calls, and only allow jmpbuf
1860 * if you are handling SIGFPE.
1862 * I avoided doing the forbidden things by setting a flag instead of calling
1863 * exit_nicely() directly.
1865 * Also note the behaviour of Windows with SIGINT, which says this:
1866 * Note SIGINT is not supported for any Win32 application, including
1867 * Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs,
1868 * Win32 operating systems generate a new thread to specifically handle
1869 * that interrupt. This can cause a single-thread application such as UNIX,
1870 * to become multithreaded, resulting in unexpected behavior.
1872 * I have no idea how to handle this. (Strange they call UNIX an application!)
1873 * So this will need some testing on Windows.
1878 /* handle systems that reset the handler, like Windows (grr) */
1879 pqsignal(signum, trapsig);
1880 caught_signal = true;
1884 * call exit_nicely() if we got a signal, or else output "ok".
1891 printf(_("caught signal\n"));
1894 else if (output_failed)
1896 printf(_("could not write to child process\n"));
1901 /* all seems well */
1907 * Escape any single quotes or backslashes in given string
1910 escape_quotes(const char *src)
1912 int len = strlen(src),
1914 char *result = xmalloc(len * 2 + 1);
1916 for (i = 0, j = 0; i < len; i++)
1918 if (src[i] == '\'' || src[i] == '\\')
1920 result[j++] = src[i];
1927 * check if given string is a valid locale specifier
1930 chklocale(const char *locale)
1933 int category = LC_CTYPE;
1936 save = setlocale(category, NULL);
1938 return false; /* should not happen; */
1940 save = xstrdup(save);
1942 ret = (setlocale(category, locale) != NULL);
1944 setlocale(category, save);
1947 /* should we exit here? */
1949 fprintf(stderr, _("%s: invalid locale name \"%s\"\n"), progname, locale);
1955 * set up the locale variables
1957 * assumes we have called setlocale(LC_ALL,"")
1962 /* set empty lc_* values to locale config if set */
1964 if (strlen(locale) > 0)
1966 if (strlen(lc_ctype) == 0)
1968 if (strlen(lc_collate) == 0)
1969 lc_collate = locale;
1970 if (strlen(lc_numeric) == 0)
1971 lc_numeric = locale;
1972 if (strlen(lc_time) == 0)
1974 if (strlen(lc_monetary) == 0)
1975 lc_monetary = locale;
1976 if (strlen(lc_messages) == 0)
1977 lc_messages = locale;
1981 * override absent/invalid config settings from initdb's locale
1985 if (strlen(lc_ctype) == 0 || !chklocale(lc_ctype))
1986 lc_ctype = xstrdup(setlocale(LC_CTYPE, NULL));
1987 if (strlen(lc_collate) == 0 || !chklocale(lc_collate))
1988 lc_collate = xstrdup(setlocale(LC_COLLATE, NULL));
1989 if (strlen(lc_numeric) == 0 || !chklocale(lc_numeric))
1990 lc_numeric = xstrdup(setlocale(LC_NUMERIC, NULL));
1991 if (strlen(lc_time) == 0 || !chklocale(lc_time))
1992 lc_time = xstrdup(setlocale(LC_TIME, NULL));
1993 if (strlen(lc_monetary) == 0 || !chklocale(lc_monetary))
1994 lc_monetary = xstrdup(setlocale(LC_MONETARY, NULL));
1995 if (strlen(lc_messages) == 0 || !chklocale(lc_messages))
1996 #if defined(LC_MESSAGES) && !defined(WIN32)
1998 /* when available get the current locale setting */
1999 lc_messages = xstrdup(setlocale(LC_MESSAGES, NULL));
2003 /* when not available, get the CTYPE setting */
2004 lc_messages = xstrdup(setlocale(LC_CTYPE, NULL));
2014 usage(const char *progname)
2016 printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2017 printf(_("Usage:\n"));
2018 printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2019 printf(_("\nOptions:\n"));
2020 printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2021 printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2022 printf(_(" --locale=LOCALE initialize database cluster with given locale\n"));
2023 printf(_(" --lc-collate, --lc-ctype, --lc-messages=LOCALE\n"
2024 " --lc-monetary, --lc-numeric, --lc-time=LOCALE\n"
2025 " initialize database cluster with given locale\n"
2026 " in the respective category (default taken from\n"
2027 " environment)\n"));
2028 printf(_(" --no-locale equivalent to --locale=C\n"));
2029 printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2030 printf(_(" -U, --username=NAME database superuser name\n"));
2031 printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2032 printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2033 printf(_(" -?, --help show this help, then exit\n"));
2034 printf(_(" -V, --version output version information, then exit\n"));
2035 printf(_("\nLess commonly used options:\n"));
2036 printf(_(" -d, --debug generate lots of debugging output\n"));
2037 printf(_(" -s, --show show internal settings\n"));
2038 printf(_(" -L DIRECTORY where to find the input files\n"));
2039 printf(_(" -n, --noclean do not clean up after errors\n"));
2040 printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2042 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2046 main(int argc, char *argv[])
2049 * options with no short version return a low integer, the rest return
2050 * their short version value
2052 static struct option long_options[] = {
2053 {"pgdata", required_argument, NULL, 'D'},
2054 {"encoding", required_argument, NULL, 'E'},
2055 {"locale", required_argument, NULL, 1},
2056 {"lc-collate", required_argument, NULL, 2},
2057 {"lc-ctype", required_argument, NULL, 3},
2058 {"lc-monetary", required_argument, NULL, 4},
2059 {"lc-numeric", required_argument, NULL, 5},
2060 {"lc-time", required_argument, NULL, 6},
2061 {"lc-messages", required_argument, NULL, 7},
2062 {"no-locale", no_argument, NULL, 8},
2063 {"auth", required_argument, NULL, 'A'},
2064 {"pwprompt", no_argument, NULL, 'W'},
2065 {"pwfile", required_argument, NULL, 9},
2066 {"username", required_argument, NULL, 'U'},
2067 {"help", no_argument, NULL, '?'},
2068 {"version", no_argument, NULL, 'V'},
2069 {"debug", no_argument, NULL, 'd'},
2070 {"show", no_argument, NULL, 's'},
2071 {"noclean", no_argument, NULL, 'n'},
2079 char *short_version;
2080 char *pgdenv; /* PGDATA value gotten from and sent to
2082 static const char *subdirs[] = {
2085 "pg_xlog/archive_status",
2093 progname = get_progname(argv[0]);
2094 set_pglocale_pgservice(argv[0], "initdb");
2098 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2103 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2105 puts("initdb (PostgreSQL) " PG_VERSION);
2110 /* process command-line options */
2112 while ((c = getopt_long(argc, argv, "dD:E:L:nU:WA:s", long_options, &option_index)) != -1)
2117 authmethod = xstrdup(optarg);
2120 pg_data = xstrdup(optarg);
2123 encoding = xstrdup(optarg);
2129 username = xstrdup(optarg);
2133 printf(_("Running in debug mode.\n"));
2137 printf(_("Running in noclean mode. Mistakes will not be cleaned up.\n"));
2140 share_path = xstrdup(optarg);
2143 locale = xstrdup(optarg);
2146 lc_collate = xstrdup(optarg);
2149 lc_ctype = xstrdup(optarg);
2152 lc_monetary = xstrdup(optarg);
2155 lc_numeric = xstrdup(optarg);
2158 lc_time = xstrdup(optarg);
2161 lc_messages = xstrdup(optarg);
2167 pwfilename = xstrdup(optarg);
2170 show_setting = true;
2173 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2179 /* Non-option argument specifies data directory */
2182 pg_data = xstrdup(argv[optind]);
2188 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
2189 progname, argv[optind + 1]);
2190 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2194 if (pwprompt && pwfilename)
2196 fprintf(stderr, _("%s: password prompt and password file may not be specified together\n"), progname);
2200 if (authmethod == NULL || !strlen(authmethod))
2202 authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
2203 "You can change this by editing pg_hba.conf or using the -A option the\n"
2204 "next time you run initdb.\n");
2205 authmethod = "trust";
2208 if (strcmp(authmethod, "md5") &&
2209 strcmp(authmethod, "ident") &&
2210 strncmp(authmethod, "ident ", 6) && /* ident with space =
2212 strcmp(authmethod, "trust") &&
2214 strcmp(authmethod, "pam") &&
2215 strncmp(authmethod, "pam ", 4) && /* pam with space = param */
2217 strcmp(authmethod, "crypt") &&
2218 strcmp(authmethod, "password")
2222 * Kerberos methods not listed because they are not supported over
2223 * local connections and are rejected in hba.c
2226 fprintf(stderr, _("%s: unrecognized authentication method \"%s\"\n"), progname, authmethod);
2230 if ((!strcmp(authmethod, "md5") ||
2231 !strcmp(authmethod, "crypt") ||
2232 !strcmp(authmethod, "password")) &&
2233 !(pwprompt || pwfilename))
2235 fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname, authmethod);
2239 if (strlen(pg_data) == 0)
2241 pgdenv = getenv("PGDATA");
2242 if (pgdenv && strlen(pgdenv))
2245 pg_data = xstrdup(pgdenv);
2250 _("%s: no data directory specified\n"
2251 "You must identify the directory where the data for this database system\n"
2252 "will reside. Do this with either the invocation option -D or the\n"
2253 "environment variable PGDATA.\n"),
2259 canonicalize_path(pg_data);
2262 * we have to set PGDATA for postgres rather than pass it on the
2263 * command line to avoid dumb quoting problems on Windows, and we
2264 * would especially need quotes otherwise on Windows because paths
2265 * there are most likely to have embedded spaces.
2267 pgdenv = xmalloc(8 + strlen(pg_data));
2268 sprintf(pgdenv, "PGDATA=%s", pg_data);
2271 if ((ret = find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
2274 char full_path[MAXPGPATH];
2276 if (find_my_exec(argv[0], full_path) < 0)
2277 StrNCpy(full_path, progname, MAXPGPATH);
2281 _("The program \"postgres\" is needed by %s "
2282 "but was not found in the\n"
2283 "same directory as \"%s\".\n"
2284 "Check your installation.\n"),
2285 progname, full_path);
2288 _("The program \"postgres\" was found by \"%s\"\n"
2289 "but was not the same version as %s.\n"
2290 "Check your installation.\n"),
2291 full_path, progname);
2295 /* store binary directory */
2296 strcpy(bin_path, backend_exec);
2297 *last_dir_separator(bin_path) = '\0';
2298 canonicalize_path(bin_path);
2302 share_path = xmalloc(MAXPGPATH);
2303 get_share_path(backend_exec, share_path);
2305 else if (!is_absolute_path(share_path))
2307 fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
2311 canonicalize_path(share_path);
2313 if ((short_version = get_short_version()) == NULL)
2315 fprintf(stderr, _("%s: could not determine valid short version string\n"), progname);
2319 if (strlen(username))
2320 effective_user = username;
2322 effective_user = get_id();
2324 if (strlen(encoding))
2325 encodingid = get_encoding_id(encoding);
2327 set_input(&bki_file, "postgres.bki");
2328 set_input(&desc_file, "postgres.description");
2329 set_input(&hba_file, "pg_hba.conf.sample");
2330 set_input(&ident_file, "pg_ident.conf.sample");
2331 set_input(&conf_file, "postgresql.conf.sample");
2332 set_input(&conversion_file, "conversion_create.sql");
2333 set_input(&info_schema_file, "information_schema.sql");
2334 set_input(&features_file, "sql_features.txt");
2335 set_input(&system_views_file, "system_views.sql");
2339 if (show_setting || debug)
2343 "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2344 "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2345 "POSTGRES_DESCR=%s\nPOSTGRESQL_CONF_SAMPLE=%s\n"
2346 "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2348 pg_data, share_path, bin_path,
2349 effective_user, bki_file,
2350 desc_file, conf_file,
2351 hba_file, ident_file);
2356 check_input(bki_file);
2357 check_input(desc_file);
2358 check_input(hba_file);
2359 check_input(ident_file);
2360 check_input(conf_file);
2361 check_input(conversion_file);
2362 check_input(info_schema_file);
2363 check_input(features_file);
2364 check_input(system_views_file);
2368 printf(_("The files belonging to this database system will be owned "
2370 "This user must also own the server process.\n\n"),
2373 if (strcmp(lc_ctype, lc_collate) == 0 &&
2374 strcmp(lc_ctype, lc_time) == 0 &&
2375 strcmp(lc_ctype, lc_numeric) == 0 &&
2376 strcmp(lc_ctype, lc_monetary) == 0 &&
2377 strcmp(lc_ctype, lc_messages) == 0)
2378 printf(_("The database cluster will be initialized with locale %s.\n"), lc_ctype);
2381 printf(_("The database cluster will be initialized with locales\n"
2396 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
2397 if (strcmp(lc_ctype, "C") != 0 && strcmp(lc_ctype, "POSIX") != 0)
2399 if (strlen(encoding) == 0)
2403 tmp = find_matching_encoding(lc_ctype);
2406 fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"), progname, lc_ctype);
2407 fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
2408 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
2413 encodingid = encodingid_to_string(tmp);
2414 printf(_("The default database encoding has accordingly been set to %s.\n"),
2415 pg_encoding_to_char(tmp));
2419 check_encodings_match(atoi(encodingid), lc_ctype);
2421 #endif /* HAVE_LANGINFO_H && CODESET */
2428 * now we are starting to do real work, trap signals so we can clean
2432 /* some of these are not valid on Windows */
2434 pqsignal(SIGHUP, trapsig);
2437 pqsignal(SIGINT, trapsig);
2440 pqsignal(SIGQUIT, trapsig);
2443 pqsignal(SIGTERM, trapsig);
2446 /* Ignore SIGPIPE when writing to backend, so we can clean up */
2448 pqsignal(SIGPIPE, SIG_IGN);
2451 switch (check_data_dir())
2454 /* PGDATA not there, must create it */
2455 printf(_("creating directory %s ... "),
2459 if (!mkdatadir(NULL))
2464 made_new_pgdata = true;
2468 /* Present but empty, fix permissions and use it */
2469 printf(_("fixing permissions on existing directory %s ... "),
2473 if (chmod(pg_data, 0700) != 0)
2475 fprintf(stderr, _("%s: could not change permissions of directory »%s«: %s\n"),
2476 progname, pg_data, strerror(errno));
2482 found_existing_pgdata = true;
2486 /* Present and not empty */
2488 _("%s: directory \"%s\" exists but is not empty\n"
2489 "If you want to create a new database system, either remove or empty\n"
2490 "the directory \"%s\" or run %s\n"
2491 "with an argument other than \"%s\".\n"),
2492 progname, pg_data, pg_data, progname, pg_data);
2493 exit(1); /* no further message needed */
2496 /* Trouble accessing directory */
2497 fprintf(stderr, _("%s: could not access directory »%s«: %s\n"),
2498 progname, pg_data, strerror(errno));
2502 /* Create required subdirectories */
2504 for (i = 0; i < (sizeof(subdirs) / sizeof(char *)); i++)
2506 printf(_("creating directory %s/%s ... "), pg_data, subdirs[i]);
2509 if (!mkdatadir(subdirs[i]))
2515 /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2516 set_short_version(short_version, NULL);
2519 * Determine platform-specific config settings
2521 * Use reasonable values if kernel will let us, else scale back. Probe
2522 * for max_connections first since it is subject to more constraints
2523 * than shared_buffers.
2531 /* Now create all the text config files */
2534 /* Bootstrap template1 */
2535 bootstrap_template1(short_version);
2538 * Make the per-database PG_VERSION for template1 only after init'ing
2541 set_short_version(short_version, "base/1");
2543 /* Create the stuff we don't need to use bootstrap mode for */
2546 if (pwprompt || pwfilename)
2549 unlimit_systables();
2555 setup_description();
2567 if (authwarning != NULL)
2568 fprintf(stderr, authwarning);
2570 printf(_("\nSuccess. You can now start the database server using:\n\n"
2571 " %s%s%s/postmaster -D %s%s%s\n"
2573 " %s%s%s/pg_ctl -D %s%s%s -l logfile start\n\n"),
2574 QUOTE_PATH, bin_path, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH,
2575 QUOTE_PATH, bin_path, QUOTE_PATH, QUOTE_PATH, pg_data, QUOTE_PATH);