guc.c 201.1 KB
Newer Older
1 2 3 4 5
/*--------------------------------------------------------------------
 * guc.c
 *
 * Support for grand unified configuration scheme, including SET
 * command, configuration file, and command line options.
6
 * See src/backend/utils/misc/README for more information.
7 8
 *
 *
9
 * Copyright (c) 2000-2010, PostgreSQL Global Development Group
10
 * Written by Peter Eisentraut <peter_e@gmx.net>.
11 12
 *
 * IDENTIFICATION
13
 *	  $PostgreSQL: pgsql/src/backend/utils/misc/guc.c,v 1.558 2010/07/03 20:43:58 tgl Exp $
14
 *
15 16 17 18
 *--------------------------------------------------------------------
 */
#include "postgres.h"

19
#include <ctype.h>
20
#include <float.h>
21
#include <math.h>
22 23
#include <limits.h>
#include <unistd.h>
24
#include <sys/stat.h>
25 26 27
#ifdef HAVE_SYSLOG
#include <syslog.h>
#endif
28

29
#include "access/gin.h"
30
#include "access/transam.h"
31
#include "access/twophase.h"
32
#include "access/xact.h"
33
#include "catalog/namespace.h"
34
#include "commands/async.h"
35
#include "commands/prepare.h"
36
#include "commands/vacuum.h"
37
#include "commands/variable.h"
38
#include "commands/trigger.h"
39
#include "funcapi.h"
40
#include "libpq/auth.h"
41
#include "libpq/be-fsstubs.h"
42
#include "libpq/pqformat.h"
43 44 45 46
#include "miscadmin.h"
#include "optimizer/cost.h"
#include "optimizer/geqo.h"
#include "optimizer/paths.h"
47
#include "optimizer/planmain.h"
48
#include "parser/parse_expr.h"
49
#include "parser/parse_type.h"
50
#include "parser/parser.h"
51
#include "parser/scansup.h"
52
#include "pgstat.h"
53
#include "postmaster/autovacuum.h"
54 55
#include "postmaster/bgwriter.h"
#include "postmaster/postmaster.h"
56
#include "postmaster/syslogger.h"
57
#include "postmaster/walwriter.h"
58
#include "replication/walsender.h"
59
#include "storage/bufmgr.h"
60
#include "storage/standby.h"
61
#include "storage/fd.h"
62
#include "tcop/tcopprot.h"
63
#include "tsearch/ts_cache.h"
64
#include "utils/builtins.h"
65
#include "utils/bytea.h"
66
#include "utils/guc_tables.h"
67
#include "utils/memutils.h"
68
#include "utils/pg_locale.h"
69
#include "utils/plancache.h"
70
#include "utils/portal.h"
71
#include "utils/ps_status.h"
72
#include "utils/tzparser.h"
73
#include "utils/xml.h"
74

75 76 77
#ifndef PG_KRB_SRVTAB
#define PG_KRB_SRVTAB ""
#endif
B
 
Bruce Momjian 已提交
78 79 80
#ifndef PG_KRB_SRVNAM
#define PG_KRB_SRVNAM ""
#endif
81

B
Bruce Momjian 已提交
82
#define CONFIG_FILENAME "postgresql.conf"
83 84
#define HBA_FILENAME	"pg_hba.conf"
#define IDENT_FILENAME	"pg_ident.conf"
85

B
Bruce Momjian 已提交
86 87
#ifdef EXEC_BACKEND
#define CONFIG_EXEC_PARAMS "global/config_exec_params"
88
#define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
B
Bruce Momjian 已提交
89
#endif
90

91
/* upper limit for GUC variables measured in kilobytes of memory */
92 93
/* note that various places assume the byte size fits in a "long" variable */
#if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
94 95 96 97 98
#define MAX_KILOBYTES	INT_MAX
#else
#define MAX_KILOBYTES	(INT_MAX / 1024)
#endif

99 100 101 102
#define KB_PER_MB (1024)
#define KB_PER_GB (1024*1024)

#define MS_PER_S 1000
103
#define S_PER_MIN 60
104
#define MS_PER_MIN (1000 * 60)
105 106
#define MIN_PER_H 60
#define S_PER_H (60 * 60)
107
#define MS_PER_H (1000 * 60 * 60)
108 109
#define MIN_PER_D (60 * 24)
#define S_PER_D (60 * 60 * 24)
110 111
#define MS_PER_D (1000 * 60 * 60 * 24)

112
/* XXX these should appear in other modules' header files */
113
extern bool Log_disconnections;
B
Bruce Momjian 已提交
114 115
extern int	CommitDelay;
extern int	CommitSiblings;
116
extern char *default_tablespace;
117
extern char *temp_tablespaces;
118
extern bool synchronize_seqscans;
B
Bruce Momjian 已提交
119
extern bool fullPageWrites;
120
extern int	ssl_renegotiation_limit;
121

122
#ifdef TRACE_SORT
B
Bruce Momjian 已提交
123
extern bool trace_sort;
124
#endif
125 126 127
#ifdef TRACE_SYNCSCAN
extern bool trace_syncscan;
#endif
128 129 130
#ifdef DEBUG_BOUNDED_SORT
extern bool optimize_bounded_sort;
#endif
131

T
Tom Lane 已提交
132 133 134 135
#ifdef USE_SSL
extern char *SSLCipherSuites;
#endif

136 137
static void set_config_sourcefile(const char *name, char *sourcefile,
					  int sourceline);
T
Tom Lane 已提交
138

139
static const char *assign_log_destination(const char *value,
B
Bruce Momjian 已提交
140
					   bool doit, GucSource source);
141

T
Tatsuo Ishii 已提交
142
#ifdef HAVE_SYSLOG
143
static int	syslog_facility = LOG_LOCAL0;
144

145
static bool assign_syslog_facility(int newval,
146
					   bool doit, GucSource source);
147
static const char *assign_syslog_ident(const char *ident,
B
Bruce Momjian 已提交
148
					bool doit, GucSource source);
149
#endif
150

151
static bool assign_session_replication_role(int newval, bool doit,
B
Bruce Momjian 已提交
152
								GucSource source);
153
static const char *show_num_temp_buffers(void);
154
static bool assign_phony_autocommit(bool newval, bool doit, GucSource source);
155
static const char *assign_custom_variable_classes(const char *newval, bool doit,
B
Bruce Momjian 已提交
156
							   GucSource source);
157
static bool assign_debug_assertions(bool newval, bool doit, GucSource source);
158
static bool assign_bonjour(bool newval, bool doit, GucSource source);
159
static bool assign_ssl(bool newval, bool doit, GucSource source);
160 161
static bool assign_stage_log_stats(bool newval, bool doit, GucSource source);
static bool assign_log_stats(bool newval, bool doit, GucSource source);
162
static bool assign_transaction_read_only(bool newval, bool doit, GucSource source);
163
static const char *assign_canonical_path(const char *newval, bool doit, GucSource source);
164
static const char *assign_timezone_abbreviations(const char *newval, bool doit, GucSource source);
165
static const char *show_archive_command(void);
166 167 168 169 170 171
static bool assign_tcp_keepalives_idle(int newval, bool doit, GucSource source);
static bool assign_tcp_keepalives_interval(int newval, bool doit, GucSource source);
static bool assign_tcp_keepalives_count(int newval, bool doit, GucSource source);
static const char *show_tcp_keepalives_idle(void);
static const char *show_tcp_keepalives_interval(void);
static const char *show_tcp_keepalives_count(void);
172
static bool assign_maxconnections(int newval, bool doit, GucSource source);
173 174
static bool assign_autovacuum_max_workers(int newval, bool doit, GucSource source);
static bool assign_effective_io_concurrency(int newval, bool doit, GucSource source);
175
static const char *assign_pgstat_temp_directory(const char *newval, bool doit, GucSource source);
176
static const char *assign_application_name(const char *newval, bool doit, GucSource source);
177

178 179 180
static char *config_enum_get_options(struct config_enum * record,
						const char *prefix, const char *suffix,
						const char *separator);
181 182


183 184
/*
 * Options for enum values defined in this module.
185 186
 *
 * NOTE! Option values may not contain double quotes!
187
 */
188

189 190 191 192 193 194
static const struct config_enum_entry bytea_output_options[] = {
	{"escape", BYTEA_OUTPUT_ESCAPE, false},
	{"hex", BYTEA_OUTPUT_HEX, false},
	{NULL, 0, false}
};

195 196 197 198 199
/*
 * We have different sets for client and server message level options because
 * they sort slightly different (see "log" level)
 */
static const struct config_enum_entry client_message_level_options[] = {
200
	{"debug", DEBUG2, true},
201 202 203 204 205 206
	{"debug5", DEBUG5, false},
	{"debug4", DEBUG4, false},
	{"debug3", DEBUG3, false},
	{"debug2", DEBUG2, false},
	{"debug1", DEBUG1, false},
	{"log", LOG, false},
207 208 209 210 211 212 213 214 215 216
	{"info", INFO, true},
	{"notice", NOTICE, false},
	{"warning", WARNING, false},
	{"error", ERROR, false},
	{"fatal", FATAL, true},
	{"panic", PANIC, true},
	{NULL, 0, false}
};

static const struct config_enum_entry server_message_level_options[] = {
217
	{"debug", DEBUG2, true},
218 219 220 221 222
	{"debug5", DEBUG5, false},
	{"debug4", DEBUG4, false},
	{"debug3", DEBUG3, false},
	{"debug2", DEBUG2, false},
	{"debug1", DEBUG1, false},
223 224 225 226
	{"info", INFO, false},
	{"notice", NOTICE, false},
	{"warning", WARNING, false},
	{"error", ERROR, false},
227
	{"log", LOG, false},
228 229 230
	{"fatal", FATAL, false},
	{"panic", PANIC, false},
	{NULL, 0, false}
231 232
};

233 234 235 236
static const struct config_enum_entry intervalstyle_options[] = {
	{"postgres", INTSTYLE_POSTGRES, false},
	{"postgres_verbose", INTSTYLE_POSTGRES_VERBOSE, false},
	{"sql_standard", INTSTYLE_SQL_STANDARD, false},
237
	{"iso_8601", INTSTYLE_ISO_8601, false},
238 239 240
	{NULL, 0, false}
};

241
static const struct config_enum_entry log_error_verbosity_options[] = {
242
	{"terse", PGERROR_TERSE, false},
243
	{"default", PGERROR_DEFAULT, false},
244 245
	{"verbose", PGERROR_VERBOSE, false},
	{NULL, 0, false}
246 247 248
};

static const struct config_enum_entry log_statement_options[] = {
249 250 251 252 253
	{"none", LOGSTMT_NONE, false},
	{"ddl", LOGSTMT_DDL, false},
	{"mod", LOGSTMT_MOD, false},
	{"all", LOGSTMT_ALL, false},
	{NULL, 0, false}
254 255
};

256
static const struct config_enum_entry isolation_level_options[] = {
257 258 259 260
	{"serializable", XACT_SERIALIZABLE, false},
	{"repeatable read", XACT_REPEATABLE_READ, false},
	{"read committed", XACT_READ_COMMITTED, false},
	{"read uncommitted", XACT_READ_UNCOMMITTED, false},
261 262 263 264
	{NULL, 0}
};

static const struct config_enum_entry session_replication_role_options[] = {
265 266 267 268
	{"origin", SESSION_REPLICATION_ROLE_ORIGIN, false},
	{"replica", SESSION_REPLICATION_ROLE_REPLICA, false},
	{"local", SESSION_REPLICATION_ROLE_LOCAL, false},
	{NULL, 0, false}
269 270
};

271
#ifdef HAVE_SYSLOG
272
static const struct config_enum_entry syslog_facility_options[] = {
273 274 275 276 277 278 279 280
	{"local0", LOG_LOCAL0, false},
	{"local1", LOG_LOCAL1, false},
	{"local2", LOG_LOCAL2, false},
	{"local3", LOG_LOCAL3, false},
	{"local4", LOG_LOCAL4, false},
	{"local5", LOG_LOCAL5, false},
	{"local6", LOG_LOCAL6, false},
	{"local7", LOG_LOCAL7, false},
281 282
	{NULL, 0}
};
283
#endif
284

285
static const struct config_enum_entry track_function_options[] = {
286 287 288 289
	{"none", TRACK_FUNC_OFF, false},
	{"pl", TRACK_FUNC_PL, false},
	{"all", TRACK_FUNC_ALL, false},
	{NULL, 0, false}
290 291
};

292
static const struct config_enum_entry xmlbinary_options[] = {
293 294 295
	{"base64", XMLBINARY_BASE64, false},
	{"hex", XMLBINARY_HEX, false},
	{NULL, 0, false}
296 297 298
};

static const struct config_enum_entry xmloption_options[] = {
299 300 301
	{"content", XMLOPTION_CONTENT, false},
	{"document", XMLOPTION_DOCUMENT, false},
	{NULL, 0, false}
302
};
303

304 305 306 307 308
/*
 * Although only "on", "off", and "safe_encoding" are documented, we
 * accept all the likely variants of "on" and "off".
 */
static const struct config_enum_entry backslash_quote_options[] = {
309 310 311 312 313 314 315 316 317 318
	{"safe_encoding", BACKSLASH_QUOTE_SAFE_ENCODING, false},
	{"on", BACKSLASH_QUOTE_ON, false},
	{"off", BACKSLASH_QUOTE_OFF, false},
	{"true", BACKSLASH_QUOTE_ON, true},
	{"false", BACKSLASH_QUOTE_OFF, true},
	{"yes", BACKSLASH_QUOTE_ON, true},
	{"no", BACKSLASH_QUOTE_OFF, true},
	{"1", BACKSLASH_QUOTE_ON, true},
	{"0", BACKSLASH_QUOTE_OFF, true},
	{NULL, 0, false}
319 320
};

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/*
 * Although only "on", "off", and "partition" are documented, we
 * accept all the likely variants of "on" and "off".
 */
static const struct config_enum_entry constraint_exclusion_options[] = {
	{"partition", CONSTRAINT_EXCLUSION_PARTITION, false},
	{"on", CONSTRAINT_EXCLUSION_ON, false},
	{"off", CONSTRAINT_EXCLUSION_OFF, false},
	{"true", CONSTRAINT_EXCLUSION_ON, true},
	{"false", CONSTRAINT_EXCLUSION_OFF, true},
	{"yes", CONSTRAINT_EXCLUSION_ON, true},
	{"no", CONSTRAINT_EXCLUSION_OFF, true},
	{"1", CONSTRAINT_EXCLUSION_ON, true},
	{"0", CONSTRAINT_EXCLUSION_OFF, true},
	{NULL, 0, false}
};

338 339 340
/*
 * Options for enum values stored in other modules
 */
341
extern const struct config_enum_entry wal_level_options[];
342 343
extern const struct config_enum_entry sync_method_options[];

344 345
/*
 * GUC option variables that are exported from this module
346
 */
347
#ifdef USE_ASSERT_CHECKING
B
Bruce Momjian 已提交
348
bool		assert_enabled = true;
349 350 351
#else
bool		assert_enabled = false;
#endif
B
Rename:  
Bruce Momjian 已提交
352
bool		log_duration = false;
B
Bruce Momjian 已提交
353 354 355
bool		Debug_print_plan = false;
bool		Debug_print_parse = false;
bool		Debug_print_rewritten = false;
356
bool		Debug_pretty_print = true;
357

B
Rename:  
Bruce Momjian 已提交
358 359 360
bool		log_parser_stats = false;
bool		log_planner_stats = false;
bool		log_executor_stats = false;
B
Bruce Momjian 已提交
361 362
bool		log_statement_stats = false;		/* this is sort of all three
												 * above together */
363
bool		log_btree_build_stats = false;
364

365 366
bool		check_function_bodies = true;
bool		default_with_oids = false;
B
Bruce Momjian 已提交
367
bool		SQL_inheritance = true;
368

369
bool		Password_encryption = true;
370

371
int			log_min_error_statement = ERROR;
372
int			log_min_messages = WARNING;
373
int			client_min_messages = NOTICE;
374
int			log_min_duration_statement = -1;
375
int			log_temp_files = -1;
376
int			trace_recovery_messages = LOG;
377

378 379
int			num_temp_buffers = 1000;

380 381 382 383
char	   *ConfigFileName;
char	   *HbaFileName;
char	   *IdentFileName;
char	   *external_pid_file;
384

385 386
char	   *pgstat_temp_directory;

387 388
char	   *application_name;

B
Bruce Momjian 已提交
389 390 391
int			tcp_keepalives_idle;
int			tcp_keepalives_interval;
int			tcp_keepalives_count;
392

393 394 395 396 397
/*
 * These variables are all dummies that don't do anything, except in some
 * cases provide the value for SHOW to display.  The real state is elsewhere
 * and is kept in sync by assign_hooks.
 */
398
static char *log_destination_string;
B
Bruce Momjian 已提交
399

400
#ifdef HAVE_SYSLOG
401
static char *syslog_ident_str;
402
#endif
403
static bool phony_autocommit;
404
static bool session_auth_is_superuser;
405 406 407
static double phony_random_seed;
static char *client_encoding_string;
static char *datestyle_string;
408 409
static char *locale_collate;
static char *locale_ctype;
410
static char *server_encoding_string;
411
static char *server_version_string;
B
Bruce Momjian 已提交
412
static int	server_version_num;
413
static char *timezone_string;
414
static char *log_timezone_string;
415
static char *timezone_abbreviations_string;
416
static char *XactIsoLevel_string;
417
static char *data_directory;
418
static char *custom_variable_classes;
419 420 421 422
static int	max_function_args;
static int	max_index_keys;
static int	max_identifier_length;
static int	block_size;
423 424 425
static int	segment_size;
static int	wal_block_size;
static int	wal_segment_size;
B
Bruce Momjian 已提交
426
static bool integer_datetimes;
427
static int	effective_io_concurrency;
B
Bruce Momjian 已提交
428

429 430
/* should be static, but commands/variable.c needs to get at these */
char	   *role_string;
B
Bruce Momjian 已提交
431
char	   *session_authorization_string;
432

433

434
/*
435 436 437
 * Displayable names for context types (enum GucContext)
 *
 * Note: these strings are deliberately not localized.
438
 */
B
Bruce Momjian 已提交
439
const char *const GucContext_Names[] =
440
{
B
Bruce Momjian 已提交
441 442 443 444 445 446
	 /* PGC_INTERNAL */ "internal",
	 /* PGC_POSTMASTER */ "postmaster",
	 /* PGC_SIGHUP */ "sighup",
	 /* PGC_BACKEND */ "backend",
	 /* PGC_SUSET */ "superuser",
	 /* PGC_USERSET */ "user"
447 448 449 450 451 452
};

/*
 * Displayable names for source types (enum GucSource)
 *
 * Note: these strings are deliberately not localized.
B
Bruce Momjian 已提交
453 454
 */
const char *const GucSource_Names[] =
455
{
B
Bruce Momjian 已提交
456 457 458 459 460 461
	 /* PGC_S_DEFAULT */ "default",
	 /* PGC_S_ENV_VAR */ "environment variable",
	 /* PGC_S_FILE */ "configuration file",
	 /* PGC_S_ARGV */ "command line",
	 /* PGC_S_DATABASE */ "database",
	 /* PGC_S_USER */ "user",
462
	 /* PGC_S_DATABASE_USER */ "database user",
B
Bruce Momjian 已提交
463 464 465 466 467
	 /* PGC_S_CLIENT */ "client",
	 /* PGC_S_OVERRIDE */ "override",
	 /* PGC_S_INTERACTIVE */ "interactive",
	 /* PGC_S_TEST */ "test",
	 /* PGC_S_SESSION */ "session"
468 469 470 471 472 473 474 475
};

/*
 * Displayable names for the groupings defined in enum config_group
 */
const char *const config_group_names[] =
{
	/* UNGROUPED */
476
	gettext_noop("Ungrouped"),
477 478
	/* FILE_LOCATIONS */
	gettext_noop("File Locations"),
479
	/* CONN_AUTH */
480
	gettext_noop("Connections and Authentication"),
481
	/* CONN_AUTH_SETTINGS */
482
	gettext_noop("Connections and Authentication / Connection Settings"),
483
	/* CONN_AUTH_SECURITY */
484
	gettext_noop("Connections and Authentication / Security and Authentication"),
485
	/* RESOURCES */
486
	gettext_noop("Resource Usage"),
487
	/* RESOURCES_MEM */
488
	gettext_noop("Resource Usage / Memory"),
489
	/* RESOURCES_KERNEL */
490
	gettext_noop("Resource Usage / Kernel Resources"),
491 492 493 494 495 496
	/* RESOURCES_VACUUM_DELAY */
	gettext_noop("Resource Usage / Cost-Based Vacuum Delay"),
	/* RESOURCES_BGWRITER */
	gettext_noop("Resource Usage / Background Writer"),
	/* RESOURCES_ASYNCHRONOUS */
	gettext_noop("Resource Usage / Asynchronous Behavior"),
497
	/* WAL */
498
	gettext_noop("Write-Ahead Log"),
499
	/* WAL_SETTINGS */
500
	gettext_noop("Write-Ahead Log / Settings"),
501
	/* WAL_CHECKPOINTS */
502
	gettext_noop("Write-Ahead Log / Checkpoints"),
503 504
	/* WAL_ARCHIVING */
	gettext_noop("Write-Ahead Log / Archiving"),
505
	/* WAL_REPLICATION */
506 507 508
	gettext_noop("Write-Ahead Log / Streaming Replication"),
	/* WAL_STANDBY_SERVERS */
	gettext_noop("Write-Ahead Log / Standby Servers"),
509
	/* QUERY_TUNING */
510
	gettext_noop("Query Tuning"),
511
	/* QUERY_TUNING_METHOD */
512
	gettext_noop("Query Tuning / Planner Method Configuration"),
513
	/* QUERY_TUNING_COST */
514
	gettext_noop("Query Tuning / Planner Cost Constants"),
515
	/* QUERY_TUNING_GEQO */
516
	gettext_noop("Query Tuning / Genetic Query Optimizer"),
517
	/* QUERY_TUNING_OTHER */
518
	gettext_noop("Query Tuning / Other Planner Options"),
519
	/* LOGGING */
520
	gettext_noop("Reporting and Logging"),
521 522
	/* LOGGING_WHERE */
	gettext_noop("Reporting and Logging / Where to Log"),
523
	/* LOGGING_WHEN */
524
	gettext_noop("Reporting and Logging / When to Log"),
525
	/* LOGGING_WHAT */
526
	gettext_noop("Reporting and Logging / What to Log"),
527
	/* STATS */
528
	gettext_noop("Statistics"),
529
	/* STATS_MONITORING */
530
	gettext_noop("Statistics / Monitoring"),
531
	/* STATS_COLLECTOR */
532
	gettext_noop("Statistics / Query and Index Statistics Collector"),
533
	/* AUTOVACUUM */
534
	gettext_noop("Autovacuum"),
535
	/* CLIENT_CONN */
536
	gettext_noop("Client Connection Defaults"),
537
	/* CLIENT_CONN_STATEMENT */
538
	gettext_noop("Client Connection Defaults / Statement Behavior"),
539
	/* CLIENT_CONN_LOCALE */
540
	gettext_noop("Client Connection Defaults / Locale and Formatting"),
541
	/* CLIENT_CONN_OTHER */
542
	gettext_noop("Client Connection Defaults / Other Defaults"),
543
	/* LOCK_MANAGEMENT */
544
	gettext_noop("Lock Management"),
545
	/* COMPAT_OPTIONS */
546
	gettext_noop("Version and Platform Compatibility"),
547
	/* COMPAT_OPTIONS_PREVIOUS */
548
	gettext_noop("Version and Platform Compatibility / Previous PostgreSQL Versions"),
549
	/* COMPAT_OPTIONS_CLIENT */
550
	gettext_noop("Version and Platform Compatibility / Other Platforms and Clients"),
551 552 553 554
	/* PRESET_OPTIONS */
	gettext_noop("Preset Options"),
	/* CUSTOM_OPTIONS */
	gettext_noop("Customized Options"),
555
	/* DEVELOPER_OPTIONS */
556
	gettext_noop("Developer Options"),
557
	/* help_config wants this array to be null-terminated */
558 559 560
	NULL
};

561 562 563 564 565
/*
 * Displayable names for GUC variable types (enum config_type)
 *
 * Note: these strings are deliberately not localized.
 */
B
Bruce Momjian 已提交
566
const char *const config_type_names[] =
567
{
B
Bruce Momjian 已提交
568 569 570
	 /* PGC_BOOL */ "bool",
	 /* PGC_INT */ "integer",
	 /* PGC_REAL */ "real",
571 572
	 /* PGC_STRING */ "string",
	 /* PGC_ENUM */ "enum"
573 574
};

575

576
/*
577 578 579 580
 * Contents of GUC tables
 *
 * See src/backend/utils/misc/README for design notes.
 *
581 582 583
 * TO ADD AN OPTION:
 *
 * 1. Declare a global variable of type bool, int, double, or char*
B
Bruce Momjian 已提交
584
 *	  and make use of it.
585 586
 *
 * 2. Decide at what times it's safe to set the option. See guc.h for
B
Bruce Momjian 已提交
587
 *	  details.
588 589
 *
 * 3. Decide on a name, a default value, upper and lower bounds (if
B
Bruce Momjian 已提交
590
 *	  applicable), etc.
591 592 593
 *
 * 4. Add a record below.
 *
594
 * 5. Add it to src/backend/utils/misc/postgresql.conf.sample, if
595
 *	  appropriate.
596
 *
597
 * 6. Don't forget to document the option (at least in config.sgml).
598
 *
599
 * 7. If it's a new GUC_LIST option you must edit pg_dumpall.c to ensure
B
Bruce Momjian 已提交
600
 *	  it is not single quoted at dump time.
601 602
 */

603

604
/******** option records follow ********/
605

