/* *Warningmessagesforauthenticationmethods
*/ #define AUTHTRUST_WARNING \ "# CAUTION: Configuring the system for local \"trust\" authentication\n" \ "# allows any local user to connect as any PostgreSQL user, including\n" \ "# the database superuser. If you do not trust all your local users,\n" \ "# use another authentication method.\n" staticbool authwarning = false;
#ifdef WIN32
save = _wsetlocale(category, NULL); if (!save)
pg_fatal("_wsetlocale() failed");
save = wcsdup(save); if (!save)
pg_fatal("out of memory"); #else
save = setlocale(category, NULL); if (!save)
pg_fatal("setlocale() failed");
save = pg_strdup(save); #endif return save;
}
/* *Restorethegloballocalereturnedbysave_global_locale().
*/ staticvoid
restore_global_locale(int category, save_locale_t save)
{ #ifdef WIN32 if (!_wsetlocale(category, save))
pg_fatal("failed to restore old locale"); #else if (!setlocale(category, save))
pg_fatal("failed to restore old locale \"%s\"", save); #endif
free(save);
}
/* prepare the replacement line, except for possible comment and newline */ if (mark_as_comment)
appendPQExpBufferChar(newline, '#');
appendPQExpBuffer(newline, "%s = ", guc_name); if (guc_value_requires_quotes(guc_value))
appendPQExpBuffer(newline, "'%s'", escape_quotes(guc_value)); else
appendPQExpBufferStr(newline, guc_value);
for (i = 0; lines[i]; i++)
{ constchar *where; constchar *namestart;
/* *Lookforalineassigningtoguc_name.Typicallyitwillbe *precededby'#',butthatmightnotbethecaseifa-cswitch *overridesapreviousassignment.Weallowleadingwhitespacetoo, *althoughnormallytherewouldn'tbeany.
*/
where = lines[i]; while (*where == '#' || isspace((unsignedchar) *where))
where++; if (pg_strncasecmp(where, guc_name, namelen) != 0) continue;
namestart = where;
where += namelen; while (isspace((unsignedchar) *where))
where++; if (*where != '=') continue;
/* found it -- let's use the canonical casing shown in the file */
memcpy(&newline->data[mark_as_comment ? 1 : 0], namestart, namelen);
/* now append the original comment if any */
where = strrchr(where, '#'); if (where)
{ /* *Wetrytopreserveoriginalindentation,whichistedious. *oldindentandnewindentaremeasuredinde-tab-ifiedcolumns.
*/ constchar *ptr; int oldindent = 0; int newindent;
for (ptr = lines[i]; ptr < where; ptr++)
{ if (*ptr == '\t')
oldindent += 8 - (oldindent % 8); else
oldindent++;
} /* ignore the possibility of tabs in guc_value */
newindent = newline->len; /* append appropriate tabs and spaces, forcing at least one */
oldindent = Max(oldindent, newindent + 1); while (newindent < oldindent)
{ int newindent_if_tab = newindent + 8 - (newindent % 8);
if (newindent_if_tab <= oldindent)
{
appendPQExpBufferChar(newline, '\t');
newindent = newindent_if_tab;
} else
{
appendPQExpBufferChar(newline, ' ');
newindent++;
}
} /* and finally append the old comment */
appendPQExpBufferStr(newline, where); /* we'll have appended the original newline; don't add another */
} else
appendPQExpBufferChar(newline, '\n');
/* *DecideifweshouldquoteareplacementGUCvalue.Wearen'ttootense *here,butwe'dliketoavoidquotingsimpleidentifiersandnumbers *withunits,whicharecommoncases.
*/ staticbool
guc_value_requires_quotes(constchar *guc_value)
{ /* Don't use <ctype.h> macros here, they might accept too much */ #define LETTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" #define DIGITS "0123456789"
if (*guc_value == '\0') returntrue; /* empty string must be quoted */ if (strchr(LETTERS, *guc_value))
{ if (strspn(guc_value, LETTERS DIGITS) == strlen(guc_value)) returnfalse; /* it's an identifier */ returntrue; /* nope */
} if (strchr(DIGITS, *guc_value))
{ /* skip over digits */
guc_value += strspn(guc_value, DIGITS); /* there can be zero or more unit letters after the digits */ if (strspn(guc_value, LETTERS) == strlen(guc_value)) returnfalse; /* it's a number, possibly with units */ returntrue; /* nope */
} returntrue; /* all else must be quoted */
}
/* *getthelinesfromatextfile * *Theresultisamalloc'darrayofindividuallymalloc'dstrings.
*/ staticchar **
readfile(constchar *path)
{ char **result;
FILE *infile;
StringInfoData line; int maxlines; int n;
if ((infile = fopen(path, "r")) == NULL)
pg_fatal("could not open file \"%s\" for reading: %m", path);
n = 0; while (pg_get_line_buf(infile, &line))
{ /* make sure there will be room for a trailing NULL pointer */ if (n >= maxlines - 1)
{
maxlines *= 2;
result = (char **) pg_realloc(result, maxlines * sizeof(char *));
}
if ((out_file = fopen(path, "w")) == NULL)
pg_fatal("could not open file \"%s\" for writing: %m", path); for (line = lines; *line != NULL; line++)
{ if (fputs(*line, out_file) < 0)
pg_fatal("could not write file \"%s\": %m", path);
free(*line);
} if (fclose(out_file))
pg_fatal("could not close file \"%s\": %m", path);
free(lines);
}
/* *cleanupanyfileswecreatedonfailure *ifwecreatedthedatadirectoryremoveittoo
*/ staticvoid
cleanup_directories_atexit(void)
{ if (success) return;
if (!noclean)
{ if (made_new_pgdata)
{
pg_log_info("removing data directory \"%s\"", pg_data); if (!rmtree(pg_data, true))
pg_log_error("failed to remove data directory");
} elseif (found_existing_pgdata)
{
pg_log_info("removing contents of data directory \"%s\"",
pg_data); if (!rmtree(pg_data, false))
pg_log_error("failed to remove contents of data directory");
}
if (made_new_xlogdir)
{
pg_log_info("removing WAL directory \"%s\"", xlog_dir); if (!rmtree(xlog_dir, true))
pg_log_error("failed to remove WAL directory");
} elseif (found_existing_xlogdir)
{
pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir); if (!rmtree(xlog_dir, false))
pg_log_error("failed to remove contents of WAL directory");
} /* otherwise died during startup, do nothing! */
} else
{ if (made_new_pgdata || found_existing_pgdata)
pg_log_info("data directory \"%s\" not removed at user's request",
pg_data);
if (made_new_xlogdir || found_existing_xlogdir)
pg_log_info("WAL directory \"%s\" not removed at user's request",
xlog_dir);
}
}
#ifndef WIN32 if (geteuid() == 0) /* 0 is root's uid */
{
pg_log_error("cannot be run as root");
pg_log_error_hint("Please log in (using, e.g., \"su\") as the (unprivileged) user that will own the server process."); exit(1);
} #endif
/* *gettheencodingidforagivenencodingname
*/ staticint
get_encoding_id(constchar *encoding_name)
{ int enc;
if (encoding_name && *encoding_name)
{ if ((enc = pg_valid_server_encoding(encoding_name)) >= 0) return enc;
}
pg_fatal("\"%s\" is not a valid server encoding name",
encoding_name ? encoding_name : "(null)");
}
/* *checkthatgiveninputfileexists
*/ staticvoid
check_input(char *path)
{ struct stat statbuf;
if (stat(path, &statbuf) != 0)
{ if (errno == ENOENT)
{
pg_log_error("file \"%s\" does not exist", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
} else
{
pg_log_error("could not access file \"%s\": %m", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
} exit(1);
} if (!S_ISREG(statbuf.st_mode))
{
pg_log_error("file \"%s\" is not a regular file", path);
pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L."); exit(1);
}
}
for (i = 0; i < bufslen; i++)
{ /* Use same amount of memory, independent of BLCKSZ */
test_buffs = (trial_bufs[i] * 8192) / BLCKSZ; if (test_buffs <= ok_buffers)
{
test_buffs = ok_buffers; break;
}
if (test_specific_config_settings(n_connections, n_av_slots, test_buffs)) break;
}
n_buffers = test_buffs;
/* *Nowreplaceanythingthat'soverriddenvia-cswitches.
*/ for (gnames = extra_guc_names, gvalues = extra_guc_values;
gnames != NULL; /* assume lists have the same length */
gnames = gnames->next, gvalues = gvalues->next)
{
conflines = replace_guc_value(conflines, gnames->str,
gvalues->str, false);
}
/* ... and write out the finished postgresql.conf file */
snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
writefile(path, conflines); if (chmod(path, pg_file_create_mode) != 0)
pg_fatal("could not change permissions of \"%s\": %m", path);
/* postgresql.auto.conf */
conflines = pg_malloc_array(char *, 3);
conflines[0] = pg_strdup("# Do not edit this file manually!\n");
conflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
conflines[2] = NULL;
if (strcmp(headerline, *bki_lines) != 0)
{
pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
bki_file, PG_VERSION);
pg_log_error_hint("Specify the correct path using the option -L."); exit(1);
}
/* Substitute for various symbols used in the BKI file */
if (!pwf)
pg_fatal("could not open file \"%s\" for reading: %m",
pwfilename);
pwd1 = pg_get_line(pwf, NULL); if (!pwd1)
{ if (ferror(pwf))
pg_fatal("could not read password from file \"%s\": %m",
pwfilename); else
pg_fatal("password file \"%s\" is empty",
pwfilename);
}
fclose(pwf);
/* *fillinextradescriptiondata
*/ staticvoid
setup_description(FILE *cmdfd)
{ /* Create default descriptions for operator implementation functions */
PG_CMD_PUTS("WITH funcdescs AS ( " "SELECT p.oid as p_oid, o.oid as o_oid, oprname " "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) " "INSERT INTO pg_description " " SELECT p_oid, 'pg_proc'::regclass, 0, " " 'implementation of ' || oprname || ' operator' " " FROM funcdescs " " WHERE NOT EXISTS (SELECT 1 FROM pg_description " " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass) " " AND NOT EXISTS (SELECT 1 FROM pg_description " " WHERE objoid = o_oid AND classoid = 'pg_operator'::regclass" " AND description LIKE 'deprecated%');\n\n");
}
/* *cleaneverythingupintemplate1
*/ staticvoid
vacuum_db(FILE *cmdfd)
{ /* Run analyze before VACUUM so the statistics are frozen. */
PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
}
/* *template0shouldn'thaveanycollation-dependentobjects,sounsetthe *collationversion.Thisdisablescollationversioncheckswhenmaking *anewdatabasefromit.
*/
PG_CMD_PUTS("UPDATE pg_database SET datcollversion = NULL WHERE datname = 'template0';\n\n");
/* *Whilewearehere,dosetthecollationversionontemplate1.
*/
PG_CMD_PUTS("UPDATE pg_database SET datcollversion = pg_database_collation_actual_version(oid) WHERE datname = 'template1';\n\n");
/* *Explicitlyrevokepubliccreate-schemaandcreate-temp-tableprivileges *intemplate1andtemplate0;elsethelatterwouldbeonbydefault
*/
PG_CMD_PUTS("REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n");
PG_CMD_PUTS("REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n");
PG_CMD_PUTS("COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n");
/* Don't let Windows' non-ASCII locale names in. */ if (locale && !pg_is_ascii(locale))
pg_fatal("locale name \"%s\" contains non-ASCII characters", locale);
if (canonname)
*canonname = NULL; /* in case of failure */
save = save_global_locale(category);
/* for setlocale() call */ if (!locale)
locale = "";
/* set the locale with setlocale, to see if it accepts it. */
res = setlocale(category, locale);
/* save canonical name if requested. */ if (res && canonname)
*canonname = pg_strdup(res);
/* restore old value. */
restore_global_locale(category, save);
/* complain if locale wasn't valid */ if (res == NULL)
{ if (*locale)
{
pg_log_error("invalid locale name \"%s\"", locale);
pg_log_error_hint("If the locale name is specific to ICU, use --icu-locale."); exit(1);
} else
{ /* *Ifnorelevantswitchwasgivenoncommandline,localeisan *emptystring,whichisnottoohelpfultoreport.Presumably *setlocale()foundsomethingitdidnotlikeintheenvironment. *Ideallywe'dreportthebadenvironmentvariable,butsince *setlocale'sbehaviorisimplementation-specific,it'shardto *besurewhatitdidn'tlike.Printasafegenericmessage.
*/
pg_fatal("invalid locale settings; check LANG and LC_* environment variables");
}
}
/* Don't let Windows' non-ASCII locale names out. */ if (canonname && !pg_is_ascii(*canonname))
pg_fatal("locale name \"%s\" contains non-ASCII characters",
*canonname);
}
/* *checkifthechosenencodingmatchestheencodingrequiredbythelocale * *thisshouldmatchthesimilarcheckinthebackendcreatedb()function
*/ staticbool
check_locale_encoding(constchar *locale, int user_enc)
{ int locale_enc;
/* See notes in createdb() to understand these tests */ if (!(locale_enc == user_enc ||
locale_enc == PG_SQL_ASCII ||
locale_enc == -1 || #ifdef WIN32
user_enc == PG_UTF8 || #endif
user_enc == PG_SQL_ASCII))
{
pg_log_error("encoding mismatch");
pg_log_error_detail("The encoding you selected (%s) and the encoding that the " "selected locale uses (%s) do not match. This would lead to " "misbehavior in various character string processing functions.",
pg_encoding_to_char(user_enc),
pg_encoding_to_char(locale_enc));
pg_log_error_hint("Rerun %s and either do not specify an encoding explicitly, " "or choose a matching combination.",
progname); returnfalse;
} returntrue;
}
/* *checkifthechosenencodingmatchesissupportedbyICU * *thisshouldmatchthesimilarcheckinthebackendcreatedb()function
*/ staticbool
check_icu_locale_encoding(int user_enc)
{ if (!(is_encoding_supported_by_icu(user_enc)))
{
pg_log_error("encoding mismatch");
pg_log_error_detail("The encoding you selected (%s) is not supported with the ICU provider.",
pg_encoding_to_char(user_enc));
pg_log_error_hint("Rerun %s and either do not specify an encoding explicitly, " "or choose a matching combination.",
progname); returnfalse;
} returntrue;
}
/* *ABCP47languagetagdoesn'thaveaclearly-definedupperlimit(cf. *RFC5646section4.4).Additionally,inolderICUversions, *uloc_toLanguageTag()doesn'talwaysreturntheultimatelengthonthe *firstcall,necessitatingaloop.
*/
langtag = pg_malloc(buflen); while (true)
{
status = U_ZERO_ERROR;
uloc_toLanguageTag(loc_str, langtag, buflen, strict, &status);
/* try again if the buffer is not large enough */ if (status == U_BUFFER_OVERFLOW_ERROR ||
status == U_STRING_NOT_TERMINATED_WARNING)
{
buflen = buflen * 2;
langtag = pg_realloc(langtag, buflen); continue;
}
break;
}
if (U_FAILURE(status))
{
pg_free(langtag);
pg_fatal("could not convert locale name \"%s\" to language tag: %s",
loc_str, u_errorName(status));
}
return langtag; #else
pg_fatal("ICU is not supported in this build"); return NULL; /* keep compiler quiet */ #endif
}
/* validate that we can extract the language */
status = U_ZERO_ERROR;
uloc_getLanguage(loc_str, lang, ULOC_LANG_CAPACITY, &status); if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING)
{
pg_fatal("could not get language from locale \"%s\": %s",
loc_str, u_errorName(status)); return;
}
/* check for special language name */ if (strcmp(lang, "") == 0 ||
strcmp(lang, "root") == 0 || strcmp(lang, "und") == 0)
found = true;
/* search for matching language within ICU */ for (int32_t i = 0; !found && i < uloc_countAvailable(); i++)
{ constchar *otherloc = uloc_getAvailable(i); char otherlang[ULOC_LANG_CAPACITY];
status = U_ZERO_ERROR;
uloc_getLanguage(otherloc, otherlang, ULOC_LANG_CAPACITY, &status); if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING) continue;
if (strcmp(lang, otherlang) == 0)
found = true;
}
if (!found)
pg_fatal("locale \"%s\" has unknown language \"%s\"",
loc_str, lang); #else
pg_fatal("ICU is not supported in this build"); #endif
}
if (locale_provider != COLLPROVIDER_LIBC && datlocale == NULL)
pg_fatal("locale must be specified if provider is %s",
collprovider_name(locale_provider));
/* canonicalize to a language tag */
langtag = icu_language_tag(datlocale);
printf(_("Using language tag \"%s\" for ICU locale \"%s\".\n"),
langtag, datlocale);
pg_free(datlocale);
datlocale = langtag;
icu_validate_locale(datlocale);
/* *Insupportedbuilds,theICUlocaleIDwillbeopenedduring *post-bootstrapinitialization,whichwillperformextrachecks.
*/ #ifndef USE_ICU
pg_fatal("ICU is not supported in this build"); #endif
}
}
/* *printhelptext
*/ staticvoid
usage(constchar *progname)
{
printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
printf(_("Usage:\n"));
printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
printf(_("\nOptions:\n"));
printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
printf(_(" -g, --allow-group-access allow group read/execute on data directory\n"));
printf(_(" --icu-locale=LOCALE set ICU locale ID for new databases\n"));
printf(_(" --icu-rules=RULES set additional ICU collation rules for new databases\n"));
printf(_(" -k, --data-checksums use data page checksums\n"));
printf(_(" --locale=LOCALE set default locale for new databases\n"));
printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n" " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n" " set default locale in the respective category for\n" " new databases (default taken from environment)\n"));
printf(_(" --no-locale equivalent to --locale=C\n"));
printf(_(" --builtin-locale=LOCALE\n" " set builtin locale name for new databases\n"));
printf(_(" --locale-provider={builtin|libc|icu}\n" " set default locale provider for new databases\n"));
printf(_(" --no-data-checksums do not use data page checksums\n"));
printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
printf(_(" -T, --text-search-config=CFG\n" " default text search configuration\n"));
printf(_(" -U, --username=NAME database superuser name\n"));
printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
printf(_(" -X, --waldir=WALDIR location for the write-ahead log directory\n"));
printf(_(" --wal-segsize=SIZE size of WAL segments, in megabytes\n"));
printf(_("\nLess commonly used options:\n"));
printf(_(" -c, --set NAME=VALUE override default setting for server parameter\n"));
printf(_(" -d, --debug generate lots of debugging output\n"));
printf(_(" --discard-caches set debug_discard_caches=1\n"));
printf(_(" -L DIRECTORY where to find the input files\n"));
printf(_(" -n, --no-clean do not clean up after errors\n"));
printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
printf(_(" --no-sync-data-files do not sync files within database directories\n"));
printf(_(" --no-instructions do not print instructions for next steps\n"));
printf(_(" -s, --show show internal settings, then exit\n"));
printf(_(" --sync-method=METHOD set method for syncing files to disk\n"));
printf(_(" -S, --sync-only only sync database files to disk, then exit\n"));
printf(_("\nOther options:\n"));
printf(_(" -V, --version output version information, then exit\n"));
printf(_(" -?, --help show this help, then exit\n"));
printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n" "is used.\n"));
printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
}
if (!pg_data)
{
pgdata_get_env = getenv("PGDATA"); if (pgdata_get_env && strlen(pgdata_get_env))
{ /* PGDATA found */
pg_data = pg_strdup(pgdata_get_env);
} else
{
pg_log_error("no data directory specified");
pg_log_error_hint("You must identify the directory where the data for this database system " "will reside. Do this with either the invocation option -D or the " "environment variable PGDATA."); exit(1);
}
}
if (find_my_exec(argv0, full_path) < 0)
strlcpy(full_path, progname, sizeof(full_path));
if (ret == -1)
pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"", "postgres", progname, full_path); else
pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s", "postgres", full_path, progname);
}
if (!share_path)
{
share_path = pg_malloc(MAXPGPATH);
get_share_path(backend_exec, share_path);
} elseif (!is_absolute_path(share_path))
pg_fatal("input file location must be an absolute path");
if (ctype_enc == -1)
{ /* Couldn't recognize the locale's codeset */
pg_log_error("could not find suitable encoding for locale \"%s\"",
lc_ctype);
pg_log_error_hint("Rerun %s with the -E option.", progname);
pg_log_error_hint("Try \"%s --help\" for more information.", progname); exit(1);
} elseif (!pg_valid_server_encoding_id(ctype_enc))
{ /* *Werecognizedit,butit'snotalegalserverencoding.On *Windows,UTF-8workswithanylocale,sowecanfallbackto *UTF-8.
*/ #ifdef WIN32
encodingid = PG_UTF8;
printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n" "The default database encoding will be set to \"%s\" instead.\n"),
pg_encoding_to_char(ctype_enc),
pg_encoding_to_char(encodingid)); #else
pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
lc_ctype, pg_encoding_to_char(ctype_enc));
pg_log_error_detail("Encoding \"%s\" is not allowed as a server-side encoding.",
pg_encoding_to_char(ctype_enc));
pg_log_error_hint("Rerun %s with a different locale selection.",
progname); exit(1); #endif
} else
{
encodingid = ctype_enc;
printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
pg_encoding_to_char(encodingid));
}
} else
encodingid = get_encoding_id(encoding);
if (!check_locale_encoding(lc_ctype, encodingid) ||
!check_locale_encoding(lc_collate, encodingid)) exit(1); /* check_locale_encoding printed the error */
/* the following are not valid on Windows */ #ifndef WIN32
pqsignal(SIGHUP, trapsig);
pqsignal(SIGQUIT, trapsig);
/* Ignore SIGPIPE when writing to backend, so we can clean up */
pqsignal(SIGPIPE, SIG_IGN);
/* Prevent SIGSYS so we can probe for kernel calls that might not work */
pqsignal(SIGSYS, SIG_IGN); #endif
}
void
create_data_directory(void)
{ int ret;
switch ((ret = pg_check_dir(pg_data)))
{ case0: /* PGDATA not there, must create it */
printf(_("creating directory %s ... "),
pg_data);
fflush(stdout);
if (pg_mkdir_p(pg_data, pg_dir_create_mode) != 0)
pg_fatal("could not create directory \"%s\": %m", pg_data); else
check_ok();
made_new_pgdata = true; break;
case1: /* Present but empty, fix permissions and use it */
printf(_("fixing permissions on existing directory %s ... "),
pg_data);
fflush(stdout);
if (chmod(pg_data, pg_dir_create_mode) != 0)
pg_fatal("could not change permissions of directory \"%s\": %m",
pg_data); else
check_ok();
found_existing_pgdata = true; break;
case2: case3: case4: /* Present and not empty */
pg_log_error("directory \"%s\" exists but is not empty", pg_data); if (ret != 4)
warn_on_mount_point(ret); else
pg_log_error_hint("If you want to create a new database system, either remove or empty " "the directory \"%s\" or run %s " "with an argument other than \"%s\".",
pg_data, progname, pg_data); exit(1); /* no further message needed */
/* Create WAL directory, and symlink if required */ void
create_xlog_or_symlink(void)
{ char *subdirloc;
/* form name of the place for the subdirectory or symlink */
subdirloc = psprintf("%s/pg_wal", pg_data);
if (xlog_dir)
{ int ret;
/* clean up xlog directory name, check it's absolute */
canonicalize_path(xlog_dir); if (!is_absolute_path(xlog_dir))
pg_fatal("WAL directory location must be an absolute path");
/* check if the specified xlog directory exists/is empty */ switch ((ret = pg_check_dir(xlog_dir)))
{ case0: /* xlog directory not there, must create it */
printf(_("creating directory %s ... "),
xlog_dir);
fflush(stdout);
if (pg_mkdir_p(xlog_dir, pg_dir_create_mode) != 0)
pg_fatal("could not create directory \"%s\": %m",
xlog_dir); else
check_ok();
made_new_xlogdir = true; break;
case1: /* Present but empty, fix permissions and use it */
printf(_("fixing permissions on existing directory %s ... "),
xlog_dir);
fflush(stdout);
if (chmod(xlog_dir, pg_dir_create_mode) != 0)
pg_fatal("could not change permissions of directory \"%s\": %m",
xlog_dir); else
check_ok();
found_existing_xlogdir = true; break;
case2: case3: case4: /* Present and not empty */
pg_log_error("directory \"%s\" exists but is not empty", xlog_dir); if (ret != 4)
warn_on_mount_point(ret); else
pg_log_error_hint("If you want to store the WAL there, either remove or empty the directory \"%s\".",
xlog_dir); exit(1);
if (symlink(xlog_dir, subdirloc) != 0)
pg_fatal("could not create symbolic link \"%s\": %m",
subdirloc);
} else
{ /* Without -X option, just make the subdirectory normally */ if (mkdir(subdirloc, pg_dir_create_mode) < 0)
pg_fatal("could not create directory \"%s\": %m",
subdirloc);
}
free(subdirloc);
}
void
warn_on_mount_point(int error)
{ if (error == 2)
pg_log_error_detail("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point."); elseif (error == 3)
pg_log_error_detail("It contains a lost+found directory, perhaps due to it being a mount point.");
pg_log_error_hint("Using a mount point directly as the data directory is not recommended.\n" "Create a subdirectory under the mount point.");
}
void
initialize_data_directory(void)
{
PG_CMD_DECL;
PQExpBufferData cmd; int i;
if (optind < argc)
{
pg_log_error("too many command-line arguments (first is \"%s\")",
argv[optind]);
pg_log_error_hint("Try \"%s --help\" for more information.", progname); exit(1);
}
if (builtin_locale_specified && locale_provider != COLLPROVIDER_BUILTIN)
pg_fatal("%s cannot be specified unless locale provider \"%s\" is chosen", "--builtin-locale", "builtin");
if (icu_locale_specified && locale_provider != COLLPROVIDER_ICU)
pg_fatal("%s cannot be specified unless locale provider \"%s\" is chosen", "--icu-locale", "icu");
if (icu_rules && locale_provider != COLLPROVIDER_ICU)
pg_fatal("%s cannot be specified unless locale provider \"%s\" is chosen", "--icu-rules", "icu");
atexit(cleanup_directories_atexit);
/* If we only need to sync, just do it and exit */ if (sync_only)
{
setup_pgdata();
/* must check that directory is readable */ if (pg_check_dir(pg_data) <= 0)
pg_fatal("could not access directory \"%s\": %m", pg_data);
fputs(_("syncing data to disk ... "), stdout);
fflush(stdout);
sync_pgdata(pg_data, PG_VERSION_NUM, sync_method, sync_data_files);
check_ok(); return0;
}
if (pwprompt && pwfilename)
pg_fatal("password prompt and password file cannot be specified together");
if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
pg_fatal("argument of %s must be a power of two between 1 and 1024", "--wal-segsize");
get_restricted_token();
setup_pgdata();
setup_bin_paths(argv[0]);
effective_user = get_id(); if (!username)
username = effective_user;
if (strncmp(username, "pg_", 3) == 0)
pg_fatal("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
printf(_("The files belonging to this database system will be owned " "by user \"%s\".\n" "This user must also own the server process.\n\n"),
effective_user);
set_info_version();
setup_data_file_paths();
setup_locale_encoding();
setup_text_search();
printf("\n");
if (data_checksums)
printf(_("Data page checksums are enabled.\n")); else
printf(_("Data page checksums are disabled.\n"));
if (pwprompt || pwfilename)
get_su_pwd();
printf("\n");
initialize_data_directory();
if (do_sync)
{
fputs(_("syncing data to disk ... "), stdout);
fflush(stdout);
sync_pgdata(pg_data, PG_VERSION_NUM, sync_method, sync_data_files);
check_ok();
} else
printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
if (authwarning)
{
printf("\n");
pg_log_warning("enabling \"trust\" authentication for local connections");
pg_log_warning_hint("You can change this by editing pg_hba.conf or using the option -A, or " "--auth-local and --auth-host, the next time you run initdb.");
}
if (!noinstructions)
{ /* *Buildupashellcommandtotelltheuserhowtostarttheserver
*/
start_db_cmd = createPQExpBuffer();
/* Get directory specification used to start initdb ... */
strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
canonicalize_path(pg_ctl_path);
get_parent_directory(pg_ctl_path); /* ... and tag on pg_ctl instead */
join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
/* Convert the path to use native separators */
make_native_path(pg_ctl_path);
/* path to pg_ctl, properly quoted */
appendShellString(start_db_cmd, pg_ctl_path);
/* add -D switch, with properly quoted data directory */
appendPQExpBufferStr(start_db_cmd, " -D ");
appendShellString(start_db_cmd, pgdata_native);
/* add suggested -l switch and "start" command */ /* translator: This is a placeholder in a shell command. */
appendPQExpBuffer(start_db_cmd, " -l %s start", _("logfile"));
printf(_("\nSuccess. You can now start the database server using:\n\n" " %s\n\n"),
start_db_cmd->data);
destroyPQExpBuffer(start_db_cmd);
}
success = true; return0;
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.109 Sekunden
(vorverarbeitet am 2026-08-07)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.