PostgreSQL Source Code  git master
initdb.c File Reference
#include "postgres_fe.h"
#include <dirent.h>
#include <fcntl.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include "sys/mman.h"
#include "access/xlog_internal.h"
#include "catalog/pg_authid_d.h"
#include "catalog/pg_class_d.h"
#include "catalog/pg_collation_d.h"
#include "catalog/pg_database_d.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/logging.h"
#include "common/pg_prng.h"
#include "common/restricted_token.h"
#include "common/string.h"
#include "common/username.h"
#include "fe_utils/string_utils.h"
#include "getopt_long.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
Include dependency graph for initdb.c:

Go to the source code of this file.

Data Structures

struct  tsearch_config_match
 

Macros

#define AUTHTRUST_WARNING
 
#define PG_CMD_DECL   char cmd[MAXPGPATH]; FILE *cmdfd
 
#define PG_CMD_OPEN
 
#define PG_CMD_CLOSE
 
#define PG_CMD_PUTS(line)
 
#define PG_CMD_PRINTF(fmt, ...)
 
#define MIN_BUFS_FOR_CONNS(nconns)   ((nconns) * 10)
 

Functions

const char * select_default_timezone (const char *share_path)
 
static char ** replace_token (char **lines, const char *token, const char *replacement)
 
static char ** readfile (const char *path)
 
static void writefile (char *path, char **lines)
 
static FILE * popen_check (const char *command, const char *mode)
 
static char * get_id (void)
 
static int get_encoding_id (const char *encoding_name)
 
static void set_input (char **dest, const char *filename)
 
static void check_input (char *path)
 
static void write_version_file (const char *extrapath)
 
static void set_null_conf (void)
 
static void test_config_settings (void)
 
static void setup_config (void)
 
static void bootstrap_template1 (void)
 
static void setup_auth (FILE *cmdfd)
 
static void get_su_pwd (void)
 
static void setup_depend (FILE *cmdfd)
 
static void setup_run_file (FILE *cmdfd, const char *filename)
 
static void setup_description (FILE *cmdfd)
 
static void setup_collation (FILE *cmdfd)
 
static void setup_privileges (FILE *cmdfd)
 
static void set_info_version (void)
 
static void setup_schema (FILE *cmdfd)
 
static void load_plpgsql (FILE *cmdfd)
 
static void vacuum_db (FILE *cmdfd)
 
static void make_template0 (FILE *cmdfd)
 
static void make_postgres (FILE *cmdfd)
 
static void trapsig (SIGNAL_ARGS)
 
static void check_ok (void)
 
static char * escape_quotes (const char *src)
 
static char * escape_quotes_bki (const char *src)
 
static int locale_date_order (const char *locale)
 
static void check_locale_name (int category, const char *locale, char **canonname)
 
static bool check_locale_encoding (const char *locale, int user_enc)
 
static void setlocales (void)
 
static void usage (const char *progname)
 
void setup_pgdata (void)
 
void setup_bin_paths (const char *argv0)
 
void setup_data_file_paths (void)
 
void setup_locale_encoding (void)
 
void setup_signals (void)
 
void setup_text_search (void)
 
void create_data_directory (void)
 
void create_xlog_or_symlink (void)
 
void warn_on_mount_point (int error)
 
void initialize_data_directory (void)
 
static void cleanup_directories_atexit (void)
 
static char * encodingid_to_string (int enc)
 
static const char * find_matching_ts_config (const char *lc_type)
 
static const char * choose_dsm_implementation (void)
 
static char * pretty_wal_size (int segment_count)
 
static size_t my_strftime (char *s, size_t max, const char *fmt, const struct tm *tm)
 
static bool check_icu_locale_encoding (int user_enc)
 
static void check_authmethod_unspecified (const char **authmethod)
 
static void check_authmethod_valid (const char *authmethod, const char *const *valid_methods, const char *conntype)
 
static void check_need_password (const char *authmethodlocal, const char *authmethodhost)
 
int main (int argc, char *argv[])
 

Variables

static const char *const auth_methods_host []
 
static const char *const auth_methods_local []
 
static char * share_path = NULL
 
static char * pg_data = NULL
 
static char * encoding = NULL
 
static char * locale = NULL
 
static char * lc_collate = NULL
 
static char * lc_ctype = NULL
 
static char * lc_monetary = NULL
 
static char * lc_numeric = NULL
 
static char * lc_time = NULL
 
static char * lc_messages = NULL
 
static char locale_provider = COLLPROVIDER_LIBC
 
static char * icu_locale = NULL
 
static const char * default_text_search_config = NULL
 
static char * username = NULL
 
static bool pwprompt = false
 
static char * pwfilename = NULL
 
static char * superuser_password = NULL
 
static const char * authmethodhost = NULL
 
static const char * authmethodlocal = NULL
 
static bool debug = false
 
static bool noclean = false
 
static bool noinstructions = false
 
static bool do_sync = true
 
static bool sync_only = false
 
static bool show_setting = false
 
static bool data_checksums = false
 
static char * xlog_dir = NULL
 
static char * str_wal_segment_size_mb = NULL
 
static int wal_segment_size_mb
 
static const char * progname
 
static int encodingid
 
static char * bki_file
 
static char * hba_file
 
static char * ident_file
 
static char * conf_file
 
static char * dictionary_file
 
static char * info_schema_file
 
static char * features_file
 
static char * system_constraints_file
 
static char * system_functions_file
 
static char * system_views_file
 
static bool success = false
 
static bool made_new_pgdata = false
 
static bool found_existing_pgdata = false
 
static bool made_new_xlogdir = false
 
static bool found_existing_xlogdir = false
 
static char infoversion [100]
 
static bool caught_signal = false
 
static bool output_failed = false
 
static int output_errno = 0
 
static char * pgdata_native
 
static int n_connections = 10
 
static int n_buffers = 50
 
static const char * dynamic_shared_memory_type = NULL
 
static const char * default_timezone = NULL
 
static bool authwarning = false
 
static const char * boot_options = "-F -c log_checkpoints=false"
 
static const char * backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true -c log_checkpoints=false"
 
static char * extra_options = ""
 
static const char *const subdirs []
 
static char bin_path [MAXPGPATH]
 
static char backend_exec [MAXPGPATH]
 
static const struct tsearch_config_match tsearch_config_languages []
 

Macro Definition Documentation

◆ AUTHTRUST_WARNING

#define AUTHTRUST_WARNING
Value:
"# 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"

Definition at line 190 of file initdb.c.

◆ MIN_BUFS_FOR_CONNS

#define MIN_BUFS_FOR_CONNS (   nconns)    ((nconns) * 10)

◆ PG_CMD_CLOSE

#define PG_CMD_CLOSE
Value:
do { \
if (pclose_check(cmdfd)) \
exit(1); /* message already printed by pclose_check */ \
} while (0)
int pclose_check(FILE *stream)
Definition: exec.c:422

Definition at line 304 of file initdb.c.

◆ PG_CMD_DECL

#define PG_CMD_DECL   char cmd[MAXPGPATH]; FILE *cmdfd

Definition at line 295 of file initdb.c.

◆ PG_CMD_OPEN

#define PG_CMD_OPEN
Value:
do { \
cmdfd = popen_check(cmd, "w"); \
if (cmdfd == NULL) \
exit(1); /* message already printed by popen_check */ \
} while (0)
static FILE * popen_check(const char *command, const char *mode)
Definition: initdb.c:488

Definition at line 297 of file initdb.c.

◆ PG_CMD_PRINTF