606
static struct config_bool ConfigureNamesBool[] =
607
{
608
	{
609
		{"enable_seqscan", PGC_USERSET, QUERY_TUNING_METHOD,
610
			gettext_noop("Enables the planner's use of sequential-scan plans."),
611 612 613
			NULL
		},
		&enable_seqscan,
614
		true, NULL, NULL
615
	},
616
	{
617
		{"enable_indexscan", PGC_USERSET, QUERY_TUNING_METHOD,
618
			gettext_noop("Enables the planner's use of index-scan plans."),
619 620 621
			NULL
		},
		&enable_indexscan,
622
		true, NULL, NULL
623
	},
624 625 626 627 628 629 630 631
	{
		{"enable_bitmapscan", PGC_USERSET, QUERY_TUNING_METHOD,
			gettext_noop("Enables the planner's use of bitmap-scan plans."),
			NULL
		},
		&enable_bitmapscan,
		true, NULL, NULL
	},
632
	{
633
		{"enable_tidscan", PGC_USERSET, QUERY_TUNING_METHOD,
634
			gettext_noop("Enables the planner's use of TID scan plans."),
635 636 637
			NULL
		},
		&enable_tidscan,
638
		true, NULL, NULL
639 640
	},
	{
641
		{"enable_sort", PGC_USERSET, QUERY_TUNING_METHOD,
642
			gettext_noop("Enables the planner's use of explicit sort steps."),
643 644 645
			NULL
		},
		&enable_sort,
646
		true, NULL, NULL
647
	},
648
	{
649
		{"enable_hashagg", PGC_USERSET, QUERY_TUNING_METHOD,
650
			gettext_noop("Enables the planner's use of hashed aggregation plans."),
651 652 653
			NULL
		},
		&enable_hashagg,
654 655
		true, NULL, NULL
	},
R
Robert Haas 已提交
656 657 658 659 660 661 662 663
	{
		{"enable_material", PGC_USERSET, QUERY_TUNING_METHOD,
			gettext_noop("Enables the planner's use of materialization."),
			NULL
		},
		&enable_material,
		true, NULL, NULL
	},
664
	{
665
		{"enable_nestloop", PGC_USERSET, QUERY_TUNING_METHOD,
666
			gettext_noop("Enables the planner's use of nested-loop join plans."),
667 668 669
			NULL
		},
		&enable_nestloop,
670
		true, NULL, NULL
671 672
	},
	{
673
		{"enable_mergejoin", PGC_USERSET, QUERY_TUNING_METHOD,
674
			gettext_noop("Enables the planner's use of merge join plans."),
675 676 677
			NULL
		},
		&enable_mergejoin,
678
		true, NULL, NULL
679 680
	},
	{
681
		{"enable_hashjoin", PGC_USERSET, QUERY_TUNING_METHOD,
682
			gettext_noop("Enables the planner's use of hash join plans."),
683 684 685
			NULL
		},
		&enable_hashjoin,
686
		true, NULL, NULL
687 688
	},
	{
689
		{"geqo", PGC_USERSET, QUERY_TUNING_GEQO,
690
			gettext_noop("Enables genetic query optimization."),
691
			gettext_noop("This algorithm attempts to do planning without "
692
						 "exhaustive searching.")
693 694
		},
		&enable_geqo,
695
		true, NULL, NULL
696
	},
697
	{
698 699
		/* Not for general use --- used by SET SESSION AUTHORIZATION */
		{"is_superuser", PGC_INTERNAL, UNGROUPED,
700
			gettext_noop("Shows whether the current user is a superuser."),
701 702 703
			NULL,
			GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
704 705 706
		&session_auth_is_superuser,
		false, NULL, NULL
	},
707 708 709 710 711 712 713 714
	{
		{"bonjour", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
			gettext_noop("Enables advertising the server via Bonjour."),
			NULL
		},
		&enable_bonjour,
		false, assign_bonjour, NULL
	},
715
	{
716
		{"ssl", PGC_POSTMASTER, CONN_AUTH_SECURITY,
717
			gettext_noop("Enables SSL connections."),
718 719 720
			NULL
		},
		&EnableSSL,
721
		false, assign_ssl, NULL
722 723
	},
	{
724
		{"fsync", PGC_SIGHUP, WAL_SETTINGS,
725
			gettext_noop("Forces synchronization of updates to disk."),
726
			gettext_noop("The server will use the fsync() system call in several places to make "
727
			"sure that updates are physically written to disk. This insures "
728
						 "that a database cluster will recover to a consistent state after "
729
						 "an operating system or hardware crash.")
730 731
		},
		&enableFsync,
732
		true, NULL, NULL
733
	},
734 735 736 737 738 739
	{
		{"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
			gettext_noop("Sets immediate fsync at commit."),
			NULL
		},
		&XactSyncCommit,
740
		true, NULL, NULL
741
	},
742
	{
743
		{"zero_damaged_pages", PGC_SUSET, DEVELOPER_OPTIONS,
744
			gettext_noop("Continues processing past damaged page headers."),
745
			gettext_noop("Detection of a damaged page header normally causes PostgreSQL to "
B
Bruce Momjian 已提交
746
				"report an error, aborting the current transaction. Setting "
747 748
						 "zero_damaged_pages to true causes the system to instead report a "
						 "warning, zero out the damaged page, and continue processing. This "
749
						 "behavior will destroy data, namely all the rows on the damaged page."),
750
			GUC_NOT_IN_SAMPLE
751 752
		},
		&zero_damaged_pages,
753 754
		false, NULL, NULL
	},
755 756 757 758
	{
		{"full_page_writes", PGC_SIGHUP, WAL_SETTINGS,
			gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
			gettext_noop("A page write in process during an operating system crash might be "
B
Bruce Momjian 已提交
759
						 "only partially written to disk.  During recovery, the row changes "
760
			  "stored in WAL are not enough to recover.  This option writes "
761 762 763 764 765 766
						 "pages when first modified after a checkpoint to WAL so full recovery "
						 "is possible.")
		},
		&fullPageWrites,
		true, NULL, NULL
	},
767
	{
768
		{"silent_mode", PGC_POSTMASTER, LOGGING_WHERE,
769
			gettext_noop("Runs the server silently."),
770
			gettext_noop("If this parameter is set, the server will automatically run in the "
B
Bruce Momjian 已提交
771
				 "background and any controlling terminals are dissociated.")
772 773
		},
		&SilentMode,
774
		false, NULL, NULL
775
	},
776 777 778 779 780 781 782 783
	{
		{"log_checkpoints", PGC_SIGHUP, LOGGING_WHAT,
			gettext_noop("Logs each checkpoint."),
			NULL
		},
		&log_checkpoints,
		false, NULL, NULL
	},
784
	{
785
		{"log_connections", PGC_BACKEND, LOGGING_WHAT,
786
			gettext_noop("Logs each successful connection."),
787 788 789
			NULL
		},
		&Log_connections,
790
		false, NULL, NULL
791
	},
792 793
	{
		{"log_disconnections", PGC_BACKEND, LOGGING_WHAT,
P
Peter Eisentraut 已提交
794
			gettext_noop("Logs end of a session, including duration."),
B
Bruce Momjian 已提交
795
			NULL
796 797 798 799
		},
		&Log_disconnections,
		false, NULL, NULL
	},
800
	{
801
		{"debug_assertions", PGC_USERSET, DEVELOPER_OPTIONS,
802
			gettext_noop("Turns on various assertion checks."),
803
			gettext_noop("This is a debugging aid."),
804 805 806
			GUC_NOT_IN_SAMPLE
		},
		&assert_enabled,
807 808 809 810
#ifdef USE_ASSERT_CHECKING
		true,
#else
		false,
811
#endif
812 813
		assign_debug_assertions, NULL
	},
814 815
	{
		/* currently undocumented, so don't show in SHOW ALL */
816
		{"exit_on_error", PGC_USERSET, UNGROUPED,
817
			gettext_noop("No description available."),
818 819 820 821
			NULL,
			GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE
		},
		&ExitOnAnyError,
822 823
		false, NULL, NULL
	},
824
	{
825 826
		{"log_duration", PGC_SUSET, LOGGING_WHAT,
			gettext_noop("Logs the duration of each completed SQL statement."),
827 828 829
			NULL
		},
		&log_duration,
830
		false, NULL, NULL
831 832
	},
	{
833
		{"debug_print_parse", PGC_USERSET, LOGGING_WHAT,
834
			gettext_noop("Logs each query's parse tree."),
835
			NULL
836 837
		},
		&Debug_print_parse,
838
		false, NULL, NULL
839 840
	},
	{
841
		{"debug_print_rewritten", PGC_USERSET, LOGGING_WHAT,
842
			gettext_noop("Logs each query's rewritten parse tree."),
843 844 845
			NULL
		},
		&Debug_print_rewritten,
846
		false, NULL, NULL
847 848
	},
	{
849
		{"debug_print_plan", PGC_USERSET, LOGGING_WHAT,
850
			gettext_noop("Logs each query's execution plan."),
851 852 853
			NULL
		},
		&Debug_print_plan,
854
		false, NULL, NULL
855 856
	},
	{
857
		{"debug_pretty_print", PGC_USERSET, LOGGING_WHAT,
858
			gettext_noop("Indents parse and plan tree displays."),
859 860 861
			NULL
		},
		&Debug_pretty_print,
862
		true, NULL, NULL
863 864
	},
	{
865
		{"log_parser_stats", PGC_SUSET, STATS_MONITORING,
866
			gettext_noop("Writes parser performance statistics to the server log."),
867 868 869
			NULL
		},
		&log_parser_stats,
870
		false, assign_stage_log_stats, NULL
871 872
	},
	{
873
		{"log_planner_stats", PGC_SUSET, STATS_MONITORING,
874
			gettext_noop("Writes planner performance statistics to the server log."),
875 876 877
			NULL
		},
		&log_planner_stats,
878
		false, assign_stage_log_stats, NULL
879 880
	},
	{
881
		{"log_executor_stats", PGC_SUSET, STATS_MONITORING,
882
			gettext_noop("Writes executor performance statistics to the server log."),
883 884 885
			NULL
		},
		&log_executor_stats,
886
		false, assign_stage_log_stats, NULL
887 888
	},
	{
889
		{"log_statement_stats", PGC_SUSET, STATS_MONITORING,
890
			gettext_noop("Writes cumulative performance statistics to the server log."),
891 892 893
			NULL
		},
		&log_statement_stats,
894
		false, assign_log_stats, NULL
895
	},
896
#ifdef BTREE_BUILD_STATS
897
	{
898
		{"log_btree_build_stats", PGC_SUSET, DEVELOPER_OPTIONS,
899
			gettext_noop("No description available."),
900 901 902 903
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&log_btree_build_stats,
904
		false, NULL, NULL
905
	},
906 907
#endif

908
	{
909 910 911 912 913
		{"track_activities", PGC_SUSET, STATS_COLLECTOR,
			gettext_noop("Collects information about executing commands."),
			gettext_noop("Enables the collection of information on the currently "
						 "executing command of each session, along with "
						 "the time at which that command began execution.")
914
		},
915
		&pgstat_track_activities,
916
		true, NULL, NULL
917 918
	},
	{
919 920
		{"track_counts", PGC_SUSET, STATS_COLLECTOR,
			gettext_noop("Collects statistics on database activity."),
921 922
			NULL
		},
923
		&pgstat_track_counts,
924
		true, NULL, NULL
925 926
	},

927 928 929
	{
		{"update_process_title", PGC_SUSET, STATS_COLLECTOR,
			gettext_noop("Updates the process title to show the active SQL command."),
930
			gettext_noop("Enables updating of the process title every time a new SQL command is received by the server.")
931 932 933 934 935
		},
		&update_process_title,
		true, NULL, NULL
	},

936 937
	{
		{"autovacuum", PGC_SIGHUP, AUTOVACUUM,
P
Peter Eisentraut 已提交
938
			gettext_noop("Starts the autovacuum subprocess."),
939 940 941
			NULL
		},
		&autovacuum_start_daemon,
942
		true, NULL, NULL
943 944
	},

945
	{
946
		{"trace_notify", PGC_USERSET, DEVELOPER_OPTIONS,
947
			gettext_noop("Generates debugging output for LISTEN and NOTIFY."),
948 949 950 951
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_notify,
952
		false, NULL, NULL
953
	},
954 955

#ifdef LOCK_DEBUG
956
	{
957
		{"trace_locks", PGC_SUSET, DEVELOPER_OPTIONS,
958
			gettext_noop("No description available."),
959 960 961 962
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_locks,
963
		false, NULL, NULL
964 965
	},
	{
966
		{"trace_userlocks", PGC_SUSET, DEVELOPER_OPTIONS,
967
			gettext_noop("No description available."),
968 969 970 971
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_userlocks,
972
		false, NULL, NULL
973 974
	},
	{
975
		{"trace_lwlocks", PGC_SUSET, DEVELOPER_OPTIONS,
976
			gettext_noop("No description available."),
977 978 979 980
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_lwlocks,
981
		false, NULL, NULL
982 983
	},
	{
984
		{"debug_deadlocks", PGC_SUSET, DEVELOPER_OPTIONS,
985
			gettext_noop("No description available."),
986 987 988 989
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Debug_deadlocks,
990
		false, NULL, NULL
991
	},
992 993
#endif

994
	{
995 996
		{"log_lock_waits", PGC_SUSET, LOGGING_WHAT,
			gettext_noop("Logs long lock waits."),
997 998 999 1000 1001
			NULL
		},
		&log_lock_waits,
		false, NULL, NULL
	},
1002

1003
	{
1004
		{"log_hostname", PGC_SIGHUP, LOGGING_WHAT,
1005
			gettext_noop("Logs the host name in the connection logs."),
1006 1007
			gettext_noop("By default, connection logs only show the IP address "
						 "of the connecting host. If you want them to show the host name you "
B
Bruce Momjian 已提交
1008 1009
			  "can turn this on, but depending on your host name resolution "
			   "setup it might impose a non-negligible performance penalty.")
1010 1011
		},
		&log_hostname,
1012
		false, NULL, NULL
1013 1014
	},
	{
1015
		{"sql_inheritance", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1016
			gettext_noop("Causes subtables to be included by default in various commands."),
1017
			NULL
1018 1019
		},
		&SQL_inheritance,
1020
		true, NULL, NULL
1021 1022
	},
	{
1023
		{"password_encryption", PGC_USERSET, CONN_AUTH_SECURITY,
1024
			gettext_noop("Encrypt passwords."),
1025
			gettext_noop("When a password is specified in CREATE USER or "
B
Bruce Momjian 已提交
1026
			   "ALTER USER without writing either ENCRYPTED or UNENCRYPTED, "
1027
						 "this parameter determines whether the password is to be encrypted.")
1028 1029
		},
		&Password_encryption,
1030
		true, NULL, NULL
1031 1032
	},
	{
1033
		{"transform_null_equals", PGC_USERSET, COMPAT_OPTIONS_CLIENT,
1034
			gettext_noop("Treats \"expr=NULL\" as \"expr IS NULL\"."),
1035
			gettext_noop("When turned on, expressions of the form expr = NULL "
B
Bruce Momjian 已提交
1036 1037 1038
			   "(or NULL = expr) are treated as expr IS NULL, that is, they "
				"return true if expr evaluates to the null value, and false "
			   "otherwise. The correct behavior of expr = NULL is to always "
1039
						 "return null (unknown).")
1040 1041
		},
		&Transform_null_equals,
1042
		false, NULL, NULL
1043
	},
1044
	{
1045
		{"db_user_namespace", PGC_SIGHUP, CONN_AUTH_SECURITY,
1046
			gettext_noop("Enables per-database user names."),
1047 1048 1049
			NULL
		},
		&Db_user_namespace,
1050 1051
		false, NULL, NULL
	},
1052
	{
1053 1054
		/* only here for backwards compatibility */
		{"autocommit", PGC_USERSET, CLIENT_CONN_STATEMENT,
1055 1056
			gettext_noop("This parameter doesn't do anything."),
			gettext_noop("It's just here so that we won't choke on SET AUTOCOMMIT TO ON from 7.3-vintage clients."),
1057 1058 1059
			GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE
		},
		&phony_autocommit,
1060
		true, assign_phony_autocommit, NULL
1061
	},
1062
	{
1063
		{"default_transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1064
			gettext_noop("Sets the default read-only status of new transactions."),
1065 1066 1067
			NULL
		},
		&DefaultXactReadOnly,
1068 1069 1070
		false, NULL, NULL
	},
	{
1071
		{"transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1072
			gettext_noop("Sets the current transaction's read-only status."),
1073 1074 1075 1076
			NULL,
			GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&XactReadOnly,
1077
		false, assign_transaction_read_only, NULL
1078
	},
1079 1080
	{
		{"check_function_bodies", PGC_USERSET, CLIENT_CONN_STATEMENT,
1081
			gettext_noop("Check function bodies during CREATE FUNCTION."),
1082 1083 1084 1085 1086
			NULL
		},
		&check_function_bodies,
		true, NULL, NULL
	},
1087 1088 1089 1090
	{
		{"array_nulls", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
			gettext_noop("Enable input of NULL elements in arrays."),
			gettext_noop("When turned on, unquoted NULL in an array input "
P
Peter Eisentraut 已提交
1091
						 "value means a null value; "
1092 1093 1094 1095 1096
						 "otherwise it is taken literally.")
		},
		&Array_nulls,
		true, NULL, NULL
	},
1097 1098
	{
		{"default_with_oids", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1099
			gettext_noop("Create new tables with OIDs by default."),
B
Bruce Momjian 已提交
1100
			NULL
1101 1102
		},
		&default_with_oids,
1103
		false, NULL, NULL
1104
	},
1105
	{
1106 1107
		{"logging_collector", PGC_POSTMASTER, LOGGING_WHERE,
			gettext_noop("Start a subprocess to capture stderr output and/or csvlogs into log files."),
B
Bruce Momjian 已提交
1108
			NULL
1109
		},
1110
		&Logging_collector,
1111 1112
		false, NULL, NULL
	},
1113 1114
	{
		{"log_truncate_on_rotation", PGC_SIGHUP, LOGGING_WHERE,
P
Peter Eisentraut 已提交
1115
			gettext_noop("Truncate existing log files of same name during log rotation."),
1116 1117 1118 1119 1120
			NULL
		},
		&Log_truncate_on_rotation,
		false, NULL, NULL
	},
1121

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
#ifdef TRACE_SORT
	{
		{"trace_sort", PGC_USERSET, DEVELOPER_OPTIONS,
			gettext_noop("Emit information about resource usage in sorting."),
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&trace_sort,
		false, NULL, NULL
	},
#endif

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
#ifdef TRACE_SYNCSCAN
	/* this is undocumented because not exposed in a standard build */
	{
		{"trace_syncscan", PGC_USERSET, DEVELOPER_OPTIONS,
			gettext_noop("Generate debugging output for synchronized scanning."),
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&trace_syncscan,
		false, NULL, NULL
	},
#endif

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
#ifdef DEBUG_BOUNDED_SORT
	/* this is undocumented because not exposed in a standard build */
	{
		{
			"optimize_bounded_sort", PGC_USERSET, QUERY_TUNING_METHOD,
			gettext_noop("Enable bounded sorting using heap sort."),
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&optimize_bounded_sort,
		true, NULL, NULL
	},
#endif

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
#ifdef WAL_DEBUG
	{
		{"wal_debug", PGC_SUSET, DEVELOPER_OPTIONS,
			gettext_noop("Emit WAL-related debugging output."),
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&XLOG_DEBUG,
		false, NULL, NULL
	},
#endif

1173
	{
1174
		{"integer_datetimes", PGC_INTERNAL, PRESET_OPTIONS,
1175
			gettext_noop("Datetimes are integer based."),
1176
			NULL,
1177
			GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1178 1179 1180 1181 1182 1183 1184 1185 1186
		},
		&integer_datetimes,
#ifdef HAVE_INT64_TIMESTAMP
		true, NULL, NULL
#else
		false, NULL, NULL
#endif
	},

B
 
Bruce Momjian 已提交
1187
	{
1188
		{"krb_caseins_users", PGC_SIGHUP, CONN_AUTH_SECURITY,
1189
			gettext_noop("Sets whether Kerberos and GSSAPI user names should be treated as case-insensitive."),
B
 
Bruce Momjian 已提交
1190 1191 1192 1193 1194 1195
			NULL
		},
		&pg_krb_caseins_users,
		false, NULL, NULL
	},

1196 1197
	{
		{"escape_string_warning", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1198
			gettext_noop("Warn about backslash escapes in ordinary string literals."),
1199 1200 1201
			NULL
		},
		&escape_string_warning,
1202
		true, NULL, NULL
1203 1204 1205
	},

	{
1206
		{"standard_conforming_strings", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1207
			gettext_noop("Causes '...' strings to treat backslashes literally."),
1208
			NULL,
1209
			GUC_REPORT
1210
		},
1211
		&standard_conforming_strings,
1212 1213 1214
		false, NULL, NULL
	},

1215 1216 1217 1218 1219 1220 1221 1222 1223
	{
		{"synchronize_seqscans", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
			gettext_noop("Enable synchronized sequential scans."),
			NULL
		},
		&synchronize_seqscans,
		true, NULL, NULL
	},

B
Bruce Momjian 已提交
1224
	{
1225
		{"archive_mode", PGC_POSTMASTER, WAL_ARCHIVING,
B
Bruce Momjian 已提交
1226 1227 1228 1229 1230 1231
			gettext_noop("Allows archiving of WAL files using archive_command."),
			NULL
		},
		&XLogArchiveMode,
		false, NULL, NULL
	},
1232

1233
	{
1234
		{"hot_standby", PGC_POSTMASTER, WAL_STANDBY_SERVERS,
1235
			gettext_noop("Allows connections and queries during recovery."),
1236 1237
			NULL
		},
1238 1239
		&EnableHotStandby,
		false, NULL, NULL
1240 1241
	},

1242
	{
1243
		{"allow_system_table_mods", PGC_POSTMASTER, DEVELOPER_OPTIONS,
B
Bruce Momjian 已提交
1244 1245 1246
			gettext_noop("Allows modifications of the structure of system tables."),
			NULL,
			GUC_NOT_IN_SAMPLE
1247 1248 1249 1250 1251 1252 1253
		},
		&allowSystemTableMods,
		false, NULL, NULL
	},

	{
		{"ignore_system_indexes", PGC_BACKEND, DEVELOPER_OPTIONS,
B
Bruce Momjian 已提交
1254 1255 1256 1257
			gettext_noop("Disables reading from system indexes."),
			gettext_noop("It does not prevent updating the indexes, so it is safe "
						 "to use.  The worst consequence is slowness."),
			GUC_NOT_IN_SAMPLE
1258 1259 1260 1261 1262
		},
		&IgnoreSystemIndexes,
		false, NULL, NULL
	},

1263 1264
	{
		{"lo_compat_privileges", PGC_SUSET, COMPAT_OPTIONS_PREVIOUS,
P
Peter Eisentraut 已提交
1265
			gettext_noop("Enables backward compatibility mode for privilege checks on large objects."),
1266
			gettext_noop("Skips privilege checks when reading or modifying large objects, "
B
Bruce Momjian 已提交
1267
				  "for compatibility with PostgreSQL releases prior to 9.0.")
1268 1269 1270 1271 1272
		},
		&lo_compat_privileges,
		false, NULL, NULL
	},

1273
	/* End-of-list marker */
1274
	{
1275 1276
		{NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL
	}
1277 1278 1279
};


1280
static struct config_int ConfigureNamesInt[] =
1281
{
1282
	{
1283
		{"archive_timeout", PGC_SIGHUP, WAL_ARCHIVING,
B
Bruce Momjian 已提交
1284 1285 1286 1287
			gettext_noop("Forces a switch to the next xlog file if a "
						 "new file has not been started within N seconds."),
			NULL,
			GUC_UNIT_S
1288 1289 1290 1291
		},
		&XLogArchiveTimeout,
		0, 0, INT_MAX, NULL, NULL
	},
1292 1293
	{
		{"post_auth_delay", PGC_BACKEND, DEVELOPER_OPTIONS,
B
Bruce Momjian 已提交
1294 1295 1296
			gettext_noop("Waits N seconds on connection startup after authentication."),
			gettext_noop("This allows attaching a debugger to the process."),
			GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1297 1298 1299 1300
		},
		&PostAuthDelay,
		0, 0, INT_MAX, NULL, NULL
	},
1301
	{
1302
		{"default_statistics_target", PGC_USERSET, QUERY_TUNING_OTHER,
1303
			gettext_noop("Sets the default statistics target."),
1304
			gettext_noop("This applies to table columns that have not had a "
B
Bruce Momjian 已提交
1305
				"column-specific target set via ALTER TABLE SET STATISTICS.")
1306 1307
		},
		&default_statistics_target,
1308
		100, 1, 10000, NULL, NULL
1309
	},
1310
	{
1311
		{"from_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1312 1313
			gettext_noop("Sets the FROM-list size beyond which subqueries "
						 "are not collapsed."),
1314
			gettext_noop("The planner will merge subqueries into upper "
B
Bruce Momjian 已提交
1315
				"queries if the resulting FROM list would have no more than "
1316
						 "this many items.")
1317 1318
		},
		&from_collapse_limit,
1319 1320 1321
		8, 1, INT_MAX, NULL, NULL
	},
	{
1322
		{"join_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1323 1324
			gettext_noop("Sets the FROM-list size beyond which JOIN "
						 "constructs are not flattened."),
1325
			gettext_noop("The planner will flatten explicit JOIN "
1326 1327
						 "constructs into lists of FROM items whenever a "
						 "list of no more than this many items would result.")
1328 1329
		},
		&join_collapse_limit,
1330 1331 1332
		8, 1, INT_MAX, NULL, NULL
	},
	{
1333
		{"geqo_threshold", PGC_USERSET, QUERY_TUNING_GEQO,
1334
			gettext_noop("Sets the threshold of FROM items beyond which GEQO is used."),
1335 1336 1337
			NULL
		},
		&geqo_threshold,
1338
		12, 2, INT_MAX, NULL, NULL
1339
	},
1340
	{
1341 1342
		{"geqo_effort", PGC_USERSET, QUERY_TUNING_GEQO,
			gettext_noop("GEQO: effort is used to set the default for other GEQO parameters."),
1343 1344
			NULL
		},
1345 1346 1347 1348 1349 1350 1351 1352
		&Geqo_effort,
		DEFAULT_GEQO_EFFORT, MIN_GEQO_EFFORT, MAX_GEQO_EFFORT, NULL, NULL
	},
	{
		{"geqo_pool_size", PGC_USERSET, QUERY_TUNING_GEQO,
			gettext_noop("GEQO: number of individuals in the population."),
			gettext_noop("Zero selects a suitable default value.")
		},
1353
		&Geqo_pool_size,
1354
		0, 0, INT_MAX, NULL, NULL
1355 1356
	},
	{
1357
		{"geqo_generations", PGC_USERSET, QUERY_TUNING_GEQO,
1358
			gettext_noop("GEQO: number of iterations of the algorithm."),
1359
			gettext_noop("Zero selects a suitable default value.")
1360 1361
		},
		&Geqo_generations,
1362
		0, 0, INT_MAX, NULL, NULL
1363 1364 1365
	},

	{
1366
		/* This is PGC_SIGHUP so all backends have the same value. */
1367
		{"deadlock_timeout", PGC_SIGHUP, LOCK_MANAGEMENT,
1368
			gettext_noop("Sets the time to wait on a lock before checking for deadlock."),
1369 1370
			NULL,
			GUC_UNIT_MS
1371 1372
		},
		&DeadlockTimeout,
B
Bruce Momjian 已提交
1373
		1000, 1, INT_MAX / 1000, NULL, NULL
1374
	},
1375

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
	{
		{"max_standby_archive_delay", PGC_SIGHUP, WAL_STANDBY_SERVERS,
			gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing archived WAL data."),
			NULL,
			GUC_UNIT_MS
		},
		&max_standby_archive_delay,
		30 * 1000, -1, INT_MAX / 1000, NULL, NULL
	},

	{
		{"max_standby_streaming_delay", PGC_SIGHUP, WAL_STANDBY_SERVERS,
			gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing streamed WAL data."),
			NULL,
			GUC_UNIT_MS
		},
		&max_standby_streaming_delay,
		30 * 1000, -1, INT_MAX / 1000, NULL, NULL
	},

1396
	/*
1397 1398
	 * Note: MaxBackends is limited to INT_MAX/4 because some places compute
	 * 4*MaxBackends without any overflow check.  This check is made in
B
Bruce Momjian 已提交
1399
	 * assign_maxconnections, since MaxBackends is computed as MaxConnections
1400
	 * plus autovacuum_max_workers plus one (for the autovacuum launcher).
1401 1402
	 *
	 * Likewise we have to limit NBuffers to INT_MAX/2.
1403 1404
	 *
	 * See also CheckRequiredParameterValues() if this parameter changes
1405
	 */
1406
	{
1407
		{"max_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1408
			gettext_noop("Sets the maximum number of concurrent connections."),
1409 1410
			NULL
		},
1411 1412
		&MaxConnections,
		100, 1, INT_MAX / 4, assign_maxconnections, NULL
1413
	},
1414

1415
	{
1416
		{"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1417
			gettext_noop("Sets the number of connection slots reserved for superusers."),
1418 1419 1420
			NULL
		},
		&ReservedBackends,
1421
		3, 0, INT_MAX / 4, NULL, NULL
1422 1423
	},

1424
	{
1425
		{"shared_buffers", PGC_POSTMASTER, RESOURCES_MEM,
1426
			gettext_noop("Sets the number of shared memory buffers used by the server."),
1427 1428
			NULL,
			GUC_UNIT_BLOCKS
1429 1430
		},
		&NBuffers,
1431
		1024, 16, INT_MAX / 2, NULL, NULL
1432
	},
1433

1434 1435 1436
	{
		{"temp_buffers", PGC_USERSET, RESOURCES_MEM,
			gettext_noop("Sets the maximum number of temporary buffers used by each session."),
1437 1438
			NULL,
			GUC_UNIT_BLOCKS
1439 1440
		},
		&num_temp_buffers,
1441
		1024, 100, INT_MAX / 2, NULL, show_num_temp_buffers
1442 1443
	},

1444
	{
1445
		{"port", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1446
			gettext_noop("Sets the TCP port the server listens on."),
1447 1448 1449
			NULL
		},
		&PostPortNumber,
1450
		DEF_PGPORT, 1, 65535, NULL, NULL
1451
	},
1452

1453
	{
1454
		{"unix_socket_permissions", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1455
			gettext_noop("Sets the access permissions of the Unix-domain socket."),
1456
			gettext_noop("Unix-domain sockets use the usual Unix file system "
1457
						 "permission set. The parameter value is expected to be a numeric mode "
1458
						 "specification in the form accepted by the chmod and umask system "
1459 1460 1461 1462
						 "calls. (To use the customary octal format the number must start with "
						 "a 0 (zero).)")
		},
		&Unix_socket_permissions,
1463
		0777, 0000, 0777, NULL, NULL
1464
	},
1465

1466
	{
1467 1468
		{"work_mem", PGC_USERSET, RESOURCES_MEM,
			gettext_noop("Sets the maximum memory to be used for query workspaces."),
1469
			gettext_noop("This much memory can be used by each internal "
B
Bruce Momjian 已提交
1470
						 "sort operation and hash table before switching to "
1471 1472
						 "temporary disk files."),
			GUC_UNIT_KB
1473
		},
1474
		&work_mem,
1475
		1024, 64, MAX_KILOBYTES, NULL, NULL
1476
	},
1477

1478
	{
1479
		{"maintenance_work_mem", PGC_USERSET, RESOURCES_MEM,
1480
			gettext_noop("Sets the maximum memory to be used for maintenance operations."),
1481 1482
			gettext_noop("This includes operations such as VACUUM and CREATE INDEX."),
			GUC_UNIT_KB
1483
		},
1484
		&maintenance_work_mem,
1485
		16384, 1024, MAX_KILOBYTES, NULL, NULL
1486
	},
1487

1488 1489 1490
	{
		{"max_stack_depth", PGC_SUSET, RESOURCES_MEM,
			gettext_noop("Sets the maximum stack depth, in kilobytes."),
1491 1492
			NULL,
			GUC_UNIT_KB
1493 1494
		},
		&max_stack_depth,
1495
		100, 100, MAX_KILOBYTES, assign_max_stack_depth, NULL
1496 1497
	},

J
Jan Wieck 已提交
1498
	{
1499
		{"vacuum_cost_page_hit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
J
Jan Wieck 已提交
1500 1501 1502 1503 1504 1505 1506 1507
			gettext_noop("Vacuum cost for a page found in the buffer cache."),
			NULL
		},
		&VacuumCostPageHit,
		1, 0, 10000, NULL, NULL
	},

	{
1508
		{"vacuum_cost_page_miss", PGC_USERSET, RESOURCES_VACUUM_DELAY,
J
Jan Wieck 已提交
1509 1510 1511 1512 1513 1514 1515 1516
			gettext_noop("Vacuum cost for a page not found in the buffer cache."),
			NULL
		},
		&VacuumCostPageMiss,
		10, 0, 10000, NULL, NULL
	},

	{
1517
		{"vacuum_cost_page_dirty", PGC_USERSET, RESOURCES_VACUUM_DELAY,
J
Jan Wieck 已提交
1518 1519 1520 1521 1522 1523 1524 1525
			gettext_noop("Vacuum cost for a page dirtied by vacuum."),
			NULL
		},
		&VacuumCostPageDirty,
		20, 0, 10000, NULL, NULL
	},

	{
1526
		{"vacuum_cost_limit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
J
Jan Wieck 已提交
1527 1528 1529 1530 1531 1532 1533 1534
			gettext_noop("Vacuum cost amount available before napping."),
			NULL
		},
		&VacuumCostLimit,
		200, 1, 10000, NULL, NULL
	},

	{
1535
		{"vacuum_cost_delay", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1536
			gettext_noop("Vacuum cost delay in milliseconds."),
1537 1538
			NULL,
			GUC_UNIT_MS
J
Jan Wieck 已提交
1539
		},
1540
		&VacuumCostDelay,
1541
		0, 0, 100, NULL, NULL
J
Jan Wieck 已提交
1542 1543
	},

1544 1545 1546
	{
		{"autovacuum_vacuum_cost_delay", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Vacuum cost delay in milliseconds, for autovacuum."),
1547 1548
			NULL,
			GUC_UNIT_MS
1549 1550
		},
		&autovacuum_vac_cost_delay,
1551
		20, -1, 100, NULL, NULL
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
	},

	{
		{"autovacuum_vacuum_cost_limit", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Vacuum cost amount available before napping, for autovacuum."),
			NULL
		},
		&autovacuum_vac_cost_limit,
		-1, -1, 10000, NULL, NULL
	},

1563
	{
1564
		{"max_files_per_process", PGC_POSTMASTER, RESOURCES_KERNEL,
1565
			gettext_noop("Sets the maximum number of simultaneously open files for each server process."),
1566 1567 1568
			NULL
		},
		&max_files_per_process,
1569
		1000, 25, INT_MAX, NULL, NULL
1570
	},
1571

1572 1573 1574
	/*
	 * See also CheckRequiredParameterValues() if this parameter changes
	 */
1575
	{
1576
		{"max_prepared_transactions", PGC_POSTMASTER, RESOURCES_MEM,
1577 1578 1579 1580
			gettext_noop("Sets the maximum number of simultaneously prepared transactions."),
			NULL
		},
		&max_prepared_xacts,
1581
		0, 0, INT_MAX / 4, NULL, NULL
1582 1583
	},

1584
#ifdef LOCK_DEBUG
1585
	{
1586
		{"trace_lock_oidmin", PGC_SUSET, DEVELOPER_OPTIONS,
1587
			gettext_noop("No description available."),
1588 1589 1590 1591
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_lock_oidmin,
1592
		FirstNormalObjectId, 0, INT_MAX, NULL, NULL
1593 1594
	},
	{
1595
		{"trace_lock_table", PGC_SUSET, DEVELOPER_OPTIONS,
1596
			gettext_noop("No description available."),
1597 1598 1599 1600
			NULL,
			GUC_NOT_IN_SAMPLE
		},
		&Trace_lock_table,
1601
		0, 0, INT_MAX, NULL, NULL
1602
	},
1603 1604
#endif

1605
	{
1606
		{"statement_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
1607
			gettext_noop("Sets the maximum allowed duration of any statement."),
1608 1609
			gettext_noop("A value of 0 turns off the timeout."),
			GUC_UNIT_MS
1610 1611
		},
		&StatementTimeout,
1612 1613 1614
		0, 0, INT_MAX, NULL, NULL
	},

1615 1616 1617 1618 1619 1620
	{
		{"vacuum_freeze_min_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Minimum age at which VACUUM should freeze a table row."),
			NULL
		},
		&vacuum_freeze_min_age,
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
		50000000, 0, 1000000000, NULL, NULL
	},

	{
		{"vacuum_freeze_table_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Age at which VACUUM should scan whole table to freeze tuples."),
			NULL
		},
		&vacuum_freeze_table_age,
		150000000, 0, 2000000000, NULL, NULL
1631 1632
	},

1633
	{
1634
		{"vacuum_defer_cleanup_age", PGC_USERSET, WAL_STANDBY_SERVERS,
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
			gettext_noop("Age by which VACUUM and HOT cleanup should be deferred, if any."),
			NULL
		},
		&vacuum_defer_cleanup_age,
		0, 0, 1000000, NULL, NULL
	},

	/*
	 * See also CheckRequiredParameterValues() if this parameter changes
	 */
1645
	{
1646
		{"max_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
1647
			gettext_noop("Sets the maximum number of locks per transaction."),
1648
			gettext_noop("The shared lock table is sized on the assumption that "
B
Bruce Momjian 已提交
1649
			  "at most max_locks_per_transaction * max_connections distinct "
1650
						 "objects will need to be locked at any one time.")
1651 1652
		},
		&max_locks_per_xact,
1653
		64, 10, INT_MAX, NULL, NULL
1654
	},
1655

1656
	{
1657
		{"authentication_timeout", PGC_SIGHUP, CONN_AUTH_SECURITY,
1658
			gettext_noop("Sets the maximum allowed time to complete client authentication."),
1659 1660
			NULL,
			GUC_UNIT_S
1661 1662
		},
		&AuthenticationTimeout,
1663
		60, 1, 600, NULL, NULL
1664
	},
1665

1666
	{
1667 1668
		/* Not for general use */
		{"pre_auth_delay", PGC_SIGHUP, DEVELOPER_OPTIONS,
1669 1670
			gettext_noop("Waits N seconds on connection startup before authentication."),
			gettext_noop("This allows attaching a debugger to the process."),
1671
			GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1672 1673
		},
		&PreAuthDelay,
1674
		0, 0, 60, NULL, NULL
1675
	},
1676

1677
	{
1678
		{"wal_keep_segments", PGC_SIGHUP, WAL_CHECKPOINTS,
P
Peter Eisentraut 已提交
1679
			gettext_noop("Sets the number of WAL files held for standby servers."),
1680 1681
			NULL
		},
1682
		&wal_keep_segments,
1683 1684 1685
		0, 0, INT_MAX, NULL, NULL
	},

1686
	{
1687
		{"checkpoint_segments", PGC_SIGHUP, WAL_CHECKPOINTS,
1688
			gettext_noop("Sets the maximum distance in log segments between automatic WAL checkpoints."),
1689 1690 1691
			NULL
		},
		&CheckPointSegments,
1692
		3, 1, INT_MAX, NULL, NULL
1693
	},
T
Tom Lane 已提交
1694

1695
	{
1696
		{"checkpoint_timeout", PGC_SIGHUP, WAL_CHECKPOINTS,
1697
			gettext_noop("Sets the maximum time between automatic WAL checkpoints."),
1698 1699
			NULL,
			GUC_UNIT_S
1700 1701
		},
		&CheckPointTimeout,
1702
		300, 30, 3600, NULL, NULL
1703
	},
V
Vadim B. Mikheev 已提交
1704

1705
	{
1706
		{"checkpoint_warning", PGC_SIGHUP, WAL_CHECKPOINTS,
1707 1708
			gettext_noop("Enables warnings if checkpoint segments are filled more "
						 "frequently than this."),
1709
			gettext_noop("Write a message to the server log if checkpoints "
B
Bruce Momjian 已提交
1710
			"caused by the filling of checkpoint segment files happens more "
1711 1712
						 "frequently than this number of seconds. Zero turns off the warning."),
			GUC_UNIT_S
1713 1714
		},
		&CheckPointWarning,
1715 1716 1717
		30, 0, INT_MAX, NULL, NULL
	},

1718
	{
1719
		{"wal_buffers", PGC_POSTMASTER, WAL_SETTINGS,
1720
			gettext_noop("Sets the number of disk-page buffers in shared memory for WAL."),
1721 1722
			NULL,
			GUC_UNIT_XBLOCKS
1723 1724
		},
		&XLOGbuffers,
1725
		8, 4, INT_MAX, NULL, NULL
1726
	},
V
Vadim B. Mikheev 已提交
1727

1728 1729
	{
		{"wal_writer_delay", PGC_SIGHUP, WAL_SETTINGS,
1730
			gettext_noop("WAL writer sleep time between WAL flushes."),
1731 1732 1733 1734 1735 1736 1737
			NULL,
			GUC_UNIT_MS
		},
		&WalWriterDelay,
		200, 1, 10000, NULL, NULL
	},

1738 1739 1740 1741 1742 1743
	{
		/* see max_connections */
		{"max_wal_senders", PGC_POSTMASTER, WAL_REPLICATION,
			gettext_noop("Sets the maximum number of simultaneously running WAL sender processes."),
			NULL
		},
1744
		&max_wal_senders,
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
		0, 0, INT_MAX / 4, NULL, NULL
	},

	{
		{"wal_sender_delay", PGC_SIGHUP, WAL_REPLICATION,
			gettext_noop("WAL sender sleep time between WAL replications."),
			NULL,
			GUC_UNIT_MS
		},
		&WalSndDelay,
		200, 1, 10000, NULL, NULL
	},

1758
	{
1759
		{"commit_delay", PGC_USERSET, WAL_SETTINGS,
1760 1761
			gettext_noop("Sets the delay in microseconds between transaction commit and "
						 "flushing WAL to disk."),
1762 1763 1764
			NULL
		},
		&CommitDelay,
1765
		0, 0, 100000, NULL, NULL
1766
	},
V
Vadim B. Mikheev 已提交
1767

1768
	{
1769
		{"commit_siblings", PGC_USERSET, WAL_SETTINGS,
1770 1771
			gettext_noop("Sets the minimum concurrent open transactions before performing "
						 "commit_delay."),
1772 1773 1774
			NULL
		},
		&CommitSiblings,
1775
		5, 1, 1000, NULL, NULL
1776
	},
1777

1778
	{
1779
		{"extra_float_digits", PGC_USERSET, CLIENT_CONN_LOCALE,
1780
			gettext_noop("Sets the number of digits displayed for floating-point values."),
1781
			gettext_noop("This affects real, double precision, and geometric data types. "
B
Bruce Momjian 已提交
1782
			 "The parameter value is added to the standard number of digits "
1783
						 "(FLT_DIG or DBL_DIG as appropriate).")
1784 1785
		},
		&extra_float_digits,
1786
		0, -15, 3, NULL, NULL
1787 1788
	},

B
Bruce Momjian 已提交
1789
	{
1790
		{"log_min_duration_statement", PGC_SUSET, LOGGING_WHEN,
1791 1792
			gettext_noop("Sets the minimum execution time above which "
						 "statements will be logged."),
1793
			gettext_noop("Zero prints all queries. -1 turns this feature off."),
1794
			GUC_UNIT_MS
1795 1796
		},
		&log_min_duration_statement,
1797
		-1, -1, INT_MAX / 1000, NULL, NULL
B
Bruce Momjian 已提交
1798 1799
	},

1800
	{
1801
		{"log_autovacuum_min_duration", PGC_SIGHUP, LOGGING_WHAT,
1802
			gettext_noop("Sets the minimum execution time above which "
1803 1804
						 "autovacuum actions will be logged."),
			gettext_noop("Zero prints all actions. -1 turns autovacuum logging off."),
1805 1806
			GUC_UNIT_MS
		},
1807
		&Log_autovacuum_min_duration,
1808 1809 1810
		-1, -1, INT_MAX / 1000, NULL, NULL
	},

J
Jan Wieck 已提交
1811
	{
1812
		{"bgwriter_delay", PGC_SIGHUP, RESOURCES_BGWRITER,
1813
			gettext_noop("Background writer sleep time between rounds."),
1814 1815
			NULL,
			GUC_UNIT_MS
J
Jan Wieck 已提交
1816 1817
		},
		&BgWriterDelay,
1818
		200, 10, 10000, NULL, NULL
J
Jan Wieck 已提交
1819 1820 1821
	},

	{
1822
		{"bgwriter_lru_maxpages", PGC_SIGHUP, RESOURCES_BGWRITER,
1823
			gettext_noop("Background writer maximum number of LRU pages to flush per round."),
J
Jan Wieck 已提交
1824 1825
			NULL
		},
1826
		&bgwriter_lru_maxpages,
1827
		100, 0, 1000, NULL, NULL
J
Jan Wieck 已提交
1828 1829
	},

1830
	{
1831 1832
		{"effective_io_concurrency",
#ifdef USE_PREFETCH
1833
			PGC_USERSET,
1834
#else
1835
			PGC_INTERNAL,
1836
#endif
1837
			RESOURCES_ASYNCHRONOUS,
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
			gettext_noop("Number of simultaneous requests that can be handled efficiently by the disk subsystem."),
			gettext_noop("For RAID arrays, this should be approximately the number of drive spindles in the array.")
		},
		&effective_io_concurrency,
#ifdef USE_PREFETCH
		1, 0, 1000,
#else
		0, 0, 0,
#endif
		assign_effective_io_concurrency, NULL
	},

1850 1851
	{
		{"log_rotation_age", PGC_SIGHUP, LOGGING_WHERE,
1852
			gettext_noop("Automatic log file rotation will occur after N minutes."),
1853 1854
			NULL,
			GUC_UNIT_MIN
1855 1856
		},
		&Log_RotationAge,
B
Bruce Momjian 已提交
1857
		HOURS_PER_DAY * MINS_PER_HOUR, 0, INT_MAX / MINS_PER_HOUR, NULL, NULL
1858 1859 1860 1861
	},

	{
		{"log_rotation_size", PGC_SIGHUP, LOGGING_WHERE,
1862
			gettext_noop("Automatic log file rotation will occur after N kilobytes."),
1863 1864
			NULL,
			GUC_UNIT_KB
1865 1866
		},
		&Log_RotationSize,
1867
		10 * 1024, 0, INT_MAX / 1024, NULL, NULL
1868 1869
	},

1870
	{
1871
		{"max_function_args", PGC_INTERNAL, PRESET_OPTIONS,
P
Peter Eisentraut 已提交
1872
			gettext_noop("Shows the maximum number of function arguments."),
1873 1874 1875 1876 1877 1878 1879 1880
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&max_function_args,
		FUNC_MAX_ARGS, FUNC_MAX_ARGS, FUNC_MAX_ARGS, NULL, NULL
	},

	{
1881
		{"max_index_keys", PGC_INTERNAL, PRESET_OPTIONS,
P
Peter Eisentraut 已提交
1882
			gettext_noop("Shows the maximum number of index keys."),
1883 1884 1885 1886 1887 1888 1889 1890
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&max_index_keys,
		INDEX_MAX_KEYS, INDEX_MAX_KEYS, INDEX_MAX_KEYS, NULL, NULL
	},

	{
1891
		{"max_identifier_length", PGC_INTERNAL, PRESET_OPTIONS,
1892
			gettext_noop("Shows the maximum identifier length."),
1893 1894 1895 1896 1897 1898 1899 1900
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&max_identifier_length,
		NAMEDATALEN - 1, NAMEDATALEN - 1, NAMEDATALEN - 1, NULL, NULL
	},

	{
1901
		{"block_size", PGC_INTERNAL, PRESET_OPTIONS,
1902
			gettext_noop("Shows the size of a disk block."),
1903 1904 1905 1906 1907 1908 1909
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&block_size,
		BLCKSZ, BLCKSZ, BLCKSZ, NULL, NULL
	},

1910 1911
	{
		{"segment_size", PGC_INTERNAL, PRESET_OPTIONS,
1912 1913 1914
			gettext_noop("Shows the number of pages per disk file."),
			NULL,
			GUC_UNIT_BLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
		},
		&segment_size,
		RELSEG_SIZE, RELSEG_SIZE, RELSEG_SIZE, NULL, NULL
	},

	{
		{"wal_block_size", PGC_INTERNAL, PRESET_OPTIONS,
			gettext_noop("Shows the block size in the write ahead log."),
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&wal_block_size,
		XLOG_BLCKSZ, XLOG_BLCKSZ, XLOG_BLCKSZ, NULL, NULL
	},

	{
		{"wal_segment_size", PGC_INTERNAL, PRESET_OPTIONS,
			gettext_noop("Shows the number of pages per write ahead log segment."),
			NULL,
			GUC_UNIT_XBLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&wal_segment_size,
1937 1938
		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
1939 1940 1941 1942
		(XLOG_SEG_SIZE / XLOG_BLCKSZ),
		NULL, NULL
	},

1943 1944
	{
		{"autovacuum_naptime", PGC_SIGHUP, AUTOVACUUM,
1945
			gettext_noop("Time to sleep between autovacuum runs."),
1946 1947
			NULL,
			GUC_UNIT_S
1948 1949
		},
		&autovacuum_naptime,
1950
		60, 1, INT_MAX / 1000, NULL, NULL
1951 1952 1953 1954 1955 1956 1957
	},
	{
		{"autovacuum_vacuum_threshold", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Minimum number of tuple updates or deletes prior to vacuum."),
			NULL
		},
		&autovacuum_vac_thresh,
1958
		50, 0, INT_MAX, NULL, NULL
1959 1960 1961 1962 1963 1964 1965
	},
	{
		{"autovacuum_analyze_threshold", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Minimum number of tuple inserts, updates or deletes prior to analyze."),
			NULL
		},
		&autovacuum_anl_thresh,
1966
		50, 0, INT_MAX, NULL, NULL
1967
	},
1968 1969 1970
	{
		/* see varsup.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
		{"autovacuum_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
P
Peter Eisentraut 已提交
1971
			gettext_noop("Age at which to autovacuum a table to prevent transaction ID wraparound."),
1972 1973 1974
			NULL
		},
		&autovacuum_freeze_max_age,
1975
		/* see pg_resetxlog if you change the upper-limit value */
1976 1977
		200000000, 100000000, 2000000000, NULL, NULL
	},
1978 1979 1980 1981 1982 1983 1984 1985 1986
	{
		/* see max_connections */
		{"autovacuum_max_workers", PGC_POSTMASTER, AUTOVACUUM,
			gettext_noop("Sets the maximum number of simultaneously running autovacuum worker processes."),
			NULL
		},
		&autovacuum_max_workers,
		3, 1, INT_MAX / 4, assign_autovacuum_max_workers, NULL
	},
1987

1988 1989
	{
		{"tcp_keepalives_idle", PGC_USERSET, CLIENT_CONN_OTHER,
1990
			gettext_noop("Time between issuing TCP keepalives."),
B
Bruce Momjian 已提交
1991
			gettext_noop("A value of 0 uses the system default."),
1992
			GUC_UNIT_S
B
Bruce Momjian 已提交
1993
		},
1994 1995 1996 1997 1998 1999
		&tcp_keepalives_idle,
		0, 0, INT_MAX, assign_tcp_keepalives_idle, show_tcp_keepalives_idle
	},

	{
		{"tcp_keepalives_interval", PGC_USERSET, CLIENT_CONN_OTHER,
2000
			gettext_noop("Time between TCP keepalive retransmits."),
B
Bruce Momjian 已提交
2001
			gettext_noop("A value of 0 uses the system default."),
2002
			GUC_UNIT_S
B
Bruce Momjian 已提交
2003
		},
2004 2005 2006 2007
		&tcp_keepalives_interval,
		0, 0, INT_MAX, assign_tcp_keepalives_interval, show_tcp_keepalives_interval
	},

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
	{
		{"ssl_renegotiation_limit", PGC_USERSET, CONN_AUTH_SECURITY,
			gettext_noop("Set the amount of traffic to send and receive before renegotiating the encryption keys."),
			NULL,
			GUC_UNIT_KB,
		},
		&ssl_renegotiation_limit,
		512 * 1024, 0, MAX_KILOBYTES, NULL, NULL
	},

2018 2019
	{
		{"tcp_keepalives_count", PGC_USERSET, CLIENT_CONN_OTHER,
B
Bruce Momjian 已提交
2020 2021 2022 2023 2024
			gettext_noop("Maximum number of TCP keepalive retransmits."),
			gettext_noop("This controls the number of consecutive keepalive retransmits that can be "
						 "lost before a connection is considered dead. A value of 0 uses the "
						 "system default."),
		},
2025 2026 2027 2028
		&tcp_keepalives_count,
		0, 0, INT_MAX, assign_tcp_keepalives_count, show_tcp_keepalives_count
	},

T
Teodor Sigaev 已提交
2029
	{
2030
		{"gin_fuzzy_search_limit", PGC_USERSET, CLIENT_CONN_OTHER,
P
Peter Eisentraut 已提交
2031
			gettext_noop("Sets the maximum allowed result for exact search by GIN."),
T
Teodor Sigaev 已提交
2032 2033 2034 2035 2036 2037 2038
			NULL,
			0
		},
		&GinFuzzySearchLimit,
		0, 0, INT_MAX, NULL, NULL
	},

2039 2040
	{
		{"effective_cache_size", PGC_USERSET, QUERY_TUNING_COST,
2041
			gettext_noop("Sets the planner's assumption about the size of the disk cache."),
2042 2043
			gettext_noop("That is, the portion of the kernel's disk cache that "
						 "will be used for PostgreSQL data files. This is measured in disk "
2044 2045
						 "pages, which are normally 8 kB each."),
			GUC_UNIT_BLOCKS,
2046 2047 2048 2049 2050
		},
		&effective_cache_size,
		DEFAULT_EFFECTIVE_CACHE_SIZE, 1, INT_MAX, NULL, NULL
	},

2051 2052 2053 2054 2055
	{
		/* Can't be set in postgresql.conf */
		{"server_version_num", PGC_INTERNAL, PRESET_OPTIONS,
			gettext_noop("Shows the server version as an integer."),
			NULL,
2056
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2057 2058 2059 2060
		},
		&server_version_num,
		PG_VERSION_NUM, PG_VERSION_NUM, PG_VERSION_NUM, NULL, NULL
	},
2061

2062
	{
2063
		{"log_temp_files", PGC_SUSET, LOGGING_WHAT,
2064
			gettext_noop("Log the use of temporary files larger than this number of bytes."),
2065
			gettext_noop("Zero logs all files. The default is -1 (turning this feature off)."),
2066
			GUC_UNIT_KB
2067 2068 2069 2070
		},
		&log_temp_files,
		-1, -1, INT_MAX, NULL, NULL
	},
2071

2072 2073 2074 2075 2076 2077 2078 2079 2080
	{
		{"track_activity_query_size", PGC_POSTMASTER, RESOURCES_MEM,
			gettext_noop("Sets the size reserved for pg_stat_activity.current_query, in bytes."),
			NULL,
		},
		&pgstat_track_activity_query_size,
		1024, 100, 102400, NULL, NULL
	},

2081
	/* End-of-list marker */
2082
	{
2083
		{NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL
2084
	}
2085 2086 2087
};


2088
static struct config_real ConfigureNamesReal[] =
2089
{
2090
	{
2091 2092 2093 2094
		{"seq_page_cost", PGC_USERSET, QUERY_TUNING_COST,
			gettext_noop("Sets the planner's estimate of the cost of a "
						 "sequentially fetched disk page."),
			NULL
2095
		},
2096 2097
		&seq_page_cost,
		DEFAULT_SEQ_PAGE_COST, 0, DBL_MAX, NULL, NULL
2098
	},
2099
	{
2100
		{"random_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2101 2102 2103
			gettext_noop("Sets the planner's estimate of the cost of a "
						 "nonsequentially fetched disk page."),
			NULL
2104 2105
		},
		&random_page_cost,
2106
		DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX, NULL, NULL
2107 2108
	},
	{
2109
		{"cpu_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2110 2111 2112
			gettext_noop("Sets the planner's estimate of the cost of "
						 "processing each tuple (row)."),
			NULL
2113 2114
		},
		&cpu_tuple_cost,
2115
		DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX, NULL, NULL
2116 2117
	},
	{
2118
		{"cpu_index_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2119 2120 2121
			gettext_noop("Sets the planner's estimate of the cost of "
						 "processing each index entry during an index scan."),
			NULL
2122 2123
		},
		&cpu_index_tuple_cost,
2124
		DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX, NULL, NULL
2125 2126
	},
	{
2127
		{"cpu_operator_cost", PGC_USERSET, QUERY_TUNING_COST,
2128 2129 2130
			gettext_noop("Sets the planner's estimate of the cost of "
						 "processing each operator or function call."),
			NULL
2131 2132
		},
		&cpu_operator_cost,
2133
		DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX, NULL, NULL
2134 2135
	},

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
	{
		{"cursor_tuple_fraction", PGC_USERSET, QUERY_TUNING_OTHER,
			gettext_noop("Sets the planner's estimate of the fraction of "
						 "a cursor's rows that will be retrieved."),
			NULL
		},
		&cursor_tuple_fraction,
		DEFAULT_CURSOR_TUPLE_FRACTION, 0.0, 1.0, NULL, NULL
	},

2146
	{
2147
		{"geqo_selection_bias", PGC_USERSET, QUERY_TUNING_GEQO,
2148
			gettext_noop("GEQO: selective pressure within the population."),
2149 2150 2151
			NULL
		},
		&Geqo_selection_bias,
2152 2153
		DEFAULT_GEQO_SELECTION_BIAS, MIN_GEQO_SELECTION_BIAS,
		MAX_GEQO_SELECTION_BIAS, NULL, NULL
2154
	},
2155 2156 2157 2158 2159 2160 2161 2162
	{
		{"geqo_seed", PGC_USERSET, QUERY_TUNING_GEQO,
			gettext_noop("GEQO: seed for random path selection."),
			NULL
		},
		&Geqo_seed,
		0.0, 0.0, 1.0, NULL, NULL
	},
2163

2164
	{
2165
		{"bgwriter_lru_multiplier", PGC_SIGHUP, RESOURCES_BGWRITER,
2166
			gettext_noop("Multiple of the average buffer usage to free per round."),
2167 2168
			NULL
		},
2169 2170
		&bgwriter_lru_multiplier,
		2.0, 0.0, 10.0, NULL, NULL
2171 2172
	},

2173
	{
2174
		{"seed", PGC_USERSET, UNGROUPED,
2175
			gettext_noop("Sets the seed for random-number generation."),
2176 2177 2178
			NULL,
			GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
2179
		&phony_random_seed,
2180
		0.0, -1.0, 1.0, assign_random_seed, show_random_seed
2181 2182
	},

2183 2184 2185 2186 2187 2188
	{
		{"autovacuum_vacuum_scale_factor", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Number of tuple updates or deletes prior to vacuum as a fraction of reltuples."),
			NULL
		},
		&autovacuum_vac_scale,
2189
		0.2, 0.0, 100.0, NULL, NULL
2190 2191 2192 2193 2194 2195 2196
	},
	{
		{"autovacuum_analyze_scale_factor", PGC_SIGHUP, AUTOVACUUM,
			gettext_noop("Number of tuple inserts, updates or deletes prior to analyze as a fraction of reltuples."),
			NULL
		},
		&autovacuum_anl_scale,
2197
		0.1, 0.0, 100.0, NULL, NULL
2198 2199
	},

2200 2201 2202 2203 2204 2205 2206 2207 2208
	{
		{"checkpoint_completion_target", PGC_SIGHUP, WAL_CHECKPOINTS,
			gettext_noop("Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval."),
			NULL
		},
		&CheckPointCompletionTarget,
		0.5, 0.0, 1.0, NULL, NULL
	},

2209
	/* End-of-list marker */
2210
	{
2211
		{NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL
2212
	}
2213 2214 2215
};


2216
static struct config_string ConfigureNamesString[] =
2217
{
B
Bruce Momjian 已提交
2218
	{
2219
		{"archive_command", PGC_SIGHUP, WAL_ARCHIVING,
2220 2221
			gettext_noop("Sets the shell command that will be called to archive a WAL file."),
			NULL
B
Bruce Momjian 已提交
2222 2223
		},
		&XLogArchiveCommand,
2224
		"", NULL, show_archive_command
B
Bruce Momjian 已提交
2225
	},
2226

2227
	{
2228
		{"client_encoding", PGC_USERSET, CLIENT_CONN_LOCALE,
2229
			gettext_noop("Sets the client's character set encoding."),
2230
			NULL,
2231
			GUC_IS_NAME | GUC_REPORT
2232
		},
2233
		&client_encoding_string,
2234
		"SQL_ASCII", assign_client_encoding, NULL
2235 2236
	},

B
Add:  
Bruce Momjian 已提交
2237 2238
	{
		{"log_line_prefix", PGC_SIGHUP, LOGGING_WHAT,
2239 2240
			gettext_noop("Controls information prefixed to each log line."),
			gettext_noop("If blank, no prefix is used.")
B
Add:  
Bruce Momjian 已提交
2241 2242 2243 2244 2245
		},
		&Log_line_prefix,
		"", NULL, NULL
	},

2246 2247 2248 2249 2250 2251 2252 2253
	{
		{"log_timezone", PGC_SIGHUP, LOGGING_WHAT,
			gettext_noop("Sets the time zone to use in log messages."),
			NULL
		},
		&log_timezone_string,
		"UNKNOWN", assign_log_timezone, show_log_timezone
	},
B
Add:  
Bruce Momjian 已提交
2254

2255
	{
2256
		{"DateStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
2257
			gettext_noop("Sets the display format for date and time values."),
2258
			gettext_noop("Also controls interpretation of ambiguous "
2259
						 "date inputs."),
2260 2261
			GUC_LIST_INPUT | GUC_REPORT
		},
2262
		&datestyle_string,
2263
		"ISO, MDY", assign_datestyle, NULL
2264
	},
2265

2266 2267 2268
	{
		{"default_tablespace", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets the default tablespace to create tables and indexes in."),
2269
			gettext_noop("An empty string selects the database's default tablespace."),
B
Bruce Momjian 已提交
2270
			GUC_IS_NAME
2271 2272 2273 2274 2275
		},
		&default_tablespace,
		"", assign_default_tablespace, NULL
	},

2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
	{
		{"temp_tablespaces", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets the tablespace(s) to use for temporary tables and sort files."),
			NULL,
			GUC_LIST_INPUT | GUC_LIST_QUOTE
		},
		&temp_tablespaces,
		"", assign_temp_tablespaces, NULL
	},

2286
	{
2287
		{"dynamic_library_path", PGC_SUSET, CLIENT_CONN_OTHER,
2288
			gettext_noop("Sets the path for dynamically loadable modules."),
2289
			gettext_noop("If a dynamically loadable module needs to be opened and "
2290
						 "the specified name does not have a directory component (i.e., the "
2291
						 "name does not contain a slash), the system will search this path for "
2292 2293
						 "the specified file."),
			GUC_SUPERUSER_ONLY
2294 2295
		},
		&Dynamic_library_path,
2296
		"$libdir", NULL, NULL
2297 2298 2299
	},

	{
2300
		{"krb_server_keyfile", PGC_SIGHUP, CONN_AUTH_SECURITY,
2301
			gettext_noop("Sets the location of the Kerberos server key file."),
2302 2303
			NULL,
			GUC_SUPERUSER_ONLY
2304 2305
		},
		&pg_krb_server_keyfile,
2306
		PG_KRB_SRVTAB, NULL, NULL
2307
	},
2308

B
 
Bruce Momjian 已提交
2309
	{
2310
		{"krb_srvname", PGC_SIGHUP, CONN_AUTH_SECURITY,
B
 
Bruce Momjian 已提交
2311 2312 2313 2314 2315 2316 2317
			gettext_noop("Sets the name of the Kerberos service."),
			NULL
		},
		&pg_krb_srvnam,
		PG_KRB_SRVNAM, NULL, NULL
	},

2318
	{
2319
		{"bonjour_name", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2320
			gettext_noop("Sets the Bonjour service name."),
2321 2322
			NULL
		},
2323
		&bonjour_name,
2324 2325 2326
		"", NULL, NULL
	},

2327 2328
	/* See main.c about why defaults for LC_foo are not all alike */

2329
	{
2330
		{"lc_collate", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2331
			gettext_noop("Shows the collation order locale."),
2332 2333 2334 2335
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&locale_collate,
2336 2337 2338 2339
		"C", NULL, NULL
	},

	{
2340
		{"lc_ctype", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2341
			gettext_noop("Shows the character classification and case conversion locale."),
2342 2343 2344 2345
			NULL,
			GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
		&locale_ctype,
2346 2347 2348
		"C", NULL, NULL
	},

2349
	{
2350
		{"lc_messages", PGC_SUSET, CLIENT_CONN_LOCALE,
2351
			gettext_noop("Sets the language in which messages are displayed."),
2352 2353 2354
			NULL
		},
		&locale_messages,
2355 2356 2357 2358
		"", locale_messages_assign, NULL
	},

	{
2359
		{"lc_monetary", PGC_USERSET, CLIENT_CONN_LOCALE,
2360
			gettext_noop("Sets the locale for formatting monetary amounts."),
2361 2362 2363
			NULL
		},
		&locale_monetary,
2364
		"C", locale_monetary_assign, NULL
2365 2366 2367
	},

	{
2368
		{"lc_numeric", PGC_USERSET, CLIENT_CONN_LOCALE,
2369
			gettext_noop("Sets the locale for formatting numbers."),
2370 2371 2372
			NULL
		},
		&locale_numeric,
2373
		"C", locale_numeric_assign, NULL
2374 2375 2376
	},

	{
2377
		{"lc_time", PGC_USERSET, CLIENT_CONN_LOCALE,
2378
			gettext_noop("Sets the locale for formatting date and time values."),
2379 2380 2381
			NULL
		},
		&locale_time,
2382
		"C", locale_time_assign, NULL
2383 2384
	},

2385
	{
2386
		{"shared_preload_libraries", PGC_POSTMASTER, RESOURCES_KERNEL,
2387
			gettext_noop("Lists shared libraries to preload into server."),
2388
			NULL,
2389
			GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
2390
		},
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
		&shared_preload_libraries_string,
		"", NULL, NULL
	},

	{
		{"local_preload_libraries", PGC_BACKEND, CLIENT_CONN_OTHER,
			gettext_noop("Lists shared libraries to preload into each backend."),
			NULL,
			GUC_LIST_INPUT | GUC_LIST_QUOTE
		},
		&local_preload_libraries_string,
2402
		"", NULL, NULL
2403 2404
	},

2405
	{
2406
		{"search_path", PGC_USERSET, CLIENT_CONN_STATEMENT,
2407
			gettext_noop("Sets the schema search order for names that are not schema-qualified."),
2408 2409 2410
			NULL,
			GUC_LIST_INPUT | GUC_LIST_QUOTE
		},
2411
		&namespace_search_path,
2412
		"\"$user\",public", assign_search_path, NULL
2413 2414 2415
	},

	{
2416 2417
		/* Can't be set in postgresql.conf */
		{"server_encoding", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2418
			gettext_noop("Sets the server (database) character set encoding."),
2419
			NULL,
2420
			GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2421
		},
2422 2423 2424 2425 2426
		&server_encoding_string,
		"SQL_ASCII", NULL, NULL
	},

	{
2427
		/* Can't be set in postgresql.conf */
2428
		{"server_version", PGC_INTERNAL, PRESET_OPTIONS,
2429
			gettext_noop("Shows the server version."),
2430 2431 2432
			NULL,
			GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
2433 2434
		&server_version_string,
		PG_VERSION, NULL, NULL
2435 2436
	},

2437 2438 2439 2440 2441
	{
		/* Not for general use --- used by SET ROLE */
		{"role", PGC_USERSET, UNGROUPED,
			gettext_noop("Sets the current role."),
			NULL,
2442
			GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
2443 2444 2445 2446 2447
		},
		&role_string,
		"none", assign_role, show_role
	},

2448
	{
2449 2450
		/* Not for general use --- used by SET SESSION AUTHORIZATION */
		{"session_authorization", PGC_USERSET, UNGROUPED,
2451
			gettext_noop("Sets the session user name."),
2452
			NULL,
2453
			GUC_IS_NAME | GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
2454
		},
2455 2456
		&session_authorization_string,
		NULL, assign_session_authorization, show_session_authorization
2457 2458
	},

2459
	{
2460
		{"log_destination", PGC_SIGHUP, LOGGING_WHERE,
B
Bruce Momjian 已提交
2461
			gettext_noop("Sets the destination for server log output."),
2462 2463 2464
			gettext_noop("Valid values are combinations of \"stderr\", "
						 "\"syslog\", \"csvlog\", and \"eventlog\", "
						 "depending on the platform."),
B
Bruce Momjian 已提交
2465
			GUC_LIST_INPUT
2466 2467 2468 2469
		},
		&log_destination_string,
		"stderr", assign_log_destination, NULL
	},
2470 2471
	{
		{"log_directory", PGC_SIGHUP, LOGGING_WHERE,
2472
			gettext_noop("Sets the destination directory for log files."),
2473
			gettext_noop("Can be specified as relative to the data directory "
2474 2475
						 "or as absolute path."),
			GUC_SUPERUSER_ONLY
2476 2477
		},
		&Log_directory,
2478
		"pg_log", assign_canonical_path, NULL
2479 2480
	},
	{
2481 2482
		{"log_filename", PGC_SIGHUP, LOGGING_WHERE,
			gettext_noop("Sets the file name pattern for log files."),
2483 2484
			NULL,
			GUC_SUPERUSER_ONLY
2485
		},
2486 2487
		&Log_filename,
		"postgresql-%Y-%m-%d_%H%M%S.log", NULL, NULL
2488
	},
2489

T
Tatsuo Ishii 已提交
2490
#ifdef HAVE_SYSLOG
2491
	{
2492 2493 2494
		{"syslog_ident", PGC_SIGHUP, LOGGING_WHERE,
			gettext_noop("Sets the program name used to identify PostgreSQL "
						 "messages in syslog."),
2495 2496
			NULL
		},
2497 2498
		&syslog_ident_str,
		"postgres", assign_syslog_ident, NULL
2499
	},
2500
#endif
2501

2502
	{
2503
		{"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
2504
			gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
2505 2506
			NULL,
			GUC_REPORT
2507 2508
		},
		&timezone_string,
2509 2510
		"UNKNOWN", assign_timezone, show_timezone
	},
2511 2512
	{
		{"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
2513
			gettext_noop("Selects a file of time zone abbreviations."),
2514
			NULL
2515
		},
2516 2517
		&timezone_abbreviations_string,
		"UNKNOWN", assign_timezone_abbreviations, NULL
2518
	},
2519 2520

	{
2521
		{"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2522
			gettext_noop("Sets the current transaction's isolation level."),
2523 2524 2525
			NULL,
			GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
		},
2526 2527 2528 2529 2530
		&XactIsoLevel_string,
		NULL, assign_XactIsoLevel, show_XactIsoLevel
	},

	{
2531
		{"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2532
			gettext_noop("Sets the owning group of the Unix-domain socket."),
2533 2534
			gettext_noop("The owning user of the socket is always the user "
						 "that starts the server.")
2535 2536
		},
		&Unix_socket_group,
2537
		"", NULL, NULL
2538
	},
2539

2540
	{
2541
		{"unix_socket_directory", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2542
			gettext_noop("Sets the directory where the Unix-domain socket will be created."),
2543 2544
			NULL,
			GUC_SUPERUSER_ONLY
2545 2546
		},
		&UnixSocketDir,
2547
		"", assign_canonical_path, NULL
2548
	},
2549

2550
	{
2551
		{"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2552 2553 2554
			gettext_noop("Sets the host name or IP address(es) to listen to."),
			NULL,
			GUC_LIST_INPUT
2555
		},
2556 2557
		&ListenAddresses,
		"localhost", NULL, NULL
2558
	},
2559

2560
	{
2561
		{"custom_variable_classes", PGC_SIGHUP, CUSTOM_OPTIONS,
2562
			gettext_noop("Sets the list of known custom variable classes."),
2563 2564 2565 2566 2567 2568 2569
			NULL,
			GUC_LIST_INPUT | GUC_LIST_QUOTE
		},
		&custom_variable_classes,
		NULL, assign_custom_variable_classes, NULL
	},

2570
	{
2571
		{"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
B
Bruce Momjian 已提交
2572 2573 2574
			gettext_noop("Sets the server's data directory."),
			NULL,
			GUC_SUPERUSER_ONLY
2575
		},
2576 2577
		&data_directory,
		NULL, NULL, NULL
2578 2579 2580
	},

	{
2581
		{"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
B
Bruce Momjian 已提交
2582 2583 2584
			gettext_noop("Sets the server's main configuration file."),
			NULL,
			GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
2585 2586 2587 2588 2589 2590 2591
		},
		&ConfigFileName,
		NULL, NULL, NULL
	},

	{
		{"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
2592
			gettext_noop("Sets the server's \"hba\" configuration file."),
B
Bruce Momjian 已提交
2593 2594
			NULL,
			GUC_SUPERUSER_ONLY
2595
		},
2596 2597
		&HbaFileName,
		NULL, NULL, NULL
2598 2599 2600
	},

	{
2601
		{"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
2602
			gettext_noop("Sets the server's \"ident\" configuration file."),
B
Bruce Momjian 已提交
2603 2604
			NULL,
			GUC_SUPERUSER_ONLY
2605
		},
2606 2607
		&IdentFileName,
		NULL, NULL, NULL
2608 2609 2610
	},

	{
2611
		{"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
B
Bruce Momjian 已提交
2612 2613 2614
			gettext_noop("Writes the postmaster PID to the specified file."),
			NULL,
			GUC_SUPERUSER_ONLY
2615
		},
2616
		&external_pid_file,
2617
		NULL, assign_canonical_path, NULL
2618 2619
	},

2620
	{
2621
		{"stats_temp_directory", PGC_SIGHUP, STATS_COLLECTOR,
2622 2623 2624 2625 2626 2627 2628 2629
			gettext_noop("Writes temporary statistics files to the specified directory."),
			NULL,
			GUC_SUPERUSER_ONLY
		},
		&pgstat_temp_directory,
		"pg_stat_tmp", assign_pgstat_temp_directory, NULL
	},

2630 2631 2632 2633 2634 2635 2636 2637 2638
	{
		{"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
			gettext_noop("Sets default text search configuration."),
			NULL
		},
		&TSCurrentConfig,
		"pg_catalog.simple", assignTSCurrentConfig, NULL
	},

T
Tom Lane 已提交
2639
#ifdef USE_SSL
B
Bruce Momjian 已提交
2640 2641 2642 2643 2644 2645 2646 2647 2648
	{
		{"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
			gettext_noop("Sets the list of allowed SSL ciphers."),
			NULL,
			GUC_SUPERUSER_ONLY
		},
		&SSLCipherSuites,
		"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH", NULL, NULL
	},
B
Bruce Momjian 已提交
2649
#endif   /* USE_SSL */
T
Tom Lane 已提交
2650

2651
	{
2652
		{"application_name", PGC_USERSET, LOGGING_WHAT,
B
Bruce Momjian 已提交
2653 2654 2655
			gettext_noop("Sets the application name to be reported in statistics and logs."),
			NULL,
			GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE
2656 2657 2658 2659 2660
		},
		&application_name,
		"", assign_application_name, NULL
	},

2661
	/* End-of-list marker */
2662
	{
2663
		{NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL
2664
	}
2665 2666 2667
};


2668 2669
static struct config_enum ConfigureNamesEnum[] =
{
2670 2671 2672
	{
		{"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
			gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
2673
			NULL
2674 2675 2676 2677 2678
		},
		&backslash_quote,
		BACKSLASH_QUOTE_SAFE_ENCODING, backslash_quote_options, NULL, NULL
	},

2679 2680 2681 2682 2683 2684 2685 2686 2687
	{
		{"bytea_output", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets the output format for bytea."),
			NULL
		},
		&bytea_output,
		BYTEA_OUTPUT_HEX, bytea_output_options, NULL, NULL
	},

2688 2689 2690
	{
		{"client_min_messages", PGC_USERSET, LOGGING_WHEN,
			gettext_noop("Sets the message levels that are sent to the client."),
2691 2692
			gettext_noop("Each level includes all the levels that follow it. The later"
						 " the level, the fewer messages are sent.")
2693 2694
		},
		&client_min_messages,
2695
		NOTICE, client_message_level_options, NULL, NULL
2696 2697
	},

2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
	{
		{"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
			gettext_noop("Enables the planner to use constraints to optimize queries."),
			gettext_noop("Table scans will be skipped if their constraints"
						 " guarantee that no rows match the query.")
		},
		&constraint_exclusion,
		CONSTRAINT_EXCLUSION_PARTITION, constraint_exclusion_options,
		NULL, NULL
	},

2709 2710 2711
	{
		{"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets the transaction isolation level of each new transaction."),
2712
			NULL
2713 2714 2715 2716 2717
		},
		&DefaultXactIsoLevel,
		XACT_READ_COMMITTED, isolation_level_options, NULL, NULL
	},

2718
	{
2719 2720 2721 2722 2723 2724 2725 2726 2727
		{"IntervalStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
			gettext_noop("Sets the display format for interval values."),
			NULL,
			GUC_REPORT
		},
		&IntervalStyle,
		INTSTYLE_POSTGRES, intervalstyle_options, NULL, NULL
	},

2728
	{
2729
		{"log_error_verbosity", PGC_SUSET, LOGGING_WHAT,
2730
			gettext_noop("Sets the verbosity of logged messages."),
2731
			NULL
2732 2733 2734 2735 2736 2737 2738 2739
		},
		&Log_error_verbosity,
		PGERROR_DEFAULT, log_error_verbosity_options, NULL, NULL
	},

	{
		{"log_min_messages", PGC_SUSET, LOGGING_WHEN,
			gettext_noop("Sets the message levels that are logged."),
2740 2741
			gettext_noop("Each level includes all the levels that follow it. The later"
						 " the level, the fewer messages are sent.")
2742 2743
		},
		&log_min_messages,
2744
		WARNING, server_message_level_options, NULL, NULL
2745 2746 2747 2748 2749
	},

	{
		{"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
			gettext_noop("Causes all statements generating error at or above this level to be logged."),
2750 2751
			gettext_noop("Each level includes all the levels that follow it. The later"
						 " the level, the fewer messages are sent.")
2752 2753
		},
		&log_min_error_statement,
2754
		ERROR, server_message_level_options, NULL, NULL
2755 2756 2757 2758 2759
	},

	{
		{"log_statement", PGC_SUSET, LOGGING_WHAT,
			gettext_noop("Sets the type of statements logged."),
2760
			NULL
2761 2762 2763 2764 2765
		},
		&log_statement,
		LOGSTMT_NONE, log_statement_options, NULL, NULL
	},

2766 2767 2768 2769
#ifdef HAVE_SYSLOG
	{
		{"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
			gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
2770
			NULL
2771 2772 2773 2774 2775 2776
		},
		&syslog_facility,
		LOG_LOCAL0, syslog_facility_options, assign_syslog_facility, NULL
	},
#endif

2777 2778 2779
	{
		{"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
2780
			NULL
2781 2782 2783 2784 2785
		},
		&SessionReplicationRole,
		SESSION_REPLICATION_ROLE_ORIGIN, session_replication_role_options,
		assign_session_replication_role, NULL
	},
2786

2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
	{
		{"trace_recovery_messages", PGC_SUSET, LOGGING_WHEN,
			gettext_noop("Sets the message levels that are logged during recovery."),
			gettext_noop("Each level includes all the levels that follow it. The later"
						 " the level, the fewer messages are sent.")
		},
		&trace_recovery_messages,
		DEBUG1, server_message_level_options, NULL, NULL
	},

2797 2798 2799
	{
		{"track_functions", PGC_SUSET, STATS_COLLECTOR,
			gettext_noop("Collects function-level statistics on database activity."),
2800
			NULL
2801 2802 2803 2804 2805
		},
		&pgstat_track_functions,
		TRACK_FUNC_OFF, track_function_options, NULL, NULL
	},

2806 2807 2808 2809 2810 2811 2812 2813 2814
	{
		{"wal_level", PGC_POSTMASTER, WAL_SETTINGS,
			gettext_noop("Set the level of information written to the WAL."),
			NULL
		},
		&wal_level,
		WAL_LEVEL_MINIMAL, wal_level_options, NULL
	},

2815 2816 2817 2818 2819 2820
	{
		{"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
			gettext_noop("Selects the method used for forcing WAL updates to disk."),
			NULL
		},
		&sync_method,
2821
		DEFAULT_SYNC_METHOD, sync_method_options,
2822 2823 2824
		assign_xlog_sync_method, NULL
	},

2825 2826 2827
	{
		{"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets how binary values are to be encoded in XML."),
2828
			NULL
2829 2830 2831 2832 2833 2834 2835 2836 2837
		},
		&xmlbinary,
		XMLBINARY_BASE64, xmlbinary_options, NULL, NULL
	},

	{
		{"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
			gettext_noop("Sets whether XML data in implicit parsing and serialization "
						 "operations is to be considered as documents or content fragments."),
2838
			NULL
2839 2840 2841 2842 2843
		},
		&xmloption,
		XMLOPTION_CONTENT, xmloption_options, NULL, NULL
	},

2844 2845 2846 2847 2848 2849 2850

	/* End-of-list marker */
	{
		{NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL
	}
};

2851
/******** end of options list ********/
2852

B
Bruce Momjian 已提交
2853

2854 2855 2856 2857 2858 2859
/*
 * To allow continued support of obsolete names for GUC variables, we apply
 * the following mappings to any unrecognized name.  Note that an old name
 * should be mapped to a new one only if the new variable has very similar
 * semantics to the old.
 */
B
Bruce Momjian 已提交
2860
static const char *const map_old_guc_names[] = {
2861 2862 2863 2864 2865 2866
	"sort_mem", "work_mem",
	"vacuum_mem", "maintenance_work_mem",
	NULL
};


2867
/*
2868
 * Actual lookup of variables is done through this single, sorted array.
2869
 */
2870 2871
static struct config_generic **guc_variables;

2872
/* Current number of variables contained in the vector */
B
Bruce Momjian 已提交
2873
static int	num_guc_variables;
2874

2875
/* Vector capacity */
B
Bruce Momjian 已提交
2876
static int	size_guc_variables;
2877

2878

2879
static bool guc_dirty;			/* TRUE if need to do commit/abort work */
2880

2881 2882
static bool reporting_enabled;	/* TRUE to enable GUC_REPORT */

2883 2884
static int	GUCNestLevel = 0;	/* 1 when in main transaction */

2885

B
Bruce Momjian 已提交
2886
static int	guc_var_compare(const void *a, const void *b);
2887
static int	guc_name_compare(const char *namea, const char *nameb);
2888
static void InitializeOneGUCOption(struct config_generic * gconf);
2889
static void push_old_value(struct config_generic * gconf, GucAction action);
2890
static void ReportGUCOption(struct config_generic * record);
2891 2892
static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
static void ShowAllGUCConfig(DestReceiver *dest);
2893
static char *_ShowOption(struct config_generic * record, bool use_units);
B
Bruce Momjian 已提交
2894
static bool is_newvalue_equal(struct config_generic * record, const char *newvalue);
2895 2896
static bool validate_option_array_item(const char *name, const char *value,
									   bool skipIfNoPermissions);
2897

2898

2899 2900 2901 2902 2903 2904
/*
 * Some infrastructure for checking malloc/strdup/realloc calls
 */
static void *
guc_malloc(int elevel, size_t size)
{
B
Bruce Momjian 已提交
2905
	void	   *data;
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917

	data = malloc(size);
	if (data == NULL)
		ereport(elevel,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));
	return data;
}

static void *
guc_realloc(int elevel, void *old, size_t size)
{
B
Bruce Momjian 已提交
2918
	void	   *data;
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930

	data = realloc(old, size);
	if (data == NULL)
		ereport(elevel,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));
	return data;
}

static char *
guc_strdup(int elevel, const char *src)
{
B
Bruce Momjian 已提交
2931
	char	   *data;
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941

	data = strdup(src);
	if (data == NULL)
		ereport(elevel,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));
	return data;
}


2942 2943 2944 2945 2946 2947
/*
 * Support for assigning to a field of a string GUC item.  Free the prior
 * value if it's not referenced anywhere else in the item (including stacked
 * states).
 */
static void
2948
set_string_field(struct config_string * conf, char **field, char *newval)
2949
{
B
Bruce Momjian 已提交
2950 2951
	char	   *oldval = *field;
	GucStack   *stack;
2952 2953 2954 2955 2956 2957 2958 2959

	/* Do the assignment */
	*field = newval;

	/* Exit if any duplicate references, or if old value was NULL anyway */
	if (oldval == NULL ||
		oldval == *(conf->variable) ||
		oldval == conf->reset_val ||
2960
		oldval == conf->boot_val)
2961 2962 2963
		return;
	for (stack = conf->gen.stack; stack; stack = stack->prev)
	{
2964 2965
		if (oldval == stack->prior.stringval ||
			oldval == stack->masked.stringval)
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
			return;
	}

	/* Not used anymore, so free it */
	free(oldval);
}

/*
 * Detect whether strval is referenced anywhere in a GUC string item
 */
static bool
B
Bruce Momjian 已提交
2977
string_field_used(struct config_string * conf, char *strval)
2978
{
B
Bruce Momjian 已提交
2979
	GucStack   *stack;
2980 2981 2982

	if (strval == *(conf->variable) ||
		strval == conf->reset_val ||
2983
		strval == conf->boot_val)
2984 2985 2986
		return true;
	for (stack = conf->gen.stack; stack; stack = stack->prev)
	{
2987 2988
		if (strval == stack->prior.stringval ||
			strval == stack->masked.stringval)
2989 2990 2991 2992 2993
			return true;
	}
	return false;
}

2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
/*
 * Support for copying a variable's active value into a stack entry
 */
static void
set_stack_value(struct config_generic * gconf, union config_var_value * val)
{
	switch (gconf->vartype)
	{
		case PGC_BOOL:
			val->boolval =
				*((struct config_bool *) gconf)->variable;
			break;
		case PGC_INT:
			val->intval =
				*((struct config_int *) gconf)->variable;
			break;
		case PGC_REAL:
			val->realval =
				*((struct config_real *) gconf)->variable;
			break;
		case PGC_STRING:
			/* we assume stringval is NULL if not valid */
			set_string_field((struct config_string *) gconf,
							 &(val->stringval),
							 *((struct config_string *) gconf)->variable);
			break;
3020
		case PGC_ENUM:
3021
			val->enumval =
3022 3023
				*((struct config_enum *) gconf)->variable;
			break;
3024 3025 3026 3027 3028 3029 3030
	}
}

/*
 * Support for discarding a no-longer-needed value in a stack entry
 */
static void
B
Bruce Momjian 已提交
3031
discard_stack_value(struct config_generic * gconf, union config_var_value * val)
3032 3033 3034 3035 3036 3037
{
	switch (gconf->vartype)
	{
		case PGC_BOOL:
		case PGC_INT:
		case PGC_REAL:
3038
		case PGC_ENUM:
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
			/* no need to do anything */
			break;
		case PGC_STRING:
			set_string_field((struct config_string *) gconf,
							 &(val->stringval),
							 NULL);
			break;
	}
}

3049

3050 3051 3052
/*
 * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
 */
3053 3054
struct config_generic **
get_guc_variables(void)
3055 3056 3057
{
	return guc_variables;
}
3058

3059

3060
/*
B
Bruce Momjian 已提交
3061
 * Build the sorted array.	This is split out so that it could be
3062 3063
 * re-executed after startup (eg, we could allow loadable modules to
 * add vars, and then we'd need to re-sort).
3064
 */
3065
void
3066
build_guc_variables(void)
3067
{
B
Bruce Momjian 已提交
3068
	int			size_vars;
3069 3070
	int			num_vars = 0;
	struct config_generic **guc_vars;
B
Bruce Momjian 已提交
3071
	int			i;
3072

3073
	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3074 3075 3076
	{
		struct config_bool *conf = &ConfigureNamesBool[i];

3077 3078 3079
		/* Rather than requiring vartype to be filled in by hand, do this: */
		conf->gen.vartype = PGC_BOOL;
		num_vars++;
3080
	}
3081

3082
	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3083 3084 3085
	{
		struct config_int *conf = &ConfigureNamesInt[i];

3086 3087
		conf->gen.vartype = PGC_INT;
		num_vars++;
3088
	}
3089

3090
	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3091 3092 3093
	{
		struct config_real *conf = &ConfigureNamesReal[i];

3094 3095
		conf->gen.vartype = PGC_REAL;
		num_vars++;
3096
	}
3097

3098
	for (i = 0; ConfigureNamesString[i].gen.name; i++)
3099
	{
3100
		struct config_string *conf = &ConfigureNamesString[i];
3101

3102 3103
		conf->gen.vartype = PGC_STRING;
		num_vars++;
3104 3105
	}

3106 3107 3108 3109 3110 3111 3112 3113
	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
	{
		struct config_enum *conf = &ConfigureNamesEnum[i];

		conf->gen.vartype = PGC_ENUM;
		num_vars++;
	}

B
Bruce Momjian 已提交
3114 3115
	/*
	 * Create table with 20% slack
3116 3117 3118
	 */
	size_vars = num_vars + num_vars / 4;

3119
	guc_vars = (struct config_generic **)
3120
		guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
3121

3122
	num_vars = 0;
3123

3124
	for (i = 0; ConfigureNamesBool[i].gen.name; i++)
B
Bruce Momjian 已提交
3125
		guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
3126

3127
	for (i = 0; ConfigureNamesInt[i].gen.name; i++)
B
Bruce Momjian 已提交
3128
		guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
3129

3130
	for (i = 0; ConfigureNamesReal[i].gen.name; i++)
B
Bruce Momjian 已提交
3131
		guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
3132

3133
	for (i = 0; ConfigureNamesString[i].gen.name; i++)
B
Bruce Momjian 已提交
3134
		guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
3135

3136 3137 3138
	for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
		guc_vars[num_vars++] = &ConfigureNamesEnum[i].gen;

3139 3140 3141 3142
	if (guc_variables)
		free(guc_variables);
	guc_variables = guc_vars;
	num_guc_variables = num_vars;
3143
	size_guc_variables = size_vars;
B
Bruce Momjian 已提交
3144 3145
	qsort((void *) guc_variables, num_guc_variables,
		  sizeof(struct config_generic *), guc_var_compare);
3146 3147
}

3148 3149 3150 3151
/*
 * Add a new GUC variable to the list of known variables. The
 * list is expanded if needed.
 */
3152
static bool
B
Bruce Momjian 已提交
3153
add_guc_variable(struct config_generic * var, int elevel)
3154
{
B
Bruce Momjian 已提交
3155
	if (num_guc_variables + 1 >= size_guc_variables)
3156
	{
B
Bruce Momjian 已提交
3157 3158
		/*
		 * Increase the vector by 25%
3159
		 */
B
Bruce Momjian 已提交
3160 3161
		int			size_vars = size_guc_variables + size_guc_variables / 4;
		struct config_generic **guc_vars;
3162

B
Bruce Momjian 已提交
3163
		if (size_vars == 0)
3164
		{
3165
			size_vars = 100;
B
Bruce Momjian 已提交
3166 3167
			guc_vars = (struct config_generic **)
				guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
3168 3169
		}
		else
3170
		{
B
Bruce Momjian 已提交
3171 3172
			guc_vars = (struct config_generic **)
				guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
3173 3174
		}

B
Bruce Momjian 已提交
3175
		if (guc_vars == NULL)
3176 3177
			return false;		/* out of memory */

3178 3179 3180 3181
		guc_variables = guc_vars;
		size_guc_variables = size_vars;
	}
	guc_variables[num_guc_variables++] = var;
B
Bruce Momjian 已提交
3182 3183
	qsort((void *) guc_variables, num_guc_variables,
		  sizeof(struct config_generic *), guc_var_compare);
3184
	return true;
3185 3186 3187
}

/*
3188
 * Create and add a placeholder variable. It's presumed to belong
3189 3190
 * to a valid custom variable class at this point.
 */
3191
static struct config_generic *
3192
add_placeholder_variable(const char *name, int elevel)
3193
{
B
Bruce Momjian 已提交
3194 3195 3196
	size_t		sz = sizeof(struct config_string) + sizeof(char *);
	struct config_string *var;
	struct config_generic *gen;
3197

B
Bruce Momjian 已提交
3198 3199
	var = (struct config_string *) guc_malloc(elevel, sz);
	if (var == NULL)
3200
		return NULL;
3201
	memset(var, 0, sz);
3202
	gen = &var->gen;
3203

3204 3205
	gen->name = guc_strdup(elevel, name);
	if (gen->name == NULL)
3206 3207 3208 3209 3210
	{
		free(var);
		return NULL;
	}

B
Bruce Momjian 已提交
3211 3212
	gen->context = PGC_USERSET;
	gen->group = CUSTOM_OPTIONS;
3213
	gen->short_desc = "GUC placeholder variable";
B
Bruce Momjian 已提交
3214 3215
	gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
	gen->vartype = PGC_STRING;
3216

B
Bruce Momjian 已提交
3217 3218
	/*
	 * The char* is allocated at the end of the struct since we have no
B
Bruce Momjian 已提交
3219 3220
	 * 'static' place to point to.	Note that the current value, as well as
	 * the boot and reset values, start out NULL.
B
Bruce Momjian 已提交
3221 3222
	 */
	var->variable = (char **) (var + 1);
3223

B
Bruce Momjian 已提交
3224
	if (!add_guc_variable((struct config_generic *) var, elevel))
3225 3226 3227 3228 3229 3230
	{
		free((void *) gen->name);
		free(var);
		return NULL;
	}

3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
	return gen;
}

/*
 * Detect whether the portion of "name" before dotPos matches any custom
 * variable class name listed in custom_var_classes.  The latter must be
 * formatted the way that assign_custom_variable_classes does it, ie,
 * no whitespace.  NULL is valid for custom_var_classes.
 */
static bool
is_custom_class(const char *name, int dotPos, const char *custom_var_classes)
{
	bool		result = false;
	const char *ccs = custom_var_classes;

	if (ccs != NULL)
	{
		const char *start = ccs;

		for (;; ++ccs)
		{
			char		c = *ccs;

			if (c == '\0' || c == ',')
			{
				if (dotPos == ccs - start && strncmp(start, name, dotPos) == 0)
				{
					result = true;
					break;
				}
				if (c == '\0')
					break;
				start = ccs + 1;
			}
		}
	}
	return result;
3268
}
3269 3270

/*
3271 3272 3273
 * Look up option NAME.  If it exists, return a pointer to its record,
 * else return NULL.  If create_placeholders is TRUE, we'll create a
 * placeholder record for a valid-looking custom variable name.
3274
 */
3275
static struct config_generic *
3276
find_option(const char *name, bool create_placeholders, int elevel)
3277
{
3278 3279
	const char **key = &name;
	struct config_generic **res;
3280
	int			i;
3281

3282
	Assert(name);
3283

3284
	/*
B
Bruce Momjian 已提交
3285 3286
	 * By equating const char ** with struct config_generic *, we are assuming
	 * the name field is first in config_generic.
3287
	 */
B
Bruce Momjian 已提交
3288 3289 3290
	res = (struct config_generic **) bsearch((void *) &key,
											 (void *) guc_variables,
											 num_guc_variables,
B
Bruce Momjian 已提交
3291
											 sizeof(struct config_generic *),
B
Bruce Momjian 已提交
3292
											 guc_var_compare);
3293 3294
	if (res)
		return *res;
3295 3296

	/*
B
Bruce Momjian 已提交
3297 3298 3299
	 * See if the name is an obsolete name for a variable.	We assume that the
	 * set of supported old names is short enough that a brute-force search is
	 * the best way.
3300 3301 3302 3303
	 */
	for (i = 0; map_old_guc_names[i] != NULL; i += 2)
	{
		if (guc_name_compare(name, map_old_guc_names[i]) == 0)
3304
			return find_option(map_old_guc_names[i + 1], false, elevel);
3305 3306
	}

3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
	if (create_placeholders)
	{
		/*
		 * Check if the name is qualified, and if so, check if the qualifier
		 * matches any custom variable class.  If so, add a placeholder.
		 */
		const char *dot = strchr(name, GUC_QUALIFIER_SEPARATOR);

		if (dot != NULL &&
			is_custom_class(name, dot - name, custom_variable_classes))
			return add_placeholder_variable(name, elevel);
	}
3319

3320
	/* Unknown name */
3321 3322
	return NULL;
}
3323 3324 3325


/*
3326
 * comparator for qsorting and bsearching guc_variables array
3327
 */
3328 3329
static int
guc_var_compare(const void *a, const void *b)
3330
{
3331 3332
	struct config_generic *confa = *(struct config_generic **) a;
	struct config_generic *confb = *(struct config_generic **) b;
3333

3334 3335 3336
	return guc_name_compare(confa->name, confb->name);
}

3337 3338 3339
/*
 * the bare comparison function for GUC names
 */
3340 3341 3342
static int
guc_name_compare(const char *namea, const char *nameb)
{
3343
	/*
B
Bruce Momjian 已提交
3344 3345 3346
	 * The temptation to use strcasecmp() here must be resisted, because the
	 * array ordering has to remain stable across setlocale() calls. So, build
	 * our own with a simple ASCII-only downcasing.
3347
	 */
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
	while (*namea && *nameb)
	{
		char		cha = *namea++;
		char		chb = *nameb++;

		if (cha >= 'A' && cha <= 'Z')
			cha += 'a' - 'A';
		if (chb >= 'A' && chb <= 'Z')
			chb += 'a' - 'A';
		if (cha != chb)
			return cha - chb;
3359
	}
3360 3361 3362 3363 3364
	if (*namea)
		return 1;				/* a is longer */
	if (*nameb)
		return -1;				/* b is longer */
	return 0;
3365
}
3366 3367 3368


/*
3369
 * Initialize GUC options during program startup.
3370 3371 3372
 *
 * Note that we cannot read the config file yet, since we have not yet
 * processed command-line switches.
3373
 */
3374 3375
void
InitializeGUCOptions(void)
3376
{
3377 3378
	int			i;
	char	   *env;
3379
	long		stack_rlimit;
3380

3381
	/*
B
Bruce Momjian 已提交
3382 3383
	 * Before log_line_prefix could possibly receive a nonempty setting, make
	 * sure that timezone processing is minimally alive (see elog.c).
3384 3385 3386
	 */
	pg_timezone_pre_initialize();

3387 3388 3389 3390
	/*
	 * Build sorted array of all GUC variables.
	 */
	build_guc_variables();
3391

3392
	/*
3393 3394
	 * Load all variables with their compiled-in defaults, and initialize
	 * status fields as needed.
3395
	 */
3396
	for (i = 0; i < num_guc_variables; i++)
3397
	{
3398
		InitializeOneGUCOption(guc_variables[i]);
3399 3400 3401 3402
	}

	guc_dirty = false;

3403 3404
	reporting_enabled = false;

3405
	/*
3406
	 * Prevent any attempt to override the transaction modes from
3407 3408
	 * non-interactive sources.
	 */
3409 3410 3411
	SetConfigOption("transaction_isolation", "default",
					PGC_POSTMASTER, PGC_S_OVERRIDE);
	SetConfigOption("transaction_read_only", "no",
3412 3413 3414
					PGC_POSTMASTER, PGC_S_OVERRIDE);

	/*
B
Bruce Momjian 已提交
3415
	 * For historical reasons, some GUC parameters can receive defaults from
B
Bruce Momjian 已提交
3416
	 * environment variables.  Process those settings.	NB: if you add or
3417
	 * remove anything here, see also ProcessConfigFile().
3418 3419 3420 3421 3422 3423
	 */

	env = getenv("PGPORT");
	if (env != NULL)
		SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);

3424 3425
	env = getenv("PGDATESTYLE");
	if (env != NULL)
3426 3427
		SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);

3428 3429
	env = getenv("PGCLIENTENCODING");
	if (env != NULL)
3430
		SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3431 3432 3433 3434 3435 3436 3437 3438 3439

	/*
	 * rlimit isn't exactly an "environment variable", but it behaves about
	 * the same.  If we can identify the platform stack depth rlimit, increase
	 * default stack depth setting up to whatever is safe (but at most 2MB).
	 */
	stack_rlimit = get_stack_depth_rlimit();
	if (stack_rlimit > 0)
	{
B
Bruce Momjian 已提交
3440
		int			new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
3441 3442 3443

		if (new_limit > 100)
		{
B
Bruce Momjian 已提交
3444
			char		limbuf[16];
3445 3446 3447 3448 3449 3450 3451

			new_limit = Min(new_limit, 2048);
			sprintf(limbuf, "%d", new_limit);
			SetConfigOption("max_stack_depth", limbuf,
							PGC_POSTMASTER, PGC_S_ENV_VAR);
		}
	}
3452 3453
}

3454 3455 3456 3457
/*
 * Initialize one GUC option variable to its compiled-in default.
 */
static void
3458
InitializeOneGUCOption(struct config_generic * gconf)
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
{
	gconf->status = 0;
	gconf->reset_source = PGC_S_DEFAULT;
	gconf->source = PGC_S_DEFAULT;
	gconf->stack = NULL;
	gconf->sourcefile = NULL;
	gconf->sourceline = 0;

	switch (gconf->vartype)
	{
		case PGC_BOOL:
			{
3471 3472 3473 3474 3475 3476 3477 3478
				struct config_bool *conf = (struct config_bool *) gconf;

				if (conf->assign_hook)
					if (!(*conf->assign_hook) (conf->boot_val, true,
											   PGC_S_DEFAULT))
						elog(FATAL, "failed to initialize %s to %d",
							 conf->gen.name, (int) conf->boot_val);
				*conf->variable = conf->reset_val = conf->boot_val;
3479 3480
				break;
			}
3481 3482 3483
		case PGC_INT:
			{
				struct config_int *conf = (struct config_int *) gconf;
3484

3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
				Assert(conf->boot_val >= conf->min);
				Assert(conf->boot_val <= conf->max);
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (conf->boot_val, true,
											   PGC_S_DEFAULT))
						elog(FATAL, "failed to initialize %s to %d",
							 conf->gen.name, conf->boot_val);
				*conf->variable = conf->reset_val = conf->boot_val;
				break;
			}
		case PGC_REAL:
			{
				struct config_real *conf = (struct config_real *) gconf;
3498

3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
				Assert(conf->boot_val >= conf->min);
				Assert(conf->boot_val <= conf->max);
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (conf->boot_val, true,
											   PGC_S_DEFAULT))
						elog(FATAL, "failed to initialize %s to %g",
							 conf->gen.name, conf->boot_val);
				*conf->variable = conf->reset_val = conf->boot_val;
				break;
			}
		case PGC_STRING:
3510
			{
3511 3512 3513 3514 3515
				struct config_string *conf = (struct config_string *) gconf;
				char	   *str;

				*conf->variable = NULL;
				conf->reset_val = NULL;
3516

3517
				if (conf->boot_val == NULL)
3518
				{
3519 3520
					/* leave the value NULL, do not call assign hook */
					break;
3521
				}
3522 3523 3524 3525 3526

				str = guc_strdup(FATAL, conf->boot_val);
				conf->reset_val = str;

				if (conf->assign_hook)
3527
				{
3528
					const char *newstr;
3529

3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
					newstr = (*conf->assign_hook) (str, true,
												   PGC_S_DEFAULT);
					if (newstr == NULL)
					{
						elog(FATAL, "failed to initialize %s to \"%s\"",
							 conf->gen.name, str);
					}
					else if (newstr != str)
					{
						free(str);

						/*
						 * See notes in set_config_option about casting
						 */
						str = (char *) newstr;
						conf->reset_val = str;
					}
3547
				}
3548 3549
				*conf->variable = str;
				break;
3550 3551
			}
		case PGC_ENUM:
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
			{
				struct config_enum *conf = (struct config_enum *) gconf;

				if (conf->assign_hook)
					if (!(*conf->assign_hook) (conf->boot_val, true,
											   PGC_S_DEFAULT))
						elog(FATAL, "failed to initialize %s to %s",
							 conf->gen.name,
						  config_enum_lookup_by_value(conf, conf->boot_val));
				*conf->variable = conf->reset_val = conf->boot_val;
				break;
			}
3564 3565 3566
	}
}

3567

3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
/*
 * Select the configuration files and data directory to be used, and
 * do the initial read of postgresql.conf.
 *
 * This is called after processing command-line switches.
 *		userDoption is the -D switch value if any (NULL if unspecified).
 *		progname is just for use in error messages.
 *
 * Returns true on success; on failure, prints a suitable error message
 * to stderr and returns false.
 */
bool
SelectConfigFiles(const char *userDoption, const char *progname)
{
3582 3583
	char	   *configdir;
	char	   *fname;
3584 3585
	struct stat stat_buf;

3586 3587 3588 3589 3590
	/* configdir is -D option, or $PGDATA if no -D */
	if (userDoption)
		configdir = make_absolute_path(userDoption);
	else
		configdir = make_absolute_path(getenv("PGDATA"));
3591 3592

	/*
3593
	 * Find the configuration file: if config_file was specified on the
B
Bruce Momjian 已提交
3594 3595 3596
	 * command line, use it, else use configdir/postgresql.conf.  In any case
	 * ensure the result is an absolute path, so that it will be interpreted
	 * the same way by future backends.
3597
	 */
3598 3599
	if (ConfigFileName)
		fname = make_absolute_path(ConfigFileName);
3600 3601 3602 3603 3604 3605 3606
	else if (configdir)
	{
		fname = guc_malloc(FATAL,
						   strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
		sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
	}
	else
3607
	{
3608
		write_stderr("%s does not know where to find the server configuration file.\n"
P
Peter Eisentraut 已提交
3609
					 "You must specify the --config-file or -D invocation "
3610 3611 3612
					 "option or set the PGDATA environment variable.\n",
					 progname);
		return false;
3613 3614
	}

3615
	/*
B
Bruce Momjian 已提交
3616 3617
	 * Set the ConfigFileName GUC variable to its final value, ensuring that
	 * it can't be overridden later.
3618 3619 3620 3621 3622 3623 3624
	 */
	SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
	free(fname);

	/*
	 * Now read the config file for the first time.
	 */
3625 3626
	if (stat(ConfigFileName, &stat_buf) != 0)
	{
3627
		write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
3628 3629 3630 3631 3632 3633 3634
					 progname, ConfigFileName, strerror(errno));
		return false;
	}

	ProcessConfigFile(PGC_POSTMASTER);

	/*
3635 3636
	 * If the data_directory GUC variable has been set, use that as DataDir;
	 * otherwise use configdir if set; else punt.
3637
	 *
3638 3639
	 * Note: SetDataDir will copy and absolute-ize its argument, so we don't
	 * have to.
3640
	 */
3641 3642 3643 3644
	if (data_directory)
		SetDataDir(data_directory);
	else if (configdir)
		SetDataDir(configdir);
3645 3646 3647
	else
	{
		write_stderr("%s does not know where to find the database system data.\n"
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
					 "This can be specified as \"data_directory\" in \"%s\", "
					 "or by the -D invocation option, or by the "
					 "PGDATA environment variable.\n",
					 progname, ConfigFileName);
		return false;
	}

	/*
	 * Reflect the final DataDir value back into the data_directory GUC var.
	 * (If you are wondering why we don't just make them a single variable,
	 * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
B
Bruce Momjian 已提交
3659 3660 3661
	 * child backends specially.  XXX is that still true?  Given that we now
	 * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
	 * DataDir in advance.)
3662 3663 3664 3665 3666 3667 3668 3669
	 */
	SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);

	/*
	 * Figure out where pg_hba.conf is, and make sure the path is absolute.
	 */
	if (HbaFileName)
		fname = make_absolute_path(HbaFileName);
3670 3671 3672 3673 3674 3675 3676
	else if (configdir)
	{
		fname = guc_malloc(FATAL,
						   strlen(configdir) + strlen(HBA_FILENAME) + 2);
		sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
	}
	else
3677 3678 3679 3680 3681
	{
		write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
					 "This can be specified as \"hba_file\" in \"%s\", "
					 "or by the -D invocation option, or by the "
					 "PGDATA environment variable.\n",
3682 3683 3684
					 progname, ConfigFileName);
		return false;
	}
3685 3686
	SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
	free(fname);
3687 3688

	/*
3689
	 * Likewise for pg_ident.conf.
3690
	 */
3691 3692
	if (IdentFileName)
		fname = make_absolute_path(IdentFileName);
3693 3694 3695 3696 3697 3698 3699
	else if (configdir)
	{
		fname = guc_malloc(FATAL,
						   strlen(configdir) + strlen(IDENT_FILENAME) + 2);
		sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
	}
	else
3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
	{
		write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
					 "This can be specified as \"ident_file\" in \"%s\", "
					 "or by the -D invocation option, or by the "
					 "PGDATA environment variable.\n",
					 progname, ConfigFileName);
		return false;
	}
	SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
	free(fname);

	free(configdir);
3712 3713 3714 3715 3716

	return true;
}


3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729
/*
 * Reset all options to their saved default values (implements RESET ALL)
 */
void
ResetAllOptions(void)
{
	int			i;

	for (i = 0; i < num_guc_variables; i++)
	{
		struct config_generic *gconf = guc_variables[i];

		/* Don't reset non-SET-able values */
3730 3731
		if (gconf->context != PGC_SUSET &&
			gconf->context != PGC_USERSET)
3732 3733 3734 3735 3736 3737 3738 3739
			continue;
		/* Don't reset if special exclusion from RESET ALL */
		if (gconf->flags & GUC_NO_RESET_ALL)
			continue;
		/* No need to reset if wasn't SET */
		if (gconf->source <= PGC_S_OVERRIDE)
			continue;

3740
		/* Save old value to support transaction abort */
3741
		push_old_value(gconf, GUC_ACTION_SET);
3742

3743 3744 3745
		switch (gconf->vartype)
		{
			case PGC_BOOL:
B
Bruce Momjian 已提交
3746 3747
				{
					struct config_bool *conf = (struct config_bool *) gconf;
3748

B
Bruce Momjian 已提交
3749
					if (conf->assign_hook)
3750 3751
						if (!(*conf->assign_hook) (conf->reset_val, true,
												   PGC_S_SESSION))
3752 3753
							elog(ERROR, "failed to reset %s to %d",
								 conf->gen.name, (int) conf->reset_val);
B
Bruce Momjian 已提交
3754 3755 3756
					*conf->variable = conf->reset_val;
					break;
				}
3757
			case PGC_INT:
B
Bruce Momjian 已提交
3758 3759
				{
					struct config_int *conf = (struct config_int *) gconf;
3760

B
Bruce Momjian 已提交
3761
					if (conf->assign_hook)
3762 3763
						if (!(*conf->assign_hook) (conf->reset_val, true,
												   PGC_S_SESSION))
3764 3765
							elog(ERROR, "failed to reset %s to %d",
								 conf->gen.name, conf->reset_val);
B
Bruce Momjian 已提交
3766 3767 3768
					*conf->variable = conf->reset_val;
					break;
				}
3769 3770
			case PGC_REAL:
				{
B
Bruce Momjian 已提交
3771 3772 3773
					struct config_real *conf = (struct config_real *) gconf;

					if (conf->assign_hook)
3774 3775
						if (!(*conf->assign_hook) (conf->reset_val, true,
												   PGC_S_SESSION))
3776 3777
							elog(ERROR, "failed to reset %s to %g",
								 conf->gen.name, conf->reset_val);
B
Bruce Momjian 已提交
3778
					*conf->variable = conf->reset_val;
3779 3780
					break;
				}
B
Bruce Momjian 已提交
3781 3782 3783 3784
			case PGC_STRING:
				{
					struct config_string *conf = (struct config_string *) gconf;
					char	   *str;
3785

B
Bruce Momjian 已提交
3786 3787
					/* We need not strdup here */
					str = conf->reset_val;
3788

3789
					if (conf->assign_hook && str)
3790
					{
B
Bruce Momjian 已提交
3791 3792
						const char *newstr;

3793 3794
						newstr = (*conf->assign_hook) (str, true,
													   PGC_S_SESSION);
B
Bruce Momjian 已提交
3795
						if (newstr == NULL)
3796 3797
							elog(ERROR, "failed to reset %s to \"%s\"",
								 conf->gen.name, str);
B
Bruce Momjian 已提交
3798 3799 3800
						else if (newstr != str)
						{
							/*
B
Bruce Momjian 已提交
3801
							 * See notes in set_config_option about casting
B
Bruce Momjian 已提交
3802 3803 3804
							 */
							str = (char *) newstr;
						}
3805 3806
					}

3807
					set_string_field(conf, conf->variable, str);
B
Bruce Momjian 已提交
3808 3809
					break;
				}
3810 3811 3812 3813 3814 3815 3816
			case PGC_ENUM:
				{
					struct config_enum *conf = (struct config_enum *) gconf;

					if (conf->assign_hook)
						if (!(*conf->assign_hook) (conf->reset_val, true,
												   PGC_S_SESSION))
3817 3818 3819
							elog(ERROR, "failed to reset %s to %s",
								 conf->gen.name,
								 config_enum_lookup_by_value(conf, conf->reset_val));
3820 3821 3822
					*conf->variable = conf->reset_val;
					break;
				}
3823
		}
3824

3825 3826
		gconf->source = gconf->reset_source;

3827 3828
		if (gconf->flags & GUC_REPORT)
			ReportGUCOption(gconf);
3829 3830 3831 3832 3833
	}
}


/*
3834
 * push_old_value
3835
 *		Push previous state during transactional assignment to a GUC variable.
3836 3837
 */
static void
3838
push_old_value(struct config_generic * gconf, GucAction action)
3839 3840 3841
{
	GucStack   *stack;

3842
	/* If we're not inside a nest level, do nothing */
3843
	if (GUCNestLevel == 0)
3844 3845
		return;

3846 3847 3848
	/* Do we already have a stack entry of the current nest level? */
	stack = gconf->stack;
	if (stack && stack->nest_level >= GUCNestLevel)
3849
	{
3850 3851 3852
		/* Yes, so adjust its state if necessary */
		Assert(stack->nest_level == GUCNestLevel);
		switch (action)
3853
		{
3854 3855 3856 3857 3858 3859 3860 3861
			case GUC_ACTION_SET:
				/* SET overrides any prior action at same nest level */
				if (stack->state == GUC_SET_LOCAL)
				{
					/* must discard old masked value */
					discard_stack_value(gconf, &stack->masked);
				}
				stack->state = GUC_SET;
3862
				break;
3863 3864 3865 3866 3867 3868 3869 3870
			case GUC_ACTION_LOCAL:
				if (stack->state == GUC_SET)
				{
					/* SET followed by SET LOCAL, remember SET's value */
					set_stack_value(gconf, &stack->masked);
					stack->state = GUC_SET_LOCAL;
				}
				/* in all other cases, no change to stack entry */
3871
				break;
3872 3873 3874
			case GUC_ACTION_SAVE:
				/* Could only have a prior SAVE of same variable */
				Assert(stack->state == GUC_SAVE);
3875 3876
				break;
		}
3877 3878 3879
		Assert(guc_dirty);		/* must be set already */
		return;
	}
3880

3881 3882 3883 3884 3885 3886 3887
	/*
	 * Push a new stack entry
	 *
	 * We keep all the stack entries in TopTransactionContext for simplicity.
	 */
	stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
												sizeof(GucStack));
3888

3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
	stack->prev = gconf->stack;
	stack->nest_level = GUCNestLevel;
	switch (action)
	{
		case GUC_ACTION_SET:
			stack->state = GUC_SET;
			break;
		case GUC_ACTION_LOCAL:
			stack->state = GUC_LOCAL;
			break;
		case GUC_ACTION_SAVE:
			stack->state = GUC_SAVE;
			break;
3902
	}
3903 3904 3905 3906 3907 3908 3909
	stack->source = gconf->source;
	set_stack_value(gconf, &stack->prior);

	gconf->stack = stack;

	/* Ensure we remember to pop at end of xact */
	guc_dirty = true;
3910 3911
}

3912

3913
/*
3914
 * Do GUC processing at main transaction start.
3915 3916
 */
void
3917 3918 3919
AtStart_GUC(void)
{
	/*
B
Bruce Momjian 已提交
3920 3921 3922
	 * The nest level should be 0 between transactions; if it isn't, somebody
	 * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
	 * throw a warning but make no other effort to clean up.
3923 3924 3925 3926 3927 3928 3929 3930 3931
	 */
	if (GUCNestLevel != 0)
		elog(WARNING, "GUC nest level = %d at transaction start",
			 GUCNestLevel);
	GUCNestLevel = 1;
}

/*
 * Enter a new nesting level for GUC values.  This is called at subtransaction
B
Bruce Momjian 已提交
3932
 * start and when entering a function that has proconfig settings.	NOTE that
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949
 * we must not risk error here, else subtransaction start will be unhappy.
 */
int
NewGUCNestLevel(void)
{
	return ++GUCNestLevel;
}

/*
 * Do GUC processing at transaction or subtransaction commit or abort, or
 * when exiting a function that has proconfig settings.  (The name is thus
 * a bit of a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
 * During abort, we discard all GUC settings that were applied at nesting
 * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
 */
void
AtEOXact_GUC(bool isCommit, int nestLevel)
3950
{
3951
	bool		still_dirty;
3952 3953
	int			i;

3954 3955 3956 3957 3958 3959 3960 3961
	/*
	 * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
	 * abort, if there is a failure during transaction start before
	 * AtStart_GUC is called.
	 */
	Assert(nestLevel > 0 &&
		   (nestLevel <= GUCNestLevel ||
			(nestLevel == GUCNestLevel + 1 && !isCommit)));
3962

3963 3964
	/* Quick exit if nothing's changed in this transaction */
	if (!guc_dirty)
3965 3966
	{
		GUCNestLevel = nestLevel - 1;
3967
		return;
3968
	}
3969

3970
	still_dirty = false;
3971 3972 3973
	for (i = 0; i < num_guc_variables; i++)
	{
		struct config_generic *gconf = guc_variables[i];
3974
		GucStack   *stack;
3975

3976
		/*
B
Bruce Momjian 已提交
3977 3978 3979
		 * Process and pop each stack entry within the nest level.	To
		 * simplify fmgr_security_definer(), we allow failure exit from a
		 * function-with-SET-options to be recovered at the surrounding
3980 3981
		 * transaction or subtransaction abort; so there could be more than
		 * one stack entry to pop.
3982
		 */
3983 3984
		while ((stack = gconf->stack) != NULL &&
			   stack->nest_level >= nestLevel)
3985
		{
3986 3987 3988 3989
			GucStack   *prev = stack->prev;
			bool		restorePrior = false;
			bool		restoreMasked = false;
			bool		changed;
3990

3991 3992 3993 3994 3995 3996
			/*
			 * In this next bit, if we don't set either restorePrior or
			 * restoreMasked, we must "discard" any unwanted fields of the
			 * stack entries to avoid leaking memory.  If we do set one of
			 * those flags, unused fields will be cleaned up after restoring.
			 */
B
Bruce Momjian 已提交
3997
			if (!isCommit)		/* if abort, always restore prior value */
3998 3999 4000 4001 4002 4003 4004 4005 4006
				restorePrior = true;
			else if (stack->state == GUC_SAVE)
				restorePrior = true;
			else if (stack->nest_level == 1)
			{
				/* transaction commit */
				if (stack->state == GUC_SET_LOCAL)
					restoreMasked = true;
				else if (stack->state == GUC_SET)
4007
				{
4008 4009 4010
					/* we keep the current active value */
					discard_stack_value(gconf, &stack->prior);
				}
B
Bruce Momjian 已提交
4011
				else	/* must be GUC_LOCAL */
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023
					restorePrior = true;
			}
			else if (prev == NULL ||
					 prev->nest_level < stack->nest_level - 1)
			{
				/* decrement entry's level and do not pop it */
				stack->nest_level--;
				continue;
			}
			else
			{
				/*
B
Bruce Momjian 已提交
4024 4025
				 * We have to merge this stack entry into prev. See README for
				 * discussion of this bit.
4026 4027 4028 4029
				 */
				switch (stack->state)
				{
					case GUC_SAVE:
B
Bruce Momjian 已提交
4030
						Assert(false);	/* can't get here */
4031 4032 4033 4034 4035 4036 4037 4038

					case GUC_SET:
						/* next level always becomes SET */
						discard_stack_value(gconf, &stack->prior);
						if (prev->state == GUC_SET_LOCAL)
							discard_stack_value(gconf, &prev->masked);
						prev->state = GUC_SET;
						break;
4039

4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
					case GUC_LOCAL:
						if (prev->state == GUC_SET)
						{
							/* LOCAL migrates down */
							prev->masked = stack->prior;
							prev->state = GUC_SET_LOCAL;
						}
						else
						{
							/* else just forget this stack level */
							discard_stack_value(gconf, &stack->prior);
						}
						break;
B
Bruce Momjian 已提交
4053

4054 4055 4056 4057 4058 4059 4060 4061 4062
					case GUC_SET_LOCAL:
						/* prior state at this level no longer wanted */
						discard_stack_value(gconf, &stack->prior);
						/* copy down the masked state */
						if (prev->state == GUC_SET_LOCAL)
							discard_stack_value(gconf, &prev->masked);
						prev->masked = stack->masked;
						prev->state = GUC_SET_LOCAL;
						break;
4063
				}
4064
			}
4065

4066
			changed = false;
B
Bruce Momjian 已提交
4067

4068 4069 4070 4071 4072 4073 4074 4075 4076 4077
			if (restorePrior || restoreMasked)
			{
				/* Perform appropriate restoration of the stacked value */
				union config_var_value newvalue;
				GucSource	newsource;

				if (restoreMasked)
				{
					newvalue = stack->masked;
					newsource = PGC_S_SESSION;
4078
				}
4079
				else
4080
				{
4081 4082 4083
					newvalue = stack->prior;
					newsource = stack->source;
				}
4084

4085 4086 4087 4088
				switch (gconf->vartype)
				{
					case PGC_BOOL:
						{
B
Bruce Momjian 已提交
4089 4090 4091 4092 4093 4094 4095 4096
							struct config_bool *conf = (struct config_bool *) gconf;
							bool		newval = newvalue.boolval;

							if (*conf->variable != newval)
							{
								if (conf->assign_hook)
									if (!(*conf->assign_hook) (newval,
													   true, PGC_S_OVERRIDE))
4097 4098
										elog(LOG, "failed to commit %s as %d",
											 conf->gen.name, (int) newval);
B
Bruce Momjian 已提交
4099 4100 4101 4102
								*conf->variable = newval;
								changed = true;
							}
							break;
4103 4104 4105
						}
					case PGC_INT:
						{
B
Bruce Momjian 已提交
4106 4107 4108 4109 4110 4111 4112 4113
							struct config_int *conf = (struct config_int *) gconf;
							int			newval = newvalue.intval;

							if (*conf->variable != newval)
							{
								if (conf->assign_hook)
									if (!(*conf->assign_hook) (newval,
													   true, PGC_S_OVERRIDE))
4114 4115
										elog(LOG, "failed to commit %s as %d",
											 conf->gen.name, newval);
B
Bruce Momjian 已提交
4116 4117 4118 4119
								*conf->variable = newval;
								changed = true;
							}
							break;
4120 4121 4122
						}
					case PGC_REAL:
						{
B
Bruce Momjian 已提交
4123 4124 4125 4126 4127 4128 4129 4130
							struct config_real *conf = (struct config_real *) gconf;
							double		newval = newvalue.realval;

							if (*conf->variable != newval)
							{
								if (conf->assign_hook)
									if (!(*conf->assign_hook) (newval,
													   true, PGC_S_OVERRIDE))
4131 4132
										elog(LOG, "failed to commit %s as %g",
											 conf->gen.name, newval);
B
Bruce Momjian 已提交
4133 4134 4135 4136
								*conf->variable = newval;
								changed = true;
							}
							break;
4137 4138
						}
					case PGC_STRING:
4139
						{
B
Bruce Momjian 已提交
4140 4141 4142 4143
							struct config_string *conf = (struct config_string *) gconf;
							char	   *newval = newvalue.stringval;

							if (*conf->variable != newval)
B
Bruce Momjian 已提交
4144
							{
B
Bruce Momjian 已提交
4145
								if (conf->assign_hook && newval)
4146
								{
B
Bruce Momjian 已提交
4147 4148 4149 4150 4151
									const char *newstr;

									newstr = (*conf->assign_hook) (newval, true,
															 PGC_S_OVERRIDE);
									if (newstr == NULL)
4152 4153
										elog(LOG, "failed to commit %s as \"%s\"",
											 conf->gen.name, newval);
B
Bruce Momjian 已提交
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164
									else if (newstr != newval)
									{
										/*
										 * If newval should now be freed,
										 * it'll be taken care of below.
										 *
										 * See notes in set_config_option
										 * about casting
										 */
										newval = (char *) newstr;
									}
4165
								}
B
Bruce Momjian 已提交
4166 4167 4168

								set_string_field(conf, conf->variable, newval);
								changed = true;
B
Bruce Momjian 已提交
4169
							}
4170

B
Bruce Momjian 已提交
4171 4172 4173 4174 4175 4176 4177 4178 4179
							/*
							 * Release stacked values if not used anymore. We
							 * could use discard_stack_value() here, but since
							 * we have type-specific code anyway, might as
							 * well inline it.
							 */
							set_string_field(conf, &stack->prior.stringval, NULL);
							set_string_field(conf, &stack->masked.stringval, NULL);
							break;
4180
						}
4181 4182 4183
					case PGC_ENUM:
						{
							struct config_enum *conf = (struct config_enum *) gconf;
4184
							int			newval = newvalue.enumval;
4185 4186 4187 4188 4189

							if (*conf->variable != newval)
							{
								if (conf->assign_hook)
									if (!(*conf->assign_hook) (newval,
4190
													   true, PGC_S_OVERRIDE))
4191 4192 4193
										elog(LOG, "failed to commit %s as %s",
											 conf->gen.name,
											 config_enum_lookup_by_value(conf, newval));
4194 4195 4196 4197 4198
								*conf->variable = newval;
								changed = true;
							}
							break;
						}
4199
				}
4200

4201 4202
				gconf->source = newsource;
			}
4203

4204 4205 4206
			/* Finish popping the state stack */
			gconf->stack = prev;
			pfree(stack);
4207

4208 4209 4210
			/* Report new value if we changed it */
			if (changed && (gconf->flags & GUC_REPORT))
				ReportGUCOption(gconf);
B
Bruce Momjian 已提交
4211
		}						/* end of stack-popping loop */
4212 4213 4214

		if (stack != NULL)
			still_dirty = true;
4215 4216
	}

4217 4218
	/* If there are no remaining stack entries, we can reset guc_dirty */
	guc_dirty = still_dirty;
4219 4220 4221

	/* Update nesting level */
	GUCNestLevel = nestLevel - 1;
4222 4223 4224
}


4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
/*
 * Start up automatic reporting of changes to variables marked GUC_REPORT.
 * This is executed at completion of backend startup.
 */
void
BeginReportingGUCOptions(void)
{
	int			i;

	/*
B
Bruce Momjian 已提交
4235 4236
	 * Don't do anything unless talking to an interactive frontend of protocol
	 * 3.0 or later.
4237
	 */
4238
	if (whereToSendOutput != DestRemote ||
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
		PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
		return;

	reporting_enabled = true;

	/* Transmit initial values of interesting variables */
	for (i = 0; i < num_guc_variables; i++)
	{
		struct config_generic *conf = guc_variables[i];

		if (conf->flags & GUC_REPORT)
			ReportGUCOption(conf);
	}
}

/*
 * ReportGUCOption: if appropriate, transmit option value to frontend
 */
static void
4258
ReportGUCOption(struct config_generic * record)
4259 4260 4261
{
	if (reporting_enabled && (record->flags & GUC_REPORT))
	{
4262
		char	   *val = _ShowOption(record, false);
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
		StringInfoData msgbuf;

		pq_beginmessage(&msgbuf, 'S');
		pq_sendstring(&msgbuf, record->name);
		pq_sendstring(&msgbuf, val);
		pq_endmessage(&msgbuf);

		pfree(val);
	}
}

4274 4275
/*
 * Try to parse value as an integer.  The accepted formats are the
4276 4277 4278 4279 4280 4281 4282
 * usual decimal, octal, or hexadecimal formats, optionally followed by
 * a unit name if "flags" indicates a unit is allowed.
 *
 * If the string parses okay, return true, else false.
 * If okay and result is not NULL, return the value in *result.
 * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
 *	HINT message, or NULL if no hint provided.
4283
 */
4284
bool
4285
parse_int(const char *value, int *result, int flags, const char **hintmsg)
4286
{
4287
	int64		val;
4288 4289
	char	   *endptr;

4290 4291 4292 4293 4294 4295 4296
	/* To suppress compiler warnings, always set output params */
	if (result)
		*result = 0;
	if (hintmsg)
		*hintmsg = NULL;

	/* We assume here that int64 is at least as wide as long */
4297 4298
	errno = 0;
	val = strtol(value, &endptr, 0);
4299

4300 4301 4302 4303
	if (endptr == value)
		return false;			/* no HINT for integer syntax error */

	if (errno == ERANGE || val != (int64) ((int32) val))
4304
	{
4305 4306 4307 4308
		if (hintmsg)
			*hintmsg = gettext_noop("Value exceeds integer range.");
		return false;
	}
4309

4310 4311 4312
	/* allow whitespace between integer and unit */
	while (isspace((unsigned char) *endptr))
		endptr++;
4313

4314 4315 4316 4317 4318 4319 4320 4321
	/* Handle possible unit */
	if (*endptr != '\0')
	{
		/*
		 * Note: the multiple-switch coding technique here is a bit tedious,
		 * but seems necessary to avoid intermediate-value overflows.
		 */
		if (flags & GUC_UNIT_MEMORY)
4322
		{
4323 4324 4325
			/* Set hint for use if no match or trailing garbage */
			if (hintmsg)
				*hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");
4326

4327 4328 4329 4330 4331
#if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
#error BLCKSZ must be between 1KB and 1MB
#endif
#if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
#error XLOG_BLCKSZ must be between 1KB and 1MB
4332 4333
#endif

4334
			if (strncmp(endptr, "kB", 2) == 0)
4335
			{
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377
				endptr += 2;
				switch (flags & GUC_UNIT_MEMORY)
				{
					case GUC_UNIT_BLOCKS:
						val /= (BLCKSZ / 1024);
						break;
					case GUC_UNIT_XBLOCKS:
						val /= (XLOG_BLCKSZ / 1024);
						break;
				}
			}
			else if (strncmp(endptr, "MB", 2) == 0)
			{
				endptr += 2;
				switch (flags & GUC_UNIT_MEMORY)
				{
					case GUC_UNIT_KB:
						val *= KB_PER_MB;
						break;
					case GUC_UNIT_BLOCKS:
						val *= KB_PER_MB / (BLCKSZ / 1024);
						break;
					case GUC_UNIT_XBLOCKS:
						val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
						break;
				}
			}
			else if (strncmp(endptr, "GB", 2) == 0)
			{
				endptr += 2;
				switch (flags & GUC_UNIT_MEMORY)
				{
					case GUC_UNIT_KB:
						val *= KB_PER_GB;
						break;
					case GUC_UNIT_BLOCKS:
						val *= KB_PER_GB / (BLCKSZ / 1024);
						break;
					case GUC_UNIT_XBLOCKS:
						val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
						break;
				}
4378 4379
			}
		}
4380 4381 4382 4383 4384
		else if (flags & GUC_UNIT_TIME)
		{
			/* Set hint for use if no match or trailing garbage */
			if (hintmsg)
				*hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
4385

4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457
			if (strncmp(endptr, "ms", 2) == 0)
			{
				endptr += 2;
				switch (flags & GUC_UNIT_TIME)
				{
					case GUC_UNIT_S:
						val /= MS_PER_S;
						break;
					case GUC_UNIT_MIN:
						val /= MS_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "s", 1) == 0)
			{
				endptr += 1;
				switch (flags & GUC_UNIT_TIME)
				{
					case GUC_UNIT_MS:
						val *= MS_PER_S;
						break;
					case GUC_UNIT_MIN:
						val /= S_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "min", 3) == 0)
			{
				endptr += 3;
				switch (flags & GUC_UNIT_TIME)
				{
					case GUC_UNIT_MS:
						val *= MS_PER_MIN;
						break;
					case GUC_UNIT_S:
						val *= S_PER_MIN;
						break;
				}
			}
			else if (strncmp(endptr, "h", 1) == 0)
			{
				endptr += 1;
				switch (flags & GUC_UNIT_TIME)
				{
					case GUC_UNIT_MS:
						val *= MS_PER_H;
						break;
					case GUC_UNIT_S:
						val *= S_PER_H;
						break;
					case GUC_UNIT_MIN:
						val *= MIN_PER_H;
						break;
				}
			}
			else if (strncmp(endptr, "d", 1) == 0)
			{
				endptr += 1;
				switch (flags & GUC_UNIT_TIME)
				{
					case GUC_UNIT_MS:
						val *= MS_PER_D;
						break;
					case GUC_UNIT_S:
						val *= S_PER_D;
						break;
					case GUC_UNIT_MIN:
						val *= MIN_PER_D;
						break;
				}
			}
		}
4458

4459 4460
		/* allow whitespace after unit */
		while (isspace((unsigned char) *endptr))
4461 4462
			endptr++;

4463 4464
		if (*endptr != '\0')
			return false;		/* appropriate hint, if any, already set */
4465

4466 4467
		/* Check for overflow due to units conversion */
		if (val != (int64) ((int32) val))
4468
		{
4469 4470 4471
			if (hintmsg)
				*hintmsg = gettext_noop("Value exceeds integer range.");
			return false;
4472
		}
4473 4474
	}

4475 4476 4477 4478 4479 4480 4481 4482
	if (result)
		*result = (int) val;
	return true;
}



/*
4483 4484 4485
 * Try to parse value as a floating point number in the usual format.
 * If the string parses okay, return true, else false.
 * If okay and result is not NULL, return the value in *result.
4486
 */
4487
bool
4488 4489 4490 4491 4492
parse_real(const char *value, double *result)
{
	double		val;
	char	   *endptr;

4493 4494 4495
	if (result)
		*result = 0;			/* suppress compiler warning */

4496 4497
	errno = 0;
	val = strtod(value, &endptr);
4498
	if (endptr == value || errno == ERANGE)
4499
		return false;
4500 4501 4502 4503 4504 4505 4506

	/* allow whitespace after number */
	while (isspace((unsigned char) *endptr))
		endptr++;
	if (*endptr != '\0')
		return false;

4507 4508 4509 4510 4511 4512
	if (result)
		*result = val;
	return true;
}


4513 4514 4515 4516 4517 4518 4519 4520
/*
 * Lookup the name for an enum option with the selected value.
 * Should only ever be called with known-valid values, so throws
 * an elog(ERROR) if the enum option is not found.
 *
 * The returned string is a pointer to static data and not
 * allocated for modification.
 */
4521
const char *
4522
config_enum_lookup_by_value(struct config_enum * record, int val)
4523
{
A
Alvaro Herrera 已提交
4524 4525 4526
	const struct config_enum_entry *entry;

	for (entry = record->options; entry && entry->name; entry++)
4527 4528 4529 4530
	{
		if (entry->val == val)
			return entry->name;
	}
A
Alvaro Herrera 已提交
4531

4532 4533
	elog(ERROR, "could not find enum option %d for %s",
		 val, record->gen.name);
4534
	return NULL;				/* silence compiler */
4535 4536 4537 4538 4539 4540 4541
}


/*
 * Lookup the value for an enum option with the selected name
 * (case-insensitive).
 * If the enum option is found, sets the retval value and returns
4542
 * true. If it's not found, return FALSE and retval is set to 0.
4543
 */
4544
bool
4545
config_enum_lookup_by_name(struct config_enum * record, const char *value,
A
Alvaro Herrera 已提交
4546
						   int *retval)
4547
{
A
Alvaro Herrera 已提交
4548 4549 4550
	const struct config_enum_entry *entry;

	for (entry = record->options; entry && entry->name; entry++)
4551
	{
4552
		if (pg_strcasecmp(value, entry->name) == 0)
4553 4554 4555 4556 4557
		{
			*retval = entry->val;
			return TRUE;
		}
	}
A
Alvaro Herrera 已提交
4558 4559

	*retval = 0;
4560 4561 4562 4563 4564
	return FALSE;
}


/*
4565
 * Return a list of all available options for an enum, excluding
A
Alvaro Herrera 已提交
4566
 * hidden ones, separated by the given separator.
4567 4568
 * If prefix is non-NULL, it is added before the first enum value.
 * If suffix is non-NULL, it is added to the end of the string.
4569 4570
 */
static char *
4571
config_enum_get_options(struct config_enum * record, const char *prefix,
4572
						const char *suffix, const char *separator)
4573
{
A
Alvaro Herrera 已提交
4574
	const struct config_enum_entry *entry;
4575
	StringInfoData retstr;
A
Alvaro Herrera 已提交
4576
	int			seplen;
4577

A
Alvaro Herrera 已提交
4578 4579
	initStringInfo(&retstr);
	appendStringInfoString(&retstr, prefix);
4580

A
Alvaro Herrera 已提交
4581 4582
	seplen = strlen(separator);
	for (entry = record->options; entry && entry->name; entry++)
4583
	{
4584 4585
		if (!entry->hidden)
		{
A
Alvaro Herrera 已提交
4586 4587
			appendStringInfoString(&retstr, entry->name);
			appendBinaryStringInfo(&retstr, separator, seplen);
4588
		}
4589 4590
	}

4591
	/*
4592 4593 4594 4595 4596
	 * All the entries may have been hidden, leaving the string empty if no
	 * prefix was given. This indicates a broken GUC setup, since there is no
	 * use for an enum without any values, so we just check to make sure we
	 * don't write to invalid memory instead of actually trying to do
	 * something smart with it.
4597
	 */
A
Alvaro Herrera 已提交
4598 4599
	if (retstr.len >= seplen)
	{
4600
		/* Replace final separator */
A
Alvaro Herrera 已提交
4601 4602 4603
		retstr.data[retstr.len - seplen] = '\0';
		retstr.len -= seplen;
	}
4604

A
Alvaro Herrera 已提交
4605
	appendStringInfoString(&retstr, suffix);
4606

A
Alvaro Herrera 已提交
4607
	return retstr.data;
4608 4609
}

4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636
/*
 * Call a GucStringAssignHook function, being careful to free the
 * "newval" string if the hook ereports.
 *
 * This is split out of set_config_option just to avoid the "volatile"
 * qualifiers that would otherwise have to be plastered all over.
 */
static const char *
call_string_assign_hook(GucStringAssignHook assign_hook,
						char *newval, bool doit, GucSource source)
{
	const char *result;

	PG_TRY();
	{
		result = (*assign_hook) (newval, doit, source);
	}
	PG_CATCH();
	{
		free(newval);
		PG_RE_THROW();
	}
	PG_END_TRY();

	return result;
}

4637

4638
/*
4639 4640 4641 4642 4643 4644
 * Sets option `name' to given value. The value should be a string
 * which is going to be parsed and converted to the appropriate data
 * type.  The context and source parameters indicate in which context this
 * function is being called so it can apply the access restrictions
 * properly.
 *
4645 4646 4647 4648 4649 4650 4651
 * If value is NULL, set the option to its default value (normally the
 * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
 *
 * action indicates whether to set the value globally in the session, locally
 * to the current top transaction, or just for the duration of a function call.
 *
 * If changeVal is false then don't really set the option but do all
4652 4653 4654 4655 4656
 * the checks to see if it would work.
 *
 * If there is an error (non-existing option, invalid value) then an
 * ereport(ERROR) is thrown *unless* this is called in a context where we
 * don't want to ereport (currently, startup or SIGHUP config file reread).
4657
 * In that case we write a suitable error message via ereport(LOG) and
4658 4659 4660 4661 4662 4663
 * return false. This is working around the deficiencies in the ereport
 * mechanism, so don't blame me.  In all other cases, the function
 * returns true, including cases where the input is valid but we chose
 * not to apply it because of context or source-priority considerations.
 *
 * See also SetConfigOption for an external interface.
4664
 */
4665 4666 4667
bool
set_config_option(const char *name, const char *value,
				  GucContext context, GucSource source,
4668
				  GucAction action, bool changeVal)
4669
{
4670 4671 4672
	struct config_generic *record;
	int			elevel;
	bool		makeDefault;
4673

4674 4675 4676 4677 4678 4679
	if (context == PGC_SIGHUP || source == PGC_S_DEFAULT)
	{
		/*
		 * To avoid cluttering the log, only the postmaster bleats loudly
		 * about problems with the config file.
		 */
4680
		elevel = IsUnderPostmaster ? DEBUG3 : LOG;
4681
	}
4682 4683
	else if (source == PGC_S_DATABASE || source == PGC_S_USER ||
			 source == PGC_S_DATABASE_USER)
4684
		elevel = WARNING;
4685 4686
	else
		elevel = ERROR;
4687

4688
	record = find_option(name, true, elevel);
4689 4690 4691 4692 4693 4694
	if (record == NULL)
	{
		ereport(elevel,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
			   errmsg("unrecognized configuration parameter \"%s\"", name)));
		return false;
4695 4696
	}

4697
	/*
B
Bruce Momjian 已提交
4698 4699 4700 4701
	 * If source is postgresql.conf, mark the found record with
	 * GUC_IS_IN_FILE. This is for the convenience of ProcessConfigFile.  Note
	 * that we do it even if changeVal is false, since ProcessConfigFile wants
	 * the marking to occur during its testing pass.
4702
	 */
4703 4704
	if (source == PGC_S_FILE)
		record->status |= GUC_IS_IN_FILE;
4705

4706 4707 4708 4709 4710
	/*
	 * Check if the option can be set at this time. See guc.h for the precise
	 * rules. Note that we don't want to throw errors if we're in the SIGHUP
	 * context. In that case we just ignore the attempt and return true.
	 */
4711 4712
	switch (record->context)
	{
4713
		case PGC_INTERNAL:
4714 4715
			if (context == PGC_SIGHUP)
				return true;
4716 4717
			if (context != PGC_INTERNAL)
			{
4718 4719
				ereport(elevel,
						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4720
						 errmsg("parameter \"%s\" cannot be changed",
4721
								name)));
4722 4723 4724
				return false;
			}
			break;
4725 4726
		case PGC_POSTMASTER:
			if (context == PGC_SIGHUP)
4727
			{
4728 4729 4730
				/*
				 * We are reading a PGC_POSTMASTER var from postgresql.conf.
				 * We can't change the setting, so give a warning if the DBA
B
Bruce Momjian 已提交
4731
				 * tries to change it.	(Throwing an error would be more
4732 4733
				 * consistent, but seems overly rigid.)
				 */
4734 4735 4736
				if (changeVal && !is_newvalue_equal(record, value))
					ereport(elevel,
							(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
B
Bruce Momjian 已提交
4737 4738
							 errmsg("parameter \"%s\" cannot be changed without restarting the server",
									name)));
4739 4740
				return true;
			}
4741 4742
			if (context != PGC_POSTMASTER)
			{
4743 4744
				ereport(elevel,
						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
B
Bruce Momjian 已提交
4745 4746
						 errmsg("parameter \"%s\" cannot be changed without restarting the server",
								name)));
4747 4748 4749 4750 4751 4752
				return false;
			}
			break;
		case PGC_SIGHUP:
			if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
			{
4753 4754
				ereport(elevel,
						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
4755
						 errmsg("parameter \"%s\" cannot be changed now",
4756
								name)));
4757 4758 4759 4760
				return false;
			}

			/*
B
Bruce Momjian 已提交
4761 4762 4763 4764
			 * Hmm, the idea of the SIGHUP context is "ought to be global, but
			 * can be changed after postmaster start". But there's nothing
			 * that prevents a crafty administrator from sending SIGHUP
			 * signals to individual backends only.
4765 4766 4767 4768 4769 4770
			 */
			break;
		case PGC_BACKEND:
			if (context == PGC_SIGHUP)
			{
				/*
B
Bruce Momjian 已提交
4771 4772 4773 4774 4775 4776
				 * If a PGC_BACKEND parameter is changed in the config file,
				 * we want to accept the new value in the postmaster (whence
				 * it will propagate to subsequently-started backends), but
				 * ignore it in existing backends.	This is a tad klugy, but
				 * necessary because we don't re-read the config file during
				 * backend start.
4777 4778
				 */
				if (IsUnderPostmaster)
4779
					return true;
4780
			}
4781 4782
			else if (context != PGC_POSTMASTER && context != PGC_BACKEND &&
					 source != PGC_S_CLIENT)
4783
			{
4784 4785
				ereport(elevel,
						(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
B
Bruce Momjian 已提交
4786
						 errmsg("parameter \"%s\" cannot be set after connection start",
4787
								name)));
4788 4789 4790 4791 4792 4793
				return false;
			}
			break;
		case PGC_SUSET:
			if (context == PGC_USERSET || context == PGC_BACKEND)
			{
4794 4795
				ereport(elevel,
						(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
4796
						 errmsg("permission denied to set parameter \"%s\"",
4797
								name)));
4798
				return false;
4799 4800 4801 4802 4803
			}
			break;
		case PGC_USERSET:
			/* always okay */
			break;
4804
	}
4805

4806
	/*
4807
	 * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
B
Bruce Momjian 已提交
4808 4809 4810
	 * security restriction context.  We can reject this regardless of the GUC
	 * context or source, mainly because sources that it might be reasonable
	 * to override for won't be seen while inside a function.
4811
	 *
4812
	 * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
4813
	 * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
4814
	 * An exception might be made if the reset value is assumed to be "safe".
4815 4816
	 *
	 * Note: this flag is currently used for "session_authorization" and
B
Bruce Momjian 已提交
4817
	 * "role".	We need to prohibit changing these inside a local userid
4818 4819
	 * context because when we exit it, GUC won't be notified, leaving things
	 * out of sync.  (This could be fixed by forcing a new GUC nesting level,
B
Bruce Momjian 已提交
4820 4821
	 * but that would change behavior in possibly-undesirable ways.)  Also, we
	 * prohibit changing these in a security-restricted operation because
4822
	 * otherwise RESET could be used to regain the session user's privileges.
4823
	 */
4824
	if (record->flags & GUC_NOT_WHILE_SEC_REST)
4825
	{
4826 4827 4828
		if (InLocalUserIdChange())
		{
			/*
B
Bruce Momjian 已提交
4829 4830
			 * Phrasing of this error message is historical, but it's the most
			 * common case.
4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845
			 */
			ereport(elevel,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("cannot set parameter \"%s\" within security-definer function",
							name)));
			return false;
		}
		if (InSecurityRestrictedOperation())
		{
			ereport(elevel,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("cannot set parameter \"%s\" within security-restricted operation",
							name)));
			return false;
		}
4846 4847
	}

4848
	/*
B
Bruce Momjian 已提交
4849 4850 4851 4852
	 * Should we set reset/stacked values?	(If so, the behavior is not
	 * transactional.)	This is done either when we get a default value from
	 * the database's/user's/client's default settings or when we reset a
	 * value to its default.
4853
	 */
4854 4855
	makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
		((value != NULL) || source == PGC_S_DEFAULT);
4856 4857

	/*
4858 4859 4860 4861 4862
	 * Ignore attempted set if overridden by previously processed setting.
	 * However, if changeVal is false then plow ahead anyway since we are
	 * trying to find out if the value is potentially good, not actually use
	 * it. Also keep going if makeDefault is true, since we may want to set
	 * the reset/stacked values even if we can't set the variable itself.
4863
	 */
4864
	if (record->source > source)
4865
	{
4866
		if (changeVal && !makeDefault)
4867
		{
4868
			elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
4869 4870 4871
				 name);
			return true;
		}
4872
		changeVal = false;
4873 4874
	}

4875
	/*
4876
	 * Evaluate value and set variable.
4877
	 */
4878
	switch (record->vartype)
4879 4880 4881
	{
		case PGC_BOOL:
			{
B
Bruce Momjian 已提交
4882
				struct config_bool *conf = (struct config_bool *) record;
4883
				bool		newval;
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895

				if (value)
				{
					if (!parse_bool(value, &newval))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						  errmsg("parameter \"%s\" requires a Boolean value",
								 name)));
						return false;
					}
				}
4896 4897
				else if (source == PGC_S_DEFAULT)
					newval = conf->boot_val;
4898 4899 4900 4901 4902 4903
				else
				{
					newval = conf->reset_val;
					source = conf->gen.reset_source;
				}

4904 4905 4906 4907
				/* Save old value to support transaction abort */
				if (changeVal && !makeDefault)
					push_old_value(&conf->gen, action);

4908 4909 4910 4911 4912 4913 4914 4915 4916
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (newval, changeVal, source))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("invalid value for parameter \"%s\": %d",
									name, (int) newval)));
						return false;
					}
4917

4918 4919 4920 4921 4922 4923
				if (changeVal)
				{
					*conf->variable = newval;
					conf->gen.source = source;
				}
				if (makeDefault)
4924
				{
4925 4926 4927
					GucStack   *stack;

					if (conf->gen.reset_source <= source)
4928
					{
4929 4930
						conf->reset_val = newval;
						conf->gen.reset_source = source;
4931
					}
4932
					for (stack = conf->gen.stack; stack; stack = stack->prev)
4933
					{
4934
						if (stack->source <= source)
4935
						{
4936 4937
							stack->prior.boolval = newval;
							stack->source = source;
4938 4939
						}
					}
4940
				}
B
Bruce Momjian 已提交
4941
				break;
4942
			}
4943 4944

		case PGC_INT:
4945
			{
B
Bruce Momjian 已提交
4946
				struct config_int *conf = (struct config_int *) record;
4947
				int			newval;
4948

4949 4950
				if (value)
				{
4951 4952 4953
					const char *hintmsg;

					if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
4954 4955 4956
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
4957 4958
						 errmsg("invalid value for parameter \"%s\": \"%s\"",
								name, value),
4959
								 hintmsg ? errhint("%s", _(hintmsg)) : 0));
4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970
						return false;
					}
					if (newval < conf->min || newval > conf->max)
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
								 errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
										newval, name, conf->min, conf->max)));
						return false;
					}
				}
