PostgreSQL Source Code  git master
initdb.c File Reference
#include "postgres_fe.h"
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <time.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 "getaddrinfo.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 ** filter_lines_with_token (char **lines, const char *token)
 
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 (int signum)
 
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 encoding)
 
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 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 189 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:408

Definition at line 306 of file initdb.c.

◆ PG_CMD_DECL

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

Definition at line 297 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:520

Definition at line 299 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:177
static void const char fflush(stdout)
static void const char * fmt
#define fprintf
Definition: port.h:229

Definition at line 318 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 312 of file initdb.c.

Function Documentation

◆ bootstrap_template1()

static void bootstrap_template1 ( void  )
static

Definition at line 1308 of file initdb.c.

1309 {
1310  PG_CMD_DECL;
1311  char **line;
1312  char **bki_lines;
1313  char headerline[MAXPGPATH];
1314  char buf[64];
1315 
1316  printf(_("running bootstrap script ... "));
1317  fflush(stdout);
1318 
1319  bki_lines = readfile(bki_file);
1320 
1321  /* Check that bki file appears to be of the right version */
1322 
1323  snprintf(headerline, sizeof(headerline), "# PostgreSQL %s\n",
1324  PG_MAJORVERSION);
1325 
1326  if (strcmp(headerline, *bki_lines) != 0)
1327  {
1328  pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
1329  bki_file, PG_VERSION);
1330  pg_log_error_hint("Specify the correct path using the option -L.");
1331  exit(1);
1332  }
1333 
1334  /* Substitute for various symbols used in the BKI file */
1335 
1336  sprintf(buf, "%d", NAMEDATALEN);
1337  bki_lines = replace_token(bki_lines, "NAMEDATALEN", buf);
1338 
1339  sprintf(buf, "%d", (int) sizeof(Pointer));
1340  bki_lines = replace_token(bki_lines, "SIZEOF_POINTER", buf);
1341 
1342  bki_lines = replace_token(bki_lines, "ALIGNOF_POINTER",
1343  (sizeof(Pointer) == 4) ? "i" : "d");
1344 
1345  bki_lines = replace_token(bki_lines, "FLOAT8PASSBYVAL",
1346  FLOAT8PASSBYVAL ? "true" : "false");
1347 
1348  bki_lines = replace_token(bki_lines, "POSTGRES",
1350 
1351  bki_lines = replace_token(bki_lines, "ENCODING",
1353 
1354  bki_lines = replace_token(bki_lines, "LC_COLLATE",
1356 
1357  bki_lines = replace_token(bki_lines, "LC_CTYPE",
1359 
1360  bki_lines = replace_token(bki_lines, "ICU_LOCALE",
1361  locale_provider == COLLPROVIDER_ICU ? escape_quotes_bki(icu_locale) : "_null_");
1362 
1363  sprintf(buf, "%c", locale_provider);
1364  bki_lines = replace_token(bki_lines, "LOCALE_PROVIDER", buf);
1365 
1366  /* Also ensure backend isn't confused by this environment var: */
1367  unsetenv("PGCLIENTENCODING");
1368 
1369  snprintf(cmd, sizeof(cmd),
1370  "\"%s\" --boot -X %d %s %s %s %s",
1371  backend_exec,
1372  wal_segment_size_mb * (1024 * 1024),
1373  data_checksums ? "-k" : "",
1375  debug ? "-d 5" : "");
1376 
1377 
1378  PG_CMD_OPEN;
1379 
1380  for (line = bki_lines; *line != NULL; line++)
1381  {
1382  PG_CMD_PUTS(*line);
1383  free(*line);
1384  }
1385 
1386  PG_CMD_CLOSE;
1387 
1388  free(bki_lines);
1389 
1390  check_ok();
1391 }
char * Pointer
Definition: c.h:418
#define FLOAT8PASSBYVAL
Definition: c.h:570
#define _(x)
Definition: elog.c:89
#define free(a)
Definition: header.h:65
static char * escape_quotes_bki(const char *src)
Definition: initdb.c:345
static char * lc_collate
Definition: initdb.c:129
#define PG_CMD_PUTS(line)
Definition: initdb.c:312
static char * lc_ctype
Definition: initdb.c:130
static char ** readfile(const char *path)
Definition: initdb.c:455
static bool debug
Definition: initdb.c:144
static char backend_exec[MAXPGPATH]
Definition: initdb.c:240
static bool data_checksums
Definition: initdb.c:150
#define PG_CMD_CLOSE
Definition: initdb.c:306
#define PG_CMD_DECL
Definition: initdb.c:297
static char locale_provider
Definition: initdb.c:135
static int wal_segment_size_mb
Definition: initdb.c:153
static char ** replace_token(char **lines, const char *token, const char *replacement)
Definition: initdb.c:372
#define PG_CMD_OPEN
Definition: initdb.c:299
static char * username
Definition: initdb.c:138
static const char * boot_options
Definition: initdb.c:206
static char * icu_locale
Definition: initdb.c:136
static int encodingid
Definition: initdb.c:158
static char * encodingid_to_string(int enc)
Definition: initdb.c:610
static void check_ok(void)
Definition: initdb.c:1908
static char * extra_options
Definition: initdb.c:210
static char * bki_file
Definition: initdb.c:159
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:227
#define snprintf
Definition: port.h:225
#define printf(...)
Definition: port.h:231
#define unsetenv(x)
Definition: win32_port.h:508

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 2209 of file initdb.c.

2210 {
2211  if (*authmethod == NULL)
2212  {
2213  authwarning = true;
2214  *authmethod = "trust";
2215  }
2216 }
static bool authwarning
Definition: initdb.c:194

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 2219 of file initdb.c.

2220 {
2221  const char *const *p;
2222 
2223  for (p = valid_methods; *p; p++)
2224  {
2225  if (strcmp(authmethod, *p) == 0)
2226  return;
2227  /* with space = param */
2228  if (strchr(authmethod, ' '))
2229  if (strncmp(authmethod, *p, (authmethod - strchr(authmethod, ' '))) == 0)
2230  return;
2231  }
2232 
2233  pg_fatal("invalid authentication method \"%s\" for \"%s\" connections",
2234  authmethod, conntype);
2235 }
#define pg_fatal(...)

References pg_fatal.

Referenced by main().

◆ check_input()

static void check_input ( char *  path)
static

Definition at line 767 of file initdb.c.

768 {
769  struct stat statbuf;
770 
771  if (stat(path, &statbuf) != 0)
772  {
773  if (errno == ENOENT)
774  {
775  pg_log_error("file \"%s\" does not exist", path);
776  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
777  }
778  else
779  {
780  pg_log_error("could not access file \"%s\": %m", path);
781  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
782  }
783  exit(1);
784  }
785  if (!S_ISREG(statbuf.st_mode))
786  {
787  pg_log_error("file \"%s\" is not a regular file", path);
788  pg_log_error_hint("This might mean you have a corrupted installation or identified the wrong directory with the invocation option -L.");
789  exit(1);
790  }
791 }
#define stat
Definition: win32_port.h:283
#define S_ISREG(m)
Definition: win32_port.h:327

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  encoding 
)
static

Definition at line 2062 of file initdb.c.

2063 {
2064  int locale_enc;
2065 
2066  locale_enc = pg_get_encoding_from_locale(locale, true);
2067 
2068  /* See notes in createdb() to understand these tests */
2069  if (!(locale_enc == user_enc ||
2070  locale_enc == PG_SQL_ASCII ||
2071  locale_enc == -1 ||
2072 #ifdef WIN32
2073  user_enc == PG_UTF8 ||
2074 #endif
2075  user_enc == PG_SQL_ASCII))
2076  {
2077  pg_log_error("encoding mismatch");
2078  pg_log_error_detail("The encoding you selected (%s) and the encoding that the "
2079  "selected locale uses (%s) do not match. This would lead to "
2080  "misbehavior in various character string processing functions.",
2081  pg_encoding_to_char(user_enc),
2082  pg_encoding_to_char(locale_enc));
2083  pg_log_error_hint("Rerun %s and either do not specify an encoding explicitly, "
2084  "or choose a matching combination.",
2085  progname);
2086  return false;
2087  }
2088  return true;
2089 }
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
static char * locale
Definition: initdb.c:128
static const char * progname
Definition: initdb.c:157
#define pg_log_error_detail(...)
Definition: logging.h:109
@ PG_SQL_ASCII
Definition: pg_wchar.h:224
@ PG_UTF8
Definition: pg_wchar.h:230
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:451

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 2005 of file initdb.c.

2006 {
2007  char *save;
2008  char *res;
2009 
2010  if (canonname)
2011  *canonname = NULL; /* in case of failure */
2012 
2013  save = setlocale(category, NULL);
2014  if (!save)
2015  pg_fatal("setlocale() failed");
2016 
2017  /* save may be pointing at a modifiable scratch variable, so copy it. */
2018  save = pg_strdup(save);
2019 
2020  /* for setlocale() call */
2021  if (!locale)
2022  locale = "";
2023 
2024  /* set the locale with setlocale, to see if it accepts it. */
2025  res = setlocale(category, locale);
2026 
2027  /* save canonical name if requested. */
2028  if (res && canonname)
2029  *canonname = pg_strdup(res);
2030 
2031  /* restore old value. */
2032  if (!setlocale(category, save))
2033  pg_fatal("failed to restore old locale \"%s\"", save);
2034  free(save);
2035 
2036  /* complain if locale wasn't valid */
2037  if (res == NULL)
2038  {
2039  if (*locale)
2040  pg_fatal("invalid locale name \"%s\"", locale);
2041  else
2042  {
2043  /*
2044  * If no relevant switch was given on command line, locale is an
2045  * empty string, which is not too helpful to report. Presumably
2046  * setlocale() found something it did not like in the environment.
2047  * Ideally we'd report the bad environment variable, but since
2048  * setlocale's behavior is implementation-specific, it's hard to
2049  * be sure what it didn't like. Print a safe generic message.
2050  */
2051  pg_fatal("invalid locale settings; check LANG and LC_* environment variables");
2052  }
2053  }
2054 }
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define setlocale(a, b)
Definition: win32_port.h:446

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 2238 of file initdb.c.

2239 {
2240  if ((strcmp(authmethodlocal, "md5") == 0 ||
2241  strcmp(authmethodlocal, "password") == 0 ||
2242  strcmp(authmethodlocal, "scram-sha-256") == 0) &&
2243  (strcmp(authmethodhost, "md5") == 0 ||
2244  strcmp(authmethodhost, "password") == 0 ||
2245  strcmp(authmethodhost, "scram-sha-256") == 0) &&
2246  !(pwprompt || pwfilename))
2247  pg_fatal("must specify a password for the superuser to enable password authentication");
2248 }
static const char * authmethodhost
Definition: initdb.c:142
static char * pwfilename
Definition: initdb.c:140
static bool pwprompt
Definition: initdb.c:139
static const char * authmethodlocal
Definition: initdb.c:143

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

Referenced by main().

◆ check_ok()

static void check_ok ( void  )
static

Definition at line 1908 of file initdb.c.

1909 {
1910  if (caught_signal)
1911  {
1912  printf(_("caught signal\n"));
1913  fflush(stdout);
1914  exit(1);
1915  }
1916  else if (output_failed)
1917  {
1918  printf(_("could not write to child process: %s\n"),
1920  fflush(stdout);
1921  exit(1);
1922  }
1923  else
1924  {
1925  /* all seems well */
1926  printf(_("ok\n"));
1927  fflush(stdout);
1928  }
1929 }
static bool output_failed
Definition: initdb.c:176
static bool caught_signal
Definition: initdb.c:175
#define strerror
Definition: port.h:238

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_composite_data_type_usage(), 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 847 of file initdb.c.

848 {
849 #ifdef HAVE_SHM_OPEN
850  int ntries = 10;
851  pg_prng_state prng_state;
852 
853  /* Initialize prng; this function is its only user in this program. */
854  pg_prng_seed(&prng_state, (uint64) (getpid() ^ time(NULL)));
855 
856  while (ntries > 0)
857  {
858  uint32 handle;
859  char name[64];
860  int fd;
861 
862  handle = pg_prng_uint32(&prng_state);
863  snprintf(name, 64, "/PostgreSQL.%u", handle);
864  if ((fd = shm_open(name, O_CREAT | O_RDWR | O_EXCL, 0600)) != -1)
865  {
866  close(fd);
867  shm_unlink(name);
868  return "posix";
869  }
870  if (errno != EEXIST)
871  break;
872  --ntries;
873  }
874 #endif
875 
876 #ifdef WIN32
877  return "windows";
878 #else
879  return "sysv";
880 #endif
881 }
unsigned int uint32
Definition: c.h:441
const char * name
Definition: encode.c:561
#define close(a)
Definition: win32.h:12
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:185
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:83
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 538 of file initdb.c.

539 {
540  if (success)
541  return;
542 
543  if (!noclean)
544  {
545  if (made_new_pgdata)
546  {
547  pg_log_info("removing data directory \"%s\"", pg_data);
548  if (!rmtree(pg_data, true))
549  pg_log_error("failed to remove data directory");
550  }
551  else if (found_existing_pgdata)
552  {
553  pg_log_info("removing contents of data directory \"%s\"",
554  pg_data);
555  if (!rmtree(pg_data, false))
556  pg_log_error("failed to remove contents of data directory");
557  }
558 
559  if (made_new_xlogdir)
560  {
561  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
562  if (!rmtree(xlog_dir, true))
563  pg_log_error("failed to remove WAL directory");
564  }
565  else if (found_existing_xlogdir)
566  {
567  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
568  if (!rmtree(xlog_dir, false))
569  pg_log_error("failed to remove contents of WAL directory");
570  }
571  /* otherwise died during startup, do nothing! */
572  }
573  else
574  {
576  pg_log_info("data directory \"%s\" not removed at user's request",
577  pg_data);
578 
580  pg_log_info("WAL directory \"%s\" not removed at user's request",
581  xlog_dir);
582  }
583 }
static bool noclean
Definition: initdb.c:145
static bool found_existing_pgdata
Definition: initdb.c:171
static bool found_existing_xlogdir
Definition: initdb.c:173
static char * xlog_dir
Definition: initdb.c:151
static bool success
Definition: initdb.c:169
static bool made_new_xlogdir
Definition: initdb.c:172
static char * pg_data
Definition: initdb.c:126
static bool made_new_pgdata
Definition: initdb.c:170
#define pg_log_info(...)
Definition: logging.h:124
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42

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 2522 of file initdb.c.

2523 {
2524  int ret;
2525 
2526  switch ((ret = pg_check_dir(pg_data)))
2527  {
2528  case 0:
2529  /* PGDATA not there, must create it */
2530  printf(_("creating directory %s ... "),
2531  pg_data);
2532  fflush(stdout);
2533 
2535  pg_fatal("could not create directory \"%s\": %m", pg_data);
2536  else
2537  check_ok();
2538 
2539  made_new_pgdata = true;
2540  break;
2541 
2542  case 1:
2543  /* Present but empty, fix permissions and use it */
2544  printf(_("fixing permissions on existing directory %s ... "),
2545  pg_data);
2546  fflush(stdout);
2547 
2548  if (chmod(pg_data, pg_dir_create_mode) != 0)
2549  pg_fatal("could not change permissions of directory \"%s\": %m",
2550  pg_data);
2551  else
2552  check_ok();
2553 
2554  found_existing_pgdata = true;
2555  break;
2556 
2557  case 2:
2558  case 3:
2559  case 4:
2560  /* Present and not empty */
2561  pg_log_error("directory \"%s\" exists but is not empty", pg_data);
2562  if (ret != 4)
2563  warn_on_mount_point(ret);
2564  else
2565  pg_log_error_hint("If you want to create a new database system, either remove or empty "
2566  "the directory \"%s\" or run %s "
2567  "with an argument other than \"%s\".",
2569  exit(1); /* no further message needed */
2570 
2571  default:
2572  /* Trouble accessing directory */
2573  pg_fatal("could not access directory \"%s\": %m", pg_data);
2574  }
2575 }
int pg_dir_create_mode
Definition: file_perm.c:18
void warn_on_mount_point(int error)
Definition: initdb.c:2667
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 2580 of file initdb.c.

2581 {
2582  char *subdirloc;
2583 
2584  /* form name of the place for the subdirectory or symlink */
2585  subdirloc = psprintf("%s/pg_wal", pg_data);
2586 
2587  if (xlog_dir)
2588  {
2589  int ret;
2590 
2591  /* clean up xlog directory name, check it's absolute */
2593  if (!is_absolute_path(xlog_dir))
2594  pg_fatal("WAL directory location must be an absolute path");
2595 
2596  /* check if the specified xlog directory exists/is empty */
2597  switch ((ret = pg_check_dir(xlog_dir)))
2598  {
2599  case 0:
2600  /* xlog directory not there, must create it */
2601  printf(_("creating directory %s ... "),
2602  xlog_dir);
2603  fflush(stdout);
2604 
2606  pg_fatal("could not create directory \"%s\": %m",
2607  xlog_dir);
2608  else
2609  check_ok();
2610 
2611  made_new_xlogdir = true;
2612  break;
2613 
2614  case 1:
2615  /* Present but empty, fix permissions and use it */
2616  printf(_("fixing permissions on existing directory %s ... "),
2617  xlog_dir);
2618  fflush(stdout);
2619 
2620  if (chmod(xlog_dir, pg_dir_create_mode) != 0)
2621  pg_fatal("could not change permissions of directory \"%s\": %m",
2622  xlog_dir);
2623  else
2624  check_ok();
2625 
2626  found_existing_xlogdir = true;
2627  break;
2628 
2629  case 2:
2630  case 3:
2631  case 4:
2632  /* Present and not empty */
2633  pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
2634  if (ret != 4)
2635  warn_on_mount_point(ret);
2636  else
2637  pg_log_error_hint("If you want to store the WAL there, either remove or empty the directory \"%s\".",
2638  xlog_dir);
2639  exit(1);
2640 
2641  default:
2642  /* Trouble accessing directory */
2643  pg_fatal("could not access directory \"%s\": %m", xlog_dir);
2644  }
2645 
2646 #ifdef HAVE_SYMLINK
2647  if (symlink(xlog_dir, subdirloc) != 0)
2648  pg_fatal("could not create symbolic link \"%s\": %m",
2649  subdirloc);
2650 #else
2651  pg_fatal("symlinks are not supported on this platform");
2652 #endif
2653  }
2654  else
2655  {
2656  /* Without -X option, just make the subdirectory normally */
2657  if (mkdir(subdirloc, pg_dir_create_mode) < 0)
2658  pg_fatal("could not create directory \"%s\": %m",
2659  subdirloc);
2660  }
2661 
2662  free(subdirloc);
2663 }
#define is_absolute_path(filename)
Definition: port.h:89
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:71
#define symlink(oldpath, newpath)
Definition: win32_port.h:235

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 610 of file initdb.c.

611 {
612  char result[20];
613 
614  sprintf(result, "%d", enc);
615  return pg_strdup(result);
616 }
struct pg_encoding enc
Definition: encode.c:562

References enc, pg_strdup(), and sprintf.

Referenced by bootstrap_template1().

◆ escape_quotes()

static char * escape_quotes ( const char *  src)
static

Definition at line 329 of file initdb.c.

330 {
331  char *result = escape_single_quotes_ascii(src);
332 
333  if (!result)
334  pg_fatal("out of memory");
335  return result;
336 }
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 345 of file initdb.c.

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

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

Referenced by bootstrap_template1().

◆ filter_lines_with_token()

static char ** filter_lines_with_token ( char **  lines,
const char *  token 
)
static

Definition at line 428 of file initdb.c.

429 {
430  int numlines = 1;
431  int i,
432  src,
433  dst;
434  char **result;
435 
436  for (i = 0; lines[i]; i++)
437  numlines++;
438 
439  result = (char **) pg_malloc(numlines * sizeof(char *));
440 
441  for (src = 0, dst = 0; src < numlines; src++)
442  {
443  if (lines[src] == NULL || strstr(lines[src], token) == NULL)
444  result[dst++] = lines[src];
445  }
446 
447  return result;
448 }
int i
Definition: isn.c:73

References i, and pg_malloc().

Referenced by setup_config().

◆ find_matching_ts_config()

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

Definition at line 712 of file initdb.c.

713 {
714  int i;
715  char *langname,
716  *ptr;
717 
718  /*
719  * Convert lc_ctype to a language name by stripping everything after an
720  * underscore (usual case) or a hyphen (Windows "locale name"; see
721  * comments at IsoLocaleName()).
722  *
723  * XXX Should ' ' be a stop character? This would select "norwegian" for
724  * the Windows locale "Norwegian (Nynorsk)_Norway.1252". If we do so, we
725  * should also accept the "nn" and "nb" Unix locales.
726  *
727  * Just for paranoia, we also stop at '.' or '@'.
728  */
729  if (lc_type == NULL)
730  langname = pg_strdup("");
731  else
732  {
733  ptr = langname = pg_strdup(lc_type);
734  while (*ptr &&
735  *ptr != '_' && *ptr != '-' && *ptr != '.' && *ptr != '@')
736  ptr++;
737  *ptr = '\0';
738  }
739 
740  for (i = 0; tsearch_config_languages[i].tsconfname; i++)
741  {
742  if (pg_strcasecmp(tsearch_config_languages[i].langname, langname) == 0)
743  {
744  free(langname);
746  }
747  }
748 
749  free(langname);
750  return NULL;
751 }
static const struct tsearch_config_match tsearch_config_languages[]
Definition: initdb.c:645
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * tsconfname
Definition: initdb.c:641

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 622 of file initdb.c.

623 {
624  int enc;
625 
626  if (encoding_name && *encoding_name)
627  {
628  if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
629  return enc;
630  }
631  pg_fatal("\"%s\" is not a valid server encoding name",
632  encoding_name ? encoding_name : "(null)");
633 }
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 591 of file initdb.c.

592 {
593  const char *username;
594 
595 #ifndef WIN32
596  if (geteuid() == 0) /* 0 is root's uid */
597  {
598  pg_log_error("cannot be run as root");
599  pg_log_error_hint("Please log in (using, e.g., \"su\") as the (unprivileged) user that will own the server process.");
600  exit(1);
601  }
602 #endif
603 
605 
606  return pg_strdup(username);
607 }
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 1421 of file initdb.c.

1422 {
1423  char *pwd1;
1424 
1425  if (pwprompt)
1426  {
1427  /*
1428  * Read password from terminal
1429  */
1430  char *pwd2;
1431 
1432  printf("\n");
1433  fflush(stdout);
1434  pwd1 = simple_prompt("Enter new superuser password: ", false);
1435  pwd2 = simple_prompt("Enter it again: ", false);
1436  if (strcmp(pwd1, pwd2) != 0)
1437  {
1438  fprintf(stderr, _("Passwords didn't match.\n"));
1439  exit(1);
1440  }
1441  free(pwd2);
1442  }
1443  else
1444  {
1445  /*
1446  * Read password from file
1447  *
1448  * Ideally this should insist that the file not be world-readable.
1449  * However, this option is mainly intended for use on Windows where
1450  * file permissions may not exist at all, so we'll skip the paranoia
1451  * for now.
1452  */
1453  FILE *pwf = fopen(pwfilename, "r");
1454 
1455  if (!pwf)
1456  pg_fatal("could not open file \"%s\" for reading: %m",
1457  pwfilename);
1458  pwd1 = pg_get_line(pwf, NULL);
1459  if (!pwd1)
1460  {
1461  if (ferror(pwf))
1462  pg_fatal("could not read password from file \"%s\": %m",
1463  pwfilename);
1464  else
1465  pg_fatal("password file \"%s\" is empty",
1466  pwfilename);
1467  }
1468  fclose(pwf);
1469 
1470  (void) pg_strip_crlf(pwd1);
1471  }
1472 
1473  superuser_password = pwd1;
1474 }
static char * superuser_password
Definition: initdb.c:141
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:121

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 2680 of file initdb.c.

2681 {
2682  PG_CMD_DECL;
2683  int i;
2684 
2685  setup_signals();
2686 
2687  /*
2688  * Set mask based on requested PGDATA permissions. pg_mode_mask, and
2689  * friends like pg_dir_create_mode, are set to owner-only by default and
2690  * then updated if -g is passed in by calling SetDataDirectoryCreatePerm()
2691  * when parsing our options (see above).
2692  */
2693  umask(pg_mode_mask);
2694 
2696 
2698 
2699  /* Create required subdirectories (other than pg_wal) */
2700  printf(_("creating subdirectories ... "));
2701  fflush(stdout);
2702 
2703  for (i = 0; i < lengthof(subdirs); i++)
2704  {
2705  char *path;
2706 
2707  path = psprintf("%s/%s", pg_data, subdirs[i]);
2708 
2709  /*
2710  * The parent directory already exists, so we only need mkdir() not
2711  * pg_mkdir_p() here, which avoids some failure modes; cf bug #13853.
2712  */
2713  if (mkdir(path, pg_dir_create_mode) < 0)
2714  pg_fatal("could not create directory \"%s\": %m", path);
2715 
2716  free(path);
2717  }
2718 
2719  check_ok();
2720 
2721  /* Top level PG_VERSION is checked by bootstrapper, so make it first */
2722  write_version_file(NULL);
2723 
2724  /* Select suitable configuration settings */
2725  set_null_conf();
2727 
2728  /* Now create all the text config files */
2729  setup_config();
2730 
2731  /* Bootstrap template1 */
2733 
2734  /*
2735  * Make the per-database PG_VERSION for template1 only after init'ing it
2736  */
2737  write_version_file("base/1");
2738 
2739  /*
2740  * Create the stuff we don't need to use bootstrap mode for, using a
2741  * backend running in simple standalone mode.
2742  */
2743  fputs(_("performing post-bootstrap initialization ... "), stdout);
2744  fflush(stdout);
2745 
2746  snprintf(cmd, sizeof(cmd),
2747  "\"%s\" %s %s template1 >%s",
2749  DEVNULL);
2750 
2751  PG_CMD_OPEN;
2752 
2753  setup_auth(cmdfd);
2754 
2756 
2758 
2759  setup_depend(cmdfd);
2760 
2761  /*
2762  * Note that no objects created after setup_depend() will be "pinned".
2763  * They are all droppable at the whim of the DBA.
2764  */
2765 
2767 
2768  setup_description(cmdfd);
2769 
2770  setup_collation(cmdfd);
2771 
2773 
2774  setup_privileges(cmdfd);
2775 
2776  setup_schema(cmdfd);
2777 
2778  load_plpgsql(cmdfd);
2779 
2780  vacuum_db(cmdfd);
2781 
2782  make_template0(cmdfd);
2783 
2784  make_postgres(cmdfd);
2785 
2786  PG_CMD_CLOSE;
2787 
2788  check_ok();
2789 }
#define lengthof(array)
Definition: c.h:734
int pg_mode_mask
Definition: file_perm.c:25
static void setup_depend(FILE *cmdfd)
Definition: initdb.c:1480
static void setup_collation(FILE *cmdfd)
Definition: initdb.c:1542
void create_data_directory(void)
Definition: initdb.c:2522
static void bootstrap_template1(void)
Definition: initdb.c:1308
static void setup_run_file(FILE *cmdfd, const char *filename)
Definition: initdb.c:1500
static const char * backend_options
Definition: initdb.c:207
static void setup_auth(FILE *cmdfd)
Definition: initdb.c:1397
static void make_postgres(FILE *cmdfd)
Definition: initdb.c:1856
static void test_config_settings(void)
Definition: initdb.c:889
static void setup_config(void)
Definition: initdb.c:1020
static void setup_privileges(FILE *cmdfd)
Definition: initdb.c:1577
static void write_version_file(const char *extrapath)
Definition: initdb.c:798
void setup_signals(void)
Definition: initdb.c:2493
static char * system_views_file
Definition: initdb.c:168
static void setup_description(FILE *cmdfd)
Definition: initdb.c:1521
static void vacuum_db(FILE *cmdfd)
Definition: initdb.c:1783
static const char *const subdirs[]
Definition: initdb.c:212
void create_xlog_or_symlink(void)
Definition: initdb.c:2580
static char * system_functions_file
Definition: initdb.c:167
static char * dictionary_file
Definition: initdb.c:163
static void setup_schema(FILE *cmdfd)
Definition: initdb.c:1754
static char * system_constraints_file
Definition: initdb.c:166
static void set_null_conf(void)
Definition: initdb.c:821
static void make_template0(FILE *cmdfd)
Definition: initdb.c:1793
static void load_plpgsql(FILE *cmdfd)
Definition: initdb.c:1774
#define DEVNULL
Definition: port.h:156

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 1774 of file initdb.c.

1775 {
1776  PG_CMD_PUTS("CREATE EXTENSION plpgsql;\n\n");
1777 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ locale_date_order()

static int locale_date_order ( const char *  locale)
static

Definition at line 1942 of file initdb.c.

1943 {
1944  struct tm testtime;
1945  char buf[128];
1946  char *posD;
1947  char *posM;
1948  char *posY;
1949  char *save;
1950  size_t res;
1951  int result;
1952 
1953  result = DATEORDER_MDY; /* default */
1954 
1955  save = setlocale(LC_TIME, NULL);
1956  if (!save)
1957  return result;
1958  save = pg_strdup(save);
1959 
1960  setlocale(LC_TIME, locale);
1961 
1962  memset(&testtime, 0, sizeof(testtime));
1963  testtime.tm_mday = 22;
1964  testtime.tm_mon = 10; /* November, should come out as "11" */
1965  testtime.tm_year = 133; /* 2033 */
1966 
1967  res = my_strftime(buf, sizeof(buf), "%x", &testtime);
1968 
1969  setlocale(LC_TIME, save);
1970  free(save);
1971 
1972  if (res == 0)
1973  return result;
1974 
1975  posM = strstr(buf, "11");
1976  posD = strstr(buf, "22");
1977  posY = strstr(buf, "33");
1978 
1979  if (!posM || !posD || !posY)
1980  return result;
1981 
1982  if (posY < posM && posM < posD)
1983  result = DATEORDER_YMD;
1984  else if (posD < posM)
1985  result = DATEORDER_DMY;
1986  else
1987  result = DATEORDER_MDY;
1988 
1989  return result;
1990 }
static size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
Definition: initdb.c:1933
static struct pg_tm tm
Definition: localtime.c:102
#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 2793 of file initdb.c.

2794 {
2795  static struct option long_options[] = {
2796  {"pgdata", required_argument, NULL, 'D'},
2797  {"encoding", required_argument, NULL, 'E'},
2798  {"locale", required_argument, NULL, 1},
2799  {"lc-collate", required_argument, NULL, 2},
2800  {"lc-ctype", required_argument, NULL, 3},
2801  {"lc-monetary", required_argument, NULL, 4},
2802  {"lc-numeric", required_argument, NULL, 5},
2803  {"lc-time", required_argument, NULL, 6},
2804  {"lc-messages", required_argument, NULL, 7},
2805  {"no-locale", no_argument, NULL, 8},
2806  {"text-search-config", required_argument, NULL, 'T'},
2807  {"auth", required_argument, NULL, 'A'},
2808  {"auth-local", required_argument, NULL, 10},
2809  {"auth-host", required_argument, NULL, 11},
2810  {"pwprompt", no_argument, NULL, 'W'},
2811  {"pwfile", required_argument, NULL, 9},
2812  {"username", required_argument, NULL, 'U'},
2813  {"help", no_argument, NULL, '?'},
2814  {"version", no_argument, NULL, 'V'},
2815  {"debug", no_argument, NULL, 'd'},
2816  {"show", no_argument, NULL, 's'},
2817  {"noclean", no_argument, NULL, 'n'}, /* for backwards compatibility */
2818  {"no-clean", no_argument, NULL, 'n'},
2819  {"nosync", no_argument, NULL, 'N'}, /* for backwards compatibility */
2820  {"no-sync", no_argument, NULL, 'N'},
2821  {"no-instructions", no_argument, NULL, 13},
2822  {"sync-only", no_argument, NULL, 'S'},
2823  {"waldir", required_argument, NULL, 'X'},
2824  {"wal-segsize", required_argument, NULL, 12},
2825  {"data-checksums", no_argument, NULL, 'k'},
2826  {"allow-group-access", no_argument, NULL, 'g'},
2827  {"discard-caches", no_argument, NULL, 14},
2828  {"locale-provider", required_argument, NULL, 15},
2829  {"icu-locale", required_argument, NULL, 16},
2830  {NULL, 0, NULL, 0}
2831  };
2832 
2833  /*
2834  * options with no short version return a low integer, the rest return
2835  * their short version value
2836  */
2837  int c;
2838  int option_index;
2839  char *effective_user;
2840  PQExpBuffer start_db_cmd;
2841  char pg_ctl_path[MAXPGPATH];
2842 
2843  /*
2844  * Ensure that buffering behavior of stdout matches what it is in
2845  * interactive usage (at least on most platforms). This prevents
2846  * unexpected output ordering when, eg, output is redirected to a file.
2847  * POSIX says we must do this before any other usage of these files.
2848  */
2849  setvbuf(stdout, NULL, PG_IOLBF, 0);
2850 
2851  pg_logging_init(argv[0]);
2852  progname = get_progname(argv[0]);
2853  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
2854 
2855  if (argc > 1)
2856  {
2857  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2858  {
2859  usage(progname);
2860  exit(0);
2861  }
2862  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2863  {
2864  puts("initdb (PostgreSQL) " PG_VERSION);
2865  exit(0);
2866  }
2867  }
2868 
2869  /* process command-line options */
2870 
2871  while ((c = getopt_long(argc, argv, "A:dD:E:gkL:nNsST:U:WX:", long_options, &option_index)) != -1)
2872  {
2873  switch (c)
2874  {
2875  case 'A':
2877 
2878  /*
2879  * When ident is specified, use peer for local connections.
2880  * Mirrored, when peer is specified, use ident for TCP/IP
2881  * connections.
2882  */
2883  if (strcmp(authmethodhost, "ident") == 0)
2884  authmethodlocal = "peer";
2885  else if (strcmp(authmethodlocal, "peer") == 0)
2886  authmethodhost = "ident";
2887  break;
2888  case 10:
2890  break;
2891  case 11:
2893  break;
2894  case 'D':
2896  break;
2897  case 'E':
2899  break;
2900  case 'W':
2901  pwprompt = true;
2902  break;
2903  case 'U':
2905  break;
2906  case 'd':
2907  debug = true;
2908  printf(_("Running in debug mode.\n"));
2909  break;
2910  case 'n':
2911  noclean = true;
2912  printf(_("Running in no-clean mode. Mistakes will not be cleaned up.\n"));
2913  break;
2914  case 'N':
2915  do_sync = false;
2916  break;
2917  case 'S':
2918  sync_only = true;
2919  break;
2920  case 'k':
2921  data_checksums = true;
2922  break;
2923  case 'L':
2925  break;
2926  case 1:
2927  locale = pg_strdup(optarg);
2928  break;
2929  case 2:
2931  break;
2932  case 3:
2934  break;
2935  case 4:
2937  break;
2938  case 5:
2940  break;
2941  case 6:
2943  break;
2944  case 7:
2946  break;
2947  case 8:
2948  locale = "C";
2949  break;
2950  case 9:
2952  break;
2953  case 's':
2954  show_setting = true;
2955  break;
2956  case 'T':
2958  break;
2959  case 'X':
2961  break;
2962  case 12:
2964  break;
2965  case 13:
2966  noinstructions = true;
2967  break;
2968  case 'g':
2970  break;
2971  case 14:
2972  extra_options = psprintf("%s %s",
2973  extra_options,
2974  "-c debug_discard_caches=1");
2975  break;
2976  case 15:
2977  if (strcmp(optarg, "icu") == 0)
2978  locale_provider = COLLPROVIDER_ICU;
2979  else if (strcmp(optarg, "libc") == 0)
2980  locale_provider = COLLPROVIDER_LIBC;
2981  else
2982  pg_fatal("unrecognized locale provider: %s", optarg);
2983  break;
2984  case 16:
2986  break;
2987  default:
2988  /* getopt_long already emitted a complaint */
2989  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2990  exit(1);
2991  }
2992  }
2993 
2994 
2995  /*
2996  * Non-option argument specifies data directory as long as it wasn't
2997  * already specified with -D / --pgdata
2998  */
2999  if (optind < argc && !pg_data)
3000  {
3001  pg_data = pg_strdup(argv[optind]);
3002  optind++;
3003  }
3004 
3005  if (optind < argc)
3006  {
3007  pg_log_error("too many command-line arguments (first is \"%s\")",
3008  argv[optind]);
3009  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3010  exit(1);
3011  }
3012 
3013  if (icu_locale && locale_provider != COLLPROVIDER_ICU)
3014  pg_fatal("%s cannot be specified unless locale provider \"%s\" is chosen",
3015  "--icu-locale", "icu");
3016 
3018 
3019  /* If we only need to fsync, just do it and exit */
3020  if (sync_only)
3021  {
3022  setup_pgdata();
3023 
3024  /* must check that directory is readable */
3025  if (pg_check_dir(pg_data) <= 0)
3026  pg_fatal("could not access directory \"%s\": %m", pg_data);
3027 
3028  fputs(_("syncing data to disk ... "), stdout);
3029  fflush(stdout);
3030  fsync_pgdata(pg_data, PG_VERSION_NUM);
3031  check_ok();
3032  return 0;
3033  }
3034 
3035  if (pwprompt && pwfilename)
3036  pg_fatal("password prompt and password file cannot be specified together");
3037 
3040 
3043 
3045 
3046  /* set wal segment size */
3047  if (str_wal_segment_size_mb == NULL)
3048  wal_segment_size_mb = (DEFAULT_XLOG_SEG_SIZE) / (1024 * 1024);
3049  else
3050  {
3051  char *endptr;
3052 
3053  /* check that the argument is a number */
3054  wal_segment_size_mb = strtol(str_wal_segment_size_mb, &endptr, 10);
3055 
3056  /* verify that wal segment size is valid */
3057  if (endptr == str_wal_segment_size_mb || *endptr != '\0')
3058  pg_fatal("argument of --wal-segsize must be a number");
3059  if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
3060  pg_fatal("argument of --wal-segsize must be a power of 2 between 1 and 1024");
3061  }
3062 
3064 
3065  setup_pgdata();
3066 
3067  setup_bin_paths(argv[0]);
3068 
3069  effective_user = get_id();
3070  if (!username)
3071  username = effective_user;
3072 
3073  if (strncmp(username, "pg_", 3) == 0)
3074  pg_fatal("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
3075 
3076  printf(_("The files belonging to this database system will be owned "
3077  "by user \"%s\".\n"
3078  "This user must also own the server process.\n\n"),
3079  effective_user);
3080 
3081  set_info_version();
3082 
3084 
3086 
3088 
3089  printf("\n");
3090 
3091  if (data_checksums)
3092  printf(_("Data page checksums are enabled.\n"));
3093  else
3094  printf(_("Data page checksums are disabled.\n"));
3095 
3096  if (pwprompt || pwfilename)
3097  get_su_pwd();
3098 
3099  printf("\n");
3100 
3102 
3103  if (do_sync)
3104  {
3105  fputs(_("syncing data to disk ... "), stdout);
3106  fflush(stdout);
3107  fsync_pgdata(pg_data, PG_VERSION_NUM);
3108  check_ok();
3109  }
3110  else
3111  printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
3112 
3113  if (authwarning)
3114  {
3115  printf("\n");
3116  pg_log_warning("enabling \"trust\" authentication for local connections");
3117  pg_log_warning_hint("You can change this by editing pg_hba.conf or using the option -A, or "
3118  "--auth-local and --auth-host, the next time you run initdb.");
3119  }
3120 
3121  if (!noinstructions)
3122  {
3123  /*
3124  * Build up a shell command to tell the user how to start the server
3125  */
3126  start_db_cmd = createPQExpBuffer();
3127 
3128  /* Get directory specification used to start initdb ... */
3129  strlcpy(pg_ctl_path, argv[0], sizeof(pg_ctl_path));
3130  canonicalize_path(pg_ctl_path);
3131  get_parent_directory(pg_ctl_path);
3132  /* ... and tag on pg_ctl instead */
3133  join_path_components(pg_ctl_path, pg_ctl_path, "pg_ctl");
3134 
3135  /* Convert the path to use native separators */
3136  make_native_path(pg_ctl_path);
3137 
3138  /* path to pg_ctl, properly quoted */
3139  appendShellString(start_db_cmd, pg_ctl_path);
3140 
3141  /* add -D switch, with properly quoted data directory */
3142  appendPQExpBufferStr(start_db_cmd, " -D ");
3143  appendShellString(start_db_cmd, pgdata_native);
3144 
3145  /* add suggested -l switch and "start" command */
3146  /* translator: This is a placeholder in a shell command. */
3147  appendPQExpBuffer(start_db_cmd, " -l %s start", _("logfile"));
3148 
3149  printf(_("\nSuccess. You can now start the database server using:\n\n"
3150  " %s\n\n"),
3151  start_db_cmd->data);
3152 
3153  destroyPQExpBuffer(start_db_cmd);
3154  }
3155 
3156 
3157  success = true;
3158  return 0;
3159 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:446
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:2161
static char * lc_time
Definition: initdb.c:133
static char * get_id(void)
Definition: initdb.c:591
static char * pgdata_native
Definition: initdb.c:178
static void check_authmethod_valid(const char *authmethod, const char *const *valid_methods, const char *conntype)
Definition: initdb.c:2219
static bool noinstructions
Definition: initdb.c:146
void initialize_data_directory(void)
Definition: initdb.c:2680
void setup_text_search(void)
Definition: initdb.c:2459
static char * share_path
Definition: initdb.c:123
void setup_bin_paths(const char *argv0)
Definition: initdb.c:2289
static void check_authmethod_unspecified(const char **authmethod)
Definition: initdb.c:2209
static char * str_wal_segment_size_mb
Definition: initdb.c:152
static const char *const auth_methods_host[]
Definition: initdb.c:84
void setup_locale_encoding(void)
Definition: initdb.c:2326
static const char *const auth_methods_local[]
Definition: initdb.c:106
static bool sync_only
Definition: initdb.c:148
static void check_need_password(const char *authmethodlocal, const char *authmethodhost)
Definition: initdb.c:2238
static bool do_sync
Definition: initdb.c:147
static void cleanup_directories_atexit(void)
Definition: initdb.c:538
static char * lc_messages
Definition: initdb.c:134
static void set_info_version(void)
Definition: initdb.c:1727
void setup_data_file_paths(void)
Definition: initdb.c:2415
static char * encoding
Definition: initdb.c:127
static char * lc_numeric
Definition: initdb.c:132
void setup_pgdata(void)
Definition: initdb.c:2252
static bool show_setting
Definition: initdb.c:149
static const char * default_text_search_config
Definition: initdb.c:137
static char * lc_monetary
Definition: initdb.c:131
static void get_su_pwd(void)
Definition: initdb.c:1421
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:354
void make_native_path(char *path)
Definition: path.c:167
void get_parent_directory(char *path)
Definition: path.c:977
const char * get_progname(const char *argv0)
Definition: path.c:574
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
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 1856 of file initdb.c.

1857 {
1858  const char *const *line;
1859 
1860  /*
1861  * Just as we did for template0, and for the same reasons, assign a fixed
1862  * OID to postgres and select the file_copy strategy.
1863  */
1864  static const char *const postgres_setup[] = {
1865  "CREATE DATABASE postgres OID = " CppAsString2(PostgresDbOid)
1866  " STRATEGY = file_copy;\n\n",
1867  "COMMENT ON DATABASE postgres IS 'default administrative connection database';\n\n",
1868  NULL
1869  };
1870 
1871  for (line = postgres_setup; *line; line++)
1872  PG_CMD_PUTS(*line);
1873 }
#define CppAsString2(x)
Definition: c.h:289

References CppAsString2, and PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ make_template0()

static void make_template0 ( FILE *  cmdfd)
static

Definition at line 1793 of file initdb.c.

1794 {
1795  const char *const *line;
1796 
1797  /*
1798  * pg_upgrade tries to preserve database OIDs across upgrades. It's smart
1799  * enough to drop and recreate a conflicting database with the same name,
1800  * but if the same OID were used for one system-created database in the
1801  * old cluster and a different system-created database in the new cluster,
1802  * it would fail. To avoid that, assign a fixed OID to template0 rather
1803  * than letting the server choose one.
1804  *
1805  * (Note that, while the user could have dropped and recreated these
1806  * objects in the old cluster, the problem scenario only exists if the OID
1807  * that is in use in the old cluster is also used in the new cluster - and
1808  * the new cluster should be the result of a fresh initdb.)
1809  *
1810  * We use "STRATEGY = file_copy" here because checkpoints during initdb
1811  * are cheap. "STRATEGY = wal_log" would generate more WAL, which would be
1812  * a little bit slower and make the new cluster a little bit bigger.
1813  */
1814  static const char *const template0_setup[] = {
1815  "CREATE DATABASE template0 IS_TEMPLATE = true ALLOW_CONNECTIONS = false"
1816  " OID = " CppAsString2(Template0DbOid)
1817  " STRATEGY = file_copy;\n\n",
1818 
1819  /*
1820  * template0 shouldn't have any collation-dependent objects, so unset
1821  * the collation version. This disables collation version checks when
1822  * making a new database from it.
1823  */
1824  "UPDATE pg_database SET datcollversion = NULL WHERE datname = 'template0';\n\n",
1825 
1826  /*
1827  * While we are here, do set the collation version on template1.
1828  */
1829  "UPDATE pg_database SET datcollversion = pg_database_collation_actual_version(oid) WHERE datname = 'template1';\n\n",
1830 
1831  /*
1832  * Explicitly revoke public create-schema and create-temp-table
1833  * privileges in template1 and template0; else the latter would be on
1834  * by default
1835  */
1836  "REVOKE CREATE,TEMPORARY ON DATABASE template1 FROM public;\n\n",
1837  "REVOKE CREATE,TEMPORARY ON DATABASE template0 FROM public;\n\n",
1838 
1839  "COMMENT ON DATABASE template0 IS 'unmodifiable empty database';\n\n",
1840 
1841  /*
1842  * Finally vacuum to clean up dead rows in pg_database
1843  */
1844  "VACUUM pg_database;\n\n",
1845  NULL
1846  };
1847 
1848  for (line = template0_setup; *line; line++)
1849  PG_CMD_PUTS(*line);
1850 }

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 1933 of file initdb.c.

1934 {
1935  return strftime(s, max, fmt, tm);
1936 }

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 520 of file initdb.c.

521 {
522  FILE *cmdfd;
523 
524  fflush(stdout);
525  fflush(stderr);
526  errno = 0;
527  cmdfd = popen(command, mode);
528  if (cmdfd == NULL)
529  pg_log_error("could not execute command \"%s\": %m", command);
530  return cmdfd;
531 }
static PgChecksumMode mode
Definition: pg_checksums.c:65

References fflush(), mode, pg_log_error, and generate_unaccent_rules::stdout.

◆ pretty_wal_size()

static char* pretty_wal_size ( int  segment_count)
static

Definition at line 1003 of file initdb.c.

1004 {
1005  int sz = wal_segment_size_mb * segment_count;
1006  char *result = pg_malloc(14);
1007 
1008  if ((sz % 1024) == 0)
1009  snprintf(result, 14, "%dGB", sz / 1024);
1010  else
1011  snprintf(result, 14, "%dMB", sz);
1012 
1013  return result;
1014 }

References pg_malloc(), snprintf, and wal_segment_size_mb.

Referenced by setup_config().

◆ readfile()

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

Definition at line 455 of file initdb.c.

456 {
457  char **result;
458  FILE *infile;
459  StringInfoData line;
460  int maxlines;
461  int n;
462 
463  if ((infile = fopen(path, "r")) == NULL)
464  pg_fatal("could not open file \"%s\" for reading: %m", path);
465 
466  initStringInfo(&line);
467 
468  maxlines = 1024;
469  result = (char **) pg_malloc(maxlines * sizeof(char *));
470 
471  n = 0;
472  while (pg_get_line_buf(infile, &line))
473  {
474  /* make sure there will be room for a trailing NULL pointer */
475  if (n >= maxlines - 1)
476  {
477  maxlines *= 2;
478  result = (char **) pg_realloc(result, maxlines * sizeof(char *));
479  }
480 
481  result[n++] = pg_strdup(line.data);
482  }
483  result[n] = NULL;
484 
485  pfree(line.data);
486 
487  fclose(infile);
488 
489  return result;
490 }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
void pfree(void *pointer)
Definition: mcxt.c:1175
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 *filename)
Definition: zic.c:1241

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 372 of file initdb.c.

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

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

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

◆ 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 1727 of file initdb.c.

1728 {
1729  char *letterversion;
1730  long major = 0,
1731  minor = 0,
1732  micro = 0;
1733  char *endptr;
1734  char *vstr = pg_strdup(PG_VERSION);
1735  char *ptr;
1736 
1737  ptr = vstr + (strlen(vstr) - 1);
1738  while (ptr != vstr && (*ptr < '0' || *ptr > '9'))
1739  ptr--;
1740  letterversion = ptr + 1;
1741  major = strtol(vstr, &endptr, 10);
1742  if (*endptr)
1743  minor = strtol(endptr + 1, &endptr, 10);
1744  if (*endptr)
1745  micro = strtol(endptr + 1, &endptr, 10);
1746  snprintf(infoversion, sizeof(infoversion), "%02ld.%02ld.%04ld%s",
1747  major, minor, micro, letterversion);
1748 }
static char infoversion[100]
Definition: initdb.c:174

References infoversion, pg_strdup(), and snprintf.

Referenced by main().

◆ set_input()

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

Definition at line 758 of file initdb.c.

759 {
760  *dest = psprintf("%s/%s", share_path, filename);
761 }
static char * filename
Definition: pg_dumpall.c:94

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 821 of file initdb.c.

822 {
823  FILE *conf_file;
824  char *path;
825 
826  path = psprintf("%s/postgresql.conf", pg_data);
827  conf_file = fopen(path, PG_BINARY_W);
828  if (conf_file == NULL)
829  pg_fatal("could not open file \"%s\" for writing: %m", path);
830  if (fclose(conf_file))
831  pg_fatal("could not write file \"%s\": %m", path);
832  free(path);
833 }
#define PG_BINARY_W
Definition: c.h:1271
static char * conf_file
Definition: initdb.c:162

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 2097 of file initdb.c.

2098 {
2099  char *canonname;
2100 
2101  /* set empty lc_* values to locale config if set */
2102 
2103  if (locale)
2104  {
2105  if (!lc_ctype)
2106  lc_ctype = locale;
2107  if (!lc_collate)
2108  lc_collate = locale;
2109  if (!lc_numeric)
2110  lc_numeric = locale;
2111  if (!lc_time)
2112  lc_time = locale;
2113  if (!lc_monetary)
2114  lc_monetary = locale;
2115  if (!lc_messages)
2116  lc_messages = locale;
2117  }
2118 
2119  /*
2120  * canonicalize locale names, and obtain any missing values from our
2121  * current environment
2122  */
2123  check_locale_name(LC_CTYPE, lc_ctype, &canonname);
2124  lc_ctype = canonname;
2125  check_locale_name(LC_COLLATE, lc_collate, &canonname);
2126  lc_collate = canonname;
2127  check_locale_name(LC_NUMERIC, lc_numeric, &canonname);
2128  lc_numeric = canonname;
2129  check_locale_name(LC_TIME, lc_time, &canonname);
2130  lc_time = canonname;
2131  check_locale_name(LC_MONETARY, lc_monetary, &canonname);
2132  lc_monetary = canonname;
2133 #if defined(LC_MESSAGES) && !defined(WIN32)
2134  check_locale_name(LC_MESSAGES, lc_messages, &canonname);
2135  lc_messages = canonname;
2136 #else
2137  /* when LC_MESSAGES is not available, use the LC_CTYPE setting */
2138  check_locale_name(LC_CTYPE, lc_messages, &canonname);
2139  lc_messages = canonname;
2140 #endif
2141 
2142  if (locale_provider == COLLPROVIDER_ICU)
2143  {
2144  if (!icu_locale)
2145  pg_fatal("ICU locale must be specified");
2146 
2147  /*
2148  * In supported builds, the ICU locale ID will be checked by the
2149  * backend during post-bootstrap initialization.
2150  */
2151 #ifndef USE_ICU
2152  pg_fatal("ICU is not supported in this build");
2153 #endif
2154  }
2155 }
static void check_locale_name(int category, const char *locale, char **canonname)
Definition: initdb.c:2005

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 1397 of file initdb.c.

1398 {
1399  const char *const *line;
1400  static const char *const pg_authid_setup[] = {
1401  /*
1402  * The authid table shouldn't be readable except through views, to
1403  * ensure passwords are not publicly visible.
1404  */
1405  "REVOKE ALL ON pg_authid FROM public;\n\n",
1406  NULL
1407  };
1408 
1409  for (line = pg_authid_setup; *line != NULL; line++)
1410  PG_CMD_PUTS(*line);
1411 
1412  if (superuser_password)
1413  PG_CMD_PRINTF("ALTER USER \"%s\" WITH PASSWORD E'%s';\n\n",
1415 }
#define PG_CMD_PRINTF(fmt,...)
Definition: initdb.c:318

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 2289 of file initdb.c.

2290 {
2291  int ret;
2292 
2293  if ((ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
2294  backend_exec)) < 0)
2295  {
2296  char full_path[MAXPGPATH];
2297 
2298  if (find_my_exec(argv0, full_path) < 0)
2299  strlcpy(full_path, progname, sizeof(full_path));
2300 
2301  if (ret == -1)
2302  pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
2303  "postgres", progname, full_path);
2304  else
2305  pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
2306  "postgres", full_path, progname);
2307  }
2308 
2309  /* store binary directory */
2310  strcpy(bin_path, backend_exec);
2311  *last_dir_separator(bin_path) = '\0';
2313 
2314  if (!share_path)
2315  {
2318  }
2319  else if (!is_absolute_path(share_path))
2320  pg_fatal("input file location must be an absolute path");
2321 
2323 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:140
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:335
static char bin_path[MAXPGPATH]
Definition: initdb.c:239
static char * argv0
Definition: pg_ctl.c:97
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:139

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 1542 of file initdb.c.

1543 {
1544  /*
1545  * Add an SQL-standard name. We don't want to pin this, so it doesn't go
1546  * in pg_collation.h. But add it before reading system collations, so
1547  * that it wins if libc defines a locale named ucs_basic.
1548  */
1549  PG_CMD_PRINTF("INSERT INTO pg_collation (oid, collname, collnamespace, collowner, collprovider, collisdeterministic, collencoding, collcollate, collctype)"
1550  "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",
1551  BOOTSTRAP_SUPERUSERID, COLLPROVIDER_LIBC, PG_UTF8);
1552 
1553  /* Now import all collations we can find in the operating system */
1554  PG_CMD_PUTS("SELECT pg_import_system_collations('pg_catalog');\n\n");
1555 }

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 1020 of file initdb.c.

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

2416 {
2417  set_input(&bki_file, "postgres.bki");
2418  set_input(&hba_file, "pg_hba.conf.sample");
2419  set_input(&ident_file, "pg_ident.conf.sample");
2420  set_input(&conf_file, "postgresql.conf.sample");
2421  set_input(&dictionary_file, "snowball_create.sql");
2422  set_input(&info_schema_file, "information_schema.sql");
2423  set_input(&features_file, "sql_features.txt");
2424  set_input(&system_constraints_file, "system_constraints.sql");
2425  set_input(&system_functions_file, "system_functions.sql");
2426  set_input(&system_views_file, "system_views.sql");
2427 
2428  if (show_setting || debug)
2429  {
2430  fprintf(stderr,
2431  "VERSION=%s\n"
2432  "PGDATA=%s\nshare_path=%s\nPGPATH=%s\n"
2433  "POSTGRES_SUPERUSERNAME=%s\nPOSTGRES_BKI=%s\n"
2434  "POSTGRESQL_CONF_SAMPLE=%s\n"
2435  "PG_HBA_SAMPLE=%s\nPG_IDENT_SAMPLE=%s\n",
2436  PG_VERSION,
2438  username, bki_file,
2439  conf_file,
2440  hba_file, ident_file);
2441  if (show_setting)
2442  exit(0);
2443  }
2444 
2455 }
static char * features_file
Definition: initdb.c:165
static void set_input(char **dest, const char *filename)
Definition: initdb.c:758
static void check_input(char *path)
Definition: initdb.c:767
static char * info_schema_file
Definition: initdb.c:164

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 1480 of file initdb.c.

1481 {
1482  const char *const *line;
1483  static const char *const pg_depend_setup[] = {
1484  /*
1485  * Advance the OID counter so that subsequently-created objects aren't
1486  * pinned.
1487  */
1488  "SELECT pg_stop_making_pinned_objects();\n\n",
1489  NULL
1490  };
1491 
1492  for (line = pg_depend_setup; *line != NULL; line++)
1493  PG_CMD_PUTS(*line);
1494 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ setup_description()

static void setup_description ( FILE *  cmdfd)
static

Definition at line 1521 of file initdb.c.

1522 {
1523  /* Create default descriptions for operator implementation functions */
1524  PG_CMD_PUTS("WITH funcdescs AS ( "
1525  "SELECT p.oid as p_oid, o.oid as o_oid, oprname "
1526  "FROM pg_proc p JOIN pg_operator o ON oprcode = p.oid ) "
1527  "INSERT INTO pg_description "
1528  " SELECT p_oid, 'pg_proc'::regclass, 0, "
1529  " 'implementation of ' || oprname || ' operator' "
1530  " FROM funcdescs "
1531  " WHERE NOT EXISTS (SELECT 1 FROM pg_description "
1532  " WHERE objoid = p_oid AND classoid = 'pg_proc'::regclass) "
1533  " AND NOT EXISTS (SELECT 1 FROM pg_description "
1534  " WHERE objoid = o_oid AND classoid = 'pg_operator'::regclass"
1535  " AND description LIKE 'deprecated%');\n\n");
1536 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ setup_locale_encoding()

void setup_locale_encoding ( void  )

Definition at line 2326 of file initdb.c.

2327 {
2328  setlocales();
2329 
2330  if (locale_provider == COLLPROVIDER_LIBC &&
2331  strcmp(lc_ctype, lc_collate) == 0 &&
2332  strcmp(lc_ctype, lc_time) == 0 &&
2333  strcmp(lc_ctype, lc_numeric) == 0 &&
2334  strcmp(lc_ctype, lc_monetary) == 0 &&
2335  strcmp(lc_ctype, lc_messages) == 0 &&
2336  (!icu_locale || strcmp(lc_ctype, icu_locale) == 0))
2337  printf(_("The database cluster will be initialized with locale \"%s\".\n"), lc_ctype);
2338  else
2339  {
2340  printf(_("The database cluster will be initialized with this locale configuration:\n"));
2341  printf(_(" provider: %s\n"), collprovider_name(locale_provider));
2342  if (icu_locale)
2343  printf(_(" ICU locale: %s\n"), icu_locale);
2344  printf(_(" LC_COLLATE: %s\n"
2345  " LC_CTYPE: %s\n"
2346  " LC_MESSAGES: %s\n"
2347  " LC_MONETARY: %s\n"
2348  " LC_NUMERIC: %s\n"
2349  " LC_TIME: %s\n"),
2350  lc_collate,
2351  lc_ctype,
2352  lc_messages,
2353  lc_monetary,
2354  lc_numeric,
2355  lc_time);
2356  }
2357 
2358  if (!encoding && locale_provider == COLLPROVIDER_ICU)
2359  encodingid = PG_UTF8;
2360  else if (!encoding)
2361  {
2362  int ctype_enc;
2363 
2364  ctype_enc = pg_get_encoding_from_locale(lc_ctype, true);
2365 
2366  if (ctype_enc == -1)
2367  {
2368  /* Couldn't recognize the locale's codeset */
2369  pg_log_error("could not find suitable encoding for locale \"%s\"",
2370  lc_ctype);
2371  pg_log_error_hint("Rerun %s with the -E option.", progname);
2372  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2373  exit(1);
2374  }
2375  else if (!pg_valid_server_encoding_id(ctype_enc))
2376  {
2377  /*
2378  * We recognized it, but it's not a legal server encoding. On
2379  * Windows, UTF-8 works with any locale, so we can fall back to
2380  * UTF-8.
2381  */
2382 #ifdef WIN32
2383  encodingid = PG_UTF8;
2384  printf(_("Encoding \"%s\" implied by locale is not allowed as a server-side encoding.\n"
2385  "The default database encoding will be set to \"%s\" instead.\n"),
2386  pg_encoding_to_char(ctype_enc),
2388 #else
2389  pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
2390  lc_ctype, pg_encoding_to_char(ctype_enc));
2391  pg_log_error_detail("Encoding \"%s\" is not allowed as a server-side encoding.",
2392  pg_encoding_to_char(ctype_enc));
2393  pg_log_error_hint("Rerun %s with a different locale selection.",
2394  progname);
2395  exit(1);
2396 #endif
2397  }
2398  else
2399  {
2400  encodingid = ctype_enc;
2401  printf(_("The default database encoding has accordingly been set to \"%s\".\n"),
2403  }
2404  }
2405  else
2407 
2410  exit(1); /* check_locale_encoding printed the error */
2411 }
int pg_valid_server_encoding_id(int encoding)
Definition: encnames.c:514
static int get_encoding_id(const char *encoding_name)
Definition: initdb.c:622
static void setlocales(void)
Definition: initdb.c:2097
static bool check_locale_encoding(const char *locale, int encoding)
Definition: initdb.c:2062

References _, 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 2252 of file initdb.c.

2253 {
2254  char *pgdata_get_env;
2255 
2256  if (!pg_data)
2257  {
2258  pgdata_get_env = getenv("PGDATA");
2259  if (pgdata_get_env && strlen(pgdata_get_env))
2260  {
2261  /* PGDATA found */
2262  pg_data = pg_strdup(pgdata_get_env);
2263  }
2264  else
2265  {
2266  pg_log_error("no data directory specified");
2267  pg_log_error_hint("You must identify the directory where the data for this database system "
2268  "will reside. Do this with either the invocation option -D or the "
2269  "environment variable PGDATA.");
2270  exit(1);
2271  }
2272  }
2273 
2276 
2277  /*
2278  * we have to set PGDATA for postgres rather than pass it on the command
2279  * line to avoid dumb quoting problems on Windows, and we would especially
2280  * need quotes otherwise on Windows because paths there are most likely to
2281  * have embedded spaces.
2282  */
2283  if (setenv("PGDATA", pg_data, 1) != 0)
2284  pg_fatal("could not set environment");
2285 }
#define setenv(x, y, z)
Definition: win32_port.h:507

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 1577 of file initdb.c.

1578 {
1579  char **line;
1580  char **priv_lines;
1581  static char *privileges_setup[] = {
1582  "UPDATE pg_class "
1583  " SET relacl = (SELECT array_agg(a.acl) FROM "
1584  " (SELECT E'=r/\"$POSTGRES_SUPERUSERNAME\"' as acl "
1585  " UNION SELECT unnest(pg_catalog.acldefault("
1586  " CASE WHEN relkind = " CppAsString2(RELKIND_SEQUENCE) " THEN 's' "
1587  " ELSE 'r' END::\"char\"," CppAsString2(BOOTSTRAP_SUPERUSERID) "::oid))"
1588  " ) as a) "
1589  " WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1590  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1591  CppAsString2(RELKIND_SEQUENCE) ")"
1592  " AND relacl IS NULL;\n\n",
1593  "GRANT USAGE ON SCHEMA pg_catalog, public TO PUBLIC;\n\n",
1594  "REVOKE ALL ON pg_largeobject FROM PUBLIC;\n\n",
1595  "INSERT INTO pg_init_privs "
1596  " (objoid, classoid, objsubid, initprivs, privtype)"
1597  " SELECT"
1598  " oid,"
1599  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1600  " 0,"
1601  " relacl,"
1602  " 'i'"
1603  " FROM"
1604  " pg_class"
1605  " WHERE"
1606  " relacl IS NOT NULL"
1607  " AND relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1608  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1609  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1610  "INSERT INTO pg_init_privs "
1611  " (objoid, classoid, objsubid, initprivs, privtype)"
1612  " SELECT"
1613  " pg_class.oid,"
1614  " (SELECT oid FROM pg_class WHERE relname = 'pg_class'),"
1615  " pg_attribute.attnum,"
1616  " pg_attribute.attacl,"
1617  " 'i'"
1618  " FROM"
1619  " pg_class"
1620  " JOIN pg_attribute ON (pg_class.oid = pg_attribute.attrelid)"
1621  " WHERE"
1622  " pg_attribute.attacl IS NOT NULL"
1623  " AND pg_class.relkind IN (" CppAsString2(RELKIND_RELATION) ", "
1624  CppAsString2(RELKIND_VIEW) ", " CppAsString2(RELKIND_MATVIEW) ", "
1625  CppAsString2(RELKIND_SEQUENCE) ");\n\n",
1626  "INSERT INTO pg_init_privs "
1627  " (objoid, classoid, objsubid, initprivs, privtype)"
1628  " SELECT"
1629  " oid,"
1630  " (SELECT oid FROM pg_class WHERE relname = 'pg_proc'),"
1631  " 0,"
1632  " proacl,"
1633  " 'i'"
1634  " FROM"
1635  " pg_proc"
1636  " WHERE"
1637  " proacl IS NOT NULL;\n\n",
1638  "INSERT INTO pg_init_privs "
1639  " (objoid, classoid, objsubid, initprivs, privtype)"
1640  " SELECT"
1641  " oid,"
1642  " (SELECT oid FROM pg_class WHERE relname = 'pg_type'),"
1643  " 0,"
1644  " typacl,"
1645  " 'i'"
1646  " FROM"
1647  " pg_type"
1648  " WHERE"
1649  " typacl IS NOT NULL;\n\n",
1650  "INSERT INTO pg_init_privs "
1651  " (objoid, classoid, objsubid, initprivs, privtype)"
1652  " SELECT"
1653  " oid,"
1654  " (SELECT oid FROM pg_class WHERE relname = 'pg_language'),"
1655  " 0,"
1656  " lanacl,"
1657  " 'i'"
1658  " FROM"
1659  " pg_language"
1660  " WHERE"
1661  " lanacl IS NOT NULL;\n\n",
1662  "INSERT INTO pg_init_privs "
1663  " (objoid, classoid, objsubid, initprivs, privtype)"
1664  " SELECT"
1665  " oid,"
1666  " (SELECT oid FROM pg_class WHERE "
1667  " relname = 'pg_largeobject_metadata'),"
1668  " 0,"
1669  " lomacl,"
1670  " 'i'"
1671  " FROM"
1672  " pg_largeobject_metadata"
1673  " WHERE"
1674  " lomacl IS NOT NULL;\n\n",
1675  "INSERT INTO pg_init_privs "
1676  " (objoid, classoid, objsubid, initprivs, privtype)"
1677  " SELECT"
1678  " oid,"
1679  " (SELECT oid FROM pg_class WHERE relname = 'pg_namespace'),"
1680  " 0,"
1681  " nspacl,"
1682  " 'i'"
1683  " FROM"
1684  " pg_namespace"
1685  " WHERE"
1686  " nspacl IS NOT NULL;\n\n",
1687  "INSERT INTO pg_init_privs "
1688  " (objoid, classoid, objsubid, initprivs, privtype)"
1689  " SELECT"
1690  " oid,"
1691  " (SELECT oid FROM pg_class WHERE "
1692  " relname = 'pg_foreign_data_wrapper'),"
1693  " 0,"
1694  " fdwacl,"
1695  " 'i'"
1696  " FROM"
1697  " pg_foreign_data_wrapper"
1698  " WHERE"
1699  " fdwacl IS NOT NULL;\n\n",
1700  "INSERT INTO pg_init_privs "
1701  " (objoid, classoid, objsubid, initprivs, privtype)"
1702  " SELECT"
1703  " oid,"
1704  " (SELECT oid FROM pg_class "
1705  " WHERE relname = 'pg_foreign_server'),"
1706  " 0,"
1707  " srvacl,"
1708  " 'i'"
1709  " FROM"
1710  " pg_foreign_server"
1711  " WHERE"
1712  " srvacl IS NOT NULL;\n\n",
1713  NULL
1714  };
1715 
1716  priv_lines = replace_token(privileges_setup, "$POSTGRES_SUPERUSERNAME",
1718  for (line = priv_lines; *line != NULL; line++)
1719  PG_CMD_PUTS(*line);
1720 }

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

Referenced by initialize_data_directory().

◆ setup_run_file()

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

Definition at line 1500 of file initdb.c.

1501 {
1502  char **lines;
1503 
1504  lines = readfile(filename);
1505 
1506  for (char **line = lines; *line != NULL; line++)
1507  {
1508  PG_CMD_PUTS(*line);
1509  free(*line);
1510  }
1511 
1512  PG_CMD_PUTS("\n\n");
1513 
1514  free(lines);
1515 }

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 1754 of file initdb.c.

1755 {
1757 
1758  PG_CMD_PRINTF("UPDATE information_schema.sql_implementation_info "
1759  " SET character_value = '%s' "
1760  " WHERE implementation_info_name = 'DBMS VERSION';\n\n",
1761  infoversion);
1762 
1763  PG_CMD_PRINTF("COPY information_schema.sql_features "
1764  " (feature_id, feature_name, sub_feature_id, "
1765  " sub_feature_name, is_supported, comments) "
1766  " FROM E'%s';\n\n",
1768 }

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 2493 of file initdb.c.

2494 {
2495  /* some of these are not valid on Windows */
2496 #ifdef SIGHUP
2498 #endif
2499 #ifdef SIGINT
2500  pqsignal(SIGINT, trapsig);
2501 #endif
2502 #ifdef SIGQUIT
2504 #endif
2505 #ifdef SIGTERM
2506  pqsignal(SIGTERM, trapsig);
2507 #endif
2508 
2509  /* Ignore SIGPIPE when writing to backend, so we can clean up */
2510 #ifdef SIGPIPE
2512 #endif
2513 
2514  /* Prevent SIGSYS so we can probe for kernel calls that might not work */
2515 #ifdef SIGSYS
2516  pqsignal(SIGSYS, SIG_IGN);
2517 #endif
2518 }
static void trapsig(int signum)
Definition: initdb.c:1897
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
#define SIGHUP
Definition: win32_port.h:167
#define SIGPIPE
Definition: win32_port.h:172
#define SIGQUIT
Definition: win32_port.h:168
#define SIG_IGN
Definition: win32_port.h:164

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 2459 of file initdb.c.

2460 {
2462  {
2465  {
2466  pg_log_info("could not find suitable text search configuration for locale \"%s\"",
2467  lc_ctype);
2468  default_text_search_config = "simple";
2469  }
2470  }
2471  else
2472  {
2473  const char *checkmatch = find_matching_ts_config(lc_ctype);
2474 
2475  if (checkmatch == NULL)
2476  {
2477  pg_log_warning("suitable text search configuration for locale \"%s\" is unknown",
2478  lc_ctype);
2479  }
2480  else if (strcmp(checkmatch, default_text_search_config) != 0)
2481  {
2482  pg_log_warning("specified text search configuration \"%s\" might not match locale \"%s\"",
2484  }
2485  }
2486 
2487  printf(_("The default text search configuration will be set to \"%s\".\n"),
2489 }
static const char * find_matching_ts_config(const char *lc_type)
Definition: initdb.c:712

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 889 of file initdb.c.

890 {
891  /*
892  * This macro defines the minimum shared_buffers we want for a given
893  * max_connections value. The arrays show the settings to try.
894  */
895 #define MIN_BUFS_FOR_CONNS(nconns) ((nconns) * 10)
896 
897  static const int trial_conns[] = {
898  100, 50, 40, 30, 20
899  };
900  static const int trial_bufs[] = {
901  16384, 8192, 4096, 3584, 3072, 2560, 2048, 1536,
902  1000, 900, 800, 700, 600, 500,
903  400, 300, 200, 100, 50
904  };
905 
906  char cmd[MAXPGPATH];
907  const int connslen = sizeof(trial_conns) / sizeof(int);
908  const int bufslen = sizeof(trial_bufs) / sizeof(int);
909  int i,
910  status,
911  test_conns,
912  test_buffs,
913  ok_buffers = 0;
914 
915  /*
916  * Need to determine working DSM implementation first so that subsequent
917  * tests don't fail because DSM setting doesn't work.
918  */
919  printf(_("selecting dynamic shared memory implementation ... "));
920  fflush(stdout);
923 
924  /*
925  * Probe for max_connections before shared_buffers, since it is subject to
926  * more constraints than shared_buffers.
927  */
928  printf(_("selecting default max_connections ... "));
929  fflush(stdout);
930 
931  for (i = 0; i < connslen; i++)
932  {
933  test_conns = trial_conns[i];
934  test_buffs = MIN_BUFS_FOR_CONNS(test_conns);
935 
936  snprintf(cmd, sizeof(cmd),
937  "\"%s\" --check %s %s "
938  "-c max_connections=%d "
939  "-c shared_buffers=%d "
940  "-c dynamic_shared_memory_type=%s "
941  "< \"%s\" > \"%s\" 2>&1",
943  test_conns, test_buffs,
945  DEVNULL, DEVNULL);
946  status = system(cmd);
947  if (status == 0)
948  {
949  ok_buffers = test_buffs;
950  break;
951  }
952  }
953  if (i >= connslen)
954  i = connslen - 1;
955  n_connections = trial_conns[i];
956 
957  printf("%d\n", n_connections);
958 
959  printf(_("selecting default shared_buffers ... "));
960  fflush(stdout);
961 
962  for (i = 0; i < bufslen; i++)
963  {
964  /* Use same amount of memory, independent of BLCKSZ */
965  test_buffs = (trial_bufs[i] * 8192) / BLCKSZ;
966  if (test_buffs <= ok_buffers)
967  {
968  test_buffs = ok_buffers;
969  break;
970  }
971 
972  snprintf(cmd, sizeof(cmd),
973  "\"%s\" --check %s %s "
974  "-c max_connections=%d "
975  "-c shared_buffers=%d "
976  "-c dynamic_shared_memory_type=%s "
977  "< \"%s\" > \"%s\" 2>&1",
979  n_connections, test_buffs,
981  DEVNULL, DEVNULL);
982  status = system(cmd);
983  if (status == 0)
984  break;
985  }
986  n_buffers = test_buffs;
987 
988  if ((n_buffers * (BLCKSZ / 1024)) % 1024 == 0)
989  printf("%dMB\n", (n_buffers * (BLCKSZ / 1024)) / 1024);
990  else
991  printf("%dkB\n", n_buffers * (BLCKSZ / 1024));
992 
993  printf(_("selecting default time zone ... "));
994  fflush(stdout);
996  printf("%s\n", default_timezone ? default_timezone : "GMT");
997 }
const char * select_default_timezone(const char *share_path)
static const char * choose_dsm_implementation(void)
Definition: initdb.c:847
#define MIN_BUFS_FOR_CONNS(nconns)
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229

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 ( int  signum)
static

Definition at line 1897 of file initdb.c.

1898 {
1899  /* handle systems that reset the handler, like Windows (grr) */
1900  pqsignal(signum, trapsig);
1901  caught_signal = true;
1902 }

References caught_signal, and pqsignal().

Referenced by setup_signals().

◆ usage()

static void usage ( const char *  progname)
static

Definition at line 2161 of file initdb.c.

2162 {
2163  printf(_("%s initializes a PostgreSQL database cluster.\n\n"), progname);
2164  printf(_("Usage:\n"));
2165  printf(_(" %s [OPTION]... [DATADIR]\n"), progname);
2166  printf(_("\nOptions:\n"));
2167  printf(_(" -A, --auth=METHOD default authentication method for local connections\n"));
2168  printf(_(" --auth-host=METHOD default authentication method for local TCP/IP connections\n"));
2169  printf(_(" --auth-local=METHOD default authentication method for local-socket connections\n"));
2170  printf(_(" [-D, --pgdata=]DATADIR location for this database cluster\n"));
2171  printf(_(" -E, --encoding=ENCODING set default encoding for new databases\n"));
2172  printf(_(" -g, --allow-group-access allow group read/execute on data directory\n"));
2173  printf(_(" --icu-locale=LOCALE set ICU locale ID for new databases\n"));
2174  printf(_(" -k, --data-checksums use data page checksums\n"));
2175  printf(_(" --locale=LOCALE set default locale for new databases\n"));
2176  printf(_(" --lc-collate=, --lc-ctype=, --lc-messages=LOCALE\n"
2177  " --lc-monetary=, --lc-numeric=, --lc-time=LOCALE\n"
2178  " set default locale in the respective category for\n"
2179  " new databases (default taken from environment)\n"));
2180  printf(_(" --no-locale equivalent to --locale=C\n"));
2181  printf(_(" --locale-provider={libc|icu}\n"
2182  " set default locale provider for new databases\n"));
2183  printf(_(" --pwfile=FILE read password for the new superuser from file\n"));
2184  printf(_(" -T, --text-search-config=CFG\n"
2185  " default text search configuration\n"));
2186  printf(_(" -U, --username=NAME database superuser name\n"));
2187  printf(_(" -W, --pwprompt prompt for a password for the new superuser\n"));
2188  printf(_(" -X, --waldir=WALDIR location for the write-ahead log directory\n"));
2189  printf(_(" --wal-segsize=SIZE size of WAL segments, in megabytes\n"));
2190  printf(_("\nLess commonly used options:\n"));
2191  printf(_(" -d, --debug generate lots of debugging output\n"));
2192  printf(_(" --discard-caches set debug_discard_caches=1\n"));
2193  printf(_(" -L DIRECTORY where to find the input files\n"));
2194  printf(_(" -n, --no-clean do not clean up after errors\n"));
2195  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
2196  printf(_(" --no-instructions do not print instructions for next steps\n"));
2197  printf(_(" -s, --show show internal settings\n"));
2198  printf(_(" -S, --sync-only only sync database files to disk, then exit\n"));
2199  printf(_("\nOther options:\n"));
2200  printf(_(" -V, --version output version information, then exit\n"));
2201  printf(_(" -?, --help show this help, then exit\n"));
2202  printf(_("\nIf the data directory is not specified, the environment variable PGDATA\n"
2203  "is used.\n"));
2204  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2205  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2206 }

References _, printf, and progname.

Referenced by main().

◆ vacuum_db()

static void vacuum_db ( FILE *  cmdfd)
static

Definition at line 1783 of file initdb.c.

1784 {
1785  /* Run analyze before VACUUM so the statistics are frozen. */
1786  PG_CMD_PUTS("ANALYZE;\n\nVACUUM FREEZE;\n\n");
1787 }

References PG_CMD_PUTS.

Referenced by initialize_data_directory().

◆ warn_on_mount_point()

void warn_on_mount_point ( int  error)

Definition at line 2667 of file initdb.c.

2668 {
2669  if (error == 2)
2670  pg_log_error_detail("It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.");
2671  else if (error == 3)
2672  pg_log_error_detail("It contains a lost+found directory, perhaps due to it being a mount point.");
2673 
2674  pg_log_error_hint("Using a mount point directly as the data directory is not recommended.\n"
2675  "Create a subdirectory under the mount point.");
2676 }
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 798 of file initdb.c.

799 {
800  FILE *version_file;
801  char *path;
802 
803  if (extrapath == NULL)
804  path = psprintf("%s/PG_VERSION", pg_data);
805  else
806  path = psprintf("%s/%s/PG_VERSION", pg_data, extrapath);
807 
808  if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
809  pg_fatal("could not open file \"%s\" for writing: %m", path);
810  if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
811  fclose(version_file))
812  pg_fatal("could not write file \"%s\": %m", path);
813  free(path);
814 }
static char version_file[MAXPGPATH]
Definition: pg_ctl.c:102

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 499 of file initdb.c.

500 {
501  FILE *out_file;
502  char **line;
503 
504  if ((out_file = fopen(path, "w")) == NULL)
505  pg_fatal("could not open file \"%s\" for writing: %m", path);
506  for (line = lines; *line != NULL; line++)
507  {
508  if (fputs(*line, out_file) < 0)
509  pg_fatal("could not write file \"%s\": %m", path);
510  free(*line);
511  }
512  if (fclose(out_file))
513  pg_fatal("could not close file \"%s\": %m", path);
514 }

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 84 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 106 of file initdb.c.

Referenced by main().

◆ authmethodhost

const char* authmethodhost = NULL
static

Definition at line 142 of file initdb.c.

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

◆ authmethodlocal

const char* authmethodlocal = NULL
static

Definition at line 143 of file initdb.c.

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

◆ authwarning

bool authwarning = false
static

Definition at line 194 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 207 of file initdb.c.

Referenced by initialize_data_directory().

◆ bin_path

char bin_path[MAXPGPATH]
static

Definition at line 239 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 159 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 206 of file initdb.c.

Referenced by bootstrap_template1(), and test_config_settings().

◆ caught_signal

bool caught_signal = false
static

Definition at line 175 of file initdb.c.

Referenced by check_ok(), and trapsig().

◆ conf_file

char* conf_file
static

Definition at line 162 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 150 of file initdb.c.

Referenced by bootstrap_template1(), and main().

◆ debug

bool debug = false
static

Definition at line 144 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 137 of file initdb.c.

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

◆ default_timezone

const char* default_timezone = NULL
static

Definition at line 184 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ dictionary_file

char* dictionary_file
static

Definition at line 163 of file initdb.c.

Referenced by initialize_data_directory(), and setup_data_file_paths().

◆ do_sync

bool do_sync = true
static

Definition at line 147 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 183 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ encoding

char* encoding = NULL
static

Definition at line 127 of file initdb.c.

Referenced by main(), and setup_locale_encoding().

◆ encodingid

int encodingid
static

Definition at line 158 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 165 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 171 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 173 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ hba_file

char* hba_file
static

Definition at line 160 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 161 of file initdb.c.

Referenced by setup_config(), and setup_data_file_paths().

◆ info_schema_file

char* info_schema_file
static

Definition at line 164 of file initdb.c.

Referenced by setup_data_file_paths(), and setup_schema().

◆ infoversion

char infoversion[100]
static

Definition at line 174 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 134 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 131 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 132 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 133 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 135 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 170 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 172 of file initdb.c.

Referenced by cleanup_directories_atexit(), and create_xlog_or_symlink().

◆ n_buffers

int n_buffers = 50
static

Definition at line 182 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ n_connections

int n_connections = 10
static

Definition at line 181 of file initdb.c.

Referenced by setup_config(), and test_config_settings().

◆ noclean

bool noclean = false
static

Definition at line 145 of file initdb.c.

Referenced by cleanup_directories_atexit(), and main().

◆ noinstructions

bool noinstructions = false
static

Definition at line 146 of file initdb.c.

Referenced by main().

◆ output_errno

int output_errno = 0
static

Definition at line 177 of file initdb.c.

Referenced by check_ok().

◆ output_failed

bool output_failed = false
static

Definition at line 176 of file initdb.c.

Referenced by check_ok().

◆ pg_data

◆ pgdata_native

char* pgdata_native
static

Definition at line 178 of file initdb.c.

Referenced by main(), and setup_pgdata().

◆ progname

const char* progname
static

◆ pwfilename

char* pwfilename = NULL
static

Definition at line 140 of file initdb.c.

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

◆ pwprompt

bool pwprompt = false
static

Definition at line 139 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 149 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 152 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 212 of file initdb.c.

Referenced by initialize_data_directory().

◆ success

◆ superuser_password

char* superuser_password = NULL
static

Definition at line 141 of file initdb.c.

Referenced by get_su_pwd(), and setup_auth().

◆ sync_only

bool sync_only = false
static

Definition at line 148 of file initdb.c.

Referenced by main().

◆ system_constraints_file

char* system_constraints_file
static

Definition at line 166 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 167 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 168 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 622 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 153 of file initdb.c.

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

◆ xlog_dir

char* xlog_dir = NULL
static

Definition at line 151 of file initdb.c.

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