#define PG_CMD_PRINTF (   fmt,
  ... 
)
Value:
do { \
if (fprintf(cmdfd, fmt, __VA_ARGS__) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)
static int output_errno
Definition: initdb.c:178
static void const char * fmt
static void const char fflush(stdout)
#define fprintf
Definition: port.h:242

Definition at line 316 of file initdb.c.

◆ PG_CMD_PUTS

#define PG_CMD_PUTS (   line)
Value:
do { \
if (fputs(line, cmdfd) < 0 || fflush(cmdfd) < 0) \
output_failed = true, output_errno = errno; \
} while (0)

Definition at line 310 of file initdb.c.

Function Documentation

◆ bootstrap_template1()

static void bootstrap_template1 ( void  )
static

Definition at line 1262 of file initdb.c.

1263 {
1264  PG_CMD_DECL;
1265  char **line;
1266  char **bki_lines;
1267  char headerline[MAXPGPATH];
1268  char buf[64];
1269 
1270  printf(_("running bootstrap script ... "));
1271  fflush(stdout);
1272 
1273  bki_lines = readfile(bki_file);
1274 
1275  /* Check that bki file appears to be of the right version */
1276 
1277  snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1278  PG_MAJORVERSION);
1279 
1280  if (strcmp(headerline, *bki_lines) != 0)
1281  {
1282  pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
1283  bki_file, PG_VERSION);
1284  pg_log_error_hint("Specify the correct path using the option -L.");
1285  exit(1);
1286  }
1287 
1288  /* Substitute for various symbols used in the BKI file */
1289 
1290  sprintf(buf, "%d", NAMEDATALEN);
1291  bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1292 
1293  sprintf(buf, "%d", (int) sizeof(Pointer));
1294  bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1295 
1296  bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1297  (sizeof(Pointer) == 4) ? "i" : "d");
1298 
1299  bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1300  FLOAT8PASSBYVAL ? "true" : "false");
1301 
1302  bki_lines = replace_token(bki_lines, "POSTGRES",
1304 
1305  bki_lines = replace_token(bki_lines, "ENCODING",
1307 
1308  bki_lines = replace_token(bki_lines, "LC_COLLATE",
1310 
1311  bki_lines = replace_token(bki_lines, "LC_CTYPE",
1313 
1314  bki_lines = replace_token(bki_lines, "ICU_LOCALE",
1315  locale_provider == COLLPROVIDER_ICU ? escape_quotes_bki(icu_locale) : "_null_");
1316 
1317  sprintf(buf, "%c", locale_provider);
1318  bki_lines = replace_token(bki_lines, "LOCALE_PROVIDER", buf);
1319 
1320  /* Also ensure backend isn't confused by this environment var: */
1321  unsetenv("PGCLIENTENCODING");
1322 
1323  snprintf(cmd, sizeof(cmd),
1324  "\"%s\" --boot -X %d %s %s %s %s",
1325  backend_exec,
1326  wal_segment_size_mb * (1024 * 1024),
1327  data_checksums ? "-k" : "",
1329  debug ? "-d 5" : "");
1330 
1331 
1332  PG_CMD_OPEN;
1333 
1334  for (line = bki_lines; *line != NULL; line++)
1335  {
1336  PG_CMD_PUTS(*line);
1337  free(*line);
1338  }
1339 
1340  PG_CMD_CLOSE;
1341 
1342  free(bki_lines);
1343 
1344  check_ok();
1345 }
char * Pointer
Definition: c.h:467
#define FLOAT8PASSBYVAL
Definition: c.h:619
#define _(x)
Definition: elog.c:91
#define free(a)
Definition: header.h:65
static char * escape_quotes_bki(const char *src)
Definition: initdb.c:343
static char * lc_collate
Definition: initdb.c:130
#define PG_CMD_PUTS(line)
Definition: initdb.c:310
static char * lc_ctype
Definition: initdb.c:131
static char ** readfile(const char *path)
Definition: initdb.c:423
static bool debug
Definition: initdb.c:145
static char backend_exec[MAXPGPATH]
Definition: initdb.c:241
static bool data_checksums
Definition: initdb.c:151
#define PG_CMD_CLOSE
Definition: initdb.c:304
#define PG_CMD_DECL
Definition: initdb.c:295
static char locale_provider
Definition: initdb.c:136
static int wal_segment_size_mb
Definition: initdb.c:154
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:370
#define PG_CMD_OPEN
Definition: initdb.c:297
static char * username
Definition: initdb.c:139
static const char * boot_options
Definition: initdb.c:207
static char * icu_locale
Definition: initdb.c:137
static int encodingid
Definition: initdb.c:159
static char * encodingid_to_string(int enc)
Definition: initdb.c:577
static void check_ok(void)
Definition: initdb.c:1823
static char * extra_options
Definition: initdb.c:211
static char * bki_file
Definition: initdb.c:160
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
#define NAMEDATALEN
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:67
#define sprintf
Definition: port.h:240
#define snprintf
Definition: port.h:238
#define printf(...)
Definition: port.h:244
#define unsetenv(x)
Definition: win32_port.h:535

References _, backend_exec, bki_file, boot_options, buf, check_ok(), data_checksums, debug, encodingid, encodingid_to_string(), escape_quotes_bki(), exit(), extra_options, fflush(), FLOAT8PASSBYVAL, free, icu_locale, lc_collate, lc_ctype, locale_provider, MAXPGPATH, NAMEDATALEN, PG_CMD_CLOSE, PG_CMD_DECL, PG_CMD_OPEN, PG_CMD_PUTS, pg_log_error, pg_log_error_hint, printf, readfile(), replace_token(), snprintf, sprintf, generate_unaccent_rules::stdout, unsetenv, username, and wal_segment_size_mb.

Referenced by initialize_data_directory().

◆ check_authmethod_unspecified()

static void check_authmethod_unspecified ( const char **  authmethod)
static

Definition at line 2145 of file initdb.c.

2146 {
2147  if (*authmethod == NULL)
2148  {
2149  authwarning = true;
2150  *authmethod = "trust";
2151  }
2152 }
static bool authwarning
Definition: initdb.c:195

References authwarning.

Referenced by main().

◆ check_authmethod_valid()

static void check_authmethod_valid ( const char *  authmethod,
const char *const *  valid_methods,
const char *  conntype 
)
static

Definition at line 2155 of file initdb.c.

2156 {
2157  const char *const *p;
2158 
2159  for (p = valid_methods; *p; p++)
2160  {
2161  if (strcmp(authmethod, *p) == 0)
2162  return;
2163  /* with space = param */
2164  if (strchr(authmethod, ' '))
2165  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2166  return;
2167  }
2168 
2169  pg_fatal("invalid authentication method \"%s\" for \"%s\" connections",
2170  authmethod, conntype);
2171 }
#define pg_fatal(...)

References pg_fatal.

Referenced by main().

◆ check_icu_locale_encoding()

static bool check_icu_locale_encoding ( int  user_enc)
static

Definition at line 2012 of file initdb.c.

2013 {
2014  if (!(is_encoding_supported_by_icu(user_enc)))
2015  {
2016  pg_log_error("encoding mismatch");
2017  pg_log_error_detail("The encoding you selected (%s) is not supported with the ICU provider.",
2018  pg_encoding_to_char(user_enc));
2019  pg_log_error_hint("Rerun %s and either do not specify an encoding explicitly, "
2020  "or choose a matching combination.",
2021  progname);
2022  return false;
2023  }
2024  return true;
2025 }
bool is_encoding_supported_by_icu(int encoding)
Definition: encnames.c:462
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
static const char * progname
Definition: initdb.c:158
#define pg_log_error_detail(...)
Definition: logging.h:109

References is_encoding_supported_by_icu(), pg_encoding_to_char(), pg_log_error, pg_log_error_detail, pg_log_error_hint, and progname.

Referenced by setup_locale_encoding().

◆ check_input()

static void check_input ( char *  path)
static

Definition at line 734 of file initdb.c.

735 {
736  struct stat statbuf;
737 
738  if (stat(path, &statbuf) != 0)
739  {
740  if (errno == ENOENT)
741  {
742  pg_log_error("file \"%s\" does not exist", path);
743  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
744  }
745  else
746  {
747  pg_log_error("could not access file \"%s\": %m", path);
748  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
749  }
750  exit(1);
751  }
752  if (!S_ISREG(statbuf.st_mode))
753  {
754  pg_log_error("file \"%s\" is not a regular file", path);
755  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
756  exit(1);
757  }
758 }
#define stat
Definition: win32_port.h:286
#define S_ISREG(m)
Definition: win32_port.h:330

References exit(), pg_log_error, pg_log_error_hint, S_ISREG, stat::st_mode, and stat.

Referenced by setup_data_file_paths().

◆ check_locale_encoding()

static bool check_locale_encoding ( const char *  locale,
int  user_enc 
)
static

Definition at line 1977 of file initdb.c.

1978 {
1979  int locale_enc;
1980 
1981  locale_enc = pg_get_encoding_from_locale(locale, true);
1982 
1983  /* See notes in createdb() to understand these tests */
1984  if (!(locale_enc == user_enc ||
1985  locale_enc == PG_SQL_ASCII ||
1986  locale_enc == -1 ||
1987 #ifdef WIN32
1988  user_enc == PG_UTF8 ||
1989 #endif
1990  user_enc == PG_SQL_ASCII))
1991  {
1992  pg_log_error("encoding mismatch");
1993  pg_log_error_detail("The encoding you selected (%s) and the encoding that the "
1994  "selected locale uses (%s) do not match. This would lead to "
1995  "misbehavior in various character string processing functions.",
1996  pg_encoding_to_char(user_enc),
1997  pg_encoding_to_char(locale_enc));
1998  pg_log_error_hint("Rerun %s and either do not specify an encoding explicitly, "
1999  "or choose a matching combination.",
2000  progname);
2001  return false;
2002  }
2003  return true;
2004 }
static char * locale
Definition: initdb.c:129
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428

References locale, pg_encoding_to_char(), pg_get_encoding_from_locale(), pg_log_error, pg_log_error_detail, pg_log_error_hint, PG_SQL_ASCII, PG_UTF8, and progname.

Referenced by setup_locale_encoding().

◆ check_locale_name()

static void check_locale_name ( int  category,
const char *  locale,
char **  canonname 
)
static

Definition at line 1920 of file initdb.c.

1921 {
1922  char *save;
1923  char *res;
1924 
1925  if (canonname)
1926  *canonname = NULL; /* in case of failure */
1927 
1928  save = setlocale(category, NULL);
1929  if (!save)
1930  pg_fatal("setlocale() failed");
1931 
1932  /* save may be pointing at a modifiable scratch variable, so copy it. */
1933  save = pg_strdup(save);
1934 
1935  /* for setlocale() call */
1936  if (!locale)
1937  locale = "";
1938 
1939  /* set the locale with setlocale, to see if it accepts it. */
1940  res = setlocale(category, locale);
1941 
1942  /* save canonical name if requested. */
1943  if (res && canonname)
1944  *canonname = pg_strdup(res);
1945 
1946  /* restore old value. */
1947  if (!setlocale(category, save))
1948  pg_fatal("failed to restore old locale \"%s\"", save);
1949  free(save);
1950 
1951  /* complain if locale wasn't valid */
1952  if (res == NULL)
1953  {
1954  if (*locale)
1955  pg_fatal("invalid locale name \"%s\"", locale);
1956  else
1957  {
1958  /*
1959  * If no relevant switch was given on command line, locale is an
1960  * empty string, which is not too helpful to report. Presumably
1961  * setlocale() found something it did not like in the environment.
1962  * Ideally we'd report the bad environment variable, but since
1963  * setlocale's behavior is implementation-specific, it's hard to
1964  * be sure what it didn't like. Print a safe generic message.
1965  */
1966  pg_fatal("invalid locale settings; check LANG and LC_* environment variables");
1967  }
1968  }
1969 }
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define setlocale(a, b)
Definition: win32_port.h:464

References free, locale, pg_fatal, pg_strdup(), res, and setlocale.

Referenced by setlocales().

◆ check_need_password()

static void check_need_password ( const char *  authmethodlocal,
const char *  authmethodhost 
)
static

Definition at line 2174 of file initdb.c.

2175 {
2176  if ((strcmp(authmethodlocal, "md5") == 0 ||
2177  strcmp(authmethodlocal, "password") == 0 ||
2178  strcmp(authmethodlocal, "scram-sha-256") == 0) &&
2179  (strcmp(authmethodhost, "md5") == 0 ||
2180  strcmp(authmethodhost, "password") == 0 ||
2181  strcmp(authmethodhost, "scram-sha-256") == 0) &&
2182  !(pwprompt || pwfilename))
2183  pg_fatal("must specify a password for the superuser to enable password authentication");
2184 }
static const char * authmethodhost
Definition: initdb.c:143
static char * pwfilename
Definition: initdb.c:141
static bool pwprompt
Definition: initdb.c:140
static const char * authmethodlocal
Definition: initdb.c:144

References authmethodhost, authmethodlocal, pg_fatal, pwfilename, and pwprompt.

Referenced by main().

◆ check_ok()

static void check_ok ( void  )
static

Definition at line 1823 of file initdb.c.

1824 {
1825  if (caught_signal)
1826  {
1827  printf(_("caught signal\n"));
1828  fflush(stdout);
1829  exit(1);
1830  }
1831  else if (output_failed)
1832  {
1833  printf(_("could not write to child process: %s\n"),
1835  fflush(stdout);
1836  exit(1);
1837  }
1838  else
1839  {
1840  /* all seems well */
1841  printf(_("ok\n"));
1842  fflush(stdout);
1843  }
1844 }
static bool output_failed
Definition: initdb.c:177
static bool caught_signal
Definition: initdb.c:176
#define strerror
Definition: port.h:251

References _, caught_signal, exit(), fflush(), output_errno, output_failed, printf, generate_unaccent_rules::stdout, and strerror.

Referenced by adjust_data_dir(), bootstrap_template1(), check_cluster_versions(), check_for_aclitem_data_type_usage(), check_for_composite_data_type_usage(), check_for_incompatible_polymorphics(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_new_tablespace_dir(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), copy_subdir_files(), copy_xact_xlog_xid(), create_data_directory(), create_new_objects(), create_script_for_old_cluster_deletion(), create_xlog_or_symlink(), disable_old_cluster(), generate_old_dump(), initialize_data_directory(), main(), old_11_check_for_sql_identifier_data_type_usage(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), prepare_new_cluster(), prepare_new_globals(), remove_new_subdir(), report_extension_updates(), set_frozenxids(), setup_config(), and transfer_all_new_tablespaces().

◆ choose_dsm_implementation()

static const char* choose_dsm_implementation ( void  )
static

Definition at line 817 of file initdb.c.

818 {
819 #if defined(HAVE_SHM_OPEN) && !defined(__sun__)
820  int ntries = 10;
821  pg_prng_state prng_state;
822 
823  /* Initialize prng; this function is its only user in this program. */
824  pg_prng_seed(&prng_state, (uint64) (getpid() ^ time(NULL)));
825 
826  while (ntries > 0)
827  {
828  uint32 handle;
829  char name[64];
830  int fd;
831 
832  handle = pg_prng_uint32(&prng_state);
833  snprintf(name, 64, "/PostgreSQL.%u", handle);
834  if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
835  {
836  close(fd);
837  shm_unlink(name);
838  return "posix";
839  }
840  if (errno != EEXIST)
841  break;
842  --ntries;
843  }
844 #endif
845 
846 #ifdef WIN32
847  return "windows";
848 #else
849  return "sysv";
850 #endif
851 }
unsigned int uint32
Definition: c.h:490
const char * name
Definition: encode.c:571
#define close(a)
Definition: win32.h:12
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:191
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
static int fd(const char *x, int i)
Definition: preproc-init.c:105

References close, fd(), name, pg_prng_seed(), pg_prng_uint32(), and snprintf.

Referenced by test_config_settings().

◆ cleanup_directories_atexit()

static void cleanup_directories_atexit ( void  )
static

Definition at line 505 of file initdb.c.

506 {
507  if (success)
508  return;
509 
510  if (!noclean)
511  {
512  if (made_new_pgdata)
513  {
514  pg_log_info("removing data directory \"%s\"", pg_data);
515  if (!rmtree(pg_data, true))
516  pg_log_error("failed to remove data directory");
517  }
518  else if (found_existing_pgdata)
519  {
520  pg_log_info("removing contents of data directory \"%s\"",
521  pg_data);
522  if (!rmtree(pg_data, false))
523  pg_log_error("failed to remove contents of data directory");
524  }
525 
526  if (made_new_xlogdir)
527  {
528  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
529  if (!rmtree(xlog_dir, true))
530  pg_log_error("failed to remove WAL directory");
531  }
532  else if (found_existing_xlogdir)
533  {
534  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
535  if (!rmtree(xlog_dir, false))
536  pg_log_error("failed to remove contents of WAL directory");
537  }
538  /* otherwise died during startup, do nothing! */
539  }
540  else
541  {
543  pg_log_info("data directory \"%s\" not removed at user's request",
544  pg_data);
545 
547  pg_log_info("WAL directory \"%s\" not removed at user's request",
548  xlog_dir);
549  }
550 }
static bool noclean
Definition: initdb.c:146
static bool found_existing_pgdata
Definition: initdb.c:172
static bool found_existing_xlogdir
Definition: initdb.c:174
static char * xlog_dir
Definition: initdb.c:152
static bool success
Definition: initdb.c:170
static bool made_new_xlogdir
Definition: initdb.c:173
static char * pg_data
Definition: initdb.c:127
static bool made_new_pgdata
Definition: initdb.c:171
#define pg_log_info(...)
Definition: logging.h:124
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50

References found_existing_pgdata, found_existing_xlogdir, made_new_pgdata, made_new_xlogdir, noclean, pg_data, pg_log_error, pg_log_info, rmtree(), success, and xlog_dir.

Referenced by main().

◆ create_data_directory()

void create_data_directory ( void  )

Definition at line 2466 of file initdb.c.

2467 {
2468  int ret;
2469 
2470  switch ((ret = pg_check_dir(pg_data)))
2471  {
2472  case 0:
2473  /* PGDATA not there, must create it */
2474  printf(_("creating directory %s ... "),
2475  pg_data);
2476  fflush(stdout);
2477 
2479  pg_fatal("could not create directory \"%s\": %m", pg_data);
2480  else
2481  check_ok();
2482 
2483  made_new_pgdata = true;
2484  break;
2485 
2486  case 1:
2487  /* Present but empty, fix permissions and use it */
2488  printf(_("fixing permissions on existing directory %s ... "),
2489  pg_data);
2490  fflush(stdout);
2491 
2492  if (chmod(pg_data, pg_dir_create_mode) != 0)
2493  pg_fatal("could not change permissions of directory \"%s\": %m",
2494  pg_data);
2495  else
2496  check_ok();
2497 
2498  found_existing_pgdata = true;
2499  break;
2500 
2501  case 2:
2502  case 3:
2503  case 4:
2504  /* Present and not empty */
2505  pg_log_error("directory \"%s\" exists but is not empty", pg_data);
2506  if (ret != 4)
2507  warn_on_mount_point(ret);
2508  else
2509  pg_log_error_hint("If you want to create a new database system, either remove or empty "
2510  "the directory \"%s\" or run %s "
2511  "with an argument other than \"%s\".",
2513  exit(1); /* no further message needed */
2514 
2515  default:
2516  /* Trouble accessing directory */
2517  pg_fatal("could not access directory \"%s\": %m", pg_data);
2518  }
2519 }
int pg_dir_create_mode
Definition: file_perm.c:18
void warn_on_mount_point(int error)
Definition: initdb.c:2607
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:33

References _, check_ok(), exit(), fflush(), found_existing_pgdata, made_new_pgdata, pg_check_dir(), pg_data, pg_dir_create_mode, pg_fatal, pg_log_error, pg_log_error_hint, pg_mkdir_p(), printf, progname, generate_unaccent_rules::stdout, and warn_on_mount_point().

Referenced by initialize_data_directory().

◆ create_xlog_or_symlink()

void create_xlog_or_symlink ( void  )

Definition at line 2524 of file initdb.c.

2525 {
2526  char *subdirloc;
2527 
2528  /* form name of the place for the subdirectory or symlink */
2529  subdirloc = psprintf("%s/pg_wal", pg_data);
2530 
2531  if (xlog_dir)
2532  {
2533  int ret;
2534 
2535  /* clean up xlog directory name, check it's absolute */
2537  if (!is_absolute_path(xlog_dir))
2538  pg_fatal("WAL directory location must be an absolute path");
2539 
2540  /* check if the specified xlog directory exists/is empty */
2541  switch ((ret = pg_check_dir(xlog_dir)))
2542  {
2543  case 0:
2544  /* xlog directory not there, must create it */
2545  printf(_("creating directory %s ... "),
2546  xlog_dir);
2547  fflush(stdout);
2548 
2550  pg_fatal("could not create directory \"%s\": %m",
2551  xlog_dir);
2552  else
2553  check_ok();
2554 
2555  made_new_xlogdir = true;
2556  break;
2557 
2558  case 1:
2559  /* Present but empty, fix permissions and use it */
2560  printf(_("fixing permissions on existing directory %s ... "),
2561  xlog_dir);
2562  fflush(stdout);
2563 
2564  if (chmod(xlog_dir, pg_dir_create_mode) != 0)
2565  pg_fatal("could not change permissions of directory \"%s\": %m",
2566  xlog_dir);
2567  else
2568  check_ok();
2569 
2570  found_existing_xlogdir = true;
2571  break;
2572 
2573  case 2:
2574  case 3:
2575  case 4:
2576  /* Present and not empty */
2577  pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
2578  if (ret != 4)
2579  warn_on_mount_point(ret);
2580  else
2581  pg_log_error_hint("If you want to store the WAL there, either remove or empty the directory \"%s\".",
2582  xlog_dir);
2583  exit(1);
2584 
2585  default:
2586  /* Trouble accessing directory */
2587  pg_fatal("could not access directory \"%s\": %m", xlog_dir);
2588  }
2589 
2590  if (symlink(xlog_dir, subdirloc) != 0)
2591  pg_fatal("could not create symbolic link \"%s\": %m",
2592  subdirloc);
2593  }
2594  else
2595  {
2596  /* Without -X option, just make the subdirectory normally */
2597  if (mkdir(subdirloc, pg_dir_create_mode) < 0)
2598  pg_fatal("could not create directory \"%s\": %m",
2599  subdirloc);
2600  }
2601 
2602  free(subdirloc);
2603 }
#define is_absolute_path(filename)
Definition: port.h:103
void canonicalize_path(char *path)
Definition: path.c:264
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define mkdir(a, b)
Definition: win32_port.h:80
#define symlink(oldpath, newpath)
Definition: win32_port.h:237

References _, canonicalize_path(), check_ok(), exit(), fflush(), found_existing_xlogdir, free, is_absolute_path, made_new_xlogdir, mkdir, pg_check_dir(), pg_data, pg_dir_create_mode, pg_fatal, pg_log_error, pg_log_error_hint, pg_mkdir_p(), printf, psprintf(), generate_unaccent_rules::stdout, symlink, warn_on_mount_point(), and xlog_dir.

Referenced by initialize_data_directory().

◆ encodingid_to_string()

static char* encodingid_to_string ( int  enc)
static

Definition at line 577 of file initdb.c.

578 {
579  char result[20];
580 
581  sprintf(result, "%d", enc);
582  return pg_strdup(result);
583 }
enc

References enc, pg_strdup(), and sprintf.

Referenced by bootstrap_template1().

◆ escape_quotes()

static char * escape_quotes ( const char *  src)
static

Definition at line 327 of file initdb.c.

328 {
329  char *result = escape_single_quotes_ascii(src);
330 
331  if (!result)
332  pg_fatal("out of memory");
333  return result;
334 }
char * escape_single_quotes_ascii(const char *src)
Definition: quotes.c:33

References escape_single_quotes_ascii(), and pg_fatal.

Referenced by escape_quotes_bki(), setup_auth(), setup_config(), setup_privileges(), and setup_schema().

◆ escape_quotes_bki()

static char * escape_quotes_bki ( const char *  src)
static

Definition at line 343 of file initdb.c.

344 {
345  char *result;
346  char *data = escape_quotes(src);
347  char *resultp;
348  char *datap;
349 
350  result = (char *) pg_malloc(strlen(data) + 3);
351  resultp = result;
352  *resultp++ = '\'';
353  for (datap = data; *datap; datap++)
354  *resultp++ = *datap;
355  *resultp++ = '\'';
356  *resultp = '\0';
357 
358  free(data);
359  return result;
360 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static char * escape_quotes(const char *src)
Definition: initdb.c:327
const void * data

References data, escape_quotes(), free, and pg_malloc().

Referenced by bootstrap_template1().

◆ find_matching_ts_config()

static const char* find_matching_ts_config ( const char *  lc_type)
static

Definition at line 679 of file initdb.c.

680 {
681  int i;
682  char *langname,
683  *ptr;
684 
685  /*
686  * Convert lc_ctype to a language name by stripping everything after an
687  * underscore (usual case) or a hyphen (Windows "locale name"; see
688  * comments at IsoLocaleName()).
689  *
690  * XXX Should ' ' be a stop character? This would select "norwegian" for
691  * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
692  * should also accept the "nn" and "nb" Unix locales.
693  *
694  * Just for paranoia, we also stop at '.' or '@'.
695  */
696  if (lc_type == NULL)
697  langname = pg_strdup("");
698  else
699  {
700  ptr = langname = pg_strdup(lc_type);
701  while (*ptr &&
702  *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
703  ptr++;
704  *ptr = '\0';
705  }
706 
707  for (i = 0; tsearch_config_languages[i].tsconfname; i++)
708  {
709  if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
710  {
711  free(langname);
713  }
714  }
715 
716  free(langname);
717  return NULL;
718 }
static const struct tsearch_config_match tsearch_config_languages[]
Definition: initdb.c:612
int i
Definition: isn.c:73
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * tsconfname
Definition: initdb.c:608

References free, i, tsearch_config_match::langname, pg_strcasecmp(), pg_strdup(), tsearch_config_match::tsconfname, and tsearch_config_languages.

Referenced by setup_text_search().

◆ get_encoding_id()

static int get_encoding_id ( const char *  encoding_name)
static

Definition at line 589 of file initdb.c.

590 {
591  int enc;
592 
593  if (encoding_name && *encoding_name)
594  {
595  if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
596  return enc;
597  }
598  pg_fatal("\"%s\" is not a valid server encoding name",
599  encoding_name ? encoding_name : "(null)");
600 }
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500

References enc, pg_fatal, and pg_valid_server_encoding().

Referenced by setup_locale_encoding().

◆ get_id()

static char * get_id ( void  )
static

Definition at line 558 of file initdb.c.

559 {
560  const char *username;
561 
562 #ifndef WIN32
563  if (geteuid() == 0) /* 0 is root's uid */
564  {
565  pg_log_error("cannot be run as root");
566  pg_log_error_hint("Please log in (using, e.g., \"su\") as the (unprivileged) user that will own the server process.");
567  exit(1);
568  }
569 #endif
570 
572 
573  return pg_strdup(username);
574 }
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74

References exit(), get_user_name_or_exit(), pg_log_error, pg_log_error_hint, pg_strdup(), progname, and username.

Referenced by main().

◆ get_su_pwd()

static void get_su_pwd ( void  )
static

Definition at line 1368 of file initdb.c.

1369 {
1370  char *pwd1;
1371 
1372  if (pwprompt)
1373  {
1374  /*
1375  * Read password from terminal
1376  */
1377  char *pwd2;
1378 
1379  printf("\n");
1380  fflush(stdout);
1381  pwd1 = simple_prompt("Enter new superuser password: ", false);
1382  pwd2 = simple_prompt("Enter it again: ", false);
1383  if (strcmp(pwd1, pwd2) != 0)
1384  {
1385  fprintf(stderr, _("Passwords didn't match.\n"));
1386  exit(1);
1387  }
1388  free(pwd2);
1389  }
1390  else
1391  {
1392  /*
1393  * Read password from file
1394  *
1395  * Ideally this should insist that the file not be world-readable.
1396  * However, this option is mainly intended for use on Windows where
1397  * file permissions may not exist at all, so we'll skip the paranoia
1398  * for now.
1399  */
1400  FILE *pwf = fopen(pwfilename, "r");
1401 
1402  if (!pwf)
1403  pg_fatal("could not open file \"%s\" for reading: %m",
1404  pwfilename);
1405  pwd1 = pg_get_line(pwf, NULL);
1406  if (!pwd1)
1407  {
1408  if (ferror(pwf))
1409  pg_fatal("could not read password from file \"%s\": %m",
1410  pwfilename);
1411  else
1412  pg_fatal("password file \"%s\" is empty",
1413  pwfilename);
1414  }
1415  fclose(pwf);
1416 
1417  (void) pg_strip_crlf(pwd1);
1418  }
1419 
1420  superuser_password = pwd1;
1421 }
static char * superuser_password
Definition: initdb.c:142
char * pg_get_line(FILE *stream, PromptInterruptContext *prompt_ctx)
Definition: pg_get_line.c:59
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
int pg_strip_crlf(char *str)
Definition: string.c:155

References _, exit(), fflush(), fprintf, free, pg_fatal, pg_get_line(), pg_strip_crlf(), printf, pwfilename, pwprompt, simple_prompt(), generate_unaccent_rules::stdout, and superuser_password.

Referenced by main().

◆ initialize_data_directory()

void initialize_data_directory ( void  )

Definition at line 2620 of file initdb.c.

2621 {
2622  PG_CMD_DECL;
2623  int i;
2624 
2625  setup_signals();
2626 
2627  /*
2628  * Set mask based on requested PGDATA permissions. pg_mode_mask, and
2629  * friends like pg_dir_create_mode, are set to owner-only by default and
2630  * then updated if -g is passed in by calling SetDataDirectoryCreatePerm()
2631  * when parsing our options (see above).
2632  */
2633  umask(pg_mode_mask);
2634 
2636 
2638 
2639  /* Create required subdirectories (other than pg_wal) */
2640  printf(_("creating subdirectories ... "));
2641  fflush(stdout);
2642 
2643  for (i = 0; i < lengthof(subdirs); i++)
2644  {
2645  char *path;
2646 
2647  path = psprintf("%s/%s", pg_data, subdirs[i]);
2648 
2649  /*
2650  * The parent directory already exists, so we only need mkdir() not
2651  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
2652  */
2653  if (mkdir(path, pg_dir_create_mode) < 0)
2654  pg_fatal("could not create directory \"%s\": %m", path);
2655 
2656  free(path);
2657  }
2658 
2659  check_ok();
2660 
2661  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2662  write_version_file(NULL);
2663 
2664  /* Select suitable configuration settings */
2665  set_null_conf();
2667 
2668  /* Now create all the text config files */
2669  setup_config();
2670 
2671  /* Bootstrap template1 */
2673 
2674  /*
2675  * Make the per-database PG_VERSION for template1 only after init'ing it
2676  */
2677  write_version_file("base/1");
2678 
2679  /*
2680  * Create the stuff we don't need to use bootstrap mode for, using a
2681  * backend running in simple standalone mode.
2682  */
2683  fputs(_("performing post-bootstrap initialization ... "), stdout);
2684  fflush(stdout);
2685 
2686  snprintf(cmd, sizeof(cmd),
2687  "\"%s\" %s %s template1 >%s",
2689  DEVNULL);
2690 
2691  PG_CMD_OPEN;
2692 
2693  setup_auth(cmdfd);
2694 
2696 
2698 
2699  setup_depend(cmdfd);
2700 
2701  /*
2702  * Note that no objects created after setup_depend() will be "pinned".
2703  * They are all droppable at the whim of the DBA.
2704  */
2705 
2707 
2708  setup_description(cmdfd);
2709 
2710  setup_collation(cmdfd);
2711 
2713 
2714  setup_privileges(cmdfd);
2715 
2716  setup_schema(cmdfd);
2717 
2718  load_plpgsql(cmdfd);
2719 
2720  vacuum_db(cmdfd);
2721 
2722  make_template0(cmdfd);
2723 
2724  make_postgres(cmdfd);
2725 
2726  PG_CMD_CLOSE;
2727 
2728  check_ok();
2729 }
#define lengthof(array)
Definition: c.h:772
int pg_mode_mask
Definition: file_perm.c:25
static void setup_depend(FILE *cmdfd)
Definition: initdb.c:1427
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1482
void create_data_directory(void)
Definition: initdb.c:2466
static void bootstrap_template1(void)
Definition: initdb.c:1262
static void setup_run_file(FILE *cmdfd, const char *filename)
Definition: initdb.c:1440
static const char * backend_options
Definition: initdb.c:208
static void setup_auth(FILE *cmdfd)
Definition: initdb.c:1351
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:1779
static void test_config_settings(void)
Definition: initdb.c:859
static void setup_config(void)
Definition: initdb.c:992
static void setup_privileges(FILE *cmdfd)
Definition: initdb.c:1517
static void write_version_file(const char *extrapath)
Definition: initdb.c:765
void setup_signals(void)
Definition: initdb.c:2437
static char * system_views_file
Definition: initdb.c:169
static void setup_description(FILE *cmdfd)
Definition: initdb.c:1461
static void vacuum_db(FILE *cmdfd)
Definition: initdb.c:1714
static const char *const subdirs[]
Definition: initdb.c:213
void create_xlog_or_symlink(void)
Definition: initdb.c:2524
static char * system_functions_file
Definition: initdb.c:168
static char * dictionary_file
Definition: initdb.c:164
static void setup_schema(FILE *cmdfd)
Definition: initdb.c:1685
static char * system_constraints_file
Definition: initdb.c:167
static void set_null_conf(void)
Definition: initdb.c:788
static void make_template0(FILE *cmdfd)
Definition: initdb.c:1724
static void load_plpgsql(FILE *cmdfd)
Definition: initdb.c:1705
#define DEVNULL
Definition: port.h:160

References _, backend_exec, backend_options, bootstrap_template1(), check_ok(), create_data_directory(), create_xlog_or_symlink(), DEVNULL, dictionary_file, extra_options, fflush(), free, i, lengthof, load_plpgsql(), make_postgres(), make_template0(), mkdir, PG_CMD_CLOSE, PG_CMD_DECL, PG_CMD_OPEN, pg_data, pg_dir_create_mode, pg_fatal, pg_mode_mask, printf, psprintf(), set_null_conf(), setup_auth(), setup_collation(), setup_config(), setup_depend(), setup_description(), setup_privileges(), setup_run_file(), setup_schema(), setup_signals(), snprintf, generate_unaccent_rules::stdout, subdirs, system_constraints_file, system_functions_file, system_views_file, test_config_settings(), vacuum_db(), and write_version_file().

Referenced by main().

◆ load_plpgsql()

static void load_plpgsql ( FILE *  cmdfd)
static

Definition at line 1705 of file initdb.c.

1706 {
1707  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
1708 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ locale_date_order()

static int locale_date_order ( const char *  locale)
static

Definition at line 1857 of file initdb.c.

1858 {
1859  struct tm testtime;
1860  char buf[128];
1861  char *posD;
1862  char *posM;
1863  char *posY;
1864  char *save;
1865  size_t res;
1866  int result;
1867 
1868  result = DATEORDER_MDY; /* default */
1869 
1870  save = setlocale(LC_TIME, NULL);
1871  if (!save)
1872  return result;
1873  save = pg_strdup(save);
1874 
1875  setlocale(LC_TIME, locale);
1876 
1877  memset(&testtime, 0, sizeof(testtime));
1878  testtime.tm_mday = 22;
1879  testtime.tm_mon = 10; /* November, should come out as "11" */
1880  testtime.tm_year = 133; /* 2033 */
1881 
1882  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
1883 
1884  setlocale(LC_TIME, save);
1885  free(save);
1886 
1887  if (res == 0)
1888  return result;
1889 
1890  posM = strstr(buf, "11");
1891  posD = strstr(buf, "22");
1892  posY = strstr(buf, "33");
1893 
1894  if (!posM || !posD || !posY)
1895  return result;
1896 
1897  if (posY < posM && posM < posD)
1898  result = DATEORDER_YMD;
1899  else if (posD < posM)
1900  result = DATEORDER_DMY;
1901  else
1902  result = DATEORDER_MDY;
1903 
1904  return result;
1905 }
static size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
Definition: initdb.c:1848
static struct pg_tm tm
Definition: localtime.c:104
#define DATEORDER_DMY
Definition: miscadmin.h:237
#define DATEORDER_MDY
Definition: miscadmin.h:238
#define DATEORDER_YMD
Definition: miscadmin.h:236

References buf, DATEORDER_DMY, DATEORDER_MDY, DATEORDER_YMD, free, locale, my_strftime(), pg_strdup(), res, setlocale, and tm.

Referenced by setup_config().

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 2733 of file initdb.c.

2734 {
2735  static struct option long_options[] = {
2736  {"pgdata", required_argument, NULL, 'D'},
2737  {"encoding", required_argument, NULL, 'E'},
2738  {"locale", required_argument, NULL, 1},
2739  {"lc-collate", required_argument, NULL, 2},
2740  {"lc-ctype", required_argument, NULL, 3},
2741  {"lc-monetary", required_argument, NULL, 4},
2742  {"lc-numeric", required_argument, NULL, 5},
2743  {"lc-time", required_argument, NULL, 6},
2744  {"lc-messages", required_argument, NULL, 7},
2745  {"no-locale", no_argument, NULL, 8},
2746  {"text-search-config", required_argument, NULL, 'T'},
2747  {"auth", required_argument, NULL, 'A'},
2748  {"auth-local", required_argument, NULL, 10},
2749  {"auth-host", required_argument, NULL, 11},
2750  {"pwprompt", no_argument, NULL, 'W'},
2751  {"pwfile", required_argument, NULL, 9},
2752  {"username", required_argument, NULL, 'U'},
2753  {"help", no_argument, NULL, '?'},
2754  {"version", no_argument, NULL, 'V'},
2755  {"debug", no_argument, NULL, 'd'},
2756  {"show", no_argument, NULL, 's'},
2757  {"noclean", no_argument, NULL, 'n'}, /* for backwards compatibility */
2758  {"no-clean", no_argument, NULL, 'n'},
2759  {"nosync", no_argument, NULL, 'N'}, /* for backwards compatibility */
2760  {"no-sync", no_argument, NULL, 'N'},
2761  {"no-instructions", no_argument, NULL, 13},
2762  {"sync-only", no_argument, NULL, 'S'},
2763  {"waldir", required_argument, NULL, 'X'},
2764  {"wal-segsize", required_argument, NULL, 12},
2765  {"data-checksums", no_argument, NULL, 'k'},
2766  {"allow-group-access", no_argument, NULL, 'g'},
2767  {"discard-caches", no_argument, NULL, 14},
2768  {"locale-provider", required_argument, NULL, 15},
2769  {"icu-locale", required_argument, NULL, 16},
2770  {NULL, 0, NULL, 0}
2771  };
2772 
2773  /*
2774  * options with no short version return a low integer, the rest return
2775  * their short version value
2776  */
2777  int c;
2778  int option_index;
2779  char *effective_user;
2780  PQExpBuffer start_db_cmd;
2781  char pg_ctl_path[MAXPGPATH];
2782 
2783  /*
2784  * Ensure that buffering behavior of stdout matches what it is in
2785  * interactive usage (at least on most platforms). This prevents
2786  * unexpected output ordering when, eg, output is redirected to a file.
2787  * POSIX says we must do this before any other usage of these files.
2788  */
2789  setvbuf(stdout, NULL, PG_IOLBF, 0);
2790 
2791  pg_logging_init(argv[0]);
2792  progname = get_progname(argv[0]);
2793  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
2794 
2795  if (argc > 1)
2796  {
2797  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2798  {
2799  usage(progname);
2800  exit(0);
2801  }
2802  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2803  {
2804  puts("initdb (PostgreSQL) " PG_VERSION);
2805  exit(0);
2806  }
2807  }
2808 
2809  /* process command-line options */
2810 
2811  while ((c = getopt_long(argc, argv, "A:dD:E:gkL:nNsST:U:WX:", long_options, &option_index)) != -1)
2812  {
2813  switch (c)
2814  {
2815  case 'A':
2817 
2818  /*
2819  * When ident is specified, use peer for local connections.
2820  * Mirrored, when peer is specified, use ident for TCP/IP
2821  * connections.
2822  */
2823  if (strcmp(authmethodhost, "ident") == 0)
2824  authmethodlocal = "peer";
2825  else if (strcmp(authmethodlocal, "peer") == 0)
2826  authmethodhost = "ident";
2827  break;
2828  case 10:
2830  break;
2831  case 11:
2833  break;
2834  case 'D':
2836  break;
2837  case 'E':
2839  break;
2840  case 'W':
2841  pwprompt = true;
2842  break;
2843  case 'U':
2845  break;
2846  case 'd':
2847  debug = true;
2848  printf(_("Running in debug mode.\n"));
2849  break;
2850  case 'n':
2851  noclean = true;
2852  printf(_("Running in no-clean mode. Mistakes will not be cleaned up.\n"));
2853  break;
2854  case 'N':
2855  do_sync = false;
2856  break;
2857  case 'S':
2858  sync_only = true;
2859  break;
2860  case 'k':
2861  data_checksums = true;
2862  break;
2863  case 'L':
2865  break;
2866  case 1:
2867  locale = pg_strdup(optarg);
2868  break;
2869  case 2:
2871  break;
2872  case 3:
2874  break;
2875  case 4:
2877  break;
2878  case 5:
2880  break;
2881  case 6:
2883  break;
2884  case 7:
2886  break;
2887  case 8:
2888  locale = "C";
2889  break;
2890  case 9:
2892  break;
2893  case 's':
2894  show_setting = true;
2895  break;
2896  case 'T':
2898  break;
2899  case 'X':
2901  break;
2902  case 12:
2904  break;
2905  case 13:
2906  noinstructions = true;
2907  break;
2908  case 'g':
2910  break;
2911  case 14:
2912  extra_options = psprintf("%s %s",
2913  extra_options,
2914  "-c debug_discard_caches=1");
2915  break;
2916  case 15:
2917  if (strcmp(optarg, "icu") == 0)
2918  locale_provider = COLLPROVIDER_ICU;
2919  else if (strcmp(optarg, "libc") == 0)
2920  locale_provider = COLLPROVIDER_LIBC;
2921  else
2922  pg_fatal("unrecognized locale provider: %s", optarg);
2923  break;
2924  case 16:
2926  break;
2927  default:
2928  /* getopt_long already emitted a complaint */
2929  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2930  exit(1);
2931  }
2932  }
2933 
2934 
2935  /*
2936  * Non-option argument specifies data directory as long as it wasn't
2937  * already specified with -D / --pgdata
2938  */
2939  if (optind < argc && !pg_data)
2940  {
2941  pg_data = pg_strdup(argv[optind]);
2942  optind++;
2943  }
2944 
2945  if (optind < argc)
2946  {
2947  pg_log_error("too many command-line arguments (first is \"%s\")",
2948  argv[optind]);
2949  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2950  exit(1);
2951  }
2952 
2953  if (icu_locale && locale_provider != COLLPROVIDER_ICU)
2954  pg_fatal("%s cannot be specified unless locale provider \"%s\" is chosen",
2955  "--icu-locale", "icu");
2956 
2958 
2959  /* If we only need to fsync, just do it and exit */
2960  if (sync_only)
2961  {
2962  setup_pgdata();
2963 
2964  /* must check that directory is readable */
2965  if (pg_check_dir(pg_data) <= 0)
2966  pg_fatal("could not access directory \"%s\": %m", pg_data);
2967 
2968  fputs(_("syncing data to disk ... "), stdout);
2969  fflush(stdout);
2970  fsync_pgdata(pg_data, PG_VERSION_NUM);
2971  check_ok();
2972  return 0;
2973  }
2974 
2975  if (pwprompt && pwfilename)
2976  pg_fatal("password prompt and password file cannot be specified together");
2977 
2980 
2983 
2985 
2986  /* set wal segment size */
2987  if (str_wal_segment_size_mb == NULL)
2988  wal_segment_size_mb = (DEFAULT_XLOG_SEG_SIZE) / (1024 * 1024);
2989  else
2990  {
2991  char *endptr;
2992 
2993  /* check that the argument is a number */
2994  wal_segment_size_mb = strtol(str_wal_segment_size_mb, &endptr, 10);
2995 
2996  /* verify that wal segment size is valid */
2997  if (endptr == str_wal_segment_size_mb || *endptr != '\0')
2998  pg_fatal("argument of --wal-segsize must be a number");
2999  if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
3000  pg_fatal("argument of --wal-segsize must be a power of 2 between 1 and 1024");
3001  }
3002 
3004 
3005  setup_pgdata();
3006 
3007  setup_bin_paths(argv[0]);
3008 
3009  effective_user = get_id();
3010  if (!username)
3011  username = effective_user;
3012 
3013  if (strncmp(username, "pg_", 3) == 0)
3014  pg_fatal("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
3015 
3016  printf(_("The files belonging to this database system will be owned "
3017  "by user \"%s\".\n"
3018  "This user must also own the server process.\n\n"),
3019  effective_user);
3020 
3021  set_info_version();
3022 
3024 
3026 
3028 
3029  printf("\n");
3030 
3031  if (data_checksums)
3032  printf(_("Data page checksums are enabled.\n"));
3033  else
3034  printf(_("Data page checksums are disabled.\n"));
3035 
3036  if (pwprompt || pwfilename)
3037  get_su_pwd();
3038 
3039  printf("\n");
3040 
3042 
3043  if (do_sync)
3044  {
3045  fputs(_("syncing data to disk ... "), stdout);
3046  fflush(stdout);
3047  fsync_pgdata(pg_data, PG_VERSION_NUM);
3048  check_ok();
3049  }
3050  else
3051  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3052 
3053  if (authwarning)
3054  {
3055  printf("\n");
3056  pg_log_warning("enabling \"trust\" authentication for local connections");
3057  pg_log_warning_hint("You can change this by editing pg_hba.conf or using the option -A, or "
3058  "--auth-local and --auth-host, the next time you run initdb.");
3059  }
3060 
3061  if (!noinstructions)
3062  {
3063  /*
3064  * Build up a shell command to tell the user how to start the server
3065  */
3066  start_db_cmd = createPQExpBuffer();
3067 
3068  /* Get directory specification used to start initdb ... */
3069  strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
3070  canonicalize_path(pg_ctl_path);
3071  get_parent_directory(pg_ctl_path);
3072  /* ... and tag on pg_ctl instead */
3073  join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
3074 
3075  /* Convert the path to use native separators */
3076  make_native_path(pg_ctl_path);
3077 
3078  /* path to pg_ctl, properly quoted */
3079  appendShellString(start_db_cmd, pg_ctl_path);
3080 
3081  /* add -D switch, with properly quoted data directory */
3082  appendPQExpBufferStr(start_db_cmd, " -D ");
3083  appendShellString(start_db_cmd, pgdata_native);
3084 
3085  /* add suggested -l switch and "start" command */
3086  /* translator: This is a placeholder in a shell command. */
3087  appendPQExpBuffer(start_db_cmd, " -l %s start", _("logfile"));
3088 
3089  printf(_("\nSuccess. You can now start the database server using:\n\n"
3090  " %s\n\n"),
3091  start_db_cmd->data);
3092 
3093  destroyPQExpBuffer(start_db_cmd);
3094  }
3095 
3096 
3097  success = true;
3098  return 0;
3099 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1204
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:460
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
#define PG_DIR_MODE_GROUP
Definition: file_perm.h:35
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
static void usage(const char *progname)
Definition: initdb.c:2097
static char * lc_time
Definition: initdb.c:134
static char * get_id(void)
Definition: initdb.c:558
static char * pgdata_native
Definition: initdb.c:179
static void check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
Definition: initdb.c:2155
static bool noinstructions
Definition: initdb.c:147
void initialize_data_directory(void)
Definition: initdb.c:2620
void setup_text_search(void)
Definition: initdb.c:2403
static char * share_path
Definition: initdb.c:124
void setup_bin_paths(const char *argv0)
Definition: initdb.c:2225
static void check_authmethod_unspecified(const char **authmethod)
Definition: initdb.c:2145
static char * str_wal_segment_size_mb
Definition: initdb.c:153
static const char *const auth_methods_host[]
Definition: initdb.c:85
void setup_locale_encoding(void)
Definition: initdb.c:2262
static const char *const auth_methods_local[]
Definition: initdb.c:107
static bool sync_only
Definition: initdb.c:149
static void check_need_password(const char *authmethodlocal, const char *authmethodhost)
Definition: initdb.c:2174
static bool do_sync
Definition: initdb.c:148
static void cleanup_directories_atexit(void)
Definition: initdb.c:505
static char * lc_messages
Definition: initdb.c:135
static void set_info_version(void)
Definition: initdb.c:1658
void setup_data_file_paths(void)
Definition: initdb.c:2359
static char * encoding
Definition: initdb.c:128
static char * lc_numeric
Definition: initdb.c:133
void setup_pgdata(void)
Definition: initdb.c:2188
static bool show_setting
Definition: initdb.c:150
static const char * default_text_search_config
Definition: initdb.c:138
static char * lc_monetary
Definition: initdb.c:132
static void get_su_pwd(void)
Definition: initdb.c:1368
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_log_warning_hint(...)
Definition: logging.h:121
#define DEFAULT_XLOG_SEG_SIZE
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define pg_log_warning(...)
Definition: pgfnames.c:24
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:219
#define PG_IOLBF
Definition: port.h:361
void get_parent_directory(char *path)
Definition: path.c:977
const char * get_progname(const char *argv0)
Definition: path.c:574
void make_native_path(char *filename)
Definition: path.c:167
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
char * c
void get_restricted_token(void)
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:429
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:96

References _, appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), auth_methods_host, auth_methods_local, authmethodhost, authmethodlocal, authwarning, canonicalize_path(), check_authmethod_unspecified(), check_authmethod_valid(), check_need_password(), check_ok(), cleanup_directories_atexit(), createPQExpBuffer(), PQExpBufferData::data, data_checksums, debug, default_text_search_config, DEFAULT_XLOG_SEG_SIZE, destroyPQExpBuffer(), do_sync, encoding, exit(), extra_options, fflush(), get_id(), get_parent_directory(), get_progname(), get_restricted_token(), get_su_pwd(), getopt_long(), icu_locale, initialize_data_directory(), IsValidWalSegSize, join_path_components(), lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, locale, locale_provider, make_native_path(), MAXPGPATH, no_argument, noclean, noinstructions, optarg, optind, pg_check_dir(), pg_data, PG_DIR_MODE_GROUP, pg_fatal, PG_IOLBF, pg_log_error, pg_log_error_hint, pg_log_warning, pg_log_warning_hint, pg_logging_init(), pg_strdup(), PG_TEXTDOMAIN, pgdata_native, printf, progname, psprintf(), pwfilename, pwprompt, required_argument, set_info_version(), set_pglocale_pgservice(), SetDataDirectoryCreatePerm(), setup_bin_paths(), setup_data_file_paths(), setup_locale_encoding(), setup_pgdata(), setup_text_search(), share_path, show_setting, generate_unaccent_rules::stdout, str_wal_segment_size_mb, strlcpy(), success, sync_only, usage(), username, wal_segment_size_mb, and xlog_dir.

◆ make_postgres()

static void make_postgres ( FILE *  cmdfd)
static

Definition at line 1779 of file initdb.c.

1780 {
1781  /*
1782  * Just as we did for template0, and for the same reasons, assign a fixed
1783  * OID to postgres and select the file_copy strategy.
1784  */
1785  PG_CMD_PUTS("CREATE DATABASE postgres OID = " CppAsString2(PostgresDbOid)
1786  " STRATEGY = file_copy;\n\n");
1787  PG_CMD_PUTS("COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n");
1788 }
#define CppAsString2(x)
Definition: c.h:311

References CppAsString2, and PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ make_template0()

static void make_template0 ( FILE *  cmdfd)
static

Definition at line 1724 of file initdb.c.

1725 {
1726  /*
1727  * pg_upgrade tries to preserve database OIDs across upgrades. It's smart
1728  * enough to drop and recreate a conflicting database with the same name,
1729  * but if the same OID were used for one system-created database in the
1730  * old cluster and a different system-created database in the new cluster,
1731  * it would fail. To avoid that, assign a fixed OID to template0 rather
1732  * than letting the server choose one.
1733  *
1734  * (Note that, while the user could have dropped and recreated these
1735  * objects in the old cluster, the problem scenario only exists if the OID
1736  * that is in use in the old cluster is also used in the new cluster - and
1737  * the new cluster should be the result of a fresh initdb.)
1738  *
1739  * We use "STRATEGY = file_copy" here because checkpoints during initdb
1740  * are cheap. "STRATEGY = wal_log" would generate more WAL, which would be
1741  * a little bit slower and make the new cluster a little bit bigger.
1742  */
1743  PG_CMD_PUTS("CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false"
1744  " OID = " CppAsString2(Template0DbOid)
1745  " STRATEGY = file_copy;\n\n");
1746 
1747  /*
1748  * template0 shouldn't have any collation-dependent objects, so unset
1749  * the collation version. This disables collation version checks when
1750  * making a new database from it.
1751  */
1752  PG_CMD_PUTS("UPDATE pg_database SET datcollversion = NULL WHERE datname = 'template0';\n\n");
1753 
1754  /*
1755  * While we are here, do set the collation version on template1.
1756  */
1757  PG_CMD_PUTS("UPDATE pg_database SET datcollversion = pg_database_collation_actual_version(oid) WHERE datname = 'template1';\n\n");
1758 
1759  /*
1760  * Explicitly revoke public create-schema and create-temp-table
1761  * privileges in template1 and template0; else the latter would be on
1762  * by default
1763  */
1764  PG_CMD_PUTS("REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n");
1765  PG_CMD_PUTS("REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n");
1766 
1767  PG_CMD_PUTS("COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n");
1768 
1769  /*
1770  * Finally vacuum to clean up dead rows in pg_database
1771  */
1772  PG_CMD_PUTS("VACUUM pg_database;\n\n");
1773 }

References CppAsString2, and PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ my_strftime()

static size_t my_strftime ( char *  s,
size_t  max,
const char *  fmt,
const struct tm tm 
)
inlinestatic

Definition at line 1848 of file initdb.c.

1849 {
1850  return strftime(s, max, fmt, tm);
1851 }

References fmt, and tm.

Referenced by locale_date_order().

◆ popen_check()

static FILE * popen_check ( const char *  command,
const char *  mode 
)
static

Definition at line 488 of file initdb.c.

489 {
490  FILE *cmdfd;
491 
492  fflush(NULL);
493  errno = 0;
494  cmdfd = popen(command, mode);
495  if (cmdfd == NULL)
496  pg_log_error("could not execute command \"%s\": %m", command);
497  return cmdfd;
498 }
static PgChecksumMode mode
Definition: pg_checksums.c:65

References fflush(), mode, and pg_log_error.

◆ pretty_wal_size()

static char* pretty_wal_size ( int  segment_count)
static

Definition at line 975 of file initdb.c.

976 {
977  int sz = wal_segment_size_mb * segment_count;
978  char *result = pg_malloc(14);
979 
980  if ((sz % 1024) == 0)
981  snprintf(result, 14, "%dGB", sz / 1024);
982  else
983  snprintf(result, 14, "%dMB", sz);
984 
985  return result;
986 }

References pg_malloc(), snprintf, and wal_segment_size_mb.

Referenced by setup_config().

◆ readfile()

static char ** readfile ( const char *  path)
static

Definition at line 423 of file initdb.c.

424 {
425  char **result;
426  FILE *infile;
427  StringInfoData line;
428  int maxlines;
429  int n;
430 
431  if ((infile = fopen(path, "r")) == NULL)
432  pg_fatal("could not open file \"%s\" for reading: %m", path);
433 
434  initStringInfo(&line);
435 
436  maxlines = 1024;
437  result = (char **) pg_malloc(maxlines * sizeof(char *));
438 
439  n = 0;
440  while (pg_get_line_buf(infile, &line))
441  {
442  /* make sure there will be room for a trailing NULL pointer */
443  if (n >= maxlines - 1)
444  {
445  maxlines *= 2;
446  result = (char **) pg_realloc(result, maxlines * sizeof(char *));
447  }
448 
449  result[n++] = pg_strdup(line.data);
450  }
451  result[n] = NULL;
452 
453  pfree(line.data);
454 
455  fclose(infile);
456 
457  return result;
458 }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
void pfree(void *pointer)
Definition: mcxt.c:1436
bool pg_get_line_buf(FILE *stream, StringInfo buf)
Definition: pg_get_line.c:95
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static void infile(const char *name)
Definition: zic.c:1243

References StringInfoData::data, infile(), initStringInfo(), pfree(), pg_fatal, pg_get_line_buf(), pg_malloc(), pg_realloc(), and pg_strdup().

Referenced by bootstrap_template1(), setup_config(), and setup_run_file().

◆ replace_token()

static char ** replace_token ( char **  lines,
const char *  token,
const char *  replacement 
)
static

Definition at line 370 of file initdb.c.

371 {
372  int numlines = 1;
373  int i;
374  char **result;
375  int toklen,
376  replen,
377  diff;
378 
379  for (i = 0; lines[i]; i++)
380  numlines++;
381 
382  result = (char **) pg_malloc(numlines * sizeof(char *));
383 
384  toklen = strlen(token);
385  replen = strlen(replacement);
386  diff = replen - toklen;
387 
388  for (i = 0; i < numlines; i++)
389  {
390  char *where;
391  char *newline;
392  int pre;
393 
394  /* just copy pointer if NULL or no change needed */
395  if (lines[i] == NULL || (where = strstr(lines[i], token)) == NULL)
396  {
397  result[i] = lines[i];
398  continue;
399  }
400 
401  /* if we get here a change is needed - set up new line */
402 
403  newline = (char *) pg_malloc(strlen(lines[i]) + diff + 1);
404 
405  pre = where - lines[i];
406 
407  memcpy(newline, lines[i], pre);
408 
409  memcpy(newline + pre, replacement, replen);
410 
411  strcpy(newline + pre + replen, lines[i] + pre + toklen);
412 
413  result[i] = newline;
414  }
415 
416  return result;
417 }
static chr newline(void)
Definition: regc_lex.c:1002

References i, newline(), and pg_malloc().

Referenced by bootstrap_template1(), and setup_config().

◆ select_default_timezone()

const char* select_default_timezone ( const char *  share_path)

Definition at line 1757 of file findtimezone.c.

1758 {
1759  const char *tzname;
1760 
1761  /* Initialize timezone directory path, if needed */
1762 #ifndef SYSTEMTZDIR
1763  snprintf(tzdirpath, sizeof(tzdirpath), "%s/timezone", share_path);
1764 #endif
1765 
1766  /* Check TZ environment variable */
1767  tzname = getenv("TZ");
1768  if (validate_zone(tzname))
1769  return tzname;
1770 
1771  /* Nope, so try to identify the system timezone */
1772  tzname = identify_system_timezone();
1773  if (validate_zone(tzname))
1774  return tzname;
1775 
1776  return NULL;
1777 }
static const char * identify_system_timezone(void)
Definition: findtimezone.c:331
static bool validate_zone(const char *tzname)
static char tzdirpath[MAXPGPATH]
Definition: findtimezone.c:27

References identify_system_timezone(), share_path, snprintf, tzdirpath, and validate_zone().

Referenced by test_config_settings().

◆ set_info_version()

static void set_info_version ( void  )
static

Definition at line 1658 of file initdb.c.

1659 {
1660  char *letterversion;
1661  long major = 0,
1662  minor = 0,
1663  micro = 0;
1664  char *endptr;
1665  char *vstr = pg_strdup(PG_VERSION);
1666  char *ptr;
1667 
1668  ptr = vstr + (strlen(vstr) - 1);
1669  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1670  ptr--;
1671  letterversion = ptr + 1;
1672  major = strtol(vstr, &endptr, 10);
1673  if (*endptr)
1674  minor = strtol(endptr + 1, &endptr, 10);
1675  if (*endptr)
1676  micro = strtol(endptr + 1, &endptr, 10);
1677  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1678  major, minor, micro, letterversion);
1679 }
static char infoversion[100]
Definition: initdb.c:175

References infoversion, pg_strdup(), and snprintf.

Referenced by main().

◆ set_input()

static void set_input ( char **  dest,
const char *  filename 
)
static

Definition at line 725 of file initdb.c.

726 {
727  *dest = psprintf("%s/%s", share_path, filename);
728 }
static char * filename
Definition: pg_dumpall.c:119

References generate_unaccent_rules::dest, filename, psprintf(), and share_path.

Referenced by setup_data_file_paths().

◆ set_null_conf()

static void set_null_conf ( void  )
static

Definition at line 788 of file initdb.c.

789 {
790  FILE *conf_file;
791  char *path;
792 
793  path = psprintf("%s/postgresql.conf", pg_data);
794  conf_file = fopen(path, PG_BINARY_W);
795  if (conf_file == NULL)
796  pg_fatal("could not open file \"%s\" for writing: %m", path);
797  if (fclose(conf_file))
798  pg_fatal("could not write file \"%s\": %m", path);
799  free(path);
800 }
#define PG_BINARY_W
Definition: c.h:1263
static char * conf_file
Definition: initdb.c:163

References conf_file, free, PG_BINARY_W, pg_data, pg_fatal, and psprintf().

Referenced by initialize_data_directory().

◆ setlocales()

static void setlocales ( void  )
static

Definition at line 2033 of file initdb.c.

2034 {
2035  char *canonname;
2036 
2037  /* set empty lc_* values to locale config if set */
2038 
2039  if (locale)
2040  {
2041  if (!lc_ctype)
2042  lc_ctype = locale;
2043  if (!lc_collate)
2044  lc_collate = locale;
2045  if (!lc_numeric)
2046  lc_numeric = locale;
2047  if (!lc_time)
2048  lc_time = locale;
2049  if (!lc_monetary)
2050  lc_monetary = locale;
2051  if (!lc_messages)
2052  lc_messages = locale;
2053  }
2054 
2055  /*
2056  * canonicalize locale names, and obtain any missing values from our
2057  * current environment
2058  */
2059  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2060  lc_ctype = canonname;
2061  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2062  lc_collate = canonname;
2063  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2064  lc_numeric = canonname;
2065  check_locale_name(LC_TIME, lc_time, &canonname);
2066  lc_time = canonname;
2067  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2068  lc_monetary = canonname;
2069 #if defined(LC_MESSAGES) && !defined(WIN32)
2070  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2071  lc_messages = canonname;
2072 #else
2073  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2074  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2075  lc_messages = canonname;
2076 #endif
2077 
2078  if (locale_provider == COLLPROVIDER_ICU)
2079  {
2080  if (!icu_locale)
2081  pg_fatal("ICU locale must be specified");
2082 
2083  /*
2084  * In supported builds, the ICU locale ID will be checked by the
2085  * backend during post-bootstrap initialization.
2086  */
2087 #ifndef USE_ICU
2088  pg_fatal("ICU is not supported in this build");
2089 #endif
2090  }
2091 }
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:1920

References check_locale_name(), icu_locale, lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, locale, locale_provider, and pg_fatal.

Referenced by setup_locale_encoding().

◆ setup_auth()

static void setup_auth ( FILE *  cmdfd)
static

Definition at line 1351 of file initdb.c.

1352 {
1353  /*
1354  * The authid table shouldn't be readable except through views, to
1355  * ensure passwords are not publicly visible.
1356  */
1357  PG_CMD_PUTS("REVOKE ALL ON pg_authid FROM public;\n\n");
1358 
1359  if (superuser_password)
1360  PG_CMD_PRINTF("ALTER USER \"%s\" WITH PASSWORD E'%s';\n\n",
1362 }
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:316

References escape_quotes(), PG_CMD_PRINTF, PG_CMD_PUTS, superuser_password, and username.

Referenced by initialize_data_directory().

◆ setup_bin_paths()

void setup_bin_paths ( const char *  argv0)

Definition at line 2225 of file initdb.c.

2226 {
2227  int ret;
2228 
2229  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2230  backend_exec)) < 0)
2231  {
2232  char full_path[MAXPGPATH];
2233 
2234  if (find_my_exec(argv0, full_path) < 0)
2235  strlcpy(full_path, progname, sizeof(full_path));
2236 
2237  if (ret == -1)
2238  pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
2239  "postgres", progname, full_path);
2240  else
2241  pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
2242  "postgres", full_path, progname);
2243  }
2244 
2245  /* store binary directory */
2246  strcpy(bin_path, backend_exec);
2247  *last_dir_separator(bin_path) = '\0';
2249 
2250  if (!share_path)
2251  {
2254  }
2255  else if (!is_absolute_path(share_path))
2256  pg_fatal("input file location must be an absolute path");
2257 
2259 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:351
static char bin_path[MAXPGPATH]
Definition: initdb.c:240
static char * argv0
Definition: pg_ctl.c:92
void get_share_path(const char *my_exec_path, char *ret_path)
Definition: path.c:825
char * last_dir_separator(const char *filename)
Definition: path.c:139
#define PG_BACKEND_VERSIONSTR
Definition: port.h:143

References argv0, backend_exec, bin_path, canonicalize_path(), find_my_exec(), find_other_exec(), get_share_path(), is_absolute_path, last_dir_separator(), MAXPGPATH, PG_BACKEND_VERSIONSTR, pg_fatal, pg_malloc(), progname, share_path, and strlcpy().

Referenced by main().

◆ setup_collation()

static void setup_collation ( FILE *  cmdfd)
static

Definition at line 1482 of file initdb.c.

1483 {
1484  /*
1485  * Add an SQL-standard name. We don't want to pin this, so it doesn't go
1486  * in pg_collation.h. But add it before reading system collations, so
1487  * that it wins if libc defines a locale named ucs_basic.
1488  */
1489  PG_CMD_PRINTF("INSERT INTO pg_collation (oid, collname, collnamespace, collowner, collprovider, collisdeterministic, collencoding, collcollate, collctype)"
1490  "VALUES (pg_nextoid('pg_catalog.pg_collation', 'oid', 'pg_catalog.pg_collation_oid_index'), 'ucs_basic', 'pg_catalog'::regnamespace, %u, '%c', true, %d, 'C', 'C');\n\n",
1491  BOOTSTRAP_SUPERUSERID, COLLPROVIDER_LIBC, PG_UTF8);
1492 
1493  /* Now import all collations we can find in the operating system */
1494  PG_CMD_PUTS("SELECT pg_import_system_collations('pg_catalog');\n\n");
1495 }

References PG_CMD_PRINTF, PG_CMD_PUTS, and PG_UTF8.

Referenced by initialize_data_directory().

◆ setup_config()

static void setup_config ( void  )
static

Definition at line 992 of file initdb.c.

993 {
994  char **conflines;
995  char repltok[MAXPGPATH];
996  char path[MAXPGPATH];
997  char *autoconflines[3];
998 
999  fputs(_("creating configuration files ... "), stdout);
1000  fflush(stdout);
1001 
1002  /* postgresql.conf */
1003 
1004  conflines = readfile(conf_file);
1005 
1006  snprintf(repltok, sizeof(repltok), "max_connections = %d", n_connections);
1007  conflines = replace_token(conflines, "#max_connections = 100", repltok);
1008 
1009  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
1010  snprintf(repltok, sizeof(repltok), "shared_buffers = %dMB",
1011  (n_buffers * (BLCKSZ / 1024)) / 1024);
1012  else
1013  snprintf(repltok, sizeof(repltok), "shared_buffers = %dkB",
1014  n_buffers * (BLCKSZ / 1024));
1015  conflines = replace_token(conflines, "#shared_buffers = 128MB", repltok);
1016 
1017  snprintf(repltok, sizeof(repltok), "#unix_socket_directories = '%s'",
1019  conflines = replace_token(conflines, "#unix_socket_directories = '/tmp'",
1020  repltok);
1021 
1022 #if DEF_PGPORT != 5432
1023  snprintf(repltok, sizeof(repltok), "#port = %d", DEF_PGPORT);
1024  conflines = replace_token(conflines, "#port = 5432", repltok);
1025 #endif
1026 
1027  /* set default max_wal_size and min_wal_size */
1028  snprintf(repltok, sizeof(repltok), "min_wal_size = %s",
1030  conflines = replace_token(conflines, "#min_wal_size = 80MB", repltok);
1031 
1032  snprintf(repltok, sizeof(repltok), "max_wal_size = %s",
1034  conflines = replace_token(conflines, "#max_wal_size = 1GB", repltok);
1035 
1036  snprintf(repltok, sizeof(repltok), "lc_messages = '%s'",
1038  conflines = replace_token(conflines, "#lc_messages = 'C'", repltok);
1039 
1040  snprintf(repltok, sizeof(repltok), "lc_monetary = '%s'",
1042  conflines = replace_token(conflines, "#lc_monetary = 'C'", repltok);
1043 
1044  snprintf(repltok, sizeof(repltok), "lc_numeric = '%s'",
1046  conflines = replace_token(conflines, "#lc_numeric = 'C'", repltok);
1047 
1048  snprintf(repltok, sizeof(repltok), "lc_time = '%s'",
1050  conflines = replace_token(conflines, "#lc_time = 'C'", repltok);
1051 
1052  switch (locale_date_order(lc_time))
1053  {
1054  case DATEORDER_YMD:
1055  strcpy(repltok, "datestyle = 'iso, ymd'");
1056  break;
1057  case DATEORDER_DMY:
1058  strcpy(repltok, "datestyle = 'iso, dmy'");
1059  break;
1060  case DATEORDER_MDY:
1061  default:
1062  strcpy(repltok, "datestyle = 'iso, mdy'");
1063  break;
1064  }
1065  conflines = replace_token(conflines, "#datestyle = 'iso, mdy'", repltok);
1066 
1067  snprintf(repltok, sizeof(repltok),
1068  "default_text_search_config = 'pg_catalog.%s'",
1070  conflines = replace_token(conflines,
1071  "#default_text_search_config = 'pg_catalog.simple'",
1072  repltok);
1073 
1074  if (default_timezone)
1075  {
1076  snprintf(repltok, sizeof(repltok), "timezone = '%s'",
1078  conflines = replace_token(conflines, "#timezone = 'GMT'", repltok);
1079  snprintf(repltok, sizeof(repltok), "log_timezone = '%s'",
1081  conflines = replace_token(conflines, "#log_timezone = 'GMT'", repltok);
1082  }
1083 
1084  snprintf(repltok, sizeof(repltok), "dynamic_shared_memory_type = %s",
1086  conflines = replace_token(conflines, "#dynamic_shared_memory_type = posix",
1087  repltok);
1088 
1089 #if DEFAULT_BACKEND_FLUSH_AFTER > 0
1090  snprintf(repltok, sizeof(repltok), "#backend_flush_after = %dkB",
1091  DEFAULT_BACKEND_FLUSH_AFTER * (BLCKSZ / 1024));
1092  conflines = replace_token(conflines, "#backend_flush_after = 0",
1093  repltok);
1094 #endif
1095 
1096 #if DEFAULT_BGWRITER_FLUSH_AFTER > 0
1097  snprintf(repltok, sizeof(repltok), "#bgwriter_flush_after = %dkB",
1098  DEFAULT_BGWRITER_FLUSH_AFTER * (BLCKSZ / 1024));
1099  conflines = replace_token(conflines, "#bgwriter_flush_after = 0",
1100  repltok);
1101 #endif
1102 
1103 #if DEFAULT_CHECKPOINT_FLUSH_AFTER > 0
1104  snprintf(repltok, sizeof(repltok), "#checkpoint_flush_after = %dkB",
1105  DEFAULT_CHECKPOINT_FLUSH_AFTER * (BLCKSZ / 1024));
1106  conflines = replace_token(conflines, "#checkpoint_flush_after = 0",
1107  repltok);
1108 #endif
1109 
1110 #ifndef USE_PREFETCH
1111  conflines = replace_token(conflines,
1112  "#effective_io_concurrency = 1",
1113  "#effective_io_concurrency = 0");
1114 #endif
1115 
1116 #ifdef WIN32
1117  conflines = replace_token(conflines,
1118  "#update_process_title = on",
1119  "#update_process_title = off");
1120 #endif
1121 
1122  /*
1123  * Change password_encryption setting to md5 if md5 was chosen as an
1124  * authentication method, unless scram-sha-256 was also chosen.
1125  */
1126  if ((strcmp(authmethodlocal, "md5") == 0 &&
1127  strcmp(authmethodhost, "scram-sha-256") != 0) ||
1128  (strcmp(authmethodhost, "md5") == 0 &&
1129  strcmp(authmethodlocal, "scram-sha-256") != 0))
1130  {
1131  conflines = replace_token(conflines,
1132  "#password_encryption = scram-sha-256",
1133  "password_encryption = md5");
1134  }
1135 
1136  /*
1137  * If group access has been enabled for the cluster then it makes sense to
1138  * ensure that the log files also allow group access. Otherwise a backup
1139  * from a user in the group would fail if the log files were not
1140  * relocated.
1141  */
1143  {
1144  conflines = replace_token(conflines,
1145  "#log_file_mode = 0600",
1146  "log_file_mode = 0640");
1147  }
1148 
1149  snprintf(path, sizeof(path), "%s/postgresql.conf", pg_data);
1150 
1151  writefile(path, conflines);
1152  if (chmod(path, pg_file_create_mode) != 0)
1153  pg_fatal("could not change permissions of \"%s\": %m", path);
1154 
1155  /*
1156  * create the automatic configuration file to store the configuration
1157  * parameters set by ALTER SYSTEM command. The parameters present in this
1158  * file will override the value of parameters that exists before parse of
1159  * this file.
1160  */
1161  autoconflines[0] = pg_strdup("# Do not edit this file manually!\n");
1162  autoconflines[1] = pg_strdup("# It will be overwritten by the ALTER SYSTEM command.\n");
1163  autoconflines[2] = NULL;
1164 
1165  sprintf(path, "%s/postgresql.auto.conf", pg_data);
1166 
1167  writefile(path, autoconflines);
1168  if (chmod(path, pg_file_create_mode) != 0)
1169  pg_fatal("could not change permissions of \"%s\": %m", path);
1170 
1171  free(conflines);
1172 
1173 
1174  /* pg_hba.conf */
1175 
1176  conflines = readfile(hba_file);
1177 
1178  conflines = replace_token(conflines, "@remove-line-for-nolocal@", "");
1179 
1180 
1181  /*
1182  * Probe to see if there is really any platform support for IPv6, and
1183  * comment out the relevant pg_hba line if not. This avoids runtime
1184  * warnings if getaddrinfo doesn't actually cope with IPv6. Particularly
1185  * useful on Windows, where executables built on a machine with IPv6 may
1186  * have to run on a machine without.
1187  */
1188  {
1189  struct addrinfo *gai_result;
1190  struct addrinfo hints;
1191  int err = 0;
1192 
1193 #ifdef WIN32
1194  /* need to call WSAStartup before calling getaddrinfo */
1195  WSADATA wsaData;
1196 
1197  err = WSAStartup(MAKEWORD(2, 2), &wsaData);
1198 #endif
1199 
1200  /* for best results, this code should match parse_hba_line() */
1201  hints.ai_flags = AI_NUMERICHOST;
1202  hints.ai_family = AF_UNSPEC;
1203  hints.ai_socktype = 0;
1204  hints.ai_protocol = 0;
1205  hints.ai_addrlen = 0;
1206  hints.ai_canonname = NULL;
1207  hints.ai_addr = NULL;
1208  hints.ai_next = NULL;
1209 
1210  if (err != 0 ||
1211  getaddrinfo("::1", NULL, &hints, &gai_result) != 0)
1212  {
1213  conflines = replace_token(conflines,
1214  "host all all ::1",
1215  "#host all all ::1");
1216  conflines = replace_token(conflines,
1217  "host replication all ::1",
1218  "#host replication all ::1");
1219  }
1220  }
1221 
1222  /* Replace default authentication methods */
1223  conflines = replace_token(conflines,
1224  "@authmethodhost@",
1225  authmethodhost);
1226  conflines = replace_token(conflines,
1227  "@authmethodlocal@",
1228  authmethodlocal);
1229 
1230  conflines = replace_token(conflines,
1231  "@authcomment@",
1232  (strcmp(authmethodlocal, "trust") == 0 || strcmp(authmethodhost, "trust") == 0) ? AUTHTRUST_WARNING : "");
1233 
1234  snprintf(path, sizeof(path), "%s/pg_hba.conf", pg_data);
1235 
1236  writefile(path, conflines);
1237  if (chmod(path, pg_file_create_mode) != 0)
1238  pg_fatal("could not change permissions of \"%s\": %m", path);
1239 
1240  free(conflines);
1241 
1242  /* pg_ident.conf */
1243 
1244  conflines = readfile(ident_file);
1245 
1246  snprintf(path, sizeof(path), "%s/pg_ident.conf", pg_data);
1247 
1248  writefile(path, conflines);
1249  if (chmod(path, pg_file_create_mode) != 0)
1250  pg_fatal("could not change permissions of \"%s\": %m", path);
1251 
1252  free(conflines);
1253 
1254  check_ok();
1255 }
int pg_file_create_mode
Definition: file_perm.c:19
static const char * default_timezone
Definition: initdb.c:185
static char * hba_file
Definition: initdb.c:161
static int n_connections
Definition: initdb.c:182
static int n_buffers
Definition: initdb.c:183
static char * ident_file
Definition: initdb.c:162
static int locale_date_order(const char *locale)
Definition: initdb.c:1857
static const char * dynamic_shared_memory_type
Definition: initdb.c:184
#define AUTHTRUST_WARNING
Definition: initdb.c:190
static void writefile(char *path, char **lines)
Definition: initdb.c:467
static char * pretty_wal_size(int segment_count)
Definition: initdb.c:975
#define DEFAULT_PGSOCKET_DIR
#define DEFAULT_BACKEND_FLUSH_AFTER
#define DEFAULT_CHECKPOINT_FLUSH_AFTER
#define DEFAULT_BGWRITER_FLUSH_AFTER
#define DEFAULT_MAX_WAL_SEGS
Definition: xlog_internal.h:92
#define DEFAULT_MIN_WAL_SEGS
Definition: xlog_internal.h:91

References _, authmethodhost, authmethodlocal, AUTHTRUST_WARNING, check_ok(), conf_file, DATEORDER_DMY, DATEORDER_MDY, DATEORDER_YMD, DEFAULT_BACKEND_FLUSH_AFTER, DEFAULT_BGWRITER_FLUSH_AFTER, DEFAULT_CHECKPOINT_FLUSH_AFTER, DEFAULT_MAX_WAL_SEGS, DEFAULT_MIN_WAL_SEGS, DEFAULT_PGSOCKET_DIR, default_text_search_config, default_timezone, dynamic_shared_memory_type, escape_quotes(), fflush(), free, hba_file, ident_file, lc_messages, lc_monetary, lc_numeric, lc_time, locale_date_order(), MAXPGPATH, n_buffers, n_connections, pg_data, pg_dir_create_mode, PG_DIR_MODE_GROUP, pg_fatal, pg_file_create_mode, pg_strdup(), pretty_wal_size(), readfile(), replace_token(), snprintf, sprintf, generate_unaccent_rules::stdout, and writefile().

Referenced by initialize_data_directory().

◆ setup_data_file_paths()

void setup_data_file_paths ( void  )

Definition at line 2359 of file initdb.c.

2360 {
2361  set_input(&bki_file, "postgres.bki");
2362  set_input(&hba_file, "pg_hba.conf.sample");
2363  set_input(&ident_file, "pg_ident.conf.sample");
2364  set_input(&conf_file, "postgresql.conf.sample");
2365  set_input(&dictionary_file, "snowball_create.sql");
2366  set_input(&info_schema_file, "information_schema.sql");
2367  set_input(&features_file, "sql_features.txt");
2368  set_input(&system_constraints_file, "system_constraints.sql");
2369  set_input(&system_functions_file, "system_functions.sql");
2370  set_input(&system_views_file, "system_views.sql");
2371 
2372  if (show_setting || debug)
2373  {
2374  fprintf(stderr,
2375  "VERSION=%s\n"
2376  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2377  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2378  "POSTGRESQL_CONF_SAMPLE=%s\n"
2379  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2380  PG_VERSION,
2382  username, bki_file,
2383  conf_file,
2384  hba_file, ident_file);
2385  if (show_setting)
2386  exit(0);
2387  }
2388 
2399 }
static char * features_file
Definition: initdb.c:166
static void set_input(char **dest, const char *filename)
Definition: initdb.c:725
static void check_input(char *path)
Definition: initdb.c:734
static char * info_schema_file
Definition: initdb.c:165

References bin_path, bki_file, check_input(), conf_file, debug, dictionary_file, exit(), features_file, fprintf, hba_file, ident_file, info_schema_file, pg_data, set_input(), share_path, show_setting, system_constraints_file, system_functions_file, system_views_file, and username.

Referenced by main().

◆ setup_depend()

static void setup_depend ( FILE *  cmdfd)
static

Definition at line 1427 of file initdb.c.

1428 {
1429  /*
1430  * Advance the OID counter so that subsequently-created objects aren't
1431  * pinned.
1432  */
1433  PG_CMD_PUTS("SELECT pg_stop_making_pinned_objects();\n\n");
1434 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ setup_description()

static void setup_description ( FILE *  cmdfd)
static

Definition at line 1461 of file initdb.c.

1462 {
1463  /* Create default descriptions for operator implementation functions */
1464  PG_CMD_PUTS("WITH funcdescs AS ( "
1465  "SELECT p.oid as p_oid, o.oid as o_oid, oprname "
1466  "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1467  "INSERT INTO pg_description "
1468  " SELECT p_oid, 'pg_proc'::regclass, 0, "
1469  " 'implementation of ' || oprname || ' operator' "
1470  " FROM funcdescs "
1471  " WHERE NOT EXISTS (SELECT 1 FROM pg_description "
1472  " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass) "
1473  " AND NOT EXISTS (SELECT 1 FROM pg_description "
1474  " WHERE objoid = o_oid AND classoid = 'pg_operator'::regclass"
1475  " AND description LIKE 'deprecated%');\n\n");
1476 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ setup_locale_encoding()

void setup_locale_encoding ( void  )

Definition at line 2262 of file initdb.c.

2263 {
2264  setlocales();
2265 
2266  if (locale_provider == COLLPROVIDER_LIBC &&
2267  strcmp(lc_ctype, lc_collate) == 0 &&
2268  strcmp(lc_ctype, lc_time) == 0 &&
2269  strcmp(lc_ctype, lc_numeric) == 0 &&
2270  strcmp(lc_ctype, lc_monetary) == 0 &&
2271  strcmp(lc_ctype, lc_messages) == 0 &&
2272  (!icu_locale || strcmp(lc_ctype, icu_locale) == 0))
2273  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2274  else
2275  {
2276  printf(_("The database cluster will be initialized with this locale configuration:\n"));
2277  printf(_(" provider: %s\n"), collprovider_name(locale_provider));
2278  if (icu_locale)
2279  printf(_(" ICU locale: %s\n"), icu_locale);
2280  printf(_(" LC_COLLATE: %s\n"
2281  " LC_CTYPE: %s\n"
2282  " LC_MESSAGES: %s\n"
2283  " LC_MONETARY: %s\n"
2284  " LC_NUMERIC: %s\n"
2285  " LC_TIME: %s\n"),
2286  lc_collate,
2287  lc_ctype,
2288  lc_messages,
2289  lc_monetary,
2290  lc_numeric,
2291  lc_time);
2292  }
2293 
2294  if (!encoding && locale_provider == COLLPROVIDER_ICU)
2295  {
2296  encodingid = PG_UTF8;
2297  printf(_("The default database encoding has been set to \"%s\".\n"),
2299  }
2300  else if (!encoding)
2301  {
2302  int ctype_enc;
2303 
2304  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2305 
2306  if (ctype_enc == -1)
2307  {
2308  /* Couldn't recognize the locale's codeset */
2309  pg_log_error("could not find suitable encoding for locale \"%s\"",
2310  lc_ctype);
2311  pg_log_error_hint("Rerun %s with the -E option.", progname);
2312  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2313  exit(1);
2314  }
2315  else if (!pg_valid_server_encoding_id(ctype_enc))
2316  {
2317  /*
2318  * We recognized it, but it's not a legal server encoding. On
2319  * Windows, UTF-8 works with any locale, so we can fall back to
2320  * UTF-8.
2321  */
2322 #ifdef WIN32
2323  encodingid = PG_UTF8;
2324  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2325  "The default database encoding will be set to \"%s\" instead.\n"),
2326  pg_encoding_to_char(ctype_enc),
2328 #else
2329  pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
2330  lc_ctype, pg_encoding_to_char(ctype_enc));
2331  pg_log_error_detail("Encoding \"%s\" is not allowed as a server-side encoding.",
2332  pg_encoding_to_char(ctype_enc));
2333  pg_log_error_hint("Rerun %s with a different locale selection.",
2334  progname);
2335  exit(1);
2336 #endif
2337  }
2338  else
2339  {
2340  encodingid = ctype_enc;
2341  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2343  }
2344  }
2345  else
2347 
2350  exit(1); /* check_locale_encoding printed the error */
2351 
2352  if (locale_provider == COLLPROVIDER_ICU &&
2354  exit(1);
2355 }
int pg_valid_server_encoding_id(int encoding)
Definition: encnames.c:514
static bool check_icu_locale_encoding(int user_enc)
Definition: initdb.c:2012
static int get_encoding_id(const char *encoding_name)
Definition: initdb.c:589
static bool check_locale_encoding(const char *locale, int user_enc)
Definition: initdb.c:1977
static void setlocales(void)
Definition: initdb.c:2033

References _, check_icu_locale_encoding(), check_locale_encoding(), encoding, encodingid, exit(), get_encoding_id(), icu_locale, lc_collate, lc_ctype, lc_messages, lc_monetary, lc_numeric, lc_time, locale_provider, pg_encoding_to_char(), pg_get_encoding_from_locale(), pg_log_error, pg_log_error_detail, pg_log_error_hint, PG_UTF8, pg_valid_server_encoding_id(), printf, progname, and setlocales().

Referenced by main().

◆ setup_pgdata()

void setup_pgdata ( void  )

Definition at line 2188 of file initdb.c.

2189 {
2190  char *pgdata_get_env;
2191 
2192  if (!pg_data)
2193  {
2194  pgdata_get_env = getenv("PGDATA");
2195  if (pgdata_get_env && strlen(pgdata_get_env))
2196  {
2197  /* PGDATA found */
2198  pg_data = pg_strdup(pgdata_get_env);
2199  }
2200  else
2201  {
2202  pg_log_error("no data directory specified");
2203  pg_log_error_hint("You must identify the directory where the data for this database system "
2204  "will reside. Do this with either the invocation option -D or the "
2205  "environment variable PGDATA.");
2206  exit(1);
2207  }
2208  }
2209 
2212 
2213  /*
2214  * we have to set PGDATA for postgres rather than pass it on the command
2215  * line to avoid dumb quoting problems on Windows, and we would especially
2216  * need quotes otherwise on Windows because paths there are most likely to
2217  * have embedded spaces.
2218  */
2219  if (setenv("PGDATA", pg_data, 1) != 0)
2220  pg_fatal("could not set environment");
2221 }
#define setenv(x, y, z)
Definition: win32_port.h:534

References canonicalize_path(), exit(), pg_data, pg_fatal, pg_log_error, pg_log_error_hint, pg_strdup(), pgdata_native, and setenv.

Referenced by main().

◆ setup_privileges()

static void setup_privileges ( FILE *  cmdfd)
static

Definition at line 1517 of file initdb.c.

1518 {
1519  PG_CMD_PRINTF("UPDATE pg_class "
1520  " SET relacl = (SELECT array_agg(a.acl) FROM "
1521  " (SELECT E'=r/\"%s\"' as acl "
1522  " UNION SELECT unnest(pg_catalog.acldefault("
1523  " CASE WHEN relkind = " CppAsString2(RELKIND_SEQUENCE) " THEN 's' "
1524  " ELSE 'r' END::\"char\"," CppAsString2(BOOTSTRAP_SUPERUSERID) "::oid))"
1525  " ) as a) "
1526  " WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1527  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1528  CppAsString2(RELKIND_SEQUENCE) ")"
1529  " AND relacl IS NULL;\n\n",
1531  PG_CMD_PUTS("GRANT USAGE ON SCHEMA pg_catalog, public TO PUBLIC;\n\n");
1532  PG_CMD_PUTS("REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n");
1533  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1534  " (objoid, classoid, objsubid, initprivs, privtype)"
1535  " SELECT"
1536  " oid,"
1537  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1538  " 0,"
1539  " relacl,"
1540  " 'i'"
1541  " FROM"
1542  " pg_class"
1543  " WHERE"
1544  " relacl IS NOT NULL"
1545  " AND relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1546  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1547  CppAsString2(RELKIND_SEQUENCE) ");\n\n");
1548  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1549  " (objoid, classoid, objsubid, initprivs, privtype)"
1550  " SELECT"
1551  " pg_class.oid,"
1552  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1553  " pg_attribute.attnum,"
1554  " pg_attribute.attacl,"
1555  " 'i'"
1556  " FROM"
1557  " pg_class"
1558  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
1559  " WHERE"
1560  " pg_attribute.attacl IS NOT NULL"
1561  " AND pg_class.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1562  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1563  CppAsString2(RELKIND_SEQUENCE) ");\n\n");
1564  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1565  " (objoid, classoid, objsubid, initprivs, privtype)"
1566  " SELECT"
1567  " oid,"
1568  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
1569  " 0,"
1570  " proacl,"
1571  " 'i'"
1572  " FROM"
1573  " pg_proc"
1574  " WHERE"
1575  " proacl IS NOT NULL;\n\n");
1576  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1577  " (objoid, classoid, objsubid, initprivs, privtype)"
1578  " SELECT"
1579  " oid,"
1580  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
1581  " 0,"
1582  " typacl,"
1583  " 'i'"
1584  " FROM"
1585  " pg_type"
1586  " WHERE"
1587  " typacl IS NOT NULL;\n\n");
1588  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1589  " (objoid, classoid, objsubid, initprivs, privtype)"
1590  " SELECT"
1591  " oid,"
1592  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
1593  " 0,"
1594  " lanacl,"
1595  " 'i'"
1596  " FROM"
1597  " pg_language"
1598  " WHERE"
1599  " lanacl IS NOT NULL;\n\n");
1600  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1601  " (objoid, classoid, objsubid, initprivs, privtype)"
1602  " SELECT"
1603  " oid,"
1604  " (SELECT oid FROM pg_class WHERE "
1605  " relname = 'pg_largeobject_metadata'),"
1606  " 0,"
1607  " lomacl,"
1608  " 'i'"
1609  " FROM"
1610  " pg_largeobject_metadata"
1611  " WHERE"
1612  " lomacl IS NOT NULL;\n\n");
1613  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1614  " (objoid, classoid, objsubid, initprivs, privtype)"
1615  " SELECT"
1616  " oid,"
1617  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
1618  " 0,"
1619  " nspacl,"
1620  " 'i'"
1621  " FROM"
1622  " pg_namespace"
1623  " WHERE"
1624  " nspacl IS NOT NULL;\n\n");
1625  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1626  " (objoid, classoid, objsubid, initprivs, privtype)"
1627  " SELECT"
1628  " oid,"
1629  " (SELECT oid FROM pg_class WHERE "
1630  " relname = 'pg_foreign_data_wrapper'),"
1631  " 0,"
1632  " fdwacl,"
1633  " 'i'"
1634  " FROM"
1635  " pg_foreign_data_wrapper"
1636  " WHERE"
1637  " fdwacl IS NOT NULL;\n\n");
1638  PG_CMD_PUTS("INSERT INTO pg_init_privs "
1639  " (objoid, classoid, objsubid, initprivs, privtype)"
1640  " SELECT"
1641  " oid,"
1642  " (SELECT oid FROM pg_class "
1643  " WHERE relname = 'pg_foreign_server'),"
1644  " 0,"
1645  " srvacl,"
1646  " 'i'"
1647  " FROM"
1648  " pg_foreign_server"
1649  " WHERE"
1650  " srvacl IS NOT NULL;\n\n");
1651 }

References CppAsString2, escape_quotes(), PG_CMD_PRINTF, PG_CMD_PUTS, and username.

Referenced by initialize_data_directory().

◆ setup_run_file()

static void setup_run_file ( FILE *  cmdfd,
const char *  filename 
)
static

Definition at line 1440 of file initdb.c.

1441 {
1442  char **lines;
1443 
1444  lines = readfile(filename);
1445 
1446  for (char **line = lines; *line != NULL; line++)
1447  {
1448  PG_CMD_PUTS(*line);
1449  free(*line);
1450  }
1451 
1452  PG_CMD_PUTS("\n\n");
1453 
1454  free(lines);
1455 }

References filename, free, PG_CMD_PUTS, and readfile().

Referenced by initialize_data_directory(), and setup_schema().

◆ setup_schema()

static void setup_schema ( FILE *  cmdfd)
static

Definition at line 1685 of file initdb.c.

1686 {
1688 
1689  PG_CMD_PRINTF("UPDATE information_schema.sql_implementation_info "
1690  " SET character_value = '%s' "
1691  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
1692  infoversion);
1693 
1694  PG_CMD_PRINTF("COPY information_schema.sql_features "
1695  " (feature_id, feature_name, sub_feature_id, "
1696  " sub_feature_name, is_supported, comments) "
1697  " FROM E'%s';\n\n",
1699 }

References escape_quotes(), features_file, info_schema_file, infoversion, PG_CMD_PRINTF, and setup_run_file().

Referenced by initialize_data_directory().

◆ setup_signals()

void setup_signals ( void  )

Definition at line 2437 of file initdb.c.

2438 {
2439  /* some of these are not valid on Windows */
2440 #ifdef SIGHUP
2442 #endif
2443 #ifdef SIGINT
2444  pqsignal(SIGINT, trapsig);
2445 #endif
2446 #ifdef SIGQUIT
2448 #endif
2449 #ifdef SIGTERM
2450  pqsignal(SIGTERM, trapsig);
2451 #endif
2452 
2453  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2454 #ifdef SIGPIPE
2456 #endif
2457 
2458  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2459 #ifdef SIGSYS
2460  pqsignal(SIGSYS, SIG_IGN);
2461 #endif
2462 }
static void trapsig(SIGNAL_ARGS)
Definition: initdb.c:1812
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define SIGHUP
Definition: win32_port.h:176
#define SIGPIPE
Definition: win32_port.h:181
#define SIGQUIT
Definition: win32_port.h:177
#define SIG_IGN
Definition: win32_port.h:173

References pqsignal(), SIG_IGN, SIGHUP, SIGPIPE, SIGQUIT, and trapsig().

Referenced by initialize_data_directory().

◆ setup_text_search()

void setup_text_search ( void  )

Definition at line 2403 of file initdb.c.

2404 {
2406  {
2409  {
2410  pg_log_info("could not find suitable text search configuration for locale \"%s\"",
2411  lc_ctype);
2412  default_text_search_config = "simple";
2413  }
2414  }
2415  else
2416  {
2417  const char *checkmatch = find_matching_ts_config(lc_ctype);
2418 
2419  if (checkmatch == NULL)
2420  {
2421  pg_log_warning("suitable text search configuration for locale \"%s\" is unknown",
2422  lc_ctype);
2423  }
2424  else if (strcmp(checkmatch, default_text_search_config) != 0)
2425  {
2426  pg_log_warning("specified text search configuration \"%s\" might not match locale \"%s\"",
2428  }
2429  }
2430 
2431  printf(_("The default text search configuration will be set to \"%s\".\n"),
2433 }
static const char * find_matching_ts_config(const char *lc_type)
Definition: initdb.c:679

References _, default_text_search_config, find_matching_ts_config(), lc_ctype, pg_log_info, pg_log_warning, and printf.

Referenced by main().

◆ test_config_settings()

static void test_config_settings ( void  )
static

Definition at line 859 of file initdb.c.

860 {
861  /*
862  * This macro defines the minimum shared_buffers we want for a given
863  * max_connections value. The arrays show the settings to try.
864  */
865 #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
866 
867  static const int trial_conns[] = {
868  100, 50, 40, 30, 20
869  };
870  static const int trial_bufs[] = {
871  16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
872  1000, 900, 800, 700, 600, 500,
873  400, 300, 200, 100, 50
874  };
875 
876  char cmd[MAXPGPATH];
877  const int connslen = sizeof(trial_conns) / sizeof(int);
878  const int bufslen = sizeof(trial_bufs) / sizeof(int);
879  int i,
880  status,
881  test_conns,
882  test_buffs,
883  ok_buffers = 0;
884 
885  /*
886  * Need to determine working DSM implementation first so that subsequent
887  * tests don't fail because DSM setting doesn't work.
888  */
889  printf(_("selecting dynamic shared memory implementation ... "));
890  fflush(stdout);
893 
894  /*
895  * Probe for max_connections before shared_buffers, since it is subject to
896  * more constraints than shared_buffers.
897  */
898  printf(_("selecting default max_connections ... "));
899  fflush(stdout);
900 
901  for (i = 0; i < connslen; i++)
902  {
903  test_conns = trial_conns[i];
904  test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
905 
906  snprintf(cmd, sizeof(cmd),
907  "\"%s\" --check %s %s "
908  "-c max_connections=%d "
909  "-c shared_buffers=%d "
910  "-c dynamic_shared_memory_type=%s "
911  "< \"%s\" > \"%s\" 2>&1",
913  test_conns, test_buffs,
915  DEVNULL, DEVNULL);
916  fflush(NULL);
917  status = system(cmd);
918  if (status == 0)
919  {
920  ok_buffers = test_buffs;
921  break;
922  }
923  }
924  if (i >= connslen)
925  i = connslen - 1;
926  n_connections = trial_conns[i];
927 
928  printf("%d\n", n_connections);
929 
930  printf(_("selecting default shared_buffers ... "));
931  fflush(stdout);
932 
933  for (i = 0; i < bufslen; i++)
934  {
935  /* Use same amount of memory, independent of BLCKSZ */
936  test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
937  if (test_buffs <= ok_buffers)
938  {
939  test_buffs = ok_buffers;
940  break;
941  }
942 
943  snprintf(cmd, sizeof(cmd),
944  "\"%s\" --check %s %s "
945  "-c max_connections=%d "
946  "-c shared_buffers=%d "
947  "-c dynamic_shared_memory_type=%s "
948  "< \"%s\" > \"%s\" 2>&1",
950  n_connections, test_buffs,
952  DEVNULL, DEVNULL);
953  fflush(NULL);
954  status = system(cmd);
955  if (status == 0)
956  break;
957  }
958  n_buffers = test_buffs;
959 
960  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
961  printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
962  else
963  printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
964 
965  printf(_("selecting default time zone ... "));
966  fflush(stdout);
968  printf("%s\n", default_timezone ? default_timezone : "GMT");
969 }
const char * select_default_timezone(const char *share_path)
static const char * choose_dsm_implementation(void)
Definition: initdb.c:817
#define MIN_BUFS_FOR_CONNS(nconns)
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224

References _, backend_exec, boot_options, choose_dsm_implementation(), default_timezone, DEVNULL, dynamic_shared_memory_type, extra_options, fflush(), i, MAXPGPATH, MIN_BUFS_FOR_CONNS, n_buffers, n_connections, printf, select_default_timezone(), share_path, snprintf, status(), and generate_unaccent_rules::stdout.

Referenced by initialize_data_directory().

◆ trapsig()

static void trapsig ( SIGNAL_ARGS  )
static

Definition at line 1812 of file initdb.c.

1813 {
1814  /* handle systems that reset the handler, like Windows (grr) */
1815  pqsignal(postgres_signal_arg, trapsig);
1816  caught_signal = true;
1817 }

References caught_signal, and pqsignal().

Referenced by setup_signals().

◆ usage()

static void usage ( const char *  progname)
static

Definition at line 2097 of file initdb.c.

2098 {
2099  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2100  printf(_("Usage:\n"));
2101  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2102  printf(_("\nOptions:\n"));
2103  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2104  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2105  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2106  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2107  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2108  printf(_(" -g, --allow-group-access allow group read/execute on data directory\n"));
2109  printf(_(" --icu-locale=LOCALE set ICU locale ID for new databases\n"));
2110  printf(_(" -k, --data-checksums use data page checksums\n"));
2111  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2112  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2113  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2114  " set default locale in the respective category for\n"
2115  " new databases (default taken from environment)\n"));
2116  printf(_(" --no-locale equivalent to --locale=C\n"));
2117  printf(_(" --locale-provider={libc|icu}\n"
2118  " set default locale provider for new databases\n"));
2119  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2120  printf(_(" -T, --text-search-config=CFG\n"
2121  " default text search configuration\n"));
2122  printf(_(" -U, --username=NAME database superuser name\n"));
2123  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2124  printf(_(" -X, --waldir=WALDIR location for the write-ahead log directory\n"));
2125  printf(_(" --wal-segsize=SIZE size of WAL segments, in megabytes\n"));
2126  printf(_("\nLess commonly used options:\n"));
2127  printf(_(" -d, --debug generate lots of debugging output\n"));
2128  printf(_(" --discard-caches set debug_discard_caches=1\n"));
2129  printf(_(" -L DIRECTORY where to find the input files\n"));
2130  printf(_(" -n, --no-clean do not clean up after errors\n"));
2131  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
2132  printf(_(" --no-instructions do not print instructions for next steps\n"));
2133  printf(_(" -s, --show show internal settings\n"));
2134  printf(_(" -S, --sync-only only sync database files to disk, then exit\n"));
2135  printf(_("\nOther options:\n"));
2136  printf(_(" -V, --version output version information, then exit\n"));
2137  printf(_(" -?, --help show this help, then exit\n"));
2138  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2139  "is used.\n"));
2140  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2141  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2142 }

References _, printf, and progname.

Referenced by main().

◆ vacuum_db()

static void vacuum_db ( FILE *  cmdfd)
static

Definition at line 1714 of file initdb.c.

1715 {
1716  /* Run analyze before VACUUM so the statistics are frozen. */
1717  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
1718 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ warn_on_mount_point()

void warn_on_mount_point ( int  error)

Definition at line 2607 of file initdb.c.

2608 {
2609  if (error == 2)
2610  pg_log_error_detail("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.");
2611  else if (error == 3)
2612  pg_log_error_detail("It contains a lost+found directory, perhaps due to it being a mount point.");
2613 
2614  pg_log_error_hint("Using a mount point directly as the data directory is not recommended.\n"
2615  "Create a subdirectory under the mount point.");
2616 }
static void error(void)
Definition: sql-dyntest.c:147

References error(), pg_log_error_detail, and pg_log_error_hint.

Referenced by create_data_directory(), and create_xlog_or_symlink().

◆ write_version_file()

static void write_version_file ( const char *  extrapath)
static

Definition at line 765 of file initdb.c.

766 {
767  FILE *version_file;
768  char *path;
769 
770  if (extrapath == NULL)
771  path = psprintf("%s/PG_VERSION", pg_data);
772  else
773  path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
774 
775  if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
776  pg_fatal("could not open file \"%s\" for writing: %m", path);
777  if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
778  fclose(version_file))
779  pg_fatal("could not write file \"%s\": %m", path);
780  free(path);
781 }
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:97

References fprintf, free, PG_BINARY_W, pg_data, pg_fatal, psprintf(), and version_file.

Referenced by initialize_data_directory().

◆ writefile()

static void writefile ( char *  path,
char **  lines 
)
static

Definition at line 467 of file initdb.c.

468 {
469  FILE *out_file;
470  char **line;
471 
472  if ((out_file = fopen(path, "w")) == NULL)
473  pg_fatal("could not open file \"%s\" for writing: %m", path);
474  for (line = lines; *line != NULL; line++)
475  {
476  if (fputs(*line, out_file) < 0)
477  pg_fatal("could not write file \"%s\": %m", path);
478  free(*line);
479  }
480  if (fclose(out_file))
481  pg_fatal("could not close file \"%s\": %m", path);
482 }

References free, and pg_fatal.

Referenced by setup_config().

Variable Documentation

◆ auth_methods_host

const char* const auth_methods_host[]
static
Initial value:
= {
"trust", "reject", "scram-sha-256", "md5", "password", "ident", "radius",
NULL
}

Definition at line 85 of file initdb.c.

Referenced by main().

◆ auth_methods_local

const char* const auth_methods_local[]
static
Initial value:
= {
"trust", "reject", "scram-sha-256", "md5", "password", "peer", "radius",
NULL
}

Definition at line 107 of file initdb.c.

Referenced by main().

◆ authmethodhost

const char* authmethodhost = NULL
static

Definition at line 143 of file initdb.c.

Referenced by check_need_password(), main(), and setup_config().

◆ authmethodlocal

const char* authmethodlocal = NULL
static

Definition at line 144 of file initdb.c.

Referenced by check_need_password(), main(), and setup_config().

◆ authwarning

bool authwarning = false
static

Definition at line 195 of file initdb.c.

Referenced by check_authmethod_unspecified(), and main().

◆ backend_exec

char backend_exec[MAXPGPATH]
static

◆ backend_options

const char* backend_options = "--single -F -O -j -c search_path=pg_catalog -c exit_on_error=true -c log_checkpoints=false"
static

Definition at line 208 of file initdb.c.

Referenced by initialize_data_directory().

◆ bin_path

char bin_path[MAXPGPATH]
static

Definition at line 240 of file initdb.c.

Referenced by make_relative_path(), setup_bin_paths(), and setup_data_file_paths().

◆ bki_file

char* bki_file
static

Definition at line 160 of file initdb.c.

Referenced by bootstrap_template1(), and setup_data_file_paths().

◆ boot_options

const char* boot_options = "-F -c log_checkpoints=false"
static

Definition at line 207 of file initdb.c.

Referenced by bootstrap_template1(), and test_config_settings().

◆ caught_signal

bool caught_signal = false
static

Definition at line 176 of file initdb.c.

Referenced by check_ok(), and trapsig().

◆ conf_file

char* conf_file
static

Definition at line 163 of file initdb.c.

Referenced by set_null_conf(), setup_config(), and setup_data_file_paths().

◆ data_checksums

bool data_checksums = false
static

Definition at line 151 of file initdb.c.

Referenced by bootstrap_template1(), and main().

◆ debug

bool debug = false
static

Definition at line 145 of file initdb.c.

Referenced by bootstrap_template1(), main(), pg_regcomp(), setup_data_file_paths(), and slice_check().

◆ default_text_search_config

const char* default_text_search_config = NULL
static

Definition at line 138 of file initdb.c.

Referenced by main(), setup_config(), and setup_text_search().

◆ default_timezone

const char* default_timezone = NULL
static

Definition at line 185 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ dictionary_file

char* dictionary_file
static

Definition at line 164 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ do_sync

bool do_sync = true
static

Definition at line 148 of file initdb.c.

Referenced by main(), sync_target_dir(), and update_controlfile().

◆ dynamic_shared_memory_type

const char* dynamic_shared_memory_type = NULL
static

Definition at line 184 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ encoding

char* encoding = NULL
static

Definition at line 128 of file initdb.c.

Referenced by main(), and setup_locale_encoding().

◆ encodingid

int encodingid
static

Definition at line 159 of file initdb.c.

Referenced by bootstrap_template1(), and setup_locale_encoding().

◆ extra_options

char* extra_options = ""
static

◆ features_file

char* features_file
static

Definition at line 166 of file initdb.c.

Referenced by setup_data_file_paths(), and setup_schema().

◆ found_existing_pgdata

bool found_existing_pgdata = false
static

Definition at line 172 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_data_directory().

◆ found_existing_xlogdir

bool found_existing_xlogdir = false
static

Definition at line 174 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ hba_file

char* hba_file
static

Definition at line 161 of file initdb.c.

Referenced by setup_config(), and setup_data_file_paths().

◆ icu_locale

char* icu_locale = NULL
static

◆ ident_file

char* ident_file
static

Definition at line 162 of file initdb.c.

Referenced by setup_config(), and setup_data_file_paths().

◆ info_schema_file

char* info_schema_file
static

Definition at line 165 of file initdb.c.

Referenced by setup_data_file_paths(), and setup_schema().

◆ infoversion

char infoversion[100]
static

Definition at line 175 of file initdb.c.

Referenced by set_info_version(), and setup_schema().

◆ lc_collate

char* lc_collate = NULL
static

◆ lc_ctype

char* lc_ctype = NULL
static

◆ lc_messages

char* lc_messages = NULL
static

Definition at line 135 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_monetary

char* lc_monetary = NULL
static

Definition at line 132 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_numeric

char* lc_numeric = NULL
static

Definition at line 133 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ lc_time

char* lc_time = NULL
static

Definition at line 134 of file initdb.c.

Referenced by get_control_data(), main(), setlocales(), setup_config(), and setup_locale_encoding().

◆ locale

◆ locale_provider

char locale_provider = COLLPROVIDER_LIBC
static

Definition at line 136 of file initdb.c.

Referenced by bootstrap_template1(), main(), setlocales(), and setup_locale_encoding().

◆ made_new_pgdata

bool made_new_pgdata = false
static

Definition at line 171 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_data_directory().

◆ made_new_xlogdir

bool made_new_xlogdir = false
static

Definition at line 173 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ n_buffers

int n_buffers = 50
static

Definition at line 183 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ n_connections

int n_connections = 10
static

Definition at line 182 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ noclean

bool noclean = false
static

Definition at line 146 of file initdb.c.

Referenced by cleanup_directories_atexit(), and main().

◆ noinstructions

bool noinstructions = false
static

Definition at line 147 of file initdb.c.

Referenced by main().

◆ output_errno

int output_errno = 0
static

Definition at line 178 of file initdb.c.

Referenced by check_ok().

◆ output_failed

bool output_failed = false
static

Definition at line 177 of file initdb.c.

Referenced by check_ok().

◆ pg_data

◆ pgdata_native

char* pgdata_native
static

Definition at line 179 of file initdb.c.

Referenced by main(), and setup_pgdata().

◆ progname

◆ pwfilename

char* pwfilename = NULL
static

Definition at line 141 of file initdb.c.

Referenced by check_need_password(), get_su_pwd(), and main().

◆ pwprompt

bool pwprompt = false
static

Definition at line 140 of file initdb.c.

Referenced by check_need_password(), get_su_pwd(), and main().

◆ share_path

char* share_path = NULL
static

◆ show_setting

bool show_setting = false
static

Definition at line 150 of file initdb.c.

Referenced by main(), and setup_data_file_paths().

◆ str_wal_segment_size_mb

char* str_wal_segment_size_mb = NULL
static

Definition at line 153 of file initdb.c.

Referenced by main().

◆ subdirs

const char* const subdirs[]
static
Initial value:
= {
"global",
"pg_wal/archive_status",
"pg_commit_ts",
"pg_dynshmem",
"pg_notify",
"pg_serial",
"pg_snapshots",
"pg_subtrans",
"pg_twophase",
"pg_multixact",
"pg_multixact/members",
"pg_multixact/offsets",
"base",
"base/1",
"pg_replslot",
"pg_tblspc",
"pg_stat",
"pg_stat_tmp",
"pg_xact",
"pg_logical",
"pg_logical/snapshots",
"pg_logical/mappings"
}

Definition at line 213 of file initdb.c.

Referenced by initialize_data_directory().

◆ success

◆ superuser_password

char* superuser_password = NULL
static

Definition at line 142 of file initdb.c.

Referenced by get_su_pwd(), and setup_auth().

◆ sync_only

bool sync_only = false
static

Definition at line 149 of file initdb.c.

Referenced by main().

◆ system_constraints_file

char* system_constraints_file
static

Definition at line 167 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ system_functions_file

char* system_functions_file
static

Definition at line 168 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ system_views_file

char* system_views_file
static

Definition at line 169 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ tsearch_config_languages

const struct tsearch_config_match tsearch_config_languages[]
static

Definition at line 589 of file initdb.c.

Referenced by find_matching_ts_config().

◆ username

char* username = NULL
static

◆ wal_segment_size_mb

int wal_segment_size_mb
static

Definition at line 154 of file initdb.c.

Referenced by bootstrap_template1(), main(), and pretty_wal_size().

◆ xlog_dir

char* xlog_dir = NULL
static

Definition at line 152 of file initdb.c.

Referenced by cleanup_directories_atexit(), create_xlog_or_symlink(), and main().