4971 4972
				else if (source == PGC_S_DEFAULT)
					newval = conf->boot_val;
4973 4974 4975 4976 4977 4978
				else
				{
					newval = conf->reset_val;
					source = conf->gen.reset_source;
				}

4979 4980 4981 4982
				/* Save old value to support transaction abort */
				if (changeVal && !makeDefault)
					push_old_value(&conf->gen, action);

4983 4984 4985 4986 4987 4988 4989 4990 4991
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (newval, changeVal, source))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("invalid value for parameter \"%s\": %d",
									name, newval)));
						return false;
					}
4992

4993 4994 4995 4996 4997 4998
				if (changeVal)
				{
					*conf->variable = newval;
					conf->gen.source = source;
				}
				if (makeDefault)
4999
				{
5000 5001 5002
					GucStack   *stack;

					if (conf->gen.reset_source <= source)
5003
					{
5004 5005
						conf->reset_val = newval;
						conf->gen.reset_source = source;
5006
					}
5007
					for (stack = conf->gen.stack; stack; stack = stack->prev)
5008
					{
5009
						if (stack->source <= source)
5010
						{
5011 5012
							stack->prior.intval = newval;
							stack->source = source;
5013 5014
						}
					}
5015
				}
B
Bruce Momjian 已提交
5016
				break;
5017
			}
5018 5019

		case PGC_REAL:
5020
			{
B
Bruce Momjian 已提交
5021
				struct config_real *conf = (struct config_real *) record;
5022
				double		newval;
5023

5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042
				if (value)
				{
					if (!parse_real(value, &newval))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						  errmsg("parameter \"%s\" requires a numeric value",
								 name)));
						return false;
					}
					if (newval < conf->min || newval > conf->max)
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
								 errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
										newval, name, conf->min, conf->max)));
						return false;
					}
				}
5043 5044
				else if (source == PGC_S_DEFAULT)
					newval = conf->boot_val;
5045 5046 5047 5048 5049 5050
				else
				{
					newval = conf->reset_val;
					source = conf->gen.reset_source;
				}

5051 5052 5053 5054
				/* Save old value to support transaction abort */
				if (changeVal && !makeDefault)
					push_old_value(&conf->gen, action);

5055 5056 5057 5058 5059 5060 5061 5062 5063
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (newval, changeVal, source))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("invalid value for parameter \"%s\": %g",
									name, newval)));
						return false;
					}
5064

5065 5066 5067 5068 5069 5070
				if (changeVal)
				{
					*conf->variable = newval;
					conf->gen.source = source;
				}
				if (makeDefault)
5071
				{
5072 5073 5074
					GucStack   *stack;

					if (conf->gen.reset_source <= source)
5075
					{
5076 5077
						conf->reset_val = newval;
						conf->gen.reset_source = source;
5078
					}
5079
					for (stack = conf->gen.stack; stack; stack = stack->prev)
5080
					{
5081
						if (stack->source <= source)
5082
						{
5083 5084
							stack->prior.realval = newval;
							stack->source = source;
5085 5086
						}
					}
5087
				}
B
Bruce Momjian 已提交
5088
				break;
5089
			}
5090 5091 5092

		case PGC_STRING:
			{
B
Bruce Momjian 已提交
5093
				struct config_string *conf = (struct config_string *) record;
5094
				char	   *newval;
B
Bruce Momjian 已提交
5095

5096 5097 5098 5099 5100
				if (value)
				{
					newval = guc_strdup(elevel, value);
					if (newval == NULL)
						return false;
B
Bruce Momjian 已提交
5101

5102
					/*
B
Bruce Momjian 已提交
5103 5104
					 * The only sort of "parsing" check we need to do is apply
					 * truncation if GUC_IS_NAME.
5105 5106 5107 5108
					 */
					if (conf->gen.flags & GUC_IS_NAME)
						truncate_identifier(newval, strlen(newval), true);
				}
5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119
				else if (source == PGC_S_DEFAULT)
				{
					if (conf->boot_val == NULL)
						newval = NULL;
					else
					{
						newval = guc_strdup(elevel, conf->boot_val);
						if (newval == NULL)
							return false;
					}
				}
5120
				else
5121 5122 5123
				{
					/*
					 * We could possibly avoid strdup here, but easier to make
5124 5125
					 * this case work the same as the normal assignment case;
					 * note the possible free of newval below.
5126
					 */
5127 5128 5129 5130 5131 5132 5133 5134
					if (conf->reset_val == NULL)
						newval = NULL;
					else
					{
						newval = guc_strdup(elevel, conf->reset_val);
						if (newval == NULL)
							return false;
					}
5135 5136 5137
					source = conf->gen.reset_source;
				}

5138 5139 5140 5141
				/* Save old value to support transaction abort */
				if (changeVal && !makeDefault)
					push_old_value(&conf->gen, action);

5142
				if (conf->assign_hook && newval)
5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177
				{
					const char *hookresult;

					/*
					 * If the hook ereports, we have to make sure we free
					 * newval, else it will be a permanent memory leak.
					 */
					hookresult = call_string_assign_hook(conf->assign_hook,
														 newval,
														 changeVal,
														 source);
					if (hookresult == NULL)
					{
						free(newval);
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("invalid value for parameter \"%s\": \"%s\"",
								name, value ? value : "")));
						return false;
					}
					else if (hookresult != newval)
					{
						free(newval);

						/*
						 * Having to cast away const here is annoying, but the
						 * alternative is to declare assign_hooks as returning
						 * char*, which would mean they'd have to cast away
						 * const, or as both taking and returning char*, which
						 * doesn't seem attractive either --- we don't want
						 * them to scribble on the passed str.
						 */
						newval = (char *) hookresult;
					}
				}
5178

5179
				if (changeVal)
5180
				{
5181 5182 5183 5184 5185 5186 5187 5188
					set_string_field(conf, conf->variable, newval);
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GucStack   *stack;

					if (conf->gen.reset_source <= source)
5189
					{
5190 5191
						set_string_field(conf, &conf->reset_val, newval);
						conf->gen.reset_source = source;
5192
					}
5193
					for (stack = conf->gen.stack; stack; stack = stack->prev)
5194
					{
5195
						if (stack->source <= source)
5196
						{
5197 5198 5199
							set_string_field(conf, &stack->prior.stringval,
											 newval);
							stack->source = source;
5200
						}
B
Bruce Momjian 已提交
5201
					}
5202
				}
5203 5204
				/* Perhaps we didn't install newval anywhere */
				if (newval && !string_field_used(conf, newval))
5205
					free(newval);
B
Bruce Momjian 已提交
5206
				break;
5207
			}
5208 5209 5210 5211 5212 5213 5214
		case PGC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) record;
				int			newval;

				if (value)
				{
5215
					if (!config_enum_lookup_by_name(conf, value, &newval))
5216
					{
5217 5218 5219 5220
						char	   *hintmsg;

						hintmsg = config_enum_get_options(conf,
														"Available values: ",
A
Alvaro Herrera 已提交
5221
														  ".", ", ");
5222 5223 5224

						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5225 5226
						 errmsg("invalid value for parameter \"%s\": \"%s\"",
								name, value),
5227
								 hintmsg ? errhint("%s", _(hintmsg)) : 0));
5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241

						if (hintmsg)
							pfree(hintmsg);
						return false;
					}
				}
				else if (source == PGC_S_DEFAULT)
					newval = conf->boot_val;
				else
				{
					newval = conf->reset_val;
					source = conf->gen.reset_source;
				}

5242 5243 5244 5245
				/* Save old value to support transaction abort */
				if (changeVal && !makeDefault)
					push_old_value(&conf->gen, action);

5246 5247 5248 5249 5250
				if (conf->assign_hook)
					if (!(*conf->assign_hook) (newval, changeVal, source))
					{
						ereport(elevel,
								(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5251 5252 5253
						 errmsg("invalid value for parameter \"%s\": \"%s\"",
								name,
								config_enum_lookup_by_value(conf, newval))));
5254 5255 5256
						return false;
					}

5257
				if (changeVal)
5258
				{
5259 5260 5261 5262 5263 5264 5265 5266
					*conf->variable = newval;
					conf->gen.source = source;
				}
				if (makeDefault)
				{
					GucStack   *stack;

					if (conf->gen.reset_source <= source)
5267
					{
5268 5269
						conf->reset_val = newval;
						conf->gen.reset_source = source;
5270
					}
5271
					for (stack = conf->gen.stack; stack; stack = stack->prev)
5272
					{
5273
						if (stack->source <= source)
5274
						{
5275 5276
							stack->prior.enumval = newval;
							stack->source = source;
5277 5278 5279 5280 5281
						}
					}
				}
				break;
			}
5282
	}
5283

5284
	if (changeVal && (record->flags & GUC_REPORT))
5285
		ReportGUCOption(record);
5286

5287 5288 5289 5290
	return true;
}


5291 5292 5293 5294 5295 5296 5297 5298 5299 5300
/*
 * Set the fields for source file and line number the setting came from.
 */
static void
set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
{
	struct config_generic *record;
	int			elevel;

	/*
5301 5302
	 * To avoid cluttering the log, only the postmaster bleats loudly about
	 * problems with the config file.
5303 5304 5305 5306 5307 5308 5309 5310
	 */
	elevel = IsUnderPostmaster ? DEBUG3 : LOG;

	record = find_option(name, true, elevel);
	/* should not happen */
	if (record == NULL)
		elog(ERROR, "unrecognized configuration parameter \"%s\"", name);

5311
	sourcefile = guc_strdup(elevel, sourcefile);
5312 5313
	if (record->sourcefile)
		free(record->sourcefile);
5314
	record->sourcefile = sourcefile;
5315 5316 5317
	record->sourceline = sourceline;
}

5318 5319
/*
 * Set a config option to the given value. See also set_config_option,
B
Bruce Momjian 已提交
5320
 * this is just the wrapper to be called from outside GUC.	NB: this
5321
 * is used only for non-transactional operations.
5322 5323 5324
 *
 * Note: there is no support here for setting source file/line, as it
 * is currently not needed.
5325 5326
 */
void
5327
SetConfigOption(const char *name, const char *value,
5328
				GucContext context, GucSource source)
5329
{
5330 5331
	(void) set_config_option(name, value, context, source,
							 GUC_ACTION_SET, true);
5332 5333 5334 5335 5336
}



/*
5337
 * Fetch the current value of the option `name'. If the option doesn't exist,
5338
 * throw an ereport and don't return.
5339
 *
5340 5341 5342 5343
 * If restrict_superuser is true, we also enforce that only superusers can
 * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
 * in user-driven calls.
 *
5344 5345 5346 5347
 * The string is *not* allocated for modification and is really only
 * valid until the next call to configuration related functions.
 */
const char *
5348
GetConfigOption(const char *name, bool restrict_superuser)
5349
{
B
Bruce Momjian 已提交
5350
	struct config_generic *record;
5351 5352
	static char buffer[256];

5353
	record = find_option(name, false, ERROR);
5354
	if (record == NULL)
5355 5356
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
5357
			   errmsg("unrecognized configuration parameter \"%s\"", name)));
5358 5359 5360
	if (restrict_superuser &&
		(record->flags & GUC_SUPERUSER_ONLY) &&
		!superuser())
5361 5362 5363
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to examine \"%s\"", name)));
5364

5365
	switch (record->vartype)
5366 5367
	{
		case PGC_BOOL:
B
Bruce Momjian 已提交
5368
			return *((struct config_bool *) record)->variable ? "on" : "off";
5369

5370
		case PGC_INT:
5371 5372
			snprintf(buffer, sizeof(buffer), "%d",
					 *((struct config_int *) record)->variable);
5373 5374
			return buffer;

5375
		case PGC_REAL:
5376 5377
			snprintf(buffer, sizeof(buffer), "%g",
					 *((struct config_real *) record)->variable);
5378 5379 5380
			return buffer;

		case PGC_STRING:
B
Bruce Momjian 已提交
5381
			return *((struct config_string *) record)->variable;
5382 5383

		case PGC_ENUM:
5384
			return config_enum_lookup_by_value((struct config_enum *) record,
5385
								 *((struct config_enum *) record)->variable);
5386 5387 5388
	}
	return NULL;
}
5389

5390 5391
/*
 * Get the RESET value associated with the given option.
5392 5393 5394 5395
 *
 * Note: this is not re-entrant, due to use of static result buffer;
 * not to mention that a string variable could have its reset_val changed.
 * Beware of assuming the result value is good for very long.
5396 5397 5398
 */
const char *
GetConfigOptionResetString(const char *name)
5399
{
5400 5401
	struct config_generic *record;
	static char buffer[256];
5402

5403
	record = find_option(name, false, ERROR);
5404
	if (record == NULL)
5405 5406
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
5407
			   errmsg("unrecognized configuration parameter \"%s\"", name)));
5408 5409 5410 5411
	if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to examine \"%s\"", name)));
5412 5413

	switch (record->vartype)
5414 5415
	{
		case PGC_BOOL:
5416
			return ((struct config_bool *) record)->reset_val ? "on" : "off";
5417

5418
		case PGC_INT:
5419
			snprintf(buffer, sizeof(buffer), "%d",
5420 5421
					 ((struct config_int *) record)->reset_val);
			return buffer;
5422 5423

		case PGC_REAL:
5424
			snprintf(buffer, sizeof(buffer), "%g",
5425 5426
					 ((struct config_real *) record)->reset_val);
			return buffer;
5427 5428

		case PGC_STRING:
5429
			return ((struct config_string *) record)->reset_val;
5430 5431

		case PGC_ENUM:
5432
			return config_enum_lookup_by_value((struct config_enum *) record,
5433
								 ((struct config_enum *) record)->reset_val);
5434 5435 5436
	}
	return NULL;
}
5437

5438

5439 5440 5441 5442 5443 5444 5445 5446
/*
 * GUC_complaint_elevel
 *		Get the ereport error level to use in an assign_hook's error report.
 *
 * This should be used by assign hooks that want to emit a custom error
 * report (in addition to the generic "invalid value for option FOO" that
 * guc.c will provide).  Note that the result might be ERROR or a lower
 * level, so the caller must be prepared for control to return from ereport,
5447
 * or not.	If control does return, return false/NULL from the hook function.
5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464
 *
 * At some point it'd be nice to replace this with a mechanism that allows
 * the custom message to become the DETAIL line of guc.c's generic message.
 */
int
GUC_complaint_elevel(GucSource source)
{
	int			elevel;

	if (source == PGC_S_FILE)
	{
		/*
		 * To avoid cluttering the log, only the postmaster bleats loudly
		 * about problems with the config file.
		 */
		elevel = IsUnderPostmaster ? DEBUG3 : LOG;
	}
5465 5466 5467 5468
	else if (source == PGC_S_OVERRIDE)
	{
		/*
		 * If we're a postmaster child, this is probably "undo" during
5469 5470 5471
		 * transaction abort, so we don't want to clutter the log.  There's a
		 * small chance of a real problem with an OVERRIDE setting, though, so
		 * suppressing the message entirely wouldn't be desirable.
5472 5473 5474
		 */
		elevel = IsUnderPostmaster ? DEBUG5 : LOG;
	}
5475 5476 5477 5478 5479 5480 5481 5482 5483
	else if (source < PGC_S_INTERACTIVE)
		elevel = LOG;
	else
		elevel = ERROR;

	return elevel;
}


5484 5485 5486 5487 5488 5489 5490 5491
/*
 * flatten_set_variable_args
 *		Given a parsenode List as emitted by the grammar for SET,
 *		convert to the flat string representation used by GUC.
 *
 * We need to be told the name of the variable the args are for, because
 * the flattening rules vary (ugh).
 *
5492
 * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
5493 5494
 * a palloc'd string.
 */
5495
static char *
5496 5497 5498 5499 5500
flatten_set_variable_args(const char *name, List *args)
{
	struct config_generic *record;
	int			flags;
	StringInfoData buf;
5501
	ListCell   *l;
5502

5503
	/* Fast path if just DEFAULT */
5504 5505 5506
	if (args == NIL)
		return NULL;

5507 5508 5509 5510 5511 5512 5513 5514 5515
	/*
	 * Get flags for the variable; if it's not known, use default flags.
	 * (Caller might throw error later, but not our business to do so here.)
	 */
	record = find_option(name, false, WARNING);
	if (record)
		flags = record->flags;
	else
		flags = 0;
5516 5517 5518

	/* Complain if list input and non-list variable */
	if ((flags & GUC_LIST_INPUT) == 0 &&
5519
		list_length(args) != 1)
5520 5521 5522
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("SET %s takes only one argument", name)));
5523 5524 5525

	initStringInfo(&buf);

A
Alvaro Herrera 已提交
5526 5527
	/*
	 * Each list member may be a plain A_Const node, or an A_Const within a
5528 5529
	 * TypeCast; the latter case is supported only for ConstInterval arguments
	 * (for SET TIME ZONE).
A
Alvaro Herrera 已提交
5530
	 */
5531 5532
	foreach(l, args)
	{
5533
		Node	   *arg = (Node *) lfirst(l);
5534
		char	   *val;
5535
		TypeName   *typeName = NULL;
5536
		A_Const    *con;
5537

5538
		if (l != list_head(args))
5539 5540
			appendStringInfo(&buf, ", ");

A
Alvaro Herrera 已提交
5541 5542
		if (IsA(arg, TypeCast))
		{
5543
			TypeCast   *tc = (TypeCast *) arg;
A
Alvaro Herrera 已提交
5544 5545

			arg = tc->arg;
5546
			typeName = tc->typeName;
A
Alvaro Herrera 已提交
5547 5548
		}

5549
		if (!IsA(arg, A_Const))
5550
			elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
A
Alvaro Herrera 已提交
5551
		con = (A_Const *) arg;
5552

A
Alvaro Herrera 已提交
5553
		switch (nodeTag(&con->val))
5554 5555
		{
			case T_Integer:
A
Alvaro Herrera 已提交
5556
				appendStringInfo(&buf, "%ld", intVal(&con->val));
5557 5558 5559
				break;
			case T_Float:
				/* represented as a string, so just copy it */
A
Alvaro Herrera 已提交
5560
				appendStringInfoString(&buf, strVal(&con->val));
5561 5562
				break;
			case T_String:
A
Alvaro Herrera 已提交
5563
				val = strVal(&con->val);
5564
				if (typeName != NULL)
5565 5566
				{
					/*
B
Bruce Momjian 已提交
5567 5568 5569
					 * Must be a ConstInterval argument for TIME ZONE. Coerce
					 * to interval and back to normalize the value and account
					 * for any typmod.
5570
					 */
5571
					Oid			typoid;
5572
					int32		typmod;
B
Bruce Momjian 已提交
5573
					Datum		interval;
B
Bruce Momjian 已提交
5574
					char	   *intervalout;
5575

5576
					typoid = typenameTypeId(NULL, typeName, &typmod);
5577
					Assert(typoid == INTERVALOID);
5578

5579
					interval =
B
Bruce Momjian 已提交
5580 5581 5582
						DirectFunctionCall3(interval_in,
											CStringGetDatum(val),
											ObjectIdGetDatum(InvalidOid),
5583
											Int32GetDatum(typmod));
5584 5585

					intervalout =
5586 5587
						DatumGetCString(DirectFunctionCall1(interval_out,
															interval));
5588 5589 5590 5591
					appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
				}
				else
				{
5592 5593 5594 5595
					/*
					 * Plain string literal or identifier.	For quote mode,
					 * quote it if it's not a vanilla identifier.
					 */
5596
					if (flags & GUC_LIST_QUOTE)
N
Neil Conway 已提交
5597
						appendStringInfoString(&buf, quote_identifier(val));
5598
					else
N
Neil Conway 已提交
5599
						appendStringInfoString(&buf, val);
5600 5601 5602
				}
				break;
			default:
5603
				elog(ERROR, "unrecognized node type: %d",
A
Alvaro Herrera 已提交
5604
					 (int) nodeTag(&con->val));
5605 5606
				break;
		}
5607
	}
5608 5609 5610 5611 5612 5613 5614 5615 5616

	return buf.data;
}


/*
 * SET command
 */
void
5617 5618
ExecSetVariableStmt(VariableSetStmt *stmt)
{
B
Bruce Momjian 已提交
5619
	GucAction	action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
5620

5621 5622 5623 5624 5625 5626 5627 5628
	switch (stmt->kind)
	{
		case VAR_SET_VALUE:
		case VAR_SET_CURRENT:
			set_config_option(stmt->name,
							  ExtractSetVariableArgs(stmt),
							  (superuser() ? PGC_SUSET : PGC_USERSET),
							  PGC_S_SESSION,
5629
							  action,
5630 5631 5632
							  true);
			break;
		case VAR_SET_MULTI:
B
Bruce Momjian 已提交
5633

5634
			/*
B
Bruce Momjian 已提交
5635 5636
			 * Special case for special SQL syntax that effectively sets more
			 * than one variable per statement.
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685
			 */
			if (strcmp(stmt->name, "TRANSACTION") == 0)
			{
				ListCell   *head;

				foreach(head, stmt->args)
				{
					DefElem    *item = (DefElem *) lfirst(head);

					if (strcmp(item->defname, "transaction_isolation") == 0)
						SetPGVariable("transaction_isolation",
									  list_make1(item->arg), stmt->is_local);
					else if (strcmp(item->defname, "transaction_read_only") == 0)
						SetPGVariable("transaction_read_only",
									  list_make1(item->arg), stmt->is_local);
					else
						elog(ERROR, "unexpected SET TRANSACTION element: %s",
							 item->defname);
				}
			}
			else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
			{
				ListCell   *head;

				foreach(head, stmt->args)
				{
					DefElem    *item = (DefElem *) lfirst(head);

					if (strcmp(item->defname, "transaction_isolation") == 0)
						SetPGVariable("default_transaction_isolation",
									  list_make1(item->arg), stmt->is_local);
					else if (strcmp(item->defname, "transaction_read_only") == 0)
						SetPGVariable("default_transaction_read_only",
									  list_make1(item->arg), stmt->is_local);
					else
						elog(ERROR, "unexpected SET SESSION element: %s",
							 item->defname);
				}
			}
			else
				elog(ERROR, "unexpected SET MULTI element: %s",
					 stmt->name);
			break;
		case VAR_SET_DEFAULT:
		case VAR_RESET:
			set_config_option(stmt->name,
							  NULL,
							  (superuser() ? PGC_SUSET : PGC_USERSET),
							  PGC_S_SESSION,
5686
							  action,
5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721
							  true);
			break;
		case VAR_RESET_ALL:
			ResetAllOptions();
			break;
	}
}

/*
 * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
 * The result is palloc'd.
 *
 * This is exported for use by actions such as ALTER ROLE SET.
 */
char *
ExtractSetVariableArgs(VariableSetStmt *stmt)
{
	switch (stmt->kind)
	{
		case VAR_SET_VALUE:
			return flatten_set_variable_args(stmt->name, stmt->args);
		case VAR_SET_CURRENT:
			return GetConfigOptionByName(stmt->name, NULL);
		default:
			return NULL;
	}
}

/*
 * SetPGVariable - SET command exported as an easily-C-callable function.
 *
 * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
 * by passing args == NIL), but not SET FROM CURRENT functionality.
 */
void
5722 5723 5724 5725 5726 5727 5728 5729 5730
SetPGVariable(const char *name, List *args, bool is_local)
{
	char	   *argstring = flatten_set_variable_args(name, args);

	/* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
	set_config_option(name,
					  argstring,
					  (superuser() ? PGC_SUSET : PGC_USERSET),
					  PGC_S_SESSION,
5731
					  is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
5732 5733 5734
					  true);
}

5735 5736 5737 5738 5739 5740
/*
 * SET command wrapped as a SQL callable function.
 */
Datum
set_config_by_name(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
5741 5742 5743 5744
	char	   *name;
	char	   *value;
	char	   *new_value;
	bool		is_local;
5745 5746

	if (PG_ARGISNULL(0))
5747 5748
		ereport(ERROR,
				(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5749
				 errmsg("SET requires parameter name")));
5750 5751

	/* Get the GUC variable name */
5752
	name = TextDatumGetCString(PG_GETARG_DATUM(0));
5753 5754 5755 5756 5757

	/* Get the desired value or set to NULL for a reset request */
	if (PG_ARGISNULL(1))
		value = NULL;
	else
5758
		value = TextDatumGetCString(PG_GETARG_DATUM(1));
5759 5760

	/*
B
Bruce Momjian 已提交
5761 5762
	 * Get the desired state of is_local. Default to false if provided value
	 * is NULL
5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773
	 */
	if (PG_ARGISNULL(2))
		is_local = false;
	else
		is_local = PG_GETARG_BOOL(2);

	/* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
	set_config_option(name,
					  value,
					  (superuser() ? PGC_SUSET : PGC_USERSET),
					  PGC_S_SESSION,
5774
					  is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
5775 5776 5777
					  true);

	/* get the new current value */
5778
	new_value = GetConfigOptionByName(name, NULL);
5779 5780

	/* Convert return string to text */
5781
	PG_RETURN_TEXT_P(cstring_to_text(new_value));
5782 5783
}

5784

5785 5786 5787 5788 5789 5790 5791 5792 5793
/*
 * Common code for DefineCustomXXXVariable subroutines: allocate the
 * new variable's config struct and fill in generic fields.
 */
static struct config_generic *
init_custom_variable(const char *name,
					 const char *short_desc,
					 const char *long_desc,
					 GucContext context,
5794
					 int flags,
5795 5796 5797 5798 5799
					 enum config_type type,
					 size_t sz)
{
	struct config_generic *gen;

5800
	/*
5801 5802 5803 5804 5805
	 * Only allow custom PGC_POSTMASTER variables to be created during shared
	 * library preload; any later than that, we can't ensure that the value
	 * doesn't change after startup.  This is a fatal elog if it happens; just
	 * erroring out isn't safe because we don't know what the calling loadable
	 * module might already have hooked into.
5806 5807 5808 5809 5810
	 */
	if (context == PGC_POSTMASTER &&
		!process_shared_preload_libraries_in_progress)
		elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");

5811 5812 5813 5814 5815 5816 5817 5818
	gen = (struct config_generic *) guc_malloc(ERROR, sz);
	memset(gen, 0, sz);

	gen->name = guc_strdup(ERROR, name);
	gen->context = context;
	gen->group = CUSTOM_OPTIONS;
	gen->short_desc = short_desc;
	gen->long_desc = long_desc;
5819
	gen->flags = flags;
5820 5821 5822 5823 5824 5825 5826 5827 5828
	gen->vartype = type;

	return gen;
}

/*
 * Common code for DefineCustomXXXVariable subroutines: insert the new
 * variable into the GUC variable array, replacing any placeholder.
 */
5829
static void
B
Bruce Momjian 已提交
5830
define_custom_variable(struct config_generic * variable)
5831
{
B
Bruce Momjian 已提交
5832 5833 5834 5835
	const char *name = variable->name;
	const char **nameAddr = &name;
	const char *value;
	struct config_string *pHolder;
5836
	GucContext	phcontext;
5837
	struct config_generic **res;
B
Bruce Momjian 已提交
5838

5839 5840 5841
	/*
	 * See if there's a placeholder by the same name.
	 */
5842 5843 5844 5845 5846
	res = (struct config_generic **) bsearch((void *) &nameAddr,
											 (void *) guc_variables,
											 num_guc_variables,
											 sizeof(struct config_generic *),
											 guc_var_compare);
B
Bruce Momjian 已提交
5847
	if (res == NULL)
5848
	{
5849 5850 5851 5852 5853
		/*
		 * No placeholder to replace, so we can just add it ... but first,
		 * make sure it's initialized to its default value.
		 */
		InitializeOneGUCOption(variable);
5854
		add_guc_variable(variable, ERROR);
5855 5856 5857
		return;
	}

B
Bruce Momjian 已提交
5858 5859
	/*
	 * This better be a placeholder
5860
	 */
B
Bruce Momjian 已提交
5861
	if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
5862 5863 5864
		ereport(ERROR,
				(errcode(ERRCODE_INTERNAL_ERROR),
				 errmsg("attempt to redefine parameter \"%s\"", name)));
5865 5866

	Assert((*res)->vartype == PGC_STRING);
5867
	pHolder = (struct config_string *) (*res);
B
Bruce Momjian 已提交
5868

5869 5870 5871 5872 5873 5874 5875
	/*
	 * First, set the variable to its default value.  We must do this even
	 * though we intend to immediately apply a new value, since it's possible
	 * that the new value is invalid.
	 */
	InitializeOneGUCOption(variable);

5876
	/*
B
Bruce Momjian 已提交
5877 5878
	 * Replace the placeholder. We aren't changing the name, so no re-sorting
	 * is necessary
5879
	 */
5880 5881
	*res = variable;

5882
	/*
5883 5884 5885
	 * Infer context for assignment based on source of existing value. We
	 * can't tell this with exact accuracy, but we can at least do something
	 * reasonable in typical cases.
5886 5887 5888 5889 5890 5891 5892
	 */
	switch (pHolder->gen.source)
	{
		case PGC_S_DEFAULT:
		case PGC_S_ENV_VAR:
		case PGC_S_FILE:
		case PGC_S_ARGV:
5893

5894
			/*
5895 5896 5897
			 * If we got past the check in init_custom_variable, we can safely
			 * assume that any existing value for a PGC_POSTMASTER variable
			 * was set in postmaster context.
5898 5899 5900 5901 5902
			 */
			if (variable->context == PGC_POSTMASTER)
				phcontext = PGC_POSTMASTER;
			else
				phcontext = PGC_SIGHUP;
5903
			break;
5904

5905 5906
		case PGC_S_DATABASE:
		case PGC_S_USER:
5907
		case PGC_S_DATABASE_USER:
5908 5909 5910 5911 5912 5913 5914 5915 5916 5917
			/*
			 * The existing value came from an ALTER ROLE/DATABASE SET command.
			 * We can assume that at the time the command was issued, we
			 * checked that the issuing user was superuser if the variable
			 * requires superuser privileges to set.  So it's safe to
			 * use SUSET context here.
			 */
			phcontext = PGC_SUSET;
			break;

5918 5919 5920
		case PGC_S_CLIENT:
		case PGC_S_SESSION:
		default:
5921 5922 5923 5924
			/*
			 * We must assume that the value came from an untrusted user,
			 * even if the current_user is a superuser.
			 */
5925 5926 5927 5928
			phcontext = PGC_USERSET;
			break;
	}

5929
	/*
B
Bruce Momjian 已提交
5930
	 * Assign the string value stored in the placeholder to the real variable.
5931 5932 5933
	 *
	 * XXX this is not really good enough --- it should be a nontransactional
	 * assignment, since we don't want it to roll back if the current xact
5934
	 * fails later.  (Or do we?)
5935
	 */
5936 5937 5938
	value = *pHolder->variable;

	if (value)
5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949
	{
		if (set_config_option(name, value,
							  phcontext, pHolder->gen.source,
							  GUC_ACTION_SET, true))
		{
			/* Also copy over any saved source-location information */
			if (pHolder->gen.sourcefile)
				set_config_sourcefile(name, pHolder->gen.sourcefile,
									  pHolder->gen.sourceline);
		}
	}
5950

5951 5952 5953
	/*
	 * Free up as much as we conveniently can of the placeholder structure
	 * (this neglects any stack items...)
5954
	 */
5955 5956
	set_string_field(pHolder, pHolder->variable, NULL);
	set_string_field(pHolder, &pHolder->reset_val, NULL);
5957 5958 5959 5960

	free(pHolder);
}

B
Bruce Momjian 已提交
5961
void
5962
DefineCustomBoolVariable(const char *name,
B
Bruce Momjian 已提交
5963 5964 5965
						 const char *short_desc,
						 const char *long_desc,
						 bool *valueAddr,
5966
						 bool bootValue,
B
Bruce Momjian 已提交
5967
						 GucContext context,
5968
						 int flags,
B
Bruce Momjian 已提交
5969 5970
						 GucBoolAssignHook assign_hook,
						 GucShowHook show_hook)
5971
{
5972
	struct config_bool *var;
5973

5974
	var = (struct config_bool *)
5975
		init_custom_variable(name, short_desc, long_desc, context, flags,
5976
							 PGC_BOOL, sizeof(struct config_bool));
B
Bruce Momjian 已提交
5977
	var->variable = valueAddr;
5978 5979
	var->boot_val = bootValue;
	var->reset_val = bootValue;
5980
	var->assign_hook = assign_hook;
B
Bruce Momjian 已提交
5981
	var->show_hook = show_hook;
5982 5983 5984
	define_custom_variable(&var->gen);
}

B
Bruce Momjian 已提交
5985
void
5986
DefineCustomIntVariable(const char *name,
B
Bruce Momjian 已提交
5987 5988 5989
						const char *short_desc,
						const char *long_desc,
						int *valueAddr,
5990
						int bootValue,
5991 5992
						int minValue,
						int maxValue,
B
Bruce Momjian 已提交
5993
						GucContext context,
5994
						int flags,
B
Bruce Momjian 已提交
5995 5996
						GucIntAssignHook assign_hook,
						GucShowHook show_hook)
5997
{
5998
	struct config_int *var;
5999

6000
	var = (struct config_int *)
6001
		init_custom_variable(name, short_desc, long_desc, context, flags,
6002
							 PGC_INT, sizeof(struct config_int));
B
Bruce Momjian 已提交
6003
	var->variable = valueAddr;
6004 6005
	var->boot_val = bootValue;
	var->reset_val = bootValue;
6006 6007
	var->min = minValue;
	var->max = maxValue;
6008
	var->assign_hook = assign_hook;
B
Bruce Momjian 已提交
6009
	var->show_hook = show_hook;
6010 6011 6012
	define_custom_variable(&var->gen);
}

B
Bruce Momjian 已提交
6013
void
6014
DefineCustomRealVariable(const char *name,
B
Bruce Momjian 已提交
6015 6016 6017
						 const char *short_desc,
						 const char *long_desc,
						 double *valueAddr,
6018
						 double bootValue,
6019 6020
						 double minValue,
						 double maxValue,
B
Bruce Momjian 已提交
6021
						 GucContext context,
6022
						 int flags,
B
Bruce Momjian 已提交
6023 6024
						 GucRealAssignHook assign_hook,
						 GucShowHook show_hook)
6025
{
6026
	struct config_real *var;
6027

6028
	var = (struct config_real *)
6029
		init_custom_variable(name, short_desc, long_desc, context, flags,
6030
							 PGC_REAL, sizeof(struct config_real));
B
Bruce Momjian 已提交
6031
	var->variable = valueAddr;
6032 6033
	var->boot_val = bootValue;
	var->reset_val = bootValue;
6034 6035
	var->min = minValue;
	var->max = maxValue;
6036
	var->assign_hook = assign_hook;
B
Bruce Momjian 已提交
6037
	var->show_hook = show_hook;
6038 6039 6040
	define_custom_variable(&var->gen);
}

B
Bruce Momjian 已提交
6041
void
6042
DefineCustomStringVariable(const char *name,
B
Bruce Momjian 已提交
6043 6044 6045
						   const char *short_desc,
						   const char *long_desc,
						   char **valueAddr,
6046
						   const char *bootValue,
B
Bruce Momjian 已提交
6047
						   GucContext context,
6048
						   int flags,
B
Bruce Momjian 已提交
6049 6050
						   GucStringAssignHook assign_hook,
						   GucShowHook show_hook)
6051
{
6052
	struct config_string *var;
6053

6054
	var = (struct config_string *)
6055
		init_custom_variable(name, short_desc, long_desc, context, flags,
6056
							 PGC_STRING, sizeof(struct config_string));
B
Bruce Momjian 已提交
6057
	var->variable = valueAddr;
6058
	var->boot_val = bootValue;
6059 6060 6061
	/* we could probably do without strdup, but keep it like normal case */
	if (var->boot_val)
		var->reset_val = guc_strdup(ERROR, var->boot_val);
6062
	var->assign_hook = assign_hook;
B
Bruce Momjian 已提交
6063
	var->show_hook = show_hook;
6064 6065 6066
	define_custom_variable(&var->gen);
}

6067 6068 6069 6070 6071
void
DefineCustomEnumVariable(const char *name,
						 const char *short_desc,
						 const char *long_desc,
						 int *valueAddr,
6072
						 int bootValue,
6073
						 const struct config_enum_entry * options,
6074
						 GucContext context,
6075
						 int flags,
6076 6077 6078 6079 6080 6081
						 GucEnumAssignHook assign_hook,
						 GucShowHook show_hook)
{
	struct config_enum *var;

	var = (struct config_enum *)
6082
		init_custom_variable(name, short_desc, long_desc, context, flags,
6083 6084
							 PGC_ENUM, sizeof(struct config_enum));
	var->variable = valueAddr;
6085 6086
	var->boot_val = bootValue;
	var->reset_val = bootValue;
6087 6088 6089 6090 6091 6092
	var->options = options;
	var->assign_hook = assign_hook;
	var->show_hook = show_hook;
	define_custom_variable(&var->gen);
}

N
Neil Conway 已提交
6093
void
B
Bruce Momjian 已提交
6094
EmitWarningsOnPlaceholders(const char *className)
6095
{
6096 6097
	int			classLen = strlen(className);
	int			i;
6098

6099
	for (i = 0; i < num_guc_variables; i++)
6100
	{
6101
		struct config_generic *var = guc_variables[i];
B
Bruce Momjian 已提交
6102 6103

		if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
6104 6105
			strncmp(className, var->name, classLen) == 0 &&
			var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
6106
		{
6107
			ereport(WARNING,
B
Bruce Momjian 已提交
6108
					(errcode(ERRCODE_UNDEFINED_OBJECT),
6109 6110
					 errmsg("unrecognized configuration parameter \"%s\"",
							var->name)));
6111 6112 6113 6114 6115
		}
	}
}


6116 6117 6118 6119
/*
 * SHOW command
 */
void
6120
GetPGVariable(const char *name, DestReceiver *dest)
6121
{
6122
	if (guc_name_compare(name, "all") == 0)
6123
		ShowAllGUCConfig(dest);
6124
	else
6125 6126 6127 6128 6129 6130 6131 6132
		ShowGUCConfigOption(name, dest);
}

TupleDesc
GetPGVariableResultDesc(const char *name)
{
	TupleDesc	tupdesc;

6133
	if (guc_name_compare(name, "all") == 0)
6134
	{
6135 6136
		/* need a tuple descriptor representing three TEXT columns */
		tupdesc = CreateTemplateTupleDesc(3, false);
6137
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6138
						   TEXTOID, -1, 0);
6139
		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6140
						   TEXTOID, -1, 0);
6141 6142
		TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
						   TEXTOID, -1, 0);
6143 6144 6145 6146 6147 6148 6149 6150 6151 6152
	}
	else
	{
		const char *varname;

		/* Get the canonical spelling of name */
		(void) GetConfigOptionByName(name, &varname);

		/* need a tuple descriptor representing a single TEXT column */
		tupdesc = CreateTemplateTupleDesc(1, false);
6153 6154
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
						   TEXTOID, -1, 0);
6155 6156
	}
	return tupdesc;
6157 6158 6159 6160 6161 6162
}


/*
 * SHOW command
 */
6163
static void
6164
ShowGUCConfigOption(const char *name, DestReceiver *dest)
6165
{
6166
	TupOutputState *tstate;
B
Bruce Momjian 已提交
6167 6168 6169
	TupleDesc	tupdesc;
	const char *varname;
	char	   *value;
6170

6171 6172 6173
	/* Get the value and canonical spelling of name */
	value = GetConfigOptionByName(name, &varname);

6174
	/* need a tuple descriptor representing a single TEXT column */
6175
	tupdesc = CreateTemplateTupleDesc(1, false);
6176
	TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6177
					   TEXTOID, -1, 0);
6178

6179 6180 6181 6182
	/* prepare for projection of tuples */
	tstate = begin_tup_output_tupdesc(dest, tupdesc);

	/* Send it */
6183
	do_text_output_oneline(tstate, value);
6184 6185

	end_tup_output(tstate);
6186 6187
}

6188 6189 6190
/*
 * SHOW ALL command
 */
6191
static void
6192
ShowAllGUCConfig(DestReceiver *dest)
6193
{
6194
	bool		am_superuser = superuser();
6195
	int			i;
6196
	TupOutputState *tstate;
B
Bruce Momjian 已提交
6197
	TupleDesc	tupdesc;
B
Bruce Momjian 已提交
6198 6199
	Datum		values[3];
	bool		isnull[3] = {false, false, false};
6200

6201 6202
	/* need a tuple descriptor representing three TEXT columns */
	tupdesc = CreateTemplateTupleDesc(3, false);
6203
	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6204
					   TEXTOID, -1, 0);
6205
	TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6206
					   TEXTOID, -1, 0);
6207 6208
	TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
					   TEXTOID, -1, 0);
B
Bruce Momjian 已提交
6209

6210 6211
	/* prepare for projection of tuples */
	tstate = begin_tup_output_tupdesc(dest, tupdesc);
6212

6213 6214
	for (i = 0; i < num_guc_variables; i++)
	{
6215
		struct config_generic *conf = guc_variables[i];
B
Bruce Momjian 已提交
6216
		char	   *setting;
6217

6218 6219
		if ((conf->flags & GUC_NO_SHOW_ALL) ||
			((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
6220
			continue;
6221 6222

		/* assign to the values array */
6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237
		values[0] = PointerGetDatum(cstring_to_text(conf->name));

		setting = _ShowOption(conf, true);
		if (setting)
		{
			values[1] = PointerGetDatum(cstring_to_text(setting));
			isnull[1] = false;
		}
		else
		{
			values[1] = PointerGetDatum(NULL);
			isnull[1] = true;
		}

		values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
6238 6239

		/* send it to dest */
6240
		do_tup_output(tstate, values, isnull);
6241

6242
		/* clean up */
6243 6244 6245 6246 6247 6248 6249
		pfree(DatumGetPointer(values[0]));
		if (setting)
		{
			pfree(setting);
			pfree(DatumGetPointer(values[1]));
		}
		pfree(DatumGetPointer(values[2]));
6250
	}
6251 6252

	end_tup_output(tstate);
6253
}
6254

6255
/*
6256 6257
 * Return GUC variable value by name; optionally return canonical
 * form of name.  Return value is palloc'd.
6258 6259
 */
char *
6260
GetConfigOptionByName(const char *name, const char **varname)
6261 6262 6263
{
	struct config_generic *record;

6264
	record = find_option(name, false, ERROR);
6265
	if (record == NULL)
6266 6267
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
6268
			   errmsg("unrecognized configuration parameter \"%s\"", name)));
6269 6270 6271 6272
	if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to examine \"%s\"", name)));
6273

6274 6275 6276
	if (varname)
		*varname = record->name;

6277
	return _ShowOption(record, true);
6278 6279 6280
}

/*
6281 6282
 * Return GUC variable value by variable number; optionally return canonical
 * form of name.  Return value is palloc'd.
6283
 */
6284 6285
void
GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
6286
{
B
Bruce Momjian 已提交
6287 6288
	char		buffer[256];
	struct config_generic *conf;
6289 6290 6291 6292 6293

	/* check requested variable number valid */
	Assert((varnum >= 0) && (varnum < num_guc_variables));

	conf = guc_variables[varnum];
6294

6295
	if (noshow)
6296 6297 6298 6299 6300 6301 6302
	{
		if ((conf->flags & GUC_NO_SHOW_ALL) ||
			((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
			*noshow = true;
		else
			*noshow = false;
	}
6303

6304 6305 6306 6307 6308 6309
	/* first get the generic attributes */

	/* name */
	values[0] = conf->name;

	/* setting : use _ShowOption in order to avoid duplicating the logic */
6310 6311 6312 6313 6314
	values[1] = _ShowOption(conf, false);

	/* unit */
	if (conf->vartype == PGC_INT)
	{
6315
		static char buf[8];
6316

6317 6318 6319 6320 6321 6322
		switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
		{
			case GUC_UNIT_KB:
				values[2] = "kB";
				break;
			case GUC_UNIT_BLOCKS:
B
Bruce Momjian 已提交
6323
				snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
6324 6325 6326
				values[2] = buf;
				break;
			case GUC_UNIT_XBLOCKS:
B
Bruce Momjian 已提交
6327
				snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341
				values[2] = buf;
				break;
			case GUC_UNIT_MS:
				values[2] = "ms";
				break;
			case GUC_UNIT_S:
				values[2] = "s";
				break;
			case GUC_UNIT_MIN:
				values[2] = "min";
				break;
			default:
				values[2] = "";
				break;
6342 6343 6344 6345
		}
	}
	else
		values[2] = NULL;
6346

6347
	/* group */
6348
	values[3] = config_group_names[conf->group];
6349 6350

	/* short_desc */
6351
	values[4] = conf->short_desc;
6352 6353

	/* extra_desc */
6354
	values[5] = conf->long_desc;
6355

6356
	/* context */
6357
	values[6] = GucContext_Names[conf->context];
6358 6359

	/* vartype */
6360
	values[7] = config_type_names[conf->vartype];
6361 6362

	/* source */
6363
	values[8] = GucSource_Names[conf->source];
6364 6365 6366 6367 6368 6369

	/* now get the type specifc attributes */
	switch (conf->vartype)
	{
		case PGC_BOOL:
			{
6370 6371
				struct config_bool *lconf = (struct config_bool *) conf;

6372
				/* min_val */
6373
				values[9] = NULL;
6374 6375

				/* max_val */
6376
				values[10] = NULL;
6377 6378 6379

				/* enumvals */
				values[11] = NULL;
6380 6381 6382 6383 6384 6385

				/* boot_val */
				values[12] = pstrdup(lconf->boot_val ? "on" : "off");

				/* reset_val */
				values[13] = pstrdup(lconf->reset_val ? "on" : "off");
6386 6387 6388 6389 6390 6391 6392 6393 6394
			}
			break;

		case PGC_INT:
			{
				struct config_int *lconf = (struct config_int *) conf;

				/* min_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->min);
6395
				values[9] = pstrdup(buffer);
6396 6397 6398

				/* max_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->max);
6399
				values[10] = pstrdup(buffer);
6400 6401 6402

				/* enumvals */
				values[11] = NULL;
6403

6404 6405 6406
				/* boot_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
				values[12] = pstrdup(buffer);
6407

6408 6409 6410
				/* reset_val */
				snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
				values[13] = pstrdup(buffer);
6411 6412 6413 6414 6415 6416 6417 6418 6419
			}
			break;

		case PGC_REAL:
			{
				struct config_real *lconf = (struct config_real *) conf;

				/* min_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->min);
6420
				values[9] = pstrdup(buffer);
6421 6422 6423

				/* max_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->max);
6424
				values[10] = pstrdup(buffer);
6425 6426 6427

				/* enumvals */
				values[11] = NULL;
6428

6429 6430 6431
				/* boot_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
				values[12] = pstrdup(buffer);
6432

6433 6434 6435
				/* reset_val */
				snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
				values[13] = pstrdup(buffer);
6436 6437 6438 6439 6440
			}
			break;

		case PGC_STRING:
			{
6441
				struct config_string *lconf = (struct config_string *) conf;
6442

6443
				/* min_val */
6444
				values[9] = NULL;
6445 6446

				/* max_val */
6447
				values[10] = NULL;
6448 6449 6450

				/* enumvals */
				values[11] = NULL;
6451

6452 6453 6454
				/* boot_val */
				if (lconf->boot_val == NULL)
					values[12] = NULL;
6455 6456 6457
				else
					values[12] = pstrdup(lconf->boot_val);

6458 6459 6460
				/* reset_val */
				if (lconf->reset_val == NULL)
					values[13] = NULL;
6461 6462
				else
					values[13] = pstrdup(lconf->reset_val);
6463 6464 6465 6466 6467
			}
			break;

		case PGC_ENUM:
			{
6468
				struct config_enum *lconf = (struct config_enum *) conf;
6469

6470 6471 6472 6473 6474 6475 6476
				/* min_val */
				values[9] = NULL;

				/* max_val */
				values[10] = NULL;

				/* enumvals */
6477 6478 6479 6480 6481

				/*
				 * NOTE! enumvals with double quotes in them are not
				 * supported!
				 */
A
Alvaro Herrera 已提交
6482 6483
				values[11] = config_enum_get_options((struct config_enum *) conf,
													 "{\"", "\"}", "\",\"");
6484

6485
				/* boot_val */
A
Alvaro Herrera 已提交
6486
				values[12] = pstrdup(config_enum_lookup_by_value(lconf,
6487
														   lconf->boot_val));
6488

6489
				/* reset_val */
A
Alvaro Herrera 已提交
6490
				values[13] = pstrdup(config_enum_lookup_by_value(lconf,
6491
														  lconf->reset_val));
6492 6493 6494 6495 6496 6497
			}
			break;

		default:
			{
				/*
B
Bruce Momjian 已提交
6498
				 * should never get here, but in case we do, set 'em to NULL
6499 6500 6501
				 */

				/* min_val */
6502
				values[9] = NULL;
6503 6504

				/* max_val */
6505
				values[10] = NULL;
6506 6507 6508

				/* enumvals */
				values[11] = NULL;
6509

6510 6511
				/* boot_val */
				values[12] = NULL;
6512

6513 6514
				/* reset_val */
				values[13] = NULL;
6515 6516 6517
			}
			break;
	}
6518

6519 6520 6521
	/*
	 * If the setting came from a config file, set the source location. For
	 * security reasons, we don't show source file/line number for
6522 6523 6524
	 * non-superusers.
	 */
	if (conf->source == PGC_S_FILE && superuser())
6525
	{
6526
		values[14] = conf->sourcefile;
6527
		snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
6528
		values[15] = pstrdup(buffer);
6529 6530 6531
	}
	else
	{
6532 6533
		values[14] = NULL;
		values[15] = NULL;
6534
	}
6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552
}

/*
 * Return the total number of GUC variables
 */
int
GetNumConfigOptions(void)
{
	return num_guc_variables;
}

/*
 * show_config_by_name - equiv to SHOW X command but implemented as
 * a function.
 */
Datum
show_config_by_name(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
6553 6554
	char	   *varname;
	char	   *varval;
6555 6556

	/* Get the GUC variable name */
6557
	varname = TextDatumGetCString(PG_GETARG_DATUM(0));
6558 6559

	/* Get the value */
6560
	varval = GetConfigOptionByName(varname, NULL);
6561 6562

	/* Convert to text */
6563
	PG_RETURN_TEXT_P(cstring_to_text(varval));
6564 6565
}

6566 6567 6568 6569
/*
 * show_all_settings - equiv to SHOW ALL command but implemented as
 * a Table Function.
 */
6570
#define NUM_PG_SETTINGS_ATTS	16
6571

6572 6573 6574
Datum
show_all_settings(PG_FUNCTION_ARGS)
{
B
Bruce Momjian 已提交
6575 6576 6577 6578 6579 6580
	FuncCallContext *funcctx;
	TupleDesc	tupdesc;
	int			call_cntr;
	int			max_calls;
	AttInMetadata *attinmeta;
	MemoryContext oldcontext;
6581 6582

	/* stuff done only on the first call of the function */
B
Bruce Momjian 已提交
6583 6584
	if (SRF_IS_FIRSTCALL())
	{
6585
		/* create a function context for cross-call persistence */
B
Bruce Momjian 已提交
6586
		funcctx = SRF_FIRSTCALL_INIT();
6587

B
Bruce Momjian 已提交
6588
		/*
B
Bruce Momjian 已提交
6589
		 * switch to memory context appropriate for multiple function calls
B
Bruce Momjian 已提交
6590
		 */
6591 6592
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

6593
		/*
B
Bruce Momjian 已提交
6594 6595
		 * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
		 * of the appropriate types
6596 6597
		 */
		tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
6598
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6599
						   TEXTOID, -1, 0);
6600
		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6601
						   TEXTOID, -1, 0);
6602 6603 6604
		TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
						   TEXTOID, -1, 0);
		TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
6605
						   TEXTOID, -1, 0);
6606
		TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
6607
						   TEXTOID, -1, 0);
6608
		TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
6609
						   TEXTOID, -1, 0);
6610
		TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
6611
						   TEXTOID, -1, 0);
6612
		TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
6613
						   TEXTOID, -1, 0);
6614
		TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
6615
						   TEXTOID, -1, 0);
6616
		TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
6617
						   TEXTOID, -1, 0);
6618
		TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
6619
						   TEXTOID, -1, 0);
6620
		TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
6621
						   TEXTARRAYOID, -1, 0);
6622 6623 6624 6625
		TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
						   TEXTOID, -1, 0);
		TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
						   TEXTOID, -1, 0);
6626
		TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
6627
						   TEXTOID, -1, 0);
6628
		TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
6629
						   INT4OID, -1, 0);
6630 6631

		/*
B
Bruce Momjian 已提交
6632 6633
		 * Generate attribute metadata needed later to produce tuples from raw
		 * C strings
6634 6635 6636 6637 6638 6639
		 */
		attinmeta = TupleDescGetAttInMetadata(tupdesc);
		funcctx->attinmeta = attinmeta;

		/* total number of tuples to be returned */
		funcctx->max_calls = GetNumConfigOptions();
6640 6641

		MemoryContextSwitchTo(oldcontext);
B
Bruce Momjian 已提交
6642
	}
6643 6644

	/* stuff done on every call of the function */
B
Bruce Momjian 已提交
6645
	funcctx = SRF_PERCALL_SETUP();
6646 6647 6648 6649 6650

	call_cntr = funcctx->call_cntr;
	max_calls = funcctx->max_calls;
	attinmeta = funcctx->attinmeta;

B
Bruce Momjian 已提交
6651 6652
	if (call_cntr < max_calls)	/* do when there is more left to send */
	{
6653
		char	   *values[NUM_PG_SETTINGS_ATTS];
6654 6655 6656 6657 6658 6659 6660 6661 6662
		bool		noshow;
		HeapTuple	tuple;
		Datum		result;

		/*
		 * Get the next visible GUC variable name and value
		 */
		do
		{
6663
			GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
6664 6665 6666 6667 6668 6669 6670
			if (noshow)
			{
				/* bump the counter and get the next config setting */
				call_cntr = ++funcctx->call_cntr;

				/* make sure we haven't gone too far now */
				if (call_cntr >= max_calls)
B
Bruce Momjian 已提交
6671
					SRF_RETURN_DONE(funcctx);
6672 6673 6674 6675 6676 6677 6678
			}
		} while (noshow);

		/* build a tuple */
		tuple = BuildTupleFromCStrings(attinmeta, values);

		/* make the tuple into a datum */
6679
		result = HeapTupleGetDatum(tuple);
6680

B
Bruce Momjian 已提交
6681 6682 6683
		SRF_RETURN_NEXT(funcctx, result);
	}
	else
6684 6685
	{
		/* do when there is no more left */
B
Bruce Momjian 已提交
6686
		SRF_RETURN_DONE(funcctx);
6687
	}
6688 6689
}

6690
static char *
6691
_ShowOption(struct config_generic * record, bool use_units)
6692 6693 6694
{
	char		buffer[256];
	const char *val;
6695

6696 6697 6698 6699 6700
	switch (record->vartype)
	{
		case PGC_BOOL:
			{
				struct config_bool *conf = (struct config_bool *) record;
6701

6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716
				if (conf->show_hook)
					val = (*conf->show_hook) ();
				else
					val = *conf->variable ? "on" : "off";
			}
			break;

		case PGC_INT:
			{
				struct config_int *conf = (struct config_int *) record;

				if (conf->show_hook)
					val = (*conf->show_hook) ();
				else
				{
6717 6718
					/*
					 * Use int64 arithmetic to avoid overflows in units
6719
					 * conversion.
6720 6721 6722
					 */
					int64		result = *conf->variable;
					const char *unit;
6723

6724 6725
					if (use_units && result > 0 &&
						(record->flags & GUC_UNIT_MEMORY))
6726
					{
6727 6728 6729
						switch (record->flags & GUC_UNIT_MEMORY)
						{
							case GUC_UNIT_BLOCKS:
B
Bruce Momjian 已提交
6730
								result *= BLCKSZ / 1024;
6731 6732
								break;
							case GUC_UNIT_XBLOCKS:
B
Bruce Momjian 已提交
6733
								result *= XLOG_BLCKSZ / 1024;
6734 6735
								break;
						}
6736 6737 6738 6739

						if (result % KB_PER_GB == 0)
						{
							result /= KB_PER_GB;
6740
							unit = "GB";
6741 6742 6743 6744
						}
						else if (result % KB_PER_MB == 0)
						{
							result /= KB_PER_MB;
6745
							unit = "MB";
6746 6747 6748
						}
						else
						{
6749
							unit = "kB";
6750 6751
						}
					}
6752 6753
					else if (use_units && result > 0 &&
							 (record->flags & GUC_UNIT_TIME))
6754
					{
6755 6756 6757 6758 6759 6760 6761 6762 6763
						switch (record->flags & GUC_UNIT_TIME)
						{
							case GUC_UNIT_S:
								result *= MS_PER_S;
								break;
							case GUC_UNIT_MIN:
								result *= MS_PER_MIN;
								break;
						}
6764 6765 6766 6767

						if (result % MS_PER_D == 0)
						{
							result /= MS_PER_D;
6768
							unit = "d";
6769 6770 6771 6772
						}
						else if (result % MS_PER_H == 0)
						{
							result /= MS_PER_H;
6773
							unit = "h";
6774 6775 6776 6777
						}
						else if (result % MS_PER_MIN == 0)
						{
							result /= MS_PER_MIN;
6778
							unit = "min";
6779 6780 6781 6782
						}
						else if (result % MS_PER_S == 0)
						{
							result /= MS_PER_S;
6783
							unit = "s";
6784 6785 6786
						}
						else
						{
6787
							unit = "ms";
6788 6789 6790
						}
					}
					else
6791
						unit = "";
6792

6793 6794
					snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
							 result, unit);
6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817
					val = buffer;
				}
			}
			break;

		case PGC_REAL:
			{
				struct config_real *conf = (struct config_real *) record;

				if (conf->show_hook)
					val = (*conf->show_hook) ();
				else
				{
					snprintf(buffer, sizeof(buffer), "%g",
							 *conf->variable);
					val = buffer;
				}
			}
			break;

		case PGC_STRING:
			{
				struct config_string *conf = (struct config_string *) record;
6818

6819 6820 6821 6822 6823
				if (conf->show_hook)
					val = (*conf->show_hook) ();
				else if (*conf->variable && **conf->variable)
					val = *conf->variable;
				else
6824
					val = "";
6825 6826
			}
			break;
6827

6828 6829 6830 6831
		case PGC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) record;

6832
				if (conf->show_hook)
6833 6834
					val = (*conf->show_hook) ();
				else
6835
					val = config_enum_lookup_by_value(conf, *conf->variable);
6836 6837 6838
			}
			break;

6839 6840 6841 6842 6843
		default:
			/* just to keep compiler quiet */
			val = "???";
			break;
	}
6844

6845
	return pstrdup(val);
6846
}
6847 6848


6849 6850 6851 6852 6853 6854 6855
/*
 * Attempt (badly) to detect if a proposed new GUC setting is the same
 * as the current value.
 *
 * XXX this does not really work because it doesn't account for the
 * effects of canonicalization of string values by assign_hooks.
 */
6856
static bool
B
Bruce Momjian 已提交
6857
is_newvalue_equal(struct config_generic * record, const char *newvalue)
6858
{
6859 6860 6861
	/* newvalue == NULL isn't supported */
	Assert(newvalue != NULL);

6862 6863 6864
	switch (record->vartype)
	{
		case PGC_BOOL:
B
Bruce Momjian 已提交
6865 6866 6867
			{
				struct config_bool *conf = (struct config_bool *) record;
				bool		newval;
6868

6869 6870
				return parse_bool(newvalue, &newval)
					&& *conf->variable == newval;
B
Bruce Momjian 已提交
6871
			}
6872
		case PGC_INT:
B
Bruce Momjian 已提交
6873 6874 6875
			{
				struct config_int *conf = (struct config_int *) record;
				int			newval;
6876

6877 6878
				return parse_int(newvalue, &newval, record->flags, NULL)
					&& *conf->variable == newval;
B
Bruce Momjian 已提交
6879
			}
6880
		case PGC_REAL:
B
Bruce Momjian 已提交
6881 6882 6883
			{
				struct config_real *conf = (struct config_real *) record;
				double		newval;
6884

6885 6886
				return parse_real(newvalue, &newval)
					&& *conf->variable == newval;
B
Bruce Momjian 已提交
6887
			}
6888
		case PGC_STRING:
B
Bruce Momjian 已提交
6889 6890
			{
				struct config_string *conf = (struct config_string *) record;
6891

6892 6893
				return *conf->variable != NULL &&
					strcmp(*conf->variable, newvalue) == 0;
B
Bruce Momjian 已提交
6894
			}
6895 6896 6897 6898 6899 6900

		case PGC_ENUM:
			{
				struct config_enum *conf = (struct config_enum *) record;
				int			newval;

A
Alvaro Herrera 已提交
6901 6902
				return config_enum_lookup_by_name(conf, newvalue, &newval) &&
					*conf->variable == newval;
6903
			}
6904 6905 6906 6907 6908 6909
	}

	return false;
}


B
Bruce Momjian 已提交
6910
#ifdef EXEC_BACKEND
6911

B
Bruce Momjian 已提交
6912
/*
6913
 *	These routines dump out all non-default GUC options into a binary
B
Bruce Momjian 已提交
6914 6915 6916 6917 6918 6919
 *	file that is read by all exec'ed backends.  The format is:
 *
 *		variable name, string, null terminated
 *		variable value, string, null terminated
 *		variable source, integer
 */
6920
static void
6921
write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
6922 6923 6924 6925 6926 6927 6928 6929 6930 6931
{
	if (gconf->source == PGC_S_DEFAULT)
		return;

	fprintf(fp, "%s", gconf->name);
	fputc(0, fp);

	switch (gconf->vartype)
	{
		case PGC_BOOL:
6932 6933
			{
				struct config_bool *conf = (struct config_bool *) gconf;
6934

6935 6936 6937 6938 6939 6940
				if (*conf->variable)
					fprintf(fp, "true");
				else
					fprintf(fp, "false");
			}
			break;
6941 6942

		case PGC_INT:
6943 6944
			{
				struct config_int *conf = (struct config_int *) gconf;
6945

6946 6947 6948
				fprintf(fp, "%d", *conf->variable);
			}
			break;
6949 6950

		case PGC_REAL:
6951 6952
			{
				struct config_real *conf = (struct config_real *) gconf;
6953

6954 6955 6956 6957
				/* Could lose precision here? */
				fprintf(fp, "%f", *conf->variable);
			}
			break;
6958 6959

		case PGC_STRING:
6960 6961
			{
				struct config_string *conf = (struct config_string *) gconf;
6962

6963 6964 6965
				fprintf(fp, "%s", *conf->variable);
			}
			break;
6966 6967

		case PGC_ENUM:
6968 6969 6970 6971 6972 6973 6974
			{
				struct config_enum *conf = (struct config_enum *) gconf;

				fprintf(fp, "%s",
						config_enum_lookup_by_value(conf, *conf->variable));
			}
			break;
6975 6976 6977 6978 6979 6980 6981
	}

	fputc(0, fp);

	fwrite(&gconf->source, sizeof(gconf->source), 1, fp);
}

B
Bruce Momjian 已提交
6982 6983 6984
void
write_nondefault_variables(GucContext context)
{
6985 6986
	int			elevel;
	FILE	   *fp;
6987 6988
	struct config_generic *cvc_conf;
	int			i;
B
Bruce Momjian 已提交
6989 6990

	Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
6991 6992

	elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
B
Bruce Momjian 已提交
6993 6994 6995 6996

	/*
	 * Open file
	 */
6997
	fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
6998 6999
	if (!fp)
	{
7000 7001
		ereport(elevel,
				(errcode_for_file_access(),
7002 7003
				 errmsg("could not write to file \"%s\": %m",
						CONFIG_EXEC_PARAMS_NEW)));
B
Bruce Momjian 已提交
7004 7005 7006
		return;
	}

7007 7008 7009 7010 7011 7012 7013 7014
	/*
	 * custom_variable_classes must be written out first; otherwise we might
	 * reject custom variable values while reading the file.
	 */
	cvc_conf = find_option("custom_variable_classes", false, ERROR);
	if (cvc_conf)
		write_one_nondefault_variable(fp, cvc_conf);

B
Bruce Momjian 已提交
7015 7016 7017 7018
	for (i = 0; i < num_guc_variables; i++)
	{
		struct config_generic *gconf = guc_variables[i];

7019 7020
		if (gconf != cvc_conf)
			write_one_nondefault_variable(fp, gconf);
B
Bruce Momjian 已提交
7021 7022
	}

7023 7024 7025 7026
	if (FreeFile(fp))
	{
		ereport(elevel,
				(errcode_for_file_access(),
7027 7028
				 errmsg("could not write to file \"%s\": %m",
						CONFIG_EXEC_PARAMS_NEW)));
7029 7030 7031
		return;
	}

7032
	/*
B
Bruce Momjian 已提交
7033 7034
	 * Put new file in place.  This could delay on Win32, but we don't hold
	 * any exclusive locks.
7035
	 */
7036
	rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
B
Bruce Momjian 已提交
7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047
}


/*
 *	Read string, including null byte from file
 *
 *	Return NULL on EOF and nothing read
 */
static char *
read_string_with_null(FILE *fp)
{
7048 7049 7050 7051
	int			i = 0,
				ch,
				maxlen = 256;
	char	   *str = NULL;
B
Bruce Momjian 已提交
7052 7053 7054 7055 7056 7057 7058 7059

	do
	{
		if ((ch = fgetc(fp)) == EOF)
		{
			if (i == 0)
				return NULL;
			else
7060
				elog(FATAL, "invalid format of exec config params file");
B
Bruce Momjian 已提交
7061 7062
		}
		if (i == 0)
7063
			str = guc_malloc(FATAL, maxlen);
B
Bruce Momjian 已提交
7064
		else if (i == maxlen)
7065
			str = guc_realloc(FATAL, str, maxlen *= 2);
B
Bruce Momjian 已提交
7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079
		str[i++] = ch;
	} while (ch != 0);

	return str;
}


/*
 *	This routine loads a previous postmaster dump of its non-default
 *	settings.
 */
void
read_nondefault_variables(void)
{
7080 7081 7082 7083
	FILE	   *fp;
	char	   *varname,
			   *varvalue;
	int			varsource;
B
Bruce Momjian 已提交
7084 7085 7086 7087

	/*
	 * Open file
	 */
7088
	fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
7089 7090 7091 7092
	if (!fp)
	{
		/* File not found is fine */
		if (errno != ENOENT)
7093 7094
			ereport(FATAL,
					(errcode_for_file_access(),
7095 7096
					 errmsg("could not read from file \"%s\": %m",
							CONFIG_EXEC_PARAMS)));
B
Bruce Momjian 已提交
7097
		return;
7098
	}
B
Bruce Momjian 已提交
7099

7100
	for (;;)
B
Bruce Momjian 已提交
7101
	{
7102 7103
		struct config_generic *record;

B
Bruce Momjian 已提交
7104 7105 7106
		if ((varname = read_string_with_null(fp)) == NULL)
			break;

7107
		if ((record = find_option(varname, true, FATAL)) == NULL)
B
Bruce Momjian 已提交
7108
			elog(FATAL, "failed to locate variable %s in exec config params file", varname);
B
Bruce Momjian 已提交
7109
		if ((varvalue = read_string_with_null(fp)) == NULL)
7110
			elog(FATAL, "invalid format of exec config params file");
7111
		if (fread(&varsource, sizeof(varsource), 1, fp) == 0)
7112
			elog(FATAL, "invalid format of exec config params file");
B
Bruce Momjian 已提交
7113

7114
		(void) set_config_option(varname, varvalue, record->context,
7115
								 varsource, GUC_ACTION_SET, true);
B
Bruce Momjian 已提交
7116 7117 7118 7119 7120 7121
		free(varname);
		free(varvalue);
	}

	FreeFile(fp);
}
B
Bruce Momjian 已提交
7122
#endif   /* EXEC_BACKEND */
B
Bruce Momjian 已提交
7123 7124


7125 7126 7127 7128 7129 7130 7131 7132
/*
 * A little "long argument" simulation, although not quite GNU
 * compliant. Takes a string of the form "some-option=some value" and
 * returns name = "some_option" and value = "some value" in malloc'ed
 * storage. Note that '-' is converted to '_' in the option name. If
 * there is no '=' in the input string then value will be NULL.
 */
void
B
Bruce Momjian 已提交
7133
ParseLongOption(const char *string, char **name, char **value)
7134
{
B
Bruce Momjian 已提交
7135 7136
	size_t		equal_pos;
	char	   *cp;
7137 7138 7139 7140 7141 7142 7143 7144 7145

	AssertArg(string);
	AssertArg(name);
	AssertArg(value);

	equal_pos = strcspn(string, "=");

	if (string[equal_pos] == '=')
	{
7146
		*name = guc_malloc(FATAL, equal_pos + 1);
7147
		strlcpy(*name, string, equal_pos + 1);
7148

7149
		*value = guc_strdup(FATAL, &string[equal_pos + 1]);
7150
	}
B
Bruce Momjian 已提交
7151
	else
7152
	{
7153
		/* no equal sign in string */
7154
		*name = guc_strdup(FATAL, string);
7155 7156 7157
		*value = NULL;
	}

B
Bruce Momjian 已提交
7158
	for (cp = *name; *cp; cp++)
7159 7160 7161
		if (*cp == '-')
			*cp = '_';
}
7162 7163


7164
/*
7165
 * Handle options fetched from pg_db_role_setting.setconfig,
B
Bruce Momjian 已提交
7166
 * pg_proc.proconfig, etc.	Caller must specify proper context/source/action.
7167
 *
7168
 * The array parameter must be an array of TEXT (it must not be NULL).
7169
 */
7170
void
7171
ProcessGUCArray(ArrayType *array,
7172
				GucContext context, GucSource source, GucAction action)
7173
{
B
Bruce Momjian 已提交
7174
	int			i;
7175

7176
	Assert(array != NULL);
7177 7178 7179
	Assert(ARR_ELEMTYPE(array) == TEXTOID);
	Assert(ARR_NDIM(array) == 1);
	Assert(ARR_LBOUND(array)[0] == 1);
7180 7181 7182 7183 7184 7185 7186 7187 7188 7189

	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
	{
		Datum		d;
		bool		isnull;
		char	   *s;
		char	   *name;
		char	   *value;

		d = array_ref(array, 1, &i,
B
Bruce Momjian 已提交
7190 7191 7192 7193
					  -1 /* varlenarray */ ,
					  -1 /* TEXT's typlen */ ,
					  false /* TEXT's typbyval */ ,
					  'i' /* TEXT's typalign */ ,
7194 7195 7196 7197 7198
					  &isnull);

		if (isnull)
			continue;

7199
		s = TextDatumGetCString(d);
7200

7201 7202 7203
		ParseLongOption(s, &name, &value);
		if (!value)
		{
7204 7205
			ereport(WARNING,
					(errcode(ERRCODE_SYNTAX_ERROR),
7206 7207
					 errmsg("could not parse setting for parameter \"%s\"",
							name)));
7208
			free(name);
B
Bruce Momjian 已提交
7209
			continue;
7210 7211
		}

7212
		(void) set_config_option(name, value, context, source, action, true);
7213 7214 7215 7216

		free(name);
		if (value)
			free(value);
7217
		pfree(s);
7218 7219 7220 7221
	}
}


7222 7223 7224 7225
/*
 * Add an entry to an option array.  The array parameter may be NULL
 * to indicate the current table entry is NULL.
 */
7226 7227 7228
ArrayType *
GUCArrayAdd(ArrayType *array, const char *name, const char *value)
{
7229
	struct config_generic *record;
7230 7231 7232 7233 7234 7235 7236
	Datum		datum;
	char	   *newval;
	ArrayType  *a;

	Assert(name);
	Assert(value);

7237 7238
	/* test if the option is valid and we're allowed to set it */
	(void) validate_option_array_item(name, value, false);
7239

7240 7241 7242 7243
	/* normalize name (converts obsolete GUC names to modern spellings) */
	record = find_option(name, false, WARNING);
	if (record)
		name = record->name;
7244

7245
	/* build new item for array */
7246 7247
	newval = palloc(strlen(name) + 1 + strlen(value) + 1);
	sprintf(newval, "%s=%s", name, value);
7248
	datum = CStringGetTextDatum(newval);
B
Bruce Momjian 已提交
7249

7250 7251
	if (array)
	{
B
Bruce Momjian 已提交
7252 7253 7254
		int			index;
		bool		isnull;
		int			i;
7255

7256 7257 7258 7259
		Assert(ARR_ELEMTYPE(array) == TEXTOID);
		Assert(ARR_NDIM(array) == 1);
		Assert(ARR_LBOUND(array)[0] == 1);

B
Bruce Momjian 已提交
7260
		index = ARR_DIMS(array)[0] + 1; /* add after end */
7261 7262 7263 7264 7265 7266 7267

		for (i = 1; i <= ARR_DIMS(array)[0]; i++)
		{
			Datum		d;
			char	   *current;

			d = array_ref(array, 1, &i,
B
Bruce Momjian 已提交
7268 7269 7270 7271
						  -1 /* varlenarray */ ,
						  -1 /* TEXT's typlen */ ,
						  false /* TEXT's typbyval */ ,
						  'i' /* TEXT's typalign */ ,
7272
						  &isnull);
7273 7274
			if (isnull)
				continue;
7275
			current = TextDatumGetCString(d);
7276 7277

			/* check for match up through and including '=' */
B
Bruce Momjian 已提交
7278
			if (strncmp(current, newval, strlen(name) + 1) == 0)
7279 7280 7281 7282 7283 7284
			{
				index = i;
				break;
			}
		}

7285 7286
		a = array_set(array, 1, &index,
					  datum,
7287 7288
					  false,
					  -1 /* varlena array */ ,
B
Bruce Momjian 已提交
7289 7290
					  -1 /* TEXT's typlen */ ,
					  false /* TEXT's typbyval */ ,
7291
					  'i' /* TEXT's typalign */ );
7292 7293
	}
	else
7294 7295 7296
		a = construct_array(&datum, 1,
							TEXTOID,
							-1, false, 'i');
7297 7298 7299 7300 7301

	return a;
}


7302 7303 7304 7305 7306
/*
 * Delete an entry from an option array.  The array parameter may be NULL
 * to indicate the current table entry is NULL.  Also, if the return value
 * is NULL then a null should be stored.
 */
7307 7308 7309
ArrayType *
GUCArrayDelete(ArrayType *array, const char *name)
{
7310
	struct config_generic *record;
B
Bruce Momjian 已提交
7311 7312 7313
	ArrayType  *newarray;
	int			i;
	int			index;
7314 7315 7316

	Assert(name);

7317 7318
	/* test if the option is valid and we're allowed to set it */
	(void) validate_option_array_item(name, NULL, false);
7319

7320 7321 7322 7323
	/* normalize name (converts obsolete GUC names to modern spellings) */
	record = find_option(name, false, WARNING);
	if (record)
		name = record->name;
7324

7325 7326 7327 7328 7329
	/* if array is currently null, then surely nothing to delete */
	if (!array)
		return NULL;

	newarray = NULL;
7330 7331 7332 7333 7334 7335 7336 7337 7338
	index = 1;

	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
	{
		Datum		d;
		char	   *val;
		bool		isnull;

		d = array_ref(array, 1, &i,
B
Bruce Momjian 已提交
7339 7340 7341 7342
					  -1 /* varlenarray */ ,
					  -1 /* TEXT's typlen */ ,
					  false /* TEXT's typbyval */ ,
					  'i' /* TEXT's typalign */ ,
7343
					  &isnull);
7344 7345
		if (isnull)
			continue;
7346
		val = TextDatumGetCString(d);
7347

7348
		/* ignore entry if it's what we want to delete */
B
Bruce Momjian 已提交
7349
		if (strncmp(val, name, strlen(name)) == 0
7350 7351 7352
			&& val[strlen(name)] == '=')
			continue;

7353 7354 7355 7356
		/* else add it to the output array */
		if (newarray)
			newarray = array_set(newarray, 1, &index,
								 d,
7357
								 false,
7358 7359 7360
								 -1 /* varlenarray */ ,
								 -1 /* TEXT's typlen */ ,
								 false /* TEXT's typbyval */ ,
7361
								 'i' /* TEXT's typalign */ );
7362 7363 7364 7365 7366
		else
			newarray = construct_array(&d, 1,
									   TEXTOID,
									   -1, false, 'i');

7367 7368 7369 7370 7371
		index++;
	}

	return newarray;
}
7372

7373

7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389
/*
 * Given a GUC array, delete all settings from it that our permission
 * level allows: if superuser, delete them all; if regular user, only
 * those that are PGC_USERSET
 */
ArrayType *
GUCArrayReset(ArrayType *array)
{
	ArrayType  *newarray;
	int			i;
	int			index;

	/* if array is currently null, nothing to do */
	if (!array)
		return NULL;

7390
	/* if we're superuser, we can delete everything, so just do it */
7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416
	if (superuser())
		return NULL;

	newarray = NULL;
	index = 1;

	for (i = 1; i <= ARR_DIMS(array)[0]; i++)
	{
		Datum		d;
		char	   *val;
		char	   *eqsgn;
		bool		isnull;

		d = array_ref(array, 1, &i,
					  -1 /* varlenarray */ ,
					  -1 /* TEXT's typlen */ ,
					  false /* TEXT's typbyval */ ,
					  'i' /* TEXT's typalign */ ,
					  &isnull);
		if (isnull)
			continue;
		val = TextDatumGetCString(d);

		eqsgn = strchr(val, '=');
		*eqsgn = '\0';

7417 7418
		/* skip if we have permission to delete it */
		if (validate_option_array_item(val, NULL, true))
7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441
			continue;

		/* else add it to the output array */
		if (newarray)
			newarray = array_set(newarray, 1, &index,
								 d,
								 false,
								 -1 /* varlenarray */ ,
								 -1 /* TEXT's typlen */ ,
								 false /* TEXT's typbyval */ ,
								 'i' /* TEXT's typalign */ );
		else
			newarray = construct_array(&d, 1,
									   TEXTOID,
									   -1, false, 'i');

		index++;
		pfree(val);
	}

	return newarray;
}

7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524
/*
 * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
 *
 * name is the option name.  value is the proposed value for the Add case,
 * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
 * not an error to have no permissions to set the option.
 *
 * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
 * have permission to change this option (all other error cases result in an
 * error being thrown).
 */
static bool
validate_option_array_item(const char *name, const char *value,
						   bool skipIfNoPermissions)

{
	struct config_generic *gconf;

	/*
	 * There are three cases to consider:
	 *
	 * name is a known GUC variable.  Check the value normally, check
	 * permissions normally (ie, allow if variable is USERSET, or if it's
	 * SUSET and user is superuser).
	 *
	 * name is not known, but exists or can be created as a placeholder
	 * (implying it has a prefix listed in custom_variable_classes).
	 * We allow this case if you're a superuser, otherwise not.  Superusers
	 * are assumed to know what they're doing.  We can't allow it for other
	 * users, because when the placeholder is resolved it might turn out to
	 * be a SUSET variable; define_custom_variable assumes we checked that.
	 *
	 * name is not known and can't be created as a placeholder.  Throw error,
	 * unless skipIfNoPermissions is true, in which case return FALSE.
	 * (It's tempting to allow this case to superusers, if the name is
	 * qualified but not listed in custom_variable_classes.  That would
	 * ease restoring of dumps containing ALTER ROLE/DATABASE SET.  However,
	 * it's not clear that this usage justifies such a loss of error checking.
	 * You can always fix custom_variable_classes before you restore.)
	 */
	gconf = find_option(name, true, WARNING);
	if (!gconf)
	{
		/* not known, failed to make a placeholder */
		if (skipIfNoPermissions)
			return false;
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("unrecognized configuration parameter \"%s\"", name)));
	}

	if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
	{
		/*
		 * We cannot do any meaningful check on the value, so only permissions
		 * are useful to check.
		 */
		if (superuser())
			return true;
		if (skipIfNoPermissions)
			return false;
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied to set parameter \"%s\"", name)));
	}

	/* manual permissions check so we can avoid an error being thrown */
	if (gconf->context == PGC_USERSET)
		/* ok */ ;
	else if (gconf->context == PGC_SUSET && superuser())
		/* ok */ ;
	else if (skipIfNoPermissions)
		return false;
	/* if a permissions error should be thrown, let set_config_option do it */

	/* test for permissions and valid option value */
	set_config_option(name, value,
					  superuser() ? PGC_SUSET : PGC_USERSET,
					  PGC_S_TEST, GUC_ACTION_SET, false);

	return true;
}

7525 7526

/*
7527
 * assign_hook and show_hook subroutines
7528 7529
 */

7530 7531 7532
static const char *
assign_log_destination(const char *value, bool doit, GucSource source)
{
B
Bruce Momjian 已提交
7533 7534 7535 7536 7537
	char	   *rawstring;
	List	   *elemlist;
	ListCell   *l;
	int			newlogdest = 0;

7538 7539 7540 7541
	/* Need a modifiable copy of string */
	rawstring = pstrdup(value);

	/* Parse string into list of identifiers */
B
Bruce Momjian 已提交
7542
	if (!SplitIdentifierString(rawstring, ',', &elemlist))
7543 7544 7545
	{
		/* syntax error in list */
		pfree(rawstring);
7546
		list_free(elemlist);
7547 7548
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7549
		   errmsg("invalid list syntax for parameter \"log_destination\"")));
7550 7551 7552 7553 7554
		return NULL;
	}

	foreach(l, elemlist)
	{
B
Bruce Momjian 已提交
7555 7556 7557
		char	   *tok = (char *) lfirst(l);

		if (pg_strcasecmp(tok, "stderr") == 0)
7558
			newlogdest |= LOG_DESTINATION_STDERR;
7559
		else if (pg_strcasecmp(tok, "csvlog") == 0)
B
Bruce Momjian 已提交
7560
			newlogdest |= LOG_DESTINATION_CSVLOG;
7561
#ifdef HAVE_SYSLOG
B
Bruce Momjian 已提交
7562
		else if (pg_strcasecmp(tok, "syslog") == 0)
7563 7564 7565
			newlogdest |= LOG_DESTINATION_SYSLOG;
#endif
#ifdef WIN32
B
Bruce Momjian 已提交
7566
		else if (pg_strcasecmp(tok, "eventlog") == 0)
7567 7568
			newlogdest |= LOG_DESTINATION_EVENTLOG;
#endif
B
Bruce Momjian 已提交
7569 7570
		else
		{
7571 7572
			ereport(GUC_complaint_elevel(source),
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
7573 7574
				  errmsg("unrecognized \"log_destination\" key word: \"%s\"",
						 tok)));
7575
			pfree(rawstring);
7576
			list_free(elemlist);
7577 7578 7579 7580
			return NULL;
		}
	}

7581 7582 7583
	if (doit)
		Log_destination = newlogdest;

7584
	pfree(rawstring);
7585
	list_free(elemlist);
7586 7587 7588 7589

	return value;
}

7590 7591
#ifdef HAVE_SYSLOG

7592 7593
static bool
assign_syslog_facility(int newval, bool doit, GucSource source)
7594
{
7595 7596
	if (doit)
		set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
7597
							  newval);
7598

7599
	return true;
7600
}
7601 7602 7603 7604 7605 7606 7607 7608 7609

static const char *
assign_syslog_ident(const char *ident, bool doit, GucSource source)
{
	if (doit)
		set_syslog_parameters(ident, syslog_facility);

	return ident;
}
B
Bruce Momjian 已提交
7610
#endif   /* HAVE_SYSLOG */
7611 7612


7613 7614
static bool
assign_session_replication_role(int newval, bool doit, GucSource source)
7615
{
7616 7617 7618 7619
	/*
	 * Must flush the plan cache when changing replication role; but don't
	 * flush unnecessarily.
	 */
7620
	if (doit && SessionReplicationRole != newval)
7621 7622 7623 7624
	{
		ResetPlanCache();
	}

7625
	return true;
7626 7627
}

7628 7629 7630 7631
static const char *
show_num_temp_buffers(void)
{
	/*
B
Bruce Momjian 已提交
7632 7633
	 * We show the GUC var until local buffers have been initialized, and
	 * NLocBuffer afterwards.
7634 7635 7636 7637 7638 7639 7640
	 */
	static char nbuf[32];

	sprintf(nbuf, "%d", NLocBuffer ? NLocBuffer : num_temp_buffers);
	return nbuf;
}

7641
static bool
7642
assign_phony_autocommit(bool newval, bool doit, GucSource source)
7643 7644 7645
{
	if (!newval)
	{
7646 7647 7648
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("SET AUTOCOMMIT TO OFF is no longer supported")));
7649 7650 7651 7652 7653
		return false;
	}
	return true;
}

7654 7655 7656
static const char *
assign_custom_variable_classes(const char *newval, bool doit, GucSource source)
{
B
Bruce Momjian 已提交
7657 7658
	/*
	 * Check syntax. newval must be a comma separated list of identifiers.
7659
	 * Whitespace is allowed but removed from the result.
7660
	 */
B
Bruce Momjian 已提交
7661
	bool		hasSpaceAfterToken = false;
7662
	const char *cp = newval;
B
Bruce Momjian 已提交
7663
	int			symLen = 0;
7664
	char		c;
7665 7666 7667
	StringInfoData buf;

	initStringInfo(&buf);
7668
	while ((c = *cp++) != '\0')
7669
	{
7670
		if (isspace((unsigned char) c))
7671
		{
B
Bruce Momjian 已提交
7672
			if (symLen > 0)
7673 7674 7675 7676
				hasSpaceAfterToken = true;
			continue;
		}

B
Bruce Momjian 已提交
7677
		if (c == ',')
7678
		{
7679
			if (symLen > 0)		/* terminate identifier */
7680 7681
			{
				appendStringInfoChar(&buf, ',');
7682
				symLen = 0;
7683
			}
7684
			hasSpaceAfterToken = false;
7685 7686 7687
			continue;
		}

7688
		if (hasSpaceAfterToken || !(isalnum((unsigned char) c) || c == '_'))
7689
		{
B
Bruce Momjian 已提交
7690
			/*
7691 7692
			 * Syntax error due to token following space after token or
			 * non-identifier character
7693
			 */
7694
			pfree(buf.data);
7695 7696
			return NULL;
		}
7697
		appendStringInfoChar(&buf, c);
7698 7699 7700
		symLen++;
	}

7701
	/* Remove stray ',' at end */
B
Bruce Momjian 已提交
7702
	if (symLen == 0 && buf.len > 0)
7703
		buf.data[--buf.len] = '\0';
7704

7705 7706
	/* GUC wants the result malloc'd */
	newval = guc_strdup(LOG, buf.data);
7707 7708 7709 7710

	pfree(buf.data);
	return newval;
}
7711

7712 7713 7714 7715 7716
static bool
assign_debug_assertions(bool newval, bool doit, GucSource source)
{
#ifndef USE_ASSERT_CHECKING
	if (newval)
7717 7718
	{
		ereport(GUC_complaint_elevel(source),
7719
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
7720
			   errmsg("assertion checking is not supported by this build")));
7721 7722
		return false;
	}
7723 7724 7725 7726
#endif
	return true;
}

7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741
static bool
assign_bonjour(bool newval, bool doit, GucSource source)
{
#ifndef USE_BONJOUR
	if (newval)
	{
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("Bonjour is not supported by this build")));
		return false;
	}
#endif
	return true;
}

7742 7743 7744 7745 7746
static bool
assign_ssl(bool newval, bool doit, GucSource source)
{
#ifndef USE_SSL
	if (newval)
7747 7748
	{
		ereport(GUC_complaint_elevel(source),
7749 7750
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("SSL is not supported by this build")));
7751 7752
		return false;
	}
7753 7754 7755 7756
#endif
	return true;
}

7757 7758 7759
static bool
assign_stage_log_stats(bool newval, bool doit, GucSource source)
{
7760
	if (newval && log_statement_stats)
7761
	{
7762 7763 7764
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("cannot enable parameter when \"log_statement_stats\" is true")));
7765
		/* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
7766
		if (source != PGC_S_OVERRIDE)
7767
			return false;
7768 7769 7770 7771 7772 7773 7774
	}
	return true;
}

static bool
assign_log_stats(bool newval, bool doit, GucSource source)
{
7775 7776
	if (newval &&
		(log_parser_stats || log_planner_stats || log_executor_stats))
7777
	{
7778 7779 7780 7781 7782
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("cannot enable \"log_statement_stats\" when "
						"\"log_parser_stats\", \"log_planner_stats\", "
						"or \"log_executor_stats\" is true")));
7783
		/* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
7784
		if (source != PGC_S_OVERRIDE)
7785
			return false;
7786 7787 7788 7789
	}
	return true;
}

7790 7791 7792
static bool
assign_transaction_read_only(bool newval, bool doit, GucSource source)
{
7793 7794 7795
	/* Can't go to r/w mode inside a r/o transaction */
	if (newval == false && XactReadOnly && IsSubTransaction())
	{
7796 7797 7798
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("cannot set transaction read-write mode inside a read-only transaction")));
7799
		/* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
7800
		if (source != PGC_S_OVERRIDE)
7801
			return false;
7802
	}
7803 7804 7805 7806 7807 7808

	/* Can't go to r/w mode while recovery is still active */
	if (newval == false && XactReadOnly && RecoveryInProgress())
	{
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
7809
		  errmsg("cannot set transaction read-write mode during recovery")));
7810 7811 7812 7813 7814
		/* source == PGC_S_OVERRIDE means do it anyway, eg at xact abort */
		if (source != PGC_S_OVERRIDE)
			return false;
	}

7815 7816
	return true;
}
7817

7818 7819 7820 7821 7822
static const char *
assign_canonical_path(const char *newval, bool doit, GucSource source)
{
	if (doit)
	{
B
Bruce Momjian 已提交
7823 7824
		char	   *canon_val = guc_strdup(ERROR, newval);

7825 7826 7827 7828 7829 7830 7831
		canonicalize_path(canon_val);
		return canon_val;
	}
	else
		return newval;
}

7832 7833 7834
static const char *
assign_timezone_abbreviations(const char *newval, bool doit, GucSource source)
{
7835 7836 7837 7838
	/*
	 * The powerup value shown above for timezone_abbreviations is "UNKNOWN".
	 * When we see this we just do nothing.  If this value isn't overridden
	 * from the config file then pg_timezone_abbrev_initialize() will
B
Bruce Momjian 已提交
7839 7840 7841 7842 7843 7844 7845 7846
	 * eventually replace it with "Default".  This hack has two purposes: to
	 * avoid wasting cycles loading values that might soon be overridden from
	 * the config file, and to avoid trying to read the timezone abbrev files
	 * during InitializeGUCOptions().  The latter doesn't work in an
	 * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
	 * we can't locate PGSHAREDIR.  (Essentially the same hack is used to
	 * delay initializing TimeZone ... if we have any more, we should try to
	 * clean up and centralize this mechanism ...)
7847 7848 7849 7850 7851 7852
	 */
	if (strcmp(newval, "UNKNOWN") == 0)
	{
		return newval;
	}

7853
	/* Loading abbrev file is expensive, so only do it when value changes */
7854 7855
	if (timezone_abbreviations_string == NULL ||
		strcmp(timezone_abbreviations_string, newval) != 0)
7856
	{
B
Bruce Momjian 已提交
7857
		int			elevel;
7858 7859 7860

		/*
		 * If reading config file, only the postmaster should bleat loudly
B
Bruce Momjian 已提交
7861
		 * about problems.	Otherwise, it's just this one process doing it,
7862 7863 7864
		 * and we use WARNING message level.
		 */
		if (source == PGC_S_FILE)
7865
			elevel = IsUnderPostmaster ? DEBUG3 : LOG;
7866 7867 7868 7869 7870 7871 7872 7873
		else
			elevel = WARNING;
		if (!load_tzoffsets(newval, doit, elevel))
			return NULL;
	}
	return newval;
}

7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889
/*
 * pg_timezone_abbrev_initialize --- set default value if not done already
 *
 * This is called after initial loading of postgresql.conf.  If no
 * timezone_abbreviations setting was found therein, select default.
 */
void
pg_timezone_abbrev_initialize(void)
{
	if (strcmp(timezone_abbreviations_string, "UNKNOWN") == 0)
	{
		SetConfigOption("timezone_abbreviations", "Default",
						PGC_POSTMASTER, PGC_S_ARGV);
	}
}

7890 7891 7892
static const char *
show_archive_command(void)
{
7893
	if (XLogArchivingActive())
7894 7895 7896 7897 7898
		return XLogArchiveCommand;
	else
		return "(disabled)";
}

7899 7900 7901
static bool
assign_tcp_keepalives_idle(int newval, bool doit, GucSource source)
{
7902
	if (doit)
7903 7904 7905 7906 7907 7908 7909 7910
		return (pq_setkeepalivesidle(newval, MyProcPort) == STATUS_OK);

	return true;
}

static const char *
show_tcp_keepalives_idle(void)
{
7911 7912 7913
	static char nbuf[16];

	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
7914 7915 7916 7917 7918 7919
	return nbuf;
}

static bool
assign_tcp_keepalives_interval(int newval, bool doit, GucSource source)
{
7920
	if (doit)
7921 7922 7923 7924 7925 7926 7927 7928
		return (pq_setkeepalivesinterval(newval, MyProcPort) == STATUS_OK);

	return true;
}

static const char *
show_tcp_keepalives_interval(void)
{
7929 7930 7931
	static char nbuf[16];

	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
7932 7933 7934 7935 7936 7937
	return nbuf;
}

static bool
assign_tcp_keepalives_count(int newval, bool doit, GucSource source)
{
7938
	if (doit)
7939 7940 7941 7942 7943 7944 7945 7946
		return (pq_setkeepalivescount(newval, MyProcPort) == STATUS_OK);

	return true;
}

static const char *
show_tcp_keepalives_count(void)
{
7947 7948 7949
	static char nbuf[16];

	snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
7950 7951
	return nbuf;
}
7952

7953 7954 7955
static bool
assign_maxconnections(int newval, bool doit, GucSource source)
{
7956
	if (newval + autovacuum_max_workers + 1 > INT_MAX / 4)
7957
		return false;
7958

7959
	if (doit)
7960
		MaxBackends = newval + autovacuum_max_workers + 1;
7961 7962 7963 7964 7965 7966 7967

	return true;
}

static bool
assign_autovacuum_max_workers(int newval, bool doit, GucSource source)
{
7968
	if (MaxConnections + newval + 1 > INT_MAX / 4)
7969
		return false;
7970

7971
	if (doit)
7972
		MaxBackends = MaxConnections + newval + 1;
7973 7974 7975

	return true;
}
7976

7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991
static bool
assign_effective_io_concurrency(int newval, bool doit, GucSource source)
{
#ifdef USE_PREFETCH
	double		new_prefetch_pages = 0.0;
	int			i;

	/*----------
	 * The user-visible GUC parameter is the number of drives (spindles),
	 * which we need to translate to a number-of-pages-to-prefetch target.
	 *
	 * The expected number of prefetch pages needed to keep N drives busy is:
	 *
	 * drives |   I/O requests
	 * -------+----------------
7992 7993 7994 7995 7996
	 *		1 |   1
	 *		2 |   2/1 + 2/2 = 3
	 *		3 |   3/1 + 3/2 + 3/3 = 5 1/2
	 *		4 |   4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
	 *		n |   n * H(n)
7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028
	 *
	 * This is called the "coupon collector problem" and H(n) is called the
	 * harmonic series.  This could be approximated by n * ln(n), but for
	 * reasonable numbers of drives we might as well just compute the series.
	 *
	 * Alternatively we could set the target to the number of pages necessary
	 * so that the expected number of active spindles is some arbitrary
	 * percentage of the total.  This sounds the same but is actually slightly
	 * different.  The result ends up being ln(1-P)/ln((n-1)/n) where P is
	 * that desired fraction.
	 *
	 * Experimental results show that both of these formulas aren't aggressive
	 * enough, but we don't really have any better proposals.
	 *
	 * Note that if newval = 0 (disabled), we must set target = 0.
	 *----------
	 */

	for (i = 1; i <= newval; i++)
		new_prefetch_pages += (double) newval / (double) i;

	/* This range check shouldn't fail, but let's be paranoid */
	if (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX)
	{
		if (doit)
			target_prefetch_pages = (int) rint(new_prefetch_pages);
		return true;
	}
	else
		return false;
#else
	return true;
8029
#endif   /* USE_PREFETCH */
8030 8031
}

8032 8033 8034 8035 8036
static const char *
assign_pgstat_temp_directory(const char *newval, bool doit, GucSource source)
{
	if (doit)
	{
8037 8038 8039 8040 8041 8042
		char	   *canon_val = guc_strdup(ERROR, newval);
		char	   *tname;
		char	   *fname;

		canonicalize_path(canon_val);

8043
		tname = guc_malloc(ERROR, strlen(canon_val) + 12);		/* /pgstat.tmp */
8044
		sprintf(tname, "%s/pgstat.tmp", canon_val);
8045
		fname = guc_malloc(ERROR, strlen(canon_val) + 13);		/* /pgstat.stat */
8046 8047
		sprintf(fname, "%s/pgstat.stat", canon_val);

8048 8049
		if (pgstat_stat_tmpname)
			free(pgstat_stat_tmpname);
8050
		pgstat_stat_tmpname = tname;
8051 8052
		if (pgstat_stat_filename)
			free(pgstat_stat_filename);
8053
		pgstat_stat_filename = fname;
8054

8055
		return canon_val;
8056
	}
8057 8058
	else
		return newval;
8059 8060
}

8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084
static const char *
assign_application_name(const char *newval, bool doit, GucSource source)
{
	if (doit)
	{
		/* Only allow clean ASCII chars in the application name */
		char	   *repval = guc_strdup(ERROR, newval);
		char	   *p;

		for (p = repval; *p; p++)
		{
			if (*p < 32 || *p > 126)
				*p = '?';
		}

		/* Update the pg_stat_activity view */
		pgstat_report_appname(repval);

		return repval;
	}
	else
		return newval;
}

8085
#include "guc-file.c"