]> granicus.if.org Git - postgresql/blob - src/backend/utils/misc/guc.c
Update copyrights for 2013
[postgresql] / src / backend / utils / misc / guc.c
1 /*--------------------------------------------------------------------
2  * guc.c
3  *
4  * Support for grand unified configuration scheme, including SET
5  * command, configuration file, and command line options.
6  * See src/backend/utils/misc/README for more information.
7  *
8  *
9  * Copyright (c) 2000-2013, PostgreSQL Global Development Group
10  * Written by Peter Eisentraut <peter_e@gmx.net>.
11  *
12  * IDENTIFICATION
13  *        src/backend/utils/misc/guc.c
14  *
15  *--------------------------------------------------------------------
16  */
17 #include "postgres.h"
18
19 #include <ctype.h>
20 #include <float.h>
21 #include <math.h>
22 #include <limits.h>
23 #include <unistd.h>
24 #include <sys/stat.h>
25 #ifdef HAVE_SYSLOG
26 #include <syslog.h>
27 #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/libpq.h"
43 #include "libpq/pqformat.h"
44 #include "miscadmin.h"
45 #include "optimizer/cost.h"
46 #include "optimizer/geqo.h"
47 #include "optimizer/paths.h"
48 #include "optimizer/planmain.h"
49 #include "parser/parse_expr.h"
50 #include "parser/parse_type.h"
51 #include "parser/parser.h"
52 #include "parser/scansup.h"
53 #include "pgstat.h"
54 #include "postmaster/autovacuum.h"
55 #include "postmaster/bgworker.h"
56 #include "postmaster/bgwriter.h"
57 #include "postmaster/postmaster.h"
58 #include "postmaster/syslogger.h"
59 #include "postmaster/walwriter.h"
60 #include "replication/syncrep.h"
61 #include "replication/walreceiver.h"
62 #include "replication/walsender.h"
63 #include "storage/bufmgr.h"
64 #include "storage/standby.h"
65 #include "storage/fd.h"
66 #include "storage/proc.h"
67 #include "storage/predicate.h"
68 #include "tcop/tcopprot.h"
69 #include "tsearch/ts_cache.h"
70 #include "utils/builtins.h"
71 #include "utils/bytea.h"
72 #include "utils/guc_tables.h"
73 #include "utils/memutils.h"
74 #include "utils/pg_locale.h"
75 #include "utils/plancache.h"
76 #include "utils/portal.h"
77 #include "utils/ps_status.h"
78 #include "utils/snapmgr.h"
79 #include "utils/tzparser.h"
80 #include "utils/xml.h"
81
82 #ifndef PG_KRB_SRVTAB
83 #define PG_KRB_SRVTAB ""
84 #endif
85 #ifndef PG_KRB_SRVNAM
86 #define PG_KRB_SRVNAM ""
87 #endif
88
89 #define CONFIG_FILENAME "postgresql.conf"
90 #define HBA_FILENAME    "pg_hba.conf"
91 #define IDENT_FILENAME  "pg_ident.conf"
92
93 #ifdef EXEC_BACKEND
94 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
95 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
96 #endif
97
98 /* upper limit for GUC variables measured in kilobytes of memory */
99 /* note that various places assume the byte size fits in a "long" variable */
100 #if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
101 #define MAX_KILOBYTES   INT_MAX
102 #else
103 #define MAX_KILOBYTES   (INT_MAX / 1024)
104 #endif
105
106 /*
107  * Note: MAX_BACKENDS is limited to 2^23-1 because inval.c stores the
108  * backend ID as a 3-byte signed integer.  Even if that limitation were
109  * removed, we still could not exceed INT_MAX/4 because some places compute
110  * 4*MaxBackends without any overflow check.  This is rechecked in
111  * check_maxconnections, since MaxBackends is computed as MaxConnections
112  * plus the number of bgworkers plus autovacuum_max_workers plus one (for the
113  * autovacuum launcher).
114  */
115 #define MAX_BACKENDS    0x7fffff
116
117 #define KB_PER_MB (1024)
118 #define KB_PER_GB (1024*1024)
119
120 #define MS_PER_S 1000
121 #define S_PER_MIN 60
122 #define MS_PER_MIN (1000 * 60)
123 #define MIN_PER_H 60
124 #define S_PER_H (60 * 60)
125 #define MS_PER_H (1000 * 60 * 60)
126 #define MIN_PER_D (60 * 24)
127 #define S_PER_D (60 * 60 * 24)
128 #define MS_PER_D (1000 * 60 * 60 * 24)
129
130 /* XXX these should appear in other modules' header files */
131 extern bool Log_disconnections;
132 extern int      CommitDelay;
133 extern int      CommitSiblings;
134 extern char *default_tablespace;
135 extern char *temp_tablespaces;
136 extern bool synchronize_seqscans;
137 extern int      ssl_renegotiation_limit;
138 extern char *SSLCipherSuites;
139
140 #ifdef TRACE_SORT
141 extern bool trace_sort;
142 #endif
143 #ifdef TRACE_SYNCSCAN
144 extern bool trace_syncscan;
145 #endif
146 #ifdef DEBUG_BOUNDED_SORT
147 extern bool optimize_bounded_sort;
148 #endif
149
150 static int      GUC_check_errcode_value;
151
152 /* global variables for check hook support */
153 char       *GUC_check_errmsg_string;
154 char       *GUC_check_errdetail_string;
155 char       *GUC_check_errhint_string;
156
157
158 static void set_config_sourcefile(const char *name, char *sourcefile,
159                                           int sourceline);
160 static bool call_bool_check_hook(struct config_bool * conf, bool *newval,
161                                          void **extra, GucSource source, int elevel);
162 static bool call_int_check_hook(struct config_int * conf, int *newval,
163                                         void **extra, GucSource source, int elevel);
164 static bool call_real_check_hook(struct config_real * conf, double *newval,
165                                          void **extra, GucSource source, int elevel);
166 static bool call_string_check_hook(struct config_string * conf, char **newval,
167                                            void **extra, GucSource source, int elevel);
168 static bool call_enum_check_hook(struct config_enum * conf, int *newval,
169                                          void **extra, GucSource source, int elevel);
170
171 static bool check_log_destination(char **newval, void **extra, GucSource source);
172 static void assign_log_destination(const char *newval, void *extra);
173
174 #ifdef HAVE_SYSLOG
175 static int      syslog_facility = LOG_LOCAL0;
176 #else
177 static int      syslog_facility = 0;
178 #endif
179
180 static void assign_syslog_facility(int newval, void *extra);
181 static void assign_syslog_ident(const char *newval, void *extra);
182 static void assign_session_replication_role(int newval, void *extra);
183 static bool check_temp_buffers(int *newval, void **extra, GucSource source);
184 static bool check_phony_autocommit(bool *newval, void **extra, GucSource source);
185 static bool check_debug_assertions(bool *newval, void **extra, GucSource source);
186 static bool check_bonjour(bool *newval, void **extra, GucSource source);
187 static bool check_ssl(bool *newval, void **extra, GucSource source);
188 static bool check_stage_log_stats(bool *newval, void **extra, GucSource source);
189 static bool check_log_stats(bool *newval, void **extra, GucSource source);
190 static bool check_canonical_path(char **newval, void **extra, GucSource source);
191 static bool check_timezone_abbreviations(char **newval, void **extra, GucSource source);
192 static void assign_timezone_abbreviations(const char *newval, void *extra);
193 static void pg_timezone_abbrev_initialize(void);
194 static const char *show_archive_command(void);
195 static void assign_tcp_keepalives_idle(int newval, void *extra);
196 static void assign_tcp_keepalives_interval(int newval, void *extra);
197 static void assign_tcp_keepalives_count(int newval, void *extra);
198 static const char *show_tcp_keepalives_idle(void);
199 static const char *show_tcp_keepalives_interval(void);
200 static const char *show_tcp_keepalives_count(void);
201 static bool check_maxconnections(int *newval, void **extra, GucSource source);
202 static void assign_maxconnections(int newval, void *extra);
203 static bool check_autovacuum_max_workers(int *newval, void **extra, GucSource source);
204 static void assign_autovacuum_max_workers(int newval, void *extra);
205 static bool check_effective_io_concurrency(int *newval, void **extra, GucSource source);
206 static void assign_effective_io_concurrency(int newval, void *extra);
207 static void assign_pgstat_temp_directory(const char *newval, void *extra);
208 static bool check_application_name(char **newval, void **extra, GucSource source);
209 static void assign_application_name(const char *newval, void *extra);
210 static const char *show_unix_socket_permissions(void);
211 static const char *show_log_file_mode(void);
212
213 static char *config_enum_get_options(struct config_enum * record,
214                                                 const char *prefix, const char *suffix,
215                                                 const char *separator);
216
217
218 /*
219  * Options for enum values defined in this module.
220  *
221  * NOTE! Option values may not contain double quotes!
222  */
223
224 static const struct config_enum_entry bytea_output_options[] = {
225         {"escape", BYTEA_OUTPUT_ESCAPE, false},
226         {"hex", BYTEA_OUTPUT_HEX, false},
227         {NULL, 0, false}
228 };
229
230 /*
231  * We have different sets for client and server message level options because
232  * they sort slightly different (see "log" level)
233  */
234 static const struct config_enum_entry client_message_level_options[] = {
235         {"debug", DEBUG2, true},
236         {"debug5", DEBUG5, false},
237         {"debug4", DEBUG4, false},
238         {"debug3", DEBUG3, false},
239         {"debug2", DEBUG2, false},
240         {"debug1", DEBUG1, false},
241         {"log", LOG, false},
242         {"info", INFO, true},
243         {"notice", NOTICE, false},
244         {"warning", WARNING, false},
245         {"error", ERROR, false},
246         {"fatal", FATAL, true},
247         {"panic", PANIC, true},
248         {NULL, 0, false}
249 };
250
251 static const struct config_enum_entry server_message_level_options[] = {
252         {"debug", DEBUG2, true},
253         {"debug5", DEBUG5, false},
254         {"debug4", DEBUG4, false},
255         {"debug3", DEBUG3, false},
256         {"debug2", DEBUG2, false},
257         {"debug1", DEBUG1, false},
258         {"info", INFO, false},
259         {"notice", NOTICE, false},
260         {"warning", WARNING, false},
261         {"error", ERROR, false},
262         {"log", LOG, false},
263         {"fatal", FATAL, false},
264         {"panic", PANIC, false},
265         {NULL, 0, false}
266 };
267
268 static const struct config_enum_entry intervalstyle_options[] = {
269         {"postgres", INTSTYLE_POSTGRES, false},
270         {"postgres_verbose", INTSTYLE_POSTGRES_VERBOSE, false},
271         {"sql_standard", INTSTYLE_SQL_STANDARD, false},
272         {"iso_8601", INTSTYLE_ISO_8601, false},
273         {NULL, 0, false}
274 };
275
276 static const struct config_enum_entry log_error_verbosity_options[] = {
277         {"terse", PGERROR_TERSE, false},
278         {"default", PGERROR_DEFAULT, false},
279         {"verbose", PGERROR_VERBOSE, false},
280         {NULL, 0, false}
281 };
282
283 static const struct config_enum_entry log_statement_options[] = {
284         {"none", LOGSTMT_NONE, false},
285         {"ddl", LOGSTMT_DDL, false},
286         {"mod", LOGSTMT_MOD, false},
287         {"all", LOGSTMT_ALL, false},
288         {NULL, 0, false}
289 };
290
291 static const struct config_enum_entry isolation_level_options[] = {
292         {"serializable", XACT_SERIALIZABLE, false},
293         {"repeatable read", XACT_REPEATABLE_READ, false},
294         {"read committed", XACT_READ_COMMITTED, false},
295         {"read uncommitted", XACT_READ_UNCOMMITTED, false},
296         {NULL, 0}
297 };
298
299 static const struct config_enum_entry session_replication_role_options[] = {
300         {"origin", SESSION_REPLICATION_ROLE_ORIGIN, false},
301         {"replica", SESSION_REPLICATION_ROLE_REPLICA, false},
302         {"local", SESSION_REPLICATION_ROLE_LOCAL, false},
303         {NULL, 0, false}
304 };
305
306 static const struct config_enum_entry syslog_facility_options[] = {
307 #ifdef HAVE_SYSLOG
308         {"local0", LOG_LOCAL0, false},
309         {"local1", LOG_LOCAL1, false},
310         {"local2", LOG_LOCAL2, false},
311         {"local3", LOG_LOCAL3, false},
312         {"local4", LOG_LOCAL4, false},
313         {"local5", LOG_LOCAL5, false},
314         {"local6", LOG_LOCAL6, false},
315         {"local7", LOG_LOCAL7, false},
316 #else
317         {"none", 0, false},
318 #endif
319         {NULL, 0}
320 };
321
322 static const struct config_enum_entry track_function_options[] = {
323         {"none", TRACK_FUNC_OFF, false},
324         {"pl", TRACK_FUNC_PL, false},
325         {"all", TRACK_FUNC_ALL, false},
326         {NULL, 0, false}
327 };
328
329 static const struct config_enum_entry xmlbinary_options[] = {
330         {"base64", XMLBINARY_BASE64, false},
331         {"hex", XMLBINARY_HEX, false},
332         {NULL, 0, false}
333 };
334
335 static const struct config_enum_entry xmloption_options[] = {
336         {"content", XMLOPTION_CONTENT, false},
337         {"document", XMLOPTION_DOCUMENT, false},
338         {NULL, 0, false}
339 };
340
341 /*
342  * Although only "on", "off", and "safe_encoding" are documented, we
343  * accept all the likely variants of "on" and "off".
344  */
345 static const struct config_enum_entry backslash_quote_options[] = {
346         {"safe_encoding", BACKSLASH_QUOTE_SAFE_ENCODING, false},
347         {"on", BACKSLASH_QUOTE_ON, false},
348         {"off", BACKSLASH_QUOTE_OFF, false},
349         {"true", BACKSLASH_QUOTE_ON, true},
350         {"false", BACKSLASH_QUOTE_OFF, true},
351         {"yes", BACKSLASH_QUOTE_ON, true},
352         {"no", BACKSLASH_QUOTE_OFF, true},
353         {"1", BACKSLASH_QUOTE_ON, true},
354         {"0", BACKSLASH_QUOTE_OFF, true},
355         {NULL, 0, false}
356 };
357
358 /*
359  * Although only "on", "off", and "partition" are documented, we
360  * accept all the likely variants of "on" and "off".
361  */
362 static const struct config_enum_entry constraint_exclusion_options[] = {
363         {"partition", CONSTRAINT_EXCLUSION_PARTITION, false},
364         {"on", CONSTRAINT_EXCLUSION_ON, false},
365         {"off", CONSTRAINT_EXCLUSION_OFF, false},
366         {"true", CONSTRAINT_EXCLUSION_ON, true},
367         {"false", CONSTRAINT_EXCLUSION_OFF, true},
368         {"yes", CONSTRAINT_EXCLUSION_ON, true},
369         {"no", CONSTRAINT_EXCLUSION_OFF, true},
370         {"1", CONSTRAINT_EXCLUSION_ON, true},
371         {"0", CONSTRAINT_EXCLUSION_OFF, true},
372         {NULL, 0, false}
373 };
374
375 /*
376  * Although only "on", "off", "remote_write", and "local" are documented, we
377  * accept all the likely variants of "on" and "off".
378  */
379 static const struct config_enum_entry synchronous_commit_options[] = {
380         {"local", SYNCHRONOUS_COMMIT_LOCAL_FLUSH, false},
381         {"remote_write", SYNCHRONOUS_COMMIT_REMOTE_WRITE, false},
382         {"on", SYNCHRONOUS_COMMIT_ON, false},
383         {"off", SYNCHRONOUS_COMMIT_OFF, false},
384         {"true", SYNCHRONOUS_COMMIT_ON, true},
385         {"false", SYNCHRONOUS_COMMIT_OFF, true},
386         {"yes", SYNCHRONOUS_COMMIT_ON, true},
387         {"no", SYNCHRONOUS_COMMIT_OFF, true},
388         {"1", SYNCHRONOUS_COMMIT_ON, true},
389         {"0", SYNCHRONOUS_COMMIT_OFF, true},
390         {NULL, 0, false}
391 };
392
393 /*
394  * Options for enum values stored in other modules
395  */
396 extern const struct config_enum_entry wal_level_options[];
397 extern const struct config_enum_entry sync_method_options[];
398
399 /*
400  * GUC option variables that are exported from this module
401  */
402 #ifdef USE_ASSERT_CHECKING
403 bool            assert_enabled = true;
404 #else
405 bool            assert_enabled = false;
406 #endif
407 bool            log_duration = false;
408 bool            Debug_print_plan = false;
409 bool            Debug_print_parse = false;
410 bool            Debug_print_rewritten = false;
411 bool            Debug_pretty_print = true;
412
413 bool            log_parser_stats = false;
414 bool            log_planner_stats = false;
415 bool            log_executor_stats = false;
416 bool            log_statement_stats = false;            /* this is sort of all three
417                                                                                                  * above together */
418 bool            log_btree_build_stats = false;
419 char       *event_source;
420
421 bool            check_function_bodies = true;
422 bool            default_with_oids = false;
423 bool            SQL_inheritance = true;
424
425 bool            Password_encryption = true;
426
427 int                     log_min_error_statement = ERROR;
428 int                     log_min_messages = WARNING;
429 int                     client_min_messages = NOTICE;
430 int                     log_min_duration_statement = -1;
431 int                     log_temp_files = -1;
432 int                     trace_recovery_messages = LOG;
433
434 int                     temp_file_limit = -1;
435
436 int                     num_temp_buffers = 1024;
437
438 char       *data_directory;
439 char       *ConfigFileName;
440 char       *HbaFileName;
441 char       *IdentFileName;
442 char       *external_pid_file;
443
444 char       *pgstat_temp_directory;
445
446 char       *application_name;
447
448 int                     tcp_keepalives_idle;
449 int                     tcp_keepalives_interval;
450 int                     tcp_keepalives_count;
451
452 /*
453  * These variables are all dummies that don't do anything, except in some
454  * cases provide the value for SHOW to display.  The real state is elsewhere
455  * and is kept in sync by assign_hooks.
456  */
457 static char *log_destination_string;
458
459 static char *syslog_ident_str;
460 static bool phony_autocommit;
461 static bool session_auth_is_superuser;
462 static double phony_random_seed;
463 static char *client_encoding_string;
464 static char *datestyle_string;
465 static char *locale_collate;
466 static char *locale_ctype;
467 static char *server_encoding_string;
468 static char *server_version_string;
469 static int      server_version_num;
470 static char *timezone_string;
471 static char *log_timezone_string;
472 static char *timezone_abbreviations_string;
473 static char *XactIsoLevel_string;
474 static char *session_authorization_string;
475 static int      max_function_args;
476 static int      max_index_keys;
477 static int      max_identifier_length;
478 static int      block_size;
479 static int      segment_size;
480 static int      wal_block_size;
481 static int      wal_segment_size;
482 static bool integer_datetimes;
483 static int      effective_io_concurrency;
484
485 /* should be static, but commands/variable.c needs to get at this */
486 char       *role_string;
487
488
489 /*
490  * Displayable names for context types (enum GucContext)
491  *
492  * Note: these strings are deliberately not localized.
493  */
494 const char *const GucContext_Names[] =
495 {
496          /* PGC_INTERNAL */ "internal",
497          /* PGC_POSTMASTER */ "postmaster",
498          /* PGC_SIGHUP */ "sighup",
499          /* PGC_BACKEND */ "backend",
500          /* PGC_SUSET */ "superuser",
501          /* PGC_USERSET */ "user"
502 };
503
504 /*
505  * Displayable names for source types (enum GucSource)
506  *
507  * Note: these strings are deliberately not localized.
508  */
509 const char *const GucSource_Names[] =
510 {
511          /* PGC_S_DEFAULT */ "default",
512          /* PGC_S_DYNAMIC_DEFAULT */ "default",
513          /* PGC_S_ENV_VAR */ "environment variable",
514          /* PGC_S_FILE */ "configuration file",
515          /* PGC_S_ARGV */ "command line",
516          /* PGC_S_DATABASE */ "database",
517          /* PGC_S_USER */ "user",
518          /* PGC_S_DATABASE_USER */ "database user",
519          /* PGC_S_CLIENT */ "client",
520          /* PGC_S_OVERRIDE */ "override",
521          /* PGC_S_INTERACTIVE */ "interactive",
522          /* PGC_S_TEST */ "test",
523          /* PGC_S_SESSION */ "session"
524 };
525
526 /*
527  * Displayable names for the groupings defined in enum config_group
528  */
529 const char *const config_group_names[] =
530 {
531         /* UNGROUPED */
532         gettext_noop("Ungrouped"),
533         /* FILE_LOCATIONS */
534         gettext_noop("File Locations"),
535         /* CONN_AUTH */
536         gettext_noop("Connections and Authentication"),
537         /* CONN_AUTH_SETTINGS */
538         gettext_noop("Connections and Authentication / Connection Settings"),
539         /* CONN_AUTH_SECURITY */
540         gettext_noop("Connections and Authentication / Security and Authentication"),
541         /* RESOURCES */
542         gettext_noop("Resource Usage"),
543         /* RESOURCES_MEM */
544         gettext_noop("Resource Usage / Memory"),
545         /* RESOURCES_DISK */
546         gettext_noop("Resource Usage / Disk"),
547         /* RESOURCES_KERNEL */
548         gettext_noop("Resource Usage / Kernel Resources"),
549         /* RESOURCES_VACUUM_DELAY */
550         gettext_noop("Resource Usage / Cost-Based Vacuum Delay"),
551         /* RESOURCES_BGWRITER */
552         gettext_noop("Resource Usage / Background Writer"),
553         /* RESOURCES_ASYNCHRONOUS */
554         gettext_noop("Resource Usage / Asynchronous Behavior"),
555         /* WAL */
556         gettext_noop("Write-Ahead Log"),
557         /* WAL_SETTINGS */
558         gettext_noop("Write-Ahead Log / Settings"),
559         /* WAL_CHECKPOINTS */
560         gettext_noop("Write-Ahead Log / Checkpoints"),
561         /* WAL_ARCHIVING */
562         gettext_noop("Write-Ahead Log / Archiving"),
563         /* REPLICATION */
564         gettext_noop("Replication"),
565         /* REPLICATION_SENDING */
566         gettext_noop("Replication / Sending Servers"),
567         /* REPLICATION_MASTER */
568         gettext_noop("Replication / Master Server"),
569         /* REPLICATION_STANDBY */
570         gettext_noop("Replication / Standby Servers"),
571         /* QUERY_TUNING */
572         gettext_noop("Query Tuning"),
573         /* QUERY_TUNING_METHOD */
574         gettext_noop("Query Tuning / Planner Method Configuration"),
575         /* QUERY_TUNING_COST */
576         gettext_noop("Query Tuning / Planner Cost Constants"),
577         /* QUERY_TUNING_GEQO */
578         gettext_noop("Query Tuning / Genetic Query Optimizer"),
579         /* QUERY_TUNING_OTHER */
580         gettext_noop("Query Tuning / Other Planner Options"),
581         /* LOGGING */
582         gettext_noop("Reporting and Logging"),
583         /* LOGGING_WHERE */
584         gettext_noop("Reporting and Logging / Where to Log"),
585         /* LOGGING_WHEN */
586         gettext_noop("Reporting and Logging / When to Log"),
587         /* LOGGING_WHAT */
588         gettext_noop("Reporting and Logging / What to Log"),
589         /* STATS */
590         gettext_noop("Statistics"),
591         /* STATS_MONITORING */
592         gettext_noop("Statistics / Monitoring"),
593         /* STATS_COLLECTOR */
594         gettext_noop("Statistics / Query and Index Statistics Collector"),
595         /* AUTOVACUUM */
596         gettext_noop("Autovacuum"),
597         /* CLIENT_CONN */
598         gettext_noop("Client Connection Defaults"),
599         /* CLIENT_CONN_STATEMENT */
600         gettext_noop("Client Connection Defaults / Statement Behavior"),
601         /* CLIENT_CONN_LOCALE */
602         gettext_noop("Client Connection Defaults / Locale and Formatting"),
603         /* CLIENT_CONN_OTHER */
604         gettext_noop("Client Connection Defaults / Other Defaults"),
605         /* LOCK_MANAGEMENT */
606         gettext_noop("Lock Management"),
607         /* COMPAT_OPTIONS */
608         gettext_noop("Version and Platform Compatibility"),
609         /* COMPAT_OPTIONS_PREVIOUS */
610         gettext_noop("Version and Platform Compatibility / Previous PostgreSQL Versions"),
611         /* COMPAT_OPTIONS_CLIENT */
612         gettext_noop("Version and Platform Compatibility / Other Platforms and Clients"),
613         /* ERROR_HANDLING */
614         gettext_noop("Error Handling"),
615         /* PRESET_OPTIONS */
616         gettext_noop("Preset Options"),
617         /* CUSTOM_OPTIONS */
618         gettext_noop("Customized Options"),
619         /* DEVELOPER_OPTIONS */
620         gettext_noop("Developer Options"),
621         /* help_config wants this array to be null-terminated */
622         NULL
623 };
624
625 /*
626  * Displayable names for GUC variable types (enum config_type)
627  *
628  * Note: these strings are deliberately not localized.
629  */
630 const char *const config_type_names[] =
631 {
632          /* PGC_BOOL */ "bool",
633          /* PGC_INT */ "integer",
634          /* PGC_REAL */ "real",
635          /* PGC_STRING */ "string",
636          /* PGC_ENUM */ "enum"
637 };
638
639
640 /*
641  * Contents of GUC tables
642  *
643  * See src/backend/utils/misc/README for design notes.
644  *
645  * TO ADD AN OPTION:
646  *
647  * 1. Declare a global variable of type bool, int, double, or char*
648  *        and make use of it.
649  *
650  * 2. Decide at what times it's safe to set the option. See guc.h for
651  *        details.
652  *
653  * 3. Decide on a name, a default value, upper and lower bounds (if
654  *        applicable), etc.
655  *
656  * 4. Add a record below.
657  *
658  * 5. Add it to src/backend/utils/misc/postgresql.conf.sample, if
659  *        appropriate.
660  *
661  * 6. Don't forget to document the option (at least in config.sgml).
662  *
663  * 7. If it's a new GUC_LIST option you must edit pg_dumpall.c to ensure
664  *        it is not single quoted at dump time.
665  */
666
667
668 /******** option records follow ********/
669
670 static struct config_bool ConfigureNamesBool[] =
671 {
672         {
673                 {"enable_seqscan", PGC_USERSET, QUERY_TUNING_METHOD,
674                         gettext_noop("Enables the planner's use of sequential-scan plans."),
675                         NULL
676                 },
677                 &enable_seqscan,
678                 true,
679                 NULL, NULL, NULL
680         },
681         {
682                 {"enable_indexscan", PGC_USERSET, QUERY_TUNING_METHOD,
683                         gettext_noop("Enables the planner's use of index-scan plans."),
684                         NULL
685                 },
686                 &enable_indexscan,
687                 true,
688                 NULL, NULL, NULL
689         },
690         {
691                 {"enable_indexonlyscan", PGC_USERSET, QUERY_TUNING_METHOD,
692                         gettext_noop("Enables the planner's use of index-only-scan plans."),
693                         NULL
694                 },
695                 &enable_indexonlyscan,
696                 true,
697                 NULL, NULL, NULL
698         },
699         {
700                 {"enable_bitmapscan", PGC_USERSET, QUERY_TUNING_METHOD,
701                         gettext_noop("Enables the planner's use of bitmap-scan plans."),
702                         NULL
703                 },
704                 &enable_bitmapscan,
705                 true,
706                 NULL, NULL, NULL
707         },
708         {
709                 {"enable_tidscan", PGC_USERSET, QUERY_TUNING_METHOD,
710                         gettext_noop("Enables the planner's use of TID scan plans."),
711                         NULL
712                 },
713                 &enable_tidscan,
714                 true,
715                 NULL, NULL, NULL
716         },
717         {
718                 {"enable_sort", PGC_USERSET, QUERY_TUNING_METHOD,
719                         gettext_noop("Enables the planner's use of explicit sort steps."),
720                         NULL
721                 },
722                 &enable_sort,
723                 true,
724                 NULL, NULL, NULL
725         },
726         {
727                 {"enable_hashagg", PGC_USERSET, QUERY_TUNING_METHOD,
728                         gettext_noop("Enables the planner's use of hashed aggregation plans."),
729                         NULL
730                 },
731                 &enable_hashagg,
732                 true,
733                 NULL, NULL, NULL
734         },
735         {
736                 {"enable_material", PGC_USERSET, QUERY_TUNING_METHOD,
737                         gettext_noop("Enables the planner's use of materialization."),
738                         NULL
739                 },
740                 &enable_material,
741                 true,
742                 NULL, NULL, NULL
743         },
744         {
745                 {"enable_nestloop", PGC_USERSET, QUERY_TUNING_METHOD,
746                         gettext_noop("Enables the planner's use of nested-loop join plans."),
747                         NULL
748                 },
749                 &enable_nestloop,
750                 true,
751                 NULL, NULL, NULL
752         },
753         {
754                 {"enable_mergejoin", PGC_USERSET, QUERY_TUNING_METHOD,
755                         gettext_noop("Enables the planner's use of merge join plans."),
756                         NULL
757                 },
758                 &enable_mergejoin,
759                 true,
760                 NULL, NULL, NULL
761         },
762         {
763                 {"enable_hashjoin", PGC_USERSET, QUERY_TUNING_METHOD,
764                         gettext_noop("Enables the planner's use of hash join plans."),
765                         NULL
766                 },
767                 &enable_hashjoin,
768                 true,
769                 NULL, NULL, NULL
770         },
771         {
772                 {"geqo", PGC_USERSET, QUERY_TUNING_GEQO,
773                         gettext_noop("Enables genetic query optimization."),
774                         gettext_noop("This algorithm attempts to do planning without "
775                                                  "exhaustive searching.")
776                 },
777                 &enable_geqo,
778                 true,
779                 NULL, NULL, NULL
780         },
781         {
782                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
783                 {"is_superuser", PGC_INTERNAL, UNGROUPED,
784                         gettext_noop("Shows whether the current user is a superuser."),
785                         NULL,
786                         GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
787                 },
788                 &session_auth_is_superuser,
789                 false,
790                 NULL, NULL, NULL
791         },
792         {
793                 {"bonjour", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
794                         gettext_noop("Enables advertising the server via Bonjour."),
795                         NULL
796                 },
797                 &enable_bonjour,
798                 false,
799                 check_bonjour, NULL, NULL
800         },
801         {
802                 {"ssl", PGC_POSTMASTER, CONN_AUTH_SECURITY,
803                         gettext_noop("Enables SSL connections."),
804                         NULL
805                 },
806                 &EnableSSL,
807                 false,
808                 check_ssl, NULL, NULL
809         },
810         {
811                 {"fsync", PGC_SIGHUP, WAL_SETTINGS,
812                         gettext_noop("Forces synchronization of updates to disk."),
813                         gettext_noop("The server will use the fsync() system call in several places to make "
814                         "sure that updates are physically written to disk. This insures "
815                                                  "that a database cluster will recover to a consistent state after "
816                                                  "an operating system or hardware crash.")
817                 },
818                 &enableFsync,
819                 true,
820                 NULL, NULL, NULL
821         },
822         {
823                 {"zero_damaged_pages", PGC_SUSET, DEVELOPER_OPTIONS,
824                         gettext_noop("Continues processing past damaged page headers."),
825                         gettext_noop("Detection of a damaged page header normally causes PostgreSQL to "
826                                 "report an error, aborting the current transaction. Setting "
827                                                  "zero_damaged_pages to true causes the system to instead report a "
828                                                  "warning, zero out the damaged page, and continue processing. This "
829                                                  "behavior will destroy data, namely all the rows on the damaged page."),
830                         GUC_NOT_IN_SAMPLE
831                 },
832                 &zero_damaged_pages,
833                 false,
834                 NULL, NULL, NULL
835         },
836         {
837                 {"full_page_writes", PGC_SIGHUP, WAL_SETTINGS,
838                         gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
839                         gettext_noop("A page write in process during an operating system crash might be "
840                                                  "only partially written to disk.  During recovery, the row changes "
841                           "stored in WAL are not enough to recover.  This option writes "
842                                                  "pages when first modified after a checkpoint to WAL so full recovery "
843                                                  "is possible.")
844                 },
845                 &fullPageWrites,
846                 true,
847                 NULL, NULL, NULL
848         },
849         {
850                 {"log_checkpoints", PGC_SIGHUP, LOGGING_WHAT,
851                         gettext_noop("Logs each checkpoint."),
852                         NULL
853                 },
854                 &log_checkpoints,
855                 false,
856                 NULL, NULL, NULL
857         },
858         {
859                 {"log_connections", PGC_BACKEND, LOGGING_WHAT,
860                         gettext_noop("Logs each successful connection."),
861                         NULL
862                 },
863                 &Log_connections,
864                 false,
865                 NULL, NULL, NULL
866         },
867         {
868                 {"log_disconnections", PGC_BACKEND, LOGGING_WHAT,
869                         gettext_noop("Logs end of a session, including duration."),
870                         NULL
871                 },
872                 &Log_disconnections,
873                 false,
874                 NULL, NULL, NULL
875         },
876         {
877                 {"debug_assertions", PGC_USERSET, DEVELOPER_OPTIONS,
878                         gettext_noop("Turns on various assertion checks."),
879                         gettext_noop("This is a debugging aid."),
880                         GUC_NOT_IN_SAMPLE
881                 },
882                 &assert_enabled,
883 #ifdef USE_ASSERT_CHECKING
884                 true,
885 #else
886                 false,
887 #endif
888                 check_debug_assertions, NULL, NULL
889         },
890
891         {
892                 {"exit_on_error", PGC_USERSET, ERROR_HANDLING_OPTIONS,
893                         gettext_noop("Terminate session on any error."),
894                         NULL
895                 },
896                 &ExitOnAnyError,
897                 false,
898                 NULL, NULL, NULL
899         },
900         {
901                 {"restart_after_crash", PGC_SIGHUP, ERROR_HANDLING_OPTIONS,
902                         gettext_noop("Reinitialize server after backend crash."),
903                         NULL
904                 },
905                 &restart_after_crash,
906                 true,
907                 NULL, NULL, NULL
908         },
909
910         {
911                 {"log_duration", PGC_SUSET, LOGGING_WHAT,
912                         gettext_noop("Logs the duration of each completed SQL statement."),
913                         NULL
914                 },
915                 &log_duration,
916                 false,
917                 NULL, NULL, NULL
918         },
919         {
920                 {"debug_print_parse", PGC_USERSET, LOGGING_WHAT,
921                         gettext_noop("Logs each query's parse tree."),
922                         NULL
923                 },
924                 &Debug_print_parse,
925                 false,
926                 NULL, NULL, NULL
927         },
928         {
929                 {"debug_print_rewritten", PGC_USERSET, LOGGING_WHAT,
930                         gettext_noop("Logs each query's rewritten parse tree."),
931                         NULL
932                 },
933                 &Debug_print_rewritten,
934                 false,
935                 NULL, NULL, NULL
936         },
937         {
938                 {"debug_print_plan", PGC_USERSET, LOGGING_WHAT,
939                         gettext_noop("Logs each query's execution plan."),
940                         NULL
941                 },
942                 &Debug_print_plan,
943                 false,
944                 NULL, NULL, NULL
945         },
946         {
947                 {"debug_pretty_print", PGC_USERSET, LOGGING_WHAT,
948                         gettext_noop("Indents parse and plan tree displays."),
949                         NULL
950                 },
951                 &Debug_pretty_print,
952                 true,
953                 NULL, NULL, NULL
954         },
955         {
956                 {"log_parser_stats", PGC_SUSET, STATS_MONITORING,
957                         gettext_noop("Writes parser performance statistics to the server log."),
958                         NULL
959                 },
960                 &log_parser_stats,
961                 false,
962                 check_stage_log_stats, NULL, NULL
963         },
964         {
965                 {"log_planner_stats", PGC_SUSET, STATS_MONITORING,
966                         gettext_noop("Writes planner performance statistics to the server log."),
967                         NULL
968                 },
969                 &log_planner_stats,
970                 false,
971                 check_stage_log_stats, NULL, NULL
972         },
973         {
974                 {"log_executor_stats", PGC_SUSET, STATS_MONITORING,
975                         gettext_noop("Writes executor performance statistics to the server log."),
976                         NULL
977                 },
978                 &log_executor_stats,
979                 false,
980                 check_stage_log_stats, NULL, NULL
981         },
982         {
983                 {"log_statement_stats", PGC_SUSET, STATS_MONITORING,
984                         gettext_noop("Writes cumulative performance statistics to the server log."),
985                         NULL
986                 },
987                 &log_statement_stats,
988                 false,
989                 check_log_stats, NULL, NULL
990         },
991 #ifdef BTREE_BUILD_STATS
992         {
993                 {"log_btree_build_stats", PGC_SUSET, DEVELOPER_OPTIONS,
994                         gettext_noop("No description available."),
995                         NULL,
996                         GUC_NOT_IN_SAMPLE
997                 },
998                 &log_btree_build_stats,
999                 false,
1000                 NULL, NULL, NULL
1001         },
1002 #endif
1003
1004         {
1005                 {"track_activities", PGC_SUSET, STATS_COLLECTOR,
1006                         gettext_noop("Collects information about executing commands."),
1007                         gettext_noop("Enables the collection of information on the currently "
1008                                                  "executing command of each session, along with "
1009                                                  "the time at which that command began execution.")
1010                 },
1011                 &pgstat_track_activities,
1012                 true,
1013                 NULL, NULL, NULL
1014         },
1015         {
1016                 {"track_counts", PGC_SUSET, STATS_COLLECTOR,
1017                         gettext_noop("Collects statistics on database activity."),
1018                         NULL
1019                 },
1020                 &pgstat_track_counts,
1021                 true,
1022                 NULL, NULL, NULL
1023         },
1024         {
1025                 {"track_io_timing", PGC_SUSET, STATS_COLLECTOR,
1026                         gettext_noop("Collects timing statistics for database I/O activity."),
1027                         NULL
1028                 },
1029                 &track_io_timing,
1030                 false,
1031                 NULL, NULL, NULL
1032         },
1033
1034         {
1035                 {"update_process_title", PGC_SUSET, STATS_COLLECTOR,
1036                         gettext_noop("Updates the process title to show the active SQL command."),
1037                         gettext_noop("Enables updating of the process title every time a new SQL command is received by the server.")
1038                 },
1039                 &update_process_title,
1040                 true,
1041                 NULL, NULL, NULL
1042         },
1043
1044         {
1045                 {"autovacuum", PGC_SIGHUP, AUTOVACUUM,
1046                         gettext_noop("Starts the autovacuum subprocess."),
1047                         NULL
1048                 },
1049                 &autovacuum_start_daemon,
1050                 true,
1051                 NULL, NULL, NULL
1052         },
1053
1054         {
1055                 {"trace_notify", PGC_USERSET, DEVELOPER_OPTIONS,
1056                         gettext_noop("Generates debugging output for LISTEN and NOTIFY."),
1057                         NULL,
1058                         GUC_NOT_IN_SAMPLE
1059                 },
1060                 &Trace_notify,
1061                 false,
1062                 NULL, NULL, NULL
1063         },
1064
1065 #ifdef LOCK_DEBUG
1066         {
1067                 {"trace_locks", PGC_SUSET, DEVELOPER_OPTIONS,
1068                         gettext_noop("No description available."),
1069                         NULL,
1070                         GUC_NOT_IN_SAMPLE
1071                 },
1072                 &Trace_locks,
1073                 false,
1074                 NULL, NULL, NULL
1075         },
1076         {
1077                 {"trace_userlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1078                         gettext_noop("No description available."),
1079                         NULL,
1080                         GUC_NOT_IN_SAMPLE
1081                 },
1082                 &Trace_userlocks,
1083                 false,
1084                 NULL, NULL, NULL
1085         },
1086         {
1087                 {"trace_lwlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1088                         gettext_noop("No description available."),
1089                         NULL,
1090                         GUC_NOT_IN_SAMPLE
1091                 },
1092                 &Trace_lwlocks,
1093                 false,
1094                 NULL, NULL, NULL
1095         },
1096         {
1097                 {"debug_deadlocks", PGC_SUSET, DEVELOPER_OPTIONS,
1098                         gettext_noop("No description available."),
1099                         NULL,
1100                         GUC_NOT_IN_SAMPLE
1101                 },
1102                 &Debug_deadlocks,
1103                 false,
1104                 NULL, NULL, NULL
1105         },
1106 #endif
1107
1108         {
1109                 {"log_lock_waits", PGC_SUSET, LOGGING_WHAT,
1110                         gettext_noop("Logs long lock waits."),
1111                         NULL
1112                 },
1113                 &log_lock_waits,
1114                 false,
1115                 NULL, NULL, NULL
1116         },
1117
1118         {
1119                 {"log_hostname", PGC_SIGHUP, LOGGING_WHAT,
1120                         gettext_noop("Logs the host name in the connection logs."),
1121                         gettext_noop("By default, connection logs only show the IP address "
1122                                                  "of the connecting host. If you want them to show the host name you "
1123                           "can turn this on, but depending on your host name resolution "
1124                            "setup it might impose a non-negligible performance penalty.")
1125                 },
1126                 &log_hostname,
1127                 false,
1128                 NULL, NULL, NULL
1129         },
1130         {
1131                 {"sql_inheritance", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1132                         gettext_noop("Causes subtables to be included by default in various commands."),
1133                         NULL
1134                 },
1135                 &SQL_inheritance,
1136                 true,
1137                 NULL, NULL, NULL
1138         },
1139         {
1140                 {"password_encryption", PGC_USERSET, CONN_AUTH_SECURITY,
1141                         gettext_noop("Encrypt passwords."),
1142                         gettext_noop("When a password is specified in CREATE USER or "
1143                            "ALTER USER without writing either ENCRYPTED or UNENCRYPTED, "
1144                                                  "this parameter determines whether the password is to be encrypted.")
1145                 },
1146                 &Password_encryption,
1147                 true,
1148                 NULL, NULL, NULL
1149         },
1150         {
1151                 {"transform_null_equals", PGC_USERSET, COMPAT_OPTIONS_CLIENT,
1152                         gettext_noop("Treats \"expr=NULL\" as \"expr IS NULL\"."),
1153                         gettext_noop("When turned on, expressions of the form expr = NULL "
1154                            "(or NULL = expr) are treated as expr IS NULL, that is, they "
1155                                 "return true if expr evaluates to the null value, and false "
1156                            "otherwise. The correct behavior of expr = NULL is to always "
1157                                                  "return null (unknown).")
1158                 },
1159                 &Transform_null_equals,
1160                 false,
1161                 NULL, NULL, NULL
1162         },
1163         {
1164                 {"db_user_namespace", PGC_SIGHUP, CONN_AUTH_SECURITY,
1165                         gettext_noop("Enables per-database user names."),
1166                         NULL
1167                 },
1168                 &Db_user_namespace,
1169                 false,
1170                 NULL, NULL, NULL
1171         },
1172         {
1173                 /* only here for backwards compatibility */
1174                 {"autocommit", PGC_USERSET, CLIENT_CONN_STATEMENT,
1175                         gettext_noop("This parameter doesn't do anything."),
1176                         gettext_noop("It's just here so that we won't choke on SET AUTOCOMMIT TO ON from 7.3-vintage clients."),
1177                         GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE
1178                 },
1179                 &phony_autocommit,
1180                 true,
1181                 check_phony_autocommit, NULL, NULL
1182         },
1183         {
1184                 {"default_transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1185                         gettext_noop("Sets the default read-only status of new transactions."),
1186                         NULL
1187                 },
1188                 &DefaultXactReadOnly,
1189                 false,
1190                 NULL, NULL, NULL
1191         },
1192         {
1193                 {"transaction_read_only", PGC_USERSET, CLIENT_CONN_STATEMENT,
1194                         gettext_noop("Sets the current transaction's read-only status."),
1195                         NULL,
1196                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1197                 },
1198                 &XactReadOnly,
1199                 false,
1200                 check_transaction_read_only, NULL, NULL
1201         },
1202         {
1203                 {"default_transaction_deferrable", PGC_USERSET, CLIENT_CONN_STATEMENT,
1204                         gettext_noop("Sets the default deferrable status of new transactions."),
1205                         NULL
1206                 },
1207                 &DefaultXactDeferrable,
1208                 false,
1209                 NULL, NULL, NULL
1210         },
1211         {
1212                 {"transaction_deferrable", PGC_USERSET, CLIENT_CONN_STATEMENT,
1213                         gettext_noop("Whether to defer a read-only serializable transaction until it can be executed with no possible serialization failures."),
1214                         NULL,
1215                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1216                 },
1217                 &XactDeferrable,
1218                 false,
1219                 check_transaction_deferrable, NULL, NULL
1220         },
1221         {
1222                 {"check_function_bodies", PGC_USERSET, CLIENT_CONN_STATEMENT,
1223                         gettext_noop("Check function bodies during CREATE FUNCTION."),
1224                         NULL
1225                 },
1226                 &check_function_bodies,
1227                 true,
1228                 NULL, NULL, NULL
1229         },
1230         {
1231                 {"array_nulls", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1232                         gettext_noop("Enable input of NULL elements in arrays."),
1233                         gettext_noop("When turned on, unquoted NULL in an array input "
1234                                                  "value means a null value; "
1235                                                  "otherwise it is taken literally.")
1236                 },
1237                 &Array_nulls,
1238                 true,
1239                 NULL, NULL, NULL
1240         },
1241         {
1242                 {"default_with_oids", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1243                         gettext_noop("Create new tables with OIDs by default."),
1244                         NULL
1245                 },
1246                 &default_with_oids,
1247                 false,
1248                 NULL, NULL, NULL
1249         },
1250         {
1251                 {"logging_collector", PGC_POSTMASTER, LOGGING_WHERE,
1252                         gettext_noop("Start a subprocess to capture stderr output and/or csvlogs into log files."),
1253                         NULL
1254                 },
1255                 &Logging_collector,
1256                 false,
1257                 NULL, NULL, NULL
1258         },
1259         {
1260                 {"log_truncate_on_rotation", PGC_SIGHUP, LOGGING_WHERE,
1261                         gettext_noop("Truncate existing log files of same name during log rotation."),
1262                         NULL
1263                 },
1264                 &Log_truncate_on_rotation,
1265                 false,
1266                 NULL, NULL, NULL
1267         },
1268
1269 #ifdef TRACE_SORT
1270         {
1271                 {"trace_sort", PGC_USERSET, DEVELOPER_OPTIONS,
1272                         gettext_noop("Emit information about resource usage in sorting."),
1273                         NULL,
1274                         GUC_NOT_IN_SAMPLE
1275                 },
1276                 &trace_sort,
1277                 false,
1278                 NULL, NULL, NULL
1279         },
1280 #endif
1281
1282 #ifdef TRACE_SYNCSCAN
1283         /* this is undocumented because not exposed in a standard build */
1284         {
1285                 {"trace_syncscan", PGC_USERSET, DEVELOPER_OPTIONS,
1286                         gettext_noop("Generate debugging output for synchronized scanning."),
1287                         NULL,
1288                         GUC_NOT_IN_SAMPLE
1289                 },
1290                 &trace_syncscan,
1291                 false,
1292                 NULL, NULL, NULL
1293         },
1294 #endif
1295
1296 #ifdef DEBUG_BOUNDED_SORT
1297         /* this is undocumented because not exposed in a standard build */
1298         {
1299                 {
1300                         "optimize_bounded_sort", PGC_USERSET, QUERY_TUNING_METHOD,
1301                         gettext_noop("Enable bounded sorting using heap sort."),
1302                         NULL,
1303                         GUC_NOT_IN_SAMPLE
1304                 },
1305                 &optimize_bounded_sort,
1306                 true,
1307                 NULL, NULL, NULL
1308         },
1309 #endif
1310
1311 #ifdef WAL_DEBUG
1312         {
1313                 {"wal_debug", PGC_SUSET, DEVELOPER_OPTIONS,
1314                         gettext_noop("Emit WAL-related debugging output."),
1315                         NULL,
1316                         GUC_NOT_IN_SAMPLE
1317                 },
1318                 &XLOG_DEBUG,
1319                 false,
1320                 NULL, NULL, NULL
1321         },
1322 #endif
1323
1324         {
1325                 {"integer_datetimes", PGC_INTERNAL, PRESET_OPTIONS,
1326                         gettext_noop("Datetimes are integer based."),
1327                         NULL,
1328                         GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
1329                 },
1330                 &integer_datetimes,
1331 #ifdef HAVE_INT64_TIMESTAMP
1332                 true,
1333 #else
1334                 false,
1335 #endif
1336                 NULL, NULL, NULL
1337         },
1338
1339         {
1340                 {"krb_caseins_users", PGC_SIGHUP, CONN_AUTH_SECURITY,
1341                         gettext_noop("Sets whether Kerberos and GSSAPI user names should be treated as case-insensitive."),
1342                         NULL
1343                 },
1344                 &pg_krb_caseins_users,
1345                 false,
1346                 NULL, NULL, NULL
1347         },
1348
1349         {
1350                 {"escape_string_warning", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1351                         gettext_noop("Warn about backslash escapes in ordinary string literals."),
1352                         NULL
1353                 },
1354                 &escape_string_warning,
1355                 true,
1356                 NULL, NULL, NULL
1357         },
1358
1359         {
1360                 {"standard_conforming_strings", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1361                         gettext_noop("Causes '...' strings to treat backslashes literally."),
1362                         NULL,
1363                         GUC_REPORT
1364                 },
1365                 &standard_conforming_strings,
1366                 true,
1367                 NULL, NULL, NULL
1368         },
1369
1370         {
1371                 {"synchronize_seqscans", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1372                         gettext_noop("Enable synchronized sequential scans."),
1373                         NULL
1374                 },
1375                 &synchronize_seqscans,
1376                 true,
1377                 NULL, NULL, NULL
1378         },
1379
1380         {
1381                 {"archive_mode", PGC_POSTMASTER, WAL_ARCHIVING,
1382                         gettext_noop("Allows archiving of WAL files using archive_command."),
1383                         NULL
1384                 },
1385                 &XLogArchiveMode,
1386                 false,
1387                 NULL, NULL, NULL
1388         },
1389
1390         {
1391                 {"hot_standby", PGC_POSTMASTER, REPLICATION_STANDBY,
1392                         gettext_noop("Allows connections and queries during recovery."),
1393                         NULL
1394                 },
1395                 &EnableHotStandby,
1396                 false,
1397                 NULL, NULL, NULL
1398         },
1399
1400         {
1401                 {"hot_standby_feedback", PGC_SIGHUP, REPLICATION_STANDBY,
1402                         gettext_noop("Allows feedback from a hot standby to the primary that will avoid query conflicts."),
1403                         NULL
1404                 },
1405                 &hot_standby_feedback,
1406                 false,
1407                 NULL, NULL, NULL
1408         },
1409
1410         {
1411                 {"allow_system_table_mods", PGC_POSTMASTER, DEVELOPER_OPTIONS,
1412                         gettext_noop("Allows modifications of the structure of system tables."),
1413                         NULL,
1414                         GUC_NOT_IN_SAMPLE
1415                 },
1416                 &allowSystemTableMods,
1417                 false,
1418                 NULL, NULL, NULL
1419         },
1420
1421         {
1422                 {"ignore_system_indexes", PGC_BACKEND, DEVELOPER_OPTIONS,
1423                         gettext_noop("Disables reading from system indexes."),
1424                         gettext_noop("It does not prevent updating the indexes, so it is safe "
1425                                                  "to use.  The worst consequence is slowness."),
1426                         GUC_NOT_IN_SAMPLE
1427                 },
1428                 &IgnoreSystemIndexes,
1429                 false,
1430                 NULL, NULL, NULL
1431         },
1432
1433         {
1434                 {"lo_compat_privileges", PGC_SUSET, COMPAT_OPTIONS_PREVIOUS,
1435                         gettext_noop("Enables backward compatibility mode for privilege checks on large objects."),
1436                         gettext_noop("Skips privilege checks when reading or modifying large objects, "
1437                                   "for compatibility with PostgreSQL releases prior to 9.0.")
1438                 },
1439                 &lo_compat_privileges,
1440                 false,
1441                 NULL, NULL, NULL
1442         },
1443
1444         {
1445                 {"quote_all_identifiers", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
1446                         gettext_noop("When generating SQL fragments, quote all identifiers."),
1447                         NULL,
1448                 },
1449                 &quote_all_identifiers,
1450                 false,
1451                 NULL, NULL, NULL
1452         },
1453
1454         /* End-of-list marker */
1455         {
1456                 {NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL, NULL
1457         }
1458 };
1459
1460
1461 static struct config_int ConfigureNamesInt[] =
1462 {
1463         {
1464                 {"archive_timeout", PGC_SIGHUP, WAL_ARCHIVING,
1465                         gettext_noop("Forces a switch to the next xlog file if a "
1466                                                  "new file has not been started within N seconds."),
1467                         NULL,
1468                         GUC_UNIT_S
1469                 },
1470                 &XLogArchiveTimeout,
1471                 0, 0, INT_MAX / 2,
1472                 NULL, NULL, NULL
1473         },
1474         {
1475                 {"post_auth_delay", PGC_BACKEND, DEVELOPER_OPTIONS,
1476                         gettext_noop("Waits N seconds on connection startup after authentication."),
1477                         gettext_noop("This allows attaching a debugger to the process."),
1478                         GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1479                 },
1480                 &PostAuthDelay,
1481                 0, 0, INT_MAX / 1000000,
1482                 NULL, NULL, NULL
1483         },
1484         {
1485                 {"default_statistics_target", PGC_USERSET, QUERY_TUNING_OTHER,
1486                         gettext_noop("Sets the default statistics target."),
1487                         gettext_noop("This applies to table columns that have not had a "
1488                                 "column-specific target set via ALTER TABLE SET STATISTICS.")
1489                 },
1490                 &default_statistics_target,
1491                 100, 1, 10000,
1492                 NULL, NULL, NULL
1493         },
1494         {
1495                 {"from_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1496                         gettext_noop("Sets the FROM-list size beyond which subqueries "
1497                                                  "are not collapsed."),
1498                         gettext_noop("The planner will merge subqueries into upper "
1499                                 "queries if the resulting FROM list would have no more than "
1500                                                  "this many items.")
1501                 },
1502                 &from_collapse_limit,
1503                 8, 1, INT_MAX,
1504                 NULL, NULL, NULL
1505         },
1506         {
1507                 {"join_collapse_limit", PGC_USERSET, QUERY_TUNING_OTHER,
1508                         gettext_noop("Sets the FROM-list size beyond which JOIN "
1509                                                  "constructs are not flattened."),
1510                         gettext_noop("The planner will flatten explicit JOIN "
1511                                                  "constructs into lists of FROM items whenever a "
1512                                                  "list of no more than this many items would result.")
1513                 },
1514                 &join_collapse_limit,
1515                 8, 1, INT_MAX,
1516                 NULL, NULL, NULL
1517         },
1518         {
1519                 {"geqo_threshold", PGC_USERSET, QUERY_TUNING_GEQO,
1520                         gettext_noop("Sets the threshold of FROM items beyond which GEQO is used."),
1521                         NULL
1522                 },
1523                 &geqo_threshold,
1524                 12, 2, INT_MAX,
1525                 NULL, NULL, NULL
1526         },
1527         {
1528                 {"geqo_effort", PGC_USERSET, QUERY_TUNING_GEQO,
1529                         gettext_noop("GEQO: effort is used to set the default for other GEQO parameters."),
1530                         NULL
1531                 },
1532                 &Geqo_effort,
1533                 DEFAULT_GEQO_EFFORT, MIN_GEQO_EFFORT, MAX_GEQO_EFFORT,
1534                 NULL, NULL, NULL
1535         },
1536         {
1537                 {"geqo_pool_size", PGC_USERSET, QUERY_TUNING_GEQO,
1538                         gettext_noop("GEQO: number of individuals in the population."),
1539                         gettext_noop("Zero selects a suitable default value.")
1540                 },
1541                 &Geqo_pool_size,
1542                 0, 0, INT_MAX,
1543                 NULL, NULL, NULL
1544         },
1545         {
1546                 {"geqo_generations", PGC_USERSET, QUERY_TUNING_GEQO,
1547                         gettext_noop("GEQO: number of iterations of the algorithm."),
1548                         gettext_noop("Zero selects a suitable default value.")
1549                 },
1550                 &Geqo_generations,
1551                 0, 0, INT_MAX,
1552                 NULL, NULL, NULL
1553         },
1554
1555         {
1556                 /* This is PGC_SUSET to prevent hiding from log_lock_waits. */
1557                 {"deadlock_timeout", PGC_SUSET, LOCK_MANAGEMENT,
1558                         gettext_noop("Sets the time to wait on a lock before checking for deadlock."),
1559                         NULL,
1560                         GUC_UNIT_MS
1561                 },
1562                 &DeadlockTimeout,
1563                 1000, 1, INT_MAX,
1564                 NULL, NULL, NULL
1565         },
1566
1567         {
1568                 {"max_standby_archive_delay", PGC_SIGHUP, REPLICATION_STANDBY,
1569                         gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing archived WAL data."),
1570                         NULL,
1571                         GUC_UNIT_MS
1572                 },
1573                 &max_standby_archive_delay,
1574                 30 * 1000, -1, INT_MAX,
1575                 NULL, NULL, NULL
1576         },
1577
1578         {
1579                 {"max_standby_streaming_delay", PGC_SIGHUP, REPLICATION_STANDBY,
1580                         gettext_noop("Sets the maximum delay before canceling queries when a hot standby server is processing streamed WAL data."),
1581                         NULL,
1582                         GUC_UNIT_MS
1583                 },
1584                 &max_standby_streaming_delay,
1585                 30 * 1000, -1, INT_MAX,
1586                 NULL, NULL, NULL
1587         },
1588
1589         {
1590                 {"wal_receiver_status_interval", PGC_SIGHUP, REPLICATION_STANDBY,
1591                         gettext_noop("Sets the maximum interval between WAL receiver status reports to the primary."),
1592                         NULL,
1593                         GUC_UNIT_S
1594                 },
1595                 &wal_receiver_status_interval,
1596                 10, 0, INT_MAX / 1000,
1597                 NULL, NULL, NULL
1598         },
1599
1600         {
1601                 {"wal_receiver_timeout", PGC_SIGHUP, REPLICATION_STANDBY,
1602                         gettext_noop("Sets the maximum wait time to receive data from master."),
1603                         NULL,
1604                         GUC_UNIT_MS
1605                 },
1606                 &wal_receiver_timeout,
1607                 60 * 1000, 0, INT_MAX,
1608                 NULL, NULL, NULL
1609         },
1610
1611         {
1612                 {"max_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1613                         gettext_noop("Sets the maximum number of concurrent connections."),
1614                         NULL
1615                 },
1616                 &MaxConnections,
1617                 100, 1, MAX_BACKENDS,
1618                 check_maxconnections, assign_maxconnections, NULL
1619         },
1620
1621         {
1622                 {"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1623                         gettext_noop("Sets the number of connection slots reserved for superusers."),
1624                         NULL
1625                 },
1626                 &ReservedBackends,
1627                 3, 0, MAX_BACKENDS,
1628                 NULL, NULL, NULL
1629         },
1630
1631         /*
1632          * We sometimes multiply the number of shared buffers by two without
1633          * checking for overflow, so we mustn't allow more than INT_MAX / 2.
1634          */
1635         {
1636                 {"shared_buffers", PGC_POSTMASTER, RESOURCES_MEM,
1637                         gettext_noop("Sets the number of shared memory buffers used by the server."),
1638                         NULL,
1639                         GUC_UNIT_BLOCKS
1640                 },
1641                 &NBuffers,
1642                 1024, 16, INT_MAX / 2,
1643                 NULL, NULL, NULL
1644         },
1645
1646         {
1647                 {"temp_buffers", PGC_USERSET, RESOURCES_MEM,
1648                         gettext_noop("Sets the maximum number of temporary buffers used by each session."),
1649                         NULL,
1650                         GUC_UNIT_BLOCKS
1651                 },
1652                 &num_temp_buffers,
1653                 1024, 100, INT_MAX / 2,
1654                 check_temp_buffers, NULL, NULL
1655         },
1656
1657         {
1658                 {"port", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1659                         gettext_noop("Sets the TCP port the server listens on."),
1660                         NULL
1661                 },
1662                 &PostPortNumber,
1663                 DEF_PGPORT, 1, 65535,
1664                 NULL, NULL, NULL
1665         },
1666
1667         {
1668                 {"unix_socket_permissions", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
1669                         gettext_noop("Sets the access permissions of the Unix-domain socket."),
1670                         gettext_noop("Unix-domain sockets use the usual Unix file system "
1671                                                  "permission set. The parameter value is expected "
1672                                                  "to be a numeric mode specification in the form "
1673                                                  "accepted by the chmod and umask system calls. "
1674                                                  "(To use the customary octal format the number must "
1675                                                  "start with a 0 (zero).)")
1676                 },
1677                 &Unix_socket_permissions,
1678                 0777, 0000, 0777,
1679                 NULL, NULL, show_unix_socket_permissions
1680         },
1681
1682         {
1683                 {"log_file_mode", PGC_SIGHUP, LOGGING_WHERE,
1684                         gettext_noop("Sets the file permissions for log files."),
1685                         gettext_noop("The parameter value is expected "
1686                                                  "to be a numeric mode specification in the form "
1687                                                  "accepted by the chmod and umask system calls. "
1688                                                  "(To use the customary octal format the number must "
1689                                                  "start with a 0 (zero).)")
1690                 },
1691                 &Log_file_mode,
1692                 0600, 0000, 0777,
1693                 NULL, NULL, show_log_file_mode
1694         },
1695
1696         {
1697                 {"work_mem", PGC_USERSET, RESOURCES_MEM,
1698                         gettext_noop("Sets the maximum memory to be used for query workspaces."),
1699                         gettext_noop("This much memory can be used by each internal "
1700                                                  "sort operation and hash table before switching to "
1701                                                  "temporary disk files."),
1702                         GUC_UNIT_KB
1703                 },
1704                 &work_mem,
1705                 1024, 64, MAX_KILOBYTES,
1706                 NULL, NULL, NULL
1707         },
1708
1709         {
1710                 {"maintenance_work_mem", PGC_USERSET, RESOURCES_MEM,
1711                         gettext_noop("Sets the maximum memory to be used for maintenance operations."),
1712                         gettext_noop("This includes operations such as VACUUM and CREATE INDEX."),
1713                         GUC_UNIT_KB
1714                 },
1715                 &maintenance_work_mem,
1716                 16384, 1024, MAX_KILOBYTES,
1717                 NULL, NULL, NULL
1718         },
1719
1720         /*
1721          * We use the hopefully-safely-small value of 100kB as the compiled-in
1722          * default for max_stack_depth.  InitializeGUCOptions will increase it if
1723          * possible, depending on the actual platform-specific stack limit.
1724          */
1725         {
1726                 {"max_stack_depth", PGC_SUSET, RESOURCES_MEM,
1727                         gettext_noop("Sets the maximum stack depth, in kilobytes."),
1728                         NULL,
1729                         GUC_UNIT_KB
1730                 },
1731                 &max_stack_depth,
1732                 100, 100, MAX_KILOBYTES,
1733                 check_max_stack_depth, assign_max_stack_depth, NULL
1734         },
1735
1736         {
1737                 {"temp_file_limit", PGC_SUSET, RESOURCES_DISK,
1738                         gettext_noop("Limits the total size of all temporary files used by each session."),
1739                         gettext_noop("-1 means no limit."),
1740                         GUC_UNIT_KB
1741                 },
1742                 &temp_file_limit,
1743                 -1, -1, INT_MAX,
1744                 NULL, NULL, NULL
1745         },
1746
1747         {
1748                 {"vacuum_cost_page_hit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1749                         gettext_noop("Vacuum cost for a page found in the buffer cache."),
1750                         NULL
1751                 },
1752                 &VacuumCostPageHit,
1753                 1, 0, 10000,
1754                 NULL, NULL, NULL
1755         },
1756
1757         {
1758                 {"vacuum_cost_page_miss", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1759                         gettext_noop("Vacuum cost for a page not found in the buffer cache."),
1760                         NULL
1761                 },
1762                 &VacuumCostPageMiss,
1763                 10, 0, 10000,
1764                 NULL, NULL, NULL
1765         },
1766
1767         {
1768                 {"vacuum_cost_page_dirty", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1769                         gettext_noop("Vacuum cost for a page dirtied by vacuum."),
1770                         NULL
1771                 },
1772                 &VacuumCostPageDirty,
1773                 20, 0, 10000,
1774                 NULL, NULL, NULL
1775         },
1776
1777         {
1778                 {"vacuum_cost_limit", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1779                         gettext_noop("Vacuum cost amount available before napping."),
1780                         NULL
1781                 },
1782                 &VacuumCostLimit,
1783                 200, 1, 10000,
1784                 NULL, NULL, NULL
1785         },
1786
1787         {
1788                 {"vacuum_cost_delay", PGC_USERSET, RESOURCES_VACUUM_DELAY,
1789                         gettext_noop("Vacuum cost delay in milliseconds."),
1790                         NULL,
1791                         GUC_UNIT_MS
1792                 },
1793                 &VacuumCostDelay,
1794                 0, 0, 100,
1795                 NULL, NULL, NULL
1796         },
1797
1798         {
1799                 {"autovacuum_vacuum_cost_delay", PGC_SIGHUP, AUTOVACUUM,
1800                         gettext_noop("Vacuum cost delay in milliseconds, for autovacuum."),
1801                         NULL,
1802                         GUC_UNIT_MS
1803                 },
1804                 &autovacuum_vac_cost_delay,
1805                 20, -1, 100,
1806                 NULL, NULL, NULL
1807         },
1808
1809         {
1810                 {"autovacuum_vacuum_cost_limit", PGC_SIGHUP, AUTOVACUUM,
1811                         gettext_noop("Vacuum cost amount available before napping, for autovacuum."),
1812                         NULL
1813                 },
1814                 &autovacuum_vac_cost_limit,
1815                 -1, -1, 10000,
1816                 NULL, NULL, NULL
1817         },
1818
1819         {
1820                 {"max_files_per_process", PGC_POSTMASTER, RESOURCES_KERNEL,
1821                         gettext_noop("Sets the maximum number of simultaneously open files for each server process."),
1822                         NULL
1823                 },
1824                 &max_files_per_process,
1825                 1000, 25, INT_MAX,
1826                 NULL, NULL, NULL
1827         },
1828
1829         /*
1830          * See also CheckRequiredParameterValues() if this parameter changes
1831          */
1832         {
1833                 {"max_prepared_transactions", PGC_POSTMASTER, RESOURCES_MEM,
1834                         gettext_noop("Sets the maximum number of simultaneously prepared transactions."),
1835                         NULL
1836                 },
1837                 &max_prepared_xacts,
1838                 0, 0, MAX_BACKENDS,
1839                 NULL, NULL, NULL
1840         },
1841
1842 #ifdef LOCK_DEBUG
1843         {
1844                 {"trace_lock_oidmin", PGC_SUSET, DEVELOPER_OPTIONS,
1845                         gettext_noop("No description available."),
1846                         NULL,
1847                         GUC_NOT_IN_SAMPLE
1848                 },
1849                 &Trace_lock_oidmin,
1850                 FirstNormalObjectId, 0, INT_MAX,
1851                 NULL, NULL, NULL
1852         },
1853         {
1854                 {"trace_lock_table", PGC_SUSET, DEVELOPER_OPTIONS,
1855                         gettext_noop("No description available."),
1856                         NULL,
1857                         GUC_NOT_IN_SAMPLE
1858                 },
1859                 &Trace_lock_table,
1860                 0, 0, INT_MAX,
1861                 NULL, NULL, NULL
1862         },
1863 #endif
1864
1865         {
1866                 {"statement_timeout", PGC_USERSET, CLIENT_CONN_STATEMENT,
1867                         gettext_noop("Sets the maximum allowed duration of any statement."),
1868                         gettext_noop("A value of 0 turns off the timeout."),
1869                         GUC_UNIT_MS
1870                 },
1871                 &StatementTimeout,
1872                 0, 0, INT_MAX,
1873                 NULL, NULL, NULL
1874         },
1875
1876         {
1877                 {"vacuum_freeze_min_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
1878                         gettext_noop("Minimum age at which VACUUM should freeze a table row."),
1879                         NULL
1880                 },
1881                 &vacuum_freeze_min_age,
1882                 50000000, 0, 1000000000,
1883                 NULL, NULL, NULL
1884         },
1885
1886         {
1887                 {"vacuum_freeze_table_age", PGC_USERSET, CLIENT_CONN_STATEMENT,
1888                         gettext_noop("Age at which VACUUM should scan whole table to freeze tuples."),
1889                         NULL
1890                 },
1891                 &vacuum_freeze_table_age,
1892                 150000000, 0, 2000000000,
1893                 NULL, NULL, NULL
1894         },
1895
1896         {
1897                 {"vacuum_defer_cleanup_age", PGC_SIGHUP, REPLICATION_MASTER,
1898                         gettext_noop("Number of transactions by which VACUUM and HOT cleanup should be deferred, if any."),
1899                         NULL
1900                 },
1901                 &vacuum_defer_cleanup_age,
1902                 0, 0, 1000000,
1903                 NULL, NULL, NULL
1904         },
1905
1906         /*
1907          * See also CheckRequiredParameterValues() if this parameter changes
1908          */
1909         {
1910                 {"max_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
1911                         gettext_noop("Sets the maximum number of locks per transaction."),
1912                         gettext_noop("The shared lock table is sized on the assumption that "
1913                           "at most max_locks_per_transaction * max_connections distinct "
1914                                                  "objects will need to be locked at any one time.")
1915                 },
1916                 &max_locks_per_xact,
1917                 64, 10, INT_MAX,
1918                 NULL, NULL, NULL
1919         },
1920
1921         {
1922                 {"max_pred_locks_per_transaction", PGC_POSTMASTER, LOCK_MANAGEMENT,
1923                         gettext_noop("Sets the maximum number of predicate locks per transaction."),
1924                         gettext_noop("The shared predicate lock table is sized on the assumption that "
1925                                                  "at most max_pred_locks_per_transaction * max_connections distinct "
1926                                                  "objects will need to be locked at any one time.")
1927                 },
1928                 &max_predicate_locks_per_xact,
1929                 64, 10, INT_MAX,
1930                 NULL, NULL, NULL
1931         },
1932
1933         {
1934                 {"authentication_timeout", PGC_SIGHUP, CONN_AUTH_SECURITY,
1935                         gettext_noop("Sets the maximum allowed time to complete client authentication."),
1936                         NULL,
1937                         GUC_UNIT_S
1938                 },
1939                 &AuthenticationTimeout,
1940                 60, 1, 600,
1941                 NULL, NULL, NULL
1942         },
1943
1944         {
1945                 /* Not for general use */
1946                 {"pre_auth_delay", PGC_SIGHUP, DEVELOPER_OPTIONS,
1947                         gettext_noop("Waits N seconds on connection startup before authentication."),
1948                         gettext_noop("This allows attaching a debugger to the process."),
1949                         GUC_NOT_IN_SAMPLE | GUC_UNIT_S
1950                 },
1951                 &PreAuthDelay,
1952                 0, 0, 60,
1953                 NULL, NULL, NULL
1954         },
1955
1956         {
1957                 {"wal_keep_segments", PGC_SIGHUP, REPLICATION_SENDING,
1958                         gettext_noop("Sets the number of WAL files held for standby servers."),
1959                         NULL
1960                 },
1961                 &wal_keep_segments,
1962                 0, 0, INT_MAX,
1963                 NULL, NULL, NULL
1964         },
1965
1966         {
1967                 {"checkpoint_segments", PGC_SIGHUP, WAL_CHECKPOINTS,
1968                         gettext_noop("Sets the maximum distance in log segments between automatic WAL checkpoints."),
1969                         NULL
1970                 },
1971                 &CheckPointSegments,
1972                 3, 1, INT_MAX,
1973                 NULL, NULL, NULL
1974         },
1975
1976         {
1977                 {"checkpoint_timeout", PGC_SIGHUP, WAL_CHECKPOINTS,
1978                         gettext_noop("Sets the maximum time between automatic WAL checkpoints."),
1979                         NULL,
1980                         GUC_UNIT_S
1981                 },
1982                 &CheckPointTimeout,
1983                 300, 30, 3600,
1984                 NULL, NULL, NULL
1985         },
1986
1987         {
1988                 {"checkpoint_warning", PGC_SIGHUP, WAL_CHECKPOINTS,
1989                         gettext_noop("Enables warnings if checkpoint segments are filled more "
1990                                                  "frequently than this."),
1991                         gettext_noop("Write a message to the server log if checkpoints "
1992                         "caused by the filling of checkpoint segment files happens more "
1993                                                  "frequently than this number of seconds. Zero turns off the warning."),
1994                         GUC_UNIT_S
1995                 },
1996                 &CheckPointWarning,
1997                 30, 0, INT_MAX,
1998                 NULL, NULL, NULL
1999         },
2000
2001         {
2002                 {"wal_buffers", PGC_POSTMASTER, WAL_SETTINGS,
2003                         gettext_noop("Sets the number of disk-page buffers in shared memory for WAL."),
2004                         NULL,
2005                         GUC_UNIT_XBLOCKS
2006                 },
2007                 &XLOGbuffers,
2008                 -1, -1, INT_MAX,
2009                 check_wal_buffers, NULL, NULL
2010         },
2011
2012         {
2013                 {"wal_writer_delay", PGC_SIGHUP, WAL_SETTINGS,
2014                         gettext_noop("WAL writer sleep time between WAL flushes."),
2015                         NULL,
2016                         GUC_UNIT_MS
2017                 },
2018                 &WalWriterDelay,
2019                 200, 1, 10000,
2020                 NULL, NULL, NULL
2021         },
2022
2023         {
2024                 /* see max_connections */
2025                 {"max_wal_senders", PGC_POSTMASTER, REPLICATION_SENDING,
2026                         gettext_noop("Sets the maximum number of simultaneously running WAL sender processes."),
2027                         NULL
2028                 },
2029                 &max_wal_senders,
2030                 0, 0, MAX_BACKENDS,
2031                 NULL, NULL, NULL
2032         },
2033
2034         {
2035                 {"wal_sender_timeout", PGC_SIGHUP, REPLICATION_SENDING,
2036                         gettext_noop("Sets the maximum time to wait for WAL replication."),
2037                         NULL,
2038                         GUC_UNIT_MS
2039                 },
2040                 &wal_sender_timeout,
2041                 60 * 1000, 0, INT_MAX,
2042                 NULL, NULL, NULL
2043         },
2044
2045         {
2046                 {"commit_delay", PGC_USERSET, WAL_SETTINGS,
2047                         gettext_noop("Sets the delay in microseconds between transaction commit and "
2048                                                  "flushing WAL to disk."),
2049                         NULL
2050                         /* we have no microseconds designation, so can't supply units here */
2051                 },
2052                 &CommitDelay,
2053                 0, 0, 100000,
2054                 NULL, NULL, NULL
2055         },
2056
2057         {
2058                 {"commit_siblings", PGC_USERSET, WAL_SETTINGS,
2059                         gettext_noop("Sets the minimum concurrent open transactions before performing "
2060                                                  "commit_delay."),
2061                         NULL
2062                 },
2063                 &CommitSiblings,
2064                 5, 0, 1000,
2065                 NULL, NULL, NULL
2066         },
2067
2068         {
2069                 {"extra_float_digits", PGC_USERSET, CLIENT_CONN_LOCALE,
2070                         gettext_noop("Sets the number of digits displayed for floating-point values."),
2071                         gettext_noop("This affects real, double precision, and geometric data types. "
2072                          "The parameter value is added to the standard number of digits "
2073                                                  "(FLT_DIG or DBL_DIG as appropriate).")
2074                 },
2075                 &extra_float_digits,
2076                 0, -15, 3,
2077                 NULL, NULL, NULL
2078         },
2079
2080         {
2081                 {"log_min_duration_statement", PGC_SUSET, LOGGING_WHEN,
2082                         gettext_noop("Sets the minimum execution time above which "
2083                                                  "statements will be logged."),
2084                         gettext_noop("Zero prints all queries. -1 turns this feature off."),
2085                         GUC_UNIT_MS
2086                 },
2087                 &log_min_duration_statement,
2088                 -1, -1, INT_MAX,
2089                 NULL, NULL, NULL
2090         },
2091
2092         {
2093                 {"log_autovacuum_min_duration", PGC_SIGHUP, LOGGING_WHAT,
2094                         gettext_noop("Sets the minimum execution time above which "
2095                                                  "autovacuum actions will be logged."),
2096                         gettext_noop("Zero prints all actions. -1 turns autovacuum logging off."),
2097                         GUC_UNIT_MS
2098                 },
2099                 &Log_autovacuum_min_duration,
2100                 -1, -1, INT_MAX,
2101                 NULL, NULL, NULL
2102         },
2103
2104         {
2105                 {"bgwriter_delay", PGC_SIGHUP, RESOURCES_BGWRITER,
2106                         gettext_noop("Background writer sleep time between rounds."),
2107                         NULL,
2108                         GUC_UNIT_MS
2109                 },
2110                 &BgWriterDelay,
2111                 200, 10, 10000,
2112                 NULL, NULL, NULL
2113         },
2114
2115         {
2116                 {"bgwriter_lru_maxpages", PGC_SIGHUP, RESOURCES_BGWRITER,
2117                         gettext_noop("Background writer maximum number of LRU pages to flush per round."),
2118                         NULL
2119                 },
2120                 &bgwriter_lru_maxpages,
2121                 100, 0, 1000,
2122                 NULL, NULL, NULL
2123         },
2124
2125         {
2126                 {"effective_io_concurrency",
2127 #ifdef USE_PREFETCH
2128                         PGC_USERSET,
2129 #else
2130                         PGC_INTERNAL,
2131 #endif
2132                         RESOURCES_ASYNCHRONOUS,
2133                         gettext_noop("Number of simultaneous requests that can be handled efficiently by the disk subsystem."),
2134                         gettext_noop("For RAID arrays, this should be approximately the number of drive spindles in the array.")
2135                 },
2136                 &effective_io_concurrency,
2137 #ifdef USE_PREFETCH
2138                 1, 0, 1000,
2139 #else
2140                 0, 0, 0,
2141 #endif
2142                 check_effective_io_concurrency, assign_effective_io_concurrency, NULL
2143         },
2144
2145         {
2146                 {"log_rotation_age", PGC_SIGHUP, LOGGING_WHERE,
2147                         gettext_noop("Automatic log file rotation will occur after N minutes."),
2148                         NULL,
2149                         GUC_UNIT_MIN
2150                 },
2151                 &Log_RotationAge,
2152                 HOURS_PER_DAY * MINS_PER_HOUR, 0, INT_MAX / SECS_PER_MINUTE,
2153                 NULL, NULL, NULL
2154         },
2155
2156         {
2157                 {"log_rotation_size", PGC_SIGHUP, LOGGING_WHERE,
2158                         gettext_noop("Automatic log file rotation will occur after N kilobytes."),
2159                         NULL,
2160                         GUC_UNIT_KB
2161                 },
2162                 &Log_RotationSize,
2163                 10 * 1024, 0, INT_MAX / 1024,
2164                 NULL, NULL, NULL
2165         },
2166
2167         {
2168                 {"max_function_args", PGC_INTERNAL, PRESET_OPTIONS,
2169                         gettext_noop("Shows the maximum number of function arguments."),
2170                         NULL,
2171                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2172                 },
2173                 &max_function_args,
2174                 FUNC_MAX_ARGS, FUNC_MAX_ARGS, FUNC_MAX_ARGS,
2175                 NULL, NULL, NULL
2176         },
2177
2178         {
2179                 {"max_index_keys", PGC_INTERNAL, PRESET_OPTIONS,
2180                         gettext_noop("Shows the maximum number of index keys."),
2181                         NULL,
2182                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2183                 },
2184                 &max_index_keys,
2185                 INDEX_MAX_KEYS, INDEX_MAX_KEYS, INDEX_MAX_KEYS,
2186                 NULL, NULL, NULL
2187         },
2188
2189         {
2190                 {"max_identifier_length", PGC_INTERNAL, PRESET_OPTIONS,
2191                         gettext_noop("Shows the maximum identifier length."),
2192                         NULL,
2193                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2194                 },
2195                 &max_identifier_length,
2196                 NAMEDATALEN - 1, NAMEDATALEN - 1, NAMEDATALEN - 1,
2197                 NULL, NULL, NULL
2198         },
2199
2200         {
2201                 {"block_size", PGC_INTERNAL, PRESET_OPTIONS,
2202                         gettext_noop("Shows the size of a disk block."),
2203                         NULL,
2204                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2205                 },
2206                 &block_size,
2207                 BLCKSZ, BLCKSZ, BLCKSZ,
2208                 NULL, NULL, NULL
2209         },
2210
2211         {
2212                 {"segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2213                         gettext_noop("Shows the number of pages per disk file."),
2214                         NULL,
2215                         GUC_UNIT_BLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2216                 },
2217                 &segment_size,
2218                 RELSEG_SIZE, RELSEG_SIZE, RELSEG_SIZE,
2219                 NULL, NULL, NULL
2220         },
2221
2222         {
2223                 {"wal_block_size", PGC_INTERNAL, PRESET_OPTIONS,
2224                         gettext_noop("Shows the block size in the write ahead log."),
2225                         NULL,
2226                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2227                 },
2228                 &wal_block_size,
2229                 XLOG_BLCKSZ, XLOG_BLCKSZ, XLOG_BLCKSZ,
2230                 NULL, NULL, NULL
2231         },
2232
2233         {
2234                 {"wal_segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2235                         gettext_noop("Shows the number of pages per write ahead log segment."),
2236                         NULL,
2237                         GUC_UNIT_XBLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2238                 },
2239                 &wal_segment_size,
2240                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2241                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2242                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2243                 NULL, NULL, NULL
2244         },
2245
2246         {
2247                 {"autovacuum_naptime", PGC_SIGHUP, AUTOVACUUM,
2248                         gettext_noop("Time to sleep between autovacuum runs."),
2249                         NULL,
2250                         GUC_UNIT_S
2251                 },
2252                 &autovacuum_naptime,
2253                 60, 1, INT_MAX / 1000,
2254                 NULL, NULL, NULL
2255         },
2256         {
2257                 {"autovacuum_vacuum_threshold", PGC_SIGHUP, AUTOVACUUM,
2258                         gettext_noop("Minimum number of tuple updates or deletes prior to vacuum."),
2259                         NULL
2260                 },
2261                 &autovacuum_vac_thresh,
2262                 50, 0, INT_MAX,
2263                 NULL, NULL, NULL
2264         },
2265         {
2266                 {"autovacuum_analyze_threshold", PGC_SIGHUP, AUTOVACUUM,
2267                         gettext_noop("Minimum number of tuple inserts, updates, or deletes prior to analyze."),
2268                         NULL
2269                 },
2270                 &autovacuum_anl_thresh,
2271                 50, 0, INT_MAX,
2272                 NULL, NULL, NULL
2273         },
2274         {
2275                 /* see varsup.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
2276                 {"autovacuum_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
2277                         gettext_noop("Age at which to autovacuum a table to prevent transaction ID wraparound."),
2278                         NULL
2279                 },
2280                 &autovacuum_freeze_max_age,
2281                 /* see pg_resetxlog if you change the upper-limit value */
2282                 200000000, 100000000, 2000000000,
2283                 NULL, NULL, NULL
2284         },
2285         {
2286                 /* see max_connections */
2287                 {"autovacuum_max_workers", PGC_POSTMASTER, AUTOVACUUM,
2288                         gettext_noop("Sets the maximum number of simultaneously running autovacuum worker processes."),
2289                         NULL
2290                 },
2291                 &autovacuum_max_workers,
2292                 3, 1, MAX_BACKENDS,
2293                 check_autovacuum_max_workers, assign_autovacuum_max_workers, NULL
2294         },
2295
2296         {
2297                 {"tcp_keepalives_idle", PGC_USERSET, CLIENT_CONN_OTHER,
2298                         gettext_noop("Time between issuing TCP keepalives."),
2299                         gettext_noop("A value of 0 uses the system default."),
2300                         GUC_UNIT_S
2301                 },
2302                 &tcp_keepalives_idle,
2303                 0, 0, INT_MAX,
2304                 NULL, assign_tcp_keepalives_idle, show_tcp_keepalives_idle
2305         },
2306
2307         {
2308                 {"tcp_keepalives_interval", PGC_USERSET, CLIENT_CONN_OTHER,
2309                         gettext_noop("Time between TCP keepalive retransmits."),
2310                         gettext_noop("A value of 0 uses the system default."),
2311                         GUC_UNIT_S
2312                 },
2313                 &tcp_keepalives_interval,
2314                 0, 0, INT_MAX,
2315                 NULL, assign_tcp_keepalives_interval, show_tcp_keepalives_interval
2316         },
2317
2318         {
2319                 {"ssl_renegotiation_limit", PGC_USERSET, CONN_AUTH_SECURITY,
2320                         gettext_noop("Set the amount of traffic to send and receive before renegotiating the encryption keys."),
2321                         NULL,
2322                         GUC_UNIT_KB,
2323                 },
2324                 &ssl_renegotiation_limit,
2325                 512 * 1024, 0, MAX_KILOBYTES,
2326                 NULL, NULL, NULL
2327         },
2328
2329         {
2330                 {"tcp_keepalives_count", PGC_USERSET, CLIENT_CONN_OTHER,
2331                         gettext_noop("Maximum number of TCP keepalive retransmits."),
2332                         gettext_noop("This controls the number of consecutive keepalive retransmits that can be "
2333                                                  "lost before a connection is considered dead. A value of 0 uses the "
2334                                                  "system default."),
2335                 },
2336                 &tcp_keepalives_count,
2337                 0, 0, INT_MAX,
2338                 NULL, assign_tcp_keepalives_count, show_tcp_keepalives_count
2339         },
2340
2341         {
2342                 {"gin_fuzzy_search_limit", PGC_USERSET, CLIENT_CONN_OTHER,
2343                         gettext_noop("Sets the maximum allowed result for exact search by GIN."),
2344                         NULL,
2345                         0
2346                 },
2347                 &GinFuzzySearchLimit,
2348                 0, 0, INT_MAX,
2349                 NULL, NULL, NULL
2350         },
2351
2352         {
2353                 {"effective_cache_size", PGC_USERSET, QUERY_TUNING_COST,
2354                         gettext_noop("Sets the planner's assumption about the size of the disk cache."),
2355                         gettext_noop("That is, the portion of the kernel's disk cache that "
2356                                                  "will be used for PostgreSQL data files. This is measured in disk "
2357                                                  "pages, which are normally 8 kB each."),
2358                         GUC_UNIT_BLOCKS,
2359                 },
2360                 &effective_cache_size,
2361                 DEFAULT_EFFECTIVE_CACHE_SIZE, 1, INT_MAX,
2362                 NULL, NULL, NULL
2363         },
2364
2365         {
2366                 /* Can't be set in postgresql.conf */
2367                 {"server_version_num", PGC_INTERNAL, PRESET_OPTIONS,
2368                         gettext_noop("Shows the server version as an integer."),
2369                         NULL,
2370                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2371                 },
2372                 &server_version_num,
2373                 PG_VERSION_NUM, PG_VERSION_NUM, PG_VERSION_NUM,
2374                 NULL, NULL, NULL
2375         },
2376
2377         {
2378                 {"log_temp_files", PGC_SUSET, LOGGING_WHAT,
2379                         gettext_noop("Log the use of temporary files larger than this number of kilobytes."),
2380                         gettext_noop("Zero logs all files. The default is -1 (turning this feature off)."),
2381                         GUC_UNIT_KB
2382                 },
2383                 &log_temp_files,
2384                 -1, -1, INT_MAX,
2385                 NULL, NULL, NULL
2386         },
2387
2388         {
2389                 {"track_activity_query_size", PGC_POSTMASTER, RESOURCES_MEM,
2390                         gettext_noop("Sets the size reserved for pg_stat_activity.query, in bytes."),
2391                         NULL,
2392                 },
2393                 &pgstat_track_activity_query_size,
2394                 1024, 100, 102400,
2395                 NULL, NULL, NULL
2396         },
2397
2398         /* End-of-list marker */
2399         {
2400                 {NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL, NULL
2401         }
2402 };
2403
2404
2405 static struct config_real ConfigureNamesReal[] =
2406 {
2407         {
2408                 {"seq_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2409                         gettext_noop("Sets the planner's estimate of the cost of a "
2410                                                  "sequentially fetched disk page."),
2411                         NULL
2412                 },
2413                 &seq_page_cost,
2414                 DEFAULT_SEQ_PAGE_COST, 0, DBL_MAX,
2415                 NULL, NULL, NULL
2416         },
2417         {
2418                 {"random_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2419                         gettext_noop("Sets the planner's estimate of the cost of a "
2420                                                  "nonsequentially fetched disk page."),
2421                         NULL
2422                 },
2423                 &random_page_cost,
2424                 DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX,
2425                 NULL, NULL, NULL
2426         },
2427         {
2428                 {"cpu_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2429                         gettext_noop("Sets the planner's estimate of the cost of "
2430                                                  "processing each tuple (row)."),
2431                         NULL
2432                 },
2433                 &cpu_tuple_cost,
2434                 DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX,
2435                 NULL, NULL, NULL
2436         },
2437         {
2438                 {"cpu_index_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2439                         gettext_noop("Sets the planner's estimate of the cost of "
2440                                                  "processing each index entry during an index scan."),
2441                         NULL
2442                 },
2443                 &cpu_index_tuple_cost,
2444                 DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX,
2445                 NULL, NULL, NULL
2446         },
2447         {
2448                 {"cpu_operator_cost", PGC_USERSET, QUERY_TUNING_COST,
2449                         gettext_noop("Sets the planner's estimate of the cost of "
2450                                                  "processing each operator or function call."),
2451                         NULL
2452                 },
2453                 &cpu_operator_cost,
2454                 DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX,
2455                 NULL, NULL, NULL
2456         },
2457
2458         {
2459                 {"cursor_tuple_fraction", PGC_USERSET, QUERY_TUNING_OTHER,
2460                         gettext_noop("Sets the planner's estimate of the fraction of "
2461                                                  "a cursor's rows that will be retrieved."),
2462                         NULL
2463                 },
2464                 &cursor_tuple_fraction,
2465                 DEFAULT_CURSOR_TUPLE_FRACTION, 0.0, 1.0,
2466                 NULL, NULL, NULL
2467         },
2468
2469         {
2470                 {"geqo_selection_bias", PGC_USERSET, QUERY_TUNING_GEQO,
2471                         gettext_noop("GEQO: selective pressure within the population."),
2472                         NULL
2473                 },
2474                 &Geqo_selection_bias,
2475                 DEFAULT_GEQO_SELECTION_BIAS,
2476                 MIN_GEQO_SELECTION_BIAS, MAX_GEQO_SELECTION_BIAS,
2477                 NULL, NULL, NULL
2478         },
2479         {
2480                 {"geqo_seed", PGC_USERSET, QUERY_TUNING_GEQO,
2481                         gettext_noop("GEQO: seed for random path selection."),
2482                         NULL
2483                 },
2484                 &Geqo_seed,
2485                 0.0, 0.0, 1.0,
2486                 NULL, NULL, NULL
2487         },
2488
2489         {
2490                 {"bgwriter_lru_multiplier", PGC_SIGHUP, RESOURCES_BGWRITER,
2491                         gettext_noop("Multiple of the average buffer usage to free per round."),
2492                         NULL
2493                 },
2494                 &bgwriter_lru_multiplier,
2495                 2.0, 0.0, 10.0,
2496                 NULL, NULL, NULL
2497         },
2498
2499         {
2500                 {"seed", PGC_USERSET, UNGROUPED,
2501                         gettext_noop("Sets the seed for random-number generation."),
2502                         NULL,
2503                         GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2504                 },
2505                 &phony_random_seed,
2506                 0.0, -1.0, 1.0,
2507                 check_random_seed, assign_random_seed, show_random_seed
2508         },
2509
2510         {
2511                 {"autovacuum_vacuum_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2512                         gettext_noop("Number of tuple updates or deletes prior to vacuum as a fraction of reltuples."),
2513                         NULL
2514                 },
2515                 &autovacuum_vac_scale,
2516                 0.2, 0.0, 100.0,
2517                 NULL, NULL, NULL
2518         },
2519         {
2520                 {"autovacuum_analyze_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2521                         gettext_noop("Number of tuple inserts, updates, or deletes prior to analyze as a fraction of reltuples."),
2522                         NULL
2523                 },
2524                 &autovacuum_anl_scale,
2525                 0.1, 0.0, 100.0,
2526                 NULL, NULL, NULL
2527         },
2528
2529         {
2530                 {"checkpoint_completion_target", PGC_SIGHUP, WAL_CHECKPOINTS,
2531                         gettext_noop("Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval."),
2532                         NULL
2533                 },
2534                 &CheckPointCompletionTarget,
2535                 0.5, 0.0, 1.0,
2536                 NULL, NULL, NULL
2537         },
2538
2539         /* End-of-list marker */
2540         {
2541                 {NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL, NULL
2542         }
2543 };
2544
2545
2546 static struct config_string ConfigureNamesString[] =
2547 {
2548         {
2549                 {"archive_command", PGC_SIGHUP, WAL_ARCHIVING,
2550                         gettext_noop("Sets the shell command that will be called to archive a WAL file."),
2551                         NULL
2552                 },
2553                 &XLogArchiveCommand,
2554                 "",
2555                 NULL, NULL, show_archive_command
2556         },
2557
2558         {
2559                 {"client_encoding", PGC_USERSET, CLIENT_CONN_LOCALE,
2560                         gettext_noop("Sets the client's character set encoding."),
2561                         NULL,
2562                         GUC_IS_NAME | GUC_REPORT
2563                 },
2564                 &client_encoding_string,
2565                 "SQL_ASCII",
2566                 check_client_encoding, assign_client_encoding, NULL
2567         },
2568
2569         {
2570                 {"log_line_prefix", PGC_SIGHUP, LOGGING_WHAT,
2571                         gettext_noop("Controls information prefixed to each log line."),
2572                         gettext_noop("If blank, no prefix is used.")
2573                 },
2574                 &Log_line_prefix,
2575                 "",
2576                 NULL, NULL, NULL
2577         },
2578
2579         {
2580                 {"log_timezone", PGC_SIGHUP, LOGGING_WHAT,
2581                         gettext_noop("Sets the time zone to use in log messages."),
2582                         NULL
2583                 },
2584                 &log_timezone_string,
2585                 "GMT",
2586                 check_log_timezone, assign_log_timezone, show_log_timezone
2587         },
2588
2589         {
2590                 {"DateStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
2591                         gettext_noop("Sets the display format for date and time values."),
2592                         gettext_noop("Also controls interpretation of ambiguous "
2593                                                  "date inputs."),
2594                         GUC_LIST_INPUT | GUC_REPORT
2595                 },
2596                 &datestyle_string,
2597                 "ISO, MDY",
2598                 check_datestyle, assign_datestyle, NULL
2599         },
2600
2601         {
2602                 {"default_tablespace", PGC_USERSET, CLIENT_CONN_STATEMENT,
2603                         gettext_noop("Sets the default tablespace to create tables and indexes in."),
2604                         gettext_noop("An empty string selects the database's default tablespace."),
2605                         GUC_IS_NAME
2606                 },
2607                 &default_tablespace,
2608                 "",
2609                 check_default_tablespace, NULL, NULL
2610         },
2611
2612         {
2613                 {"temp_tablespaces", PGC_USERSET, CLIENT_CONN_STATEMENT,
2614                         gettext_noop("Sets the tablespace(s) to use for temporary tables and sort files."),
2615                         NULL,
2616                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2617                 },
2618                 &temp_tablespaces,
2619                 "",
2620                 check_temp_tablespaces, assign_temp_tablespaces, NULL
2621         },
2622
2623         {
2624                 {"dynamic_library_path", PGC_SUSET, CLIENT_CONN_OTHER,
2625                         gettext_noop("Sets the path for dynamically loadable modules."),
2626                         gettext_noop("If a dynamically loadable module needs to be opened and "
2627                                                  "the specified name does not have a directory component (i.e., the "
2628                                                  "name does not contain a slash), the system will search this path for "
2629                                                  "the specified file."),
2630                         GUC_SUPERUSER_ONLY
2631                 },
2632                 &Dynamic_library_path,
2633                 "$libdir",
2634                 NULL, NULL, NULL
2635         },
2636
2637         {
2638                 {"krb_server_keyfile", PGC_SIGHUP, CONN_AUTH_SECURITY,
2639                         gettext_noop("Sets the location of the Kerberos server key file."),
2640                         NULL,
2641                         GUC_SUPERUSER_ONLY
2642                 },
2643                 &pg_krb_server_keyfile,
2644                 PG_KRB_SRVTAB,
2645                 NULL, NULL, NULL
2646         },
2647
2648         {
2649                 {"krb_srvname", PGC_SIGHUP, CONN_AUTH_SECURITY,
2650                         gettext_noop("Sets the name of the Kerberos service."),
2651                         NULL
2652                 },
2653                 &pg_krb_srvnam,
2654                 PG_KRB_SRVNAM,
2655                 NULL, NULL, NULL
2656         },
2657
2658         {
2659                 {"bonjour_name", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2660                         gettext_noop("Sets the Bonjour service name."),
2661                         NULL
2662                 },
2663                 &bonjour_name,
2664                 "",
2665                 NULL, NULL, NULL
2666         },
2667
2668         /* See main.c about why defaults for LC_foo are not all alike */
2669
2670         {
2671                 {"lc_collate", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2672                         gettext_noop("Shows the collation order locale."),
2673                         NULL,
2674                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2675                 },
2676                 &locale_collate,
2677                 "C",
2678                 NULL, NULL, NULL
2679         },
2680
2681         {
2682                 {"lc_ctype", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2683                         gettext_noop("Shows the character classification and case conversion locale."),
2684                         NULL,
2685                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2686                 },
2687                 &locale_ctype,
2688                 "C",
2689                 NULL, NULL, NULL
2690         },
2691
2692         {
2693                 {"lc_messages", PGC_SUSET, CLIENT_CONN_LOCALE,
2694                         gettext_noop("Sets the language in which messages are displayed."),
2695                         NULL
2696                 },
2697                 &locale_messages,
2698                 "",
2699                 check_locale_messages, assign_locale_messages, NULL
2700         },
2701
2702         {
2703                 {"lc_monetary", PGC_USERSET, CLIENT_CONN_LOCALE,
2704                         gettext_noop("Sets the locale for formatting monetary amounts."),
2705                         NULL
2706                 },
2707                 &locale_monetary,
2708                 "C",
2709                 check_locale_monetary, assign_locale_monetary, NULL
2710         },
2711
2712         {
2713                 {"lc_numeric", PGC_USERSET, CLIENT_CONN_LOCALE,
2714                         gettext_noop("Sets the locale for formatting numbers."),
2715                         NULL
2716                 },
2717                 &locale_numeric,
2718                 "C",
2719                 check_locale_numeric, assign_locale_numeric, NULL
2720         },
2721
2722         {
2723                 {"lc_time", PGC_USERSET, CLIENT_CONN_LOCALE,
2724                         gettext_noop("Sets the locale for formatting date and time values."),
2725                         NULL
2726                 },
2727                 &locale_time,
2728                 "C",
2729                 check_locale_time, assign_locale_time, NULL
2730         },
2731
2732         {
2733                 {"shared_preload_libraries", PGC_POSTMASTER, RESOURCES_KERNEL,
2734                         gettext_noop("Lists shared libraries to preload into server."),
2735                         NULL,
2736                         GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
2737                 },
2738                 &shared_preload_libraries_string,
2739                 "",
2740                 NULL, NULL, NULL
2741         },
2742
2743         {
2744                 {"local_preload_libraries", PGC_BACKEND, CLIENT_CONN_OTHER,
2745                         gettext_noop("Lists shared libraries to preload into each backend."),
2746                         NULL,
2747                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2748                 },
2749                 &local_preload_libraries_string,
2750                 "",
2751                 NULL, NULL, NULL
2752         },
2753
2754         {
2755                 {"search_path", PGC_USERSET, CLIENT_CONN_STATEMENT,
2756                         gettext_noop("Sets the schema search order for names that are not schema-qualified."),
2757                         NULL,
2758                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2759                 },
2760                 &namespace_search_path,
2761                 "\"$user\",public",
2762                 check_search_path, assign_search_path, NULL
2763         },
2764
2765         {
2766                 /* Can't be set in postgresql.conf */
2767                 {"server_encoding", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2768                         gettext_noop("Sets the server (database) character set encoding."),
2769                         NULL,
2770                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2771                 },
2772                 &server_encoding_string,
2773                 "SQL_ASCII",
2774                 NULL, NULL, NULL
2775         },
2776
2777         {
2778                 /* Can't be set in postgresql.conf */
2779                 {"server_version", PGC_INTERNAL, PRESET_OPTIONS,
2780                         gettext_noop("Shows the server version."),
2781                         NULL,
2782                         GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2783                 },
2784                 &server_version_string,
2785                 PG_VERSION,
2786                 NULL, NULL, NULL
2787         },
2788
2789         {
2790                 /* Not for general use --- used by SET ROLE */
2791                 {"role", PGC_USERSET, UNGROUPED,
2792                         gettext_noop("Sets the current role."),
2793                         NULL,
2794                         GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
2795                 },
2796                 &role_string,
2797                 "none",
2798                 check_role, assign_role, show_role
2799         },
2800
2801         {
2802                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
2803                 {"session_authorization", PGC_USERSET, UNGROUPED,
2804                         gettext_noop("Sets the session user name."),
2805                         NULL,
2806                         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
2807                 },
2808                 &session_authorization_string,
2809                 NULL,
2810                 check_session_authorization, assign_session_authorization, NULL
2811         },
2812
2813         {
2814                 {"log_destination", PGC_SIGHUP, LOGGING_WHERE,
2815                         gettext_noop("Sets the destination for server log output."),
2816                         gettext_noop("Valid values are combinations of \"stderr\", "
2817                                                  "\"syslog\", \"csvlog\", and \"eventlog\", "
2818                                                  "depending on the platform."),
2819                         GUC_LIST_INPUT
2820                 },
2821                 &log_destination_string,
2822                 "stderr",
2823                 check_log_destination, assign_log_destination, NULL
2824         },
2825         {
2826                 {"log_directory", PGC_SIGHUP, LOGGING_WHERE,
2827                         gettext_noop("Sets the destination directory for log files."),
2828                         gettext_noop("Can be specified as relative to the data directory "
2829                                                  "or as absolute path."),
2830                         GUC_SUPERUSER_ONLY
2831                 },
2832                 &Log_directory,
2833                 "pg_log",
2834                 check_canonical_path, NULL, NULL
2835         },
2836         {
2837                 {"log_filename", PGC_SIGHUP, LOGGING_WHERE,
2838                         gettext_noop("Sets the file name pattern for log files."),
2839                         NULL,
2840                         GUC_SUPERUSER_ONLY
2841                 },
2842                 &Log_filename,
2843                 "postgresql-%Y-%m-%d_%H%M%S.log",
2844                 NULL, NULL, NULL
2845         },
2846
2847         {
2848                 {"syslog_ident", PGC_SIGHUP, LOGGING_WHERE,
2849                         gettext_noop("Sets the program name used to identify PostgreSQL "
2850                                                  "messages in syslog."),
2851                         NULL
2852                 },
2853                 &syslog_ident_str,
2854                 "postgres",
2855                 NULL, assign_syslog_ident, NULL
2856         },
2857
2858         {
2859                 {"event_source", PGC_POSTMASTER, LOGGING_WHERE,
2860                         gettext_noop("Sets the application name used to identify "
2861                                                  "PostgreSQL messages in the event log."),
2862                         NULL
2863                 },
2864                 &event_source,
2865                 "PostgreSQL",
2866                 NULL, NULL, NULL
2867         },
2868
2869         {
2870                 {"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
2871                         gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
2872                         NULL,
2873                         GUC_REPORT
2874                 },
2875                 &timezone_string,
2876                 "GMT",
2877                 check_timezone, assign_timezone, show_timezone
2878         },
2879         {
2880                 {"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
2881                         gettext_noop("Selects a file of time zone abbreviations."),
2882                         NULL
2883                 },
2884                 &timezone_abbreviations_string,
2885                 NULL,
2886                 check_timezone_abbreviations, assign_timezone_abbreviations, NULL
2887         },
2888
2889         {
2890                 {"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2891                         gettext_noop("Sets the current transaction's isolation level."),
2892                         NULL,
2893                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2894                 },
2895                 &XactIsoLevel_string,
2896                 "default",
2897                 check_XactIsoLevel, assign_XactIsoLevel, show_XactIsoLevel
2898         },
2899
2900         {
2901                 {"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2902                         gettext_noop("Sets the owning group of the Unix-domain socket."),
2903                         gettext_noop("The owning user of the socket is always the user "
2904                                                  "that starts the server.")
2905                 },
2906                 &Unix_socket_group,
2907                 "",
2908                 NULL, NULL, NULL
2909         },
2910
2911         {
2912                 {"unix_socket_directories", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2913                         gettext_noop("Sets the directories where Unix-domain sockets will be created."),
2914                         NULL,
2915                         GUC_SUPERUSER_ONLY
2916                 },
2917                 &Unix_socket_directories,
2918 #ifdef HAVE_UNIX_SOCKETS
2919                 DEFAULT_PGSOCKET_DIR,
2920 #else
2921                 "",
2922 #endif
2923                 NULL, NULL, NULL
2924         },
2925
2926         {
2927                 {"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2928                         gettext_noop("Sets the host name or IP address(es) to listen to."),
2929                         NULL,
2930                         GUC_LIST_INPUT
2931                 },
2932                 &ListenAddresses,
2933                 "localhost",
2934                 NULL, NULL, NULL
2935         },
2936
2937         {
2938                 {"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
2939                         gettext_noop("Sets the server's data directory."),
2940                         NULL,
2941                         GUC_SUPERUSER_ONLY
2942                 },
2943                 &data_directory,
2944                 NULL,
2945                 NULL, NULL, NULL
2946         },
2947
2948         {
2949                 {"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
2950                         gettext_noop("Sets the server's main configuration file."),
2951                         NULL,
2952                         GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
2953                 },
2954                 &ConfigFileName,
2955                 NULL,
2956                 NULL, NULL, NULL
2957         },
2958
2959         {
2960                 {"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
2961                         gettext_noop("Sets the server's \"hba\" configuration file."),
2962                         NULL,
2963                         GUC_SUPERUSER_ONLY
2964                 },
2965                 &HbaFileName,
2966                 NULL,
2967                 NULL, NULL, NULL
2968         },
2969
2970         {
2971                 {"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
2972                         gettext_noop("Sets the server's \"ident\" configuration file."),
2973                         NULL,
2974                         GUC_SUPERUSER_ONLY
2975                 },
2976                 &IdentFileName,
2977                 NULL,
2978                 NULL, NULL, NULL
2979         },
2980
2981         {
2982                 {"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
2983                         gettext_noop("Writes the postmaster PID to the specified file."),
2984                         NULL,
2985                         GUC_SUPERUSER_ONLY
2986                 },
2987                 &external_pid_file,
2988                 NULL,
2989                 check_canonical_path, NULL, NULL
2990         },
2991
2992         {
2993                 {"ssl_cert_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2994                         gettext_noop("Location of the SSL server certificate file."),
2995                         NULL
2996                 },
2997                 &ssl_cert_file,
2998                 "server.crt",
2999                 NULL, NULL, NULL
3000         },
3001
3002         {
3003                 {"ssl_key_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3004                         gettext_noop("Location of the SSL server private key file."),
3005                         NULL
3006                 },
3007                 &ssl_key_file,
3008                 "server.key",
3009                 NULL, NULL, NULL
3010         },
3011
3012         {
3013                 {"ssl_ca_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3014                         gettext_noop("Location of the SSL certificate authority file."),
3015                         NULL
3016                 },
3017                 &ssl_ca_file,
3018                 "",
3019                 NULL, NULL, NULL
3020         },
3021
3022         {
3023                 {"ssl_crl_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3024                         gettext_noop("Location of the SSL certificate revocation list file."),
3025                         NULL
3026                 },
3027                 &ssl_crl_file,
3028                 "",
3029                 NULL, NULL, NULL
3030         },
3031
3032         {
3033                 {"stats_temp_directory", PGC_SIGHUP, STATS_COLLECTOR,
3034                         gettext_noop("Writes temporary statistics files to the specified directory."),
3035                         NULL,
3036                         GUC_SUPERUSER_ONLY
3037                 },
3038                 &pgstat_temp_directory,
3039                 "pg_stat_tmp",
3040                 check_canonical_path, assign_pgstat_temp_directory, NULL
3041         },
3042
3043         {
3044                 {"synchronous_standby_names", PGC_SIGHUP, REPLICATION_MASTER,
3045                         gettext_noop("List of names of potential synchronous standbys."),
3046                         NULL,
3047                         GUC_LIST_INPUT
3048                 },
3049                 &SyncRepStandbyNames,
3050                 "",
3051                 check_synchronous_standby_names, NULL, NULL
3052         },
3053
3054         {
3055                 {"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
3056                         gettext_noop("Sets default text search configuration."),
3057                         NULL
3058                 },
3059                 &TSCurrentConfig,
3060                 "pg_catalog.simple",
3061                 check_TSCurrentConfig, assign_TSCurrentConfig, NULL
3062         },
3063
3064         {
3065                 {"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3066                         gettext_noop("Sets the list of allowed SSL ciphers."),
3067                         NULL,
3068                         GUC_SUPERUSER_ONLY
3069                 },
3070                 &SSLCipherSuites,
3071 #ifdef USE_SSL
3072                 "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH",
3073 #else
3074                 "none",
3075 #endif
3076                 NULL, NULL, NULL
3077         },
3078
3079         {
3080                 {"application_name", PGC_USERSET, LOGGING_WHAT,
3081                         gettext_noop("Sets the application name to be reported in statistics and logs."),
3082                         NULL,
3083                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE
3084                 },
3085                 &application_name,
3086                 "",
3087                 check_application_name, assign_application_name, NULL
3088         },
3089
3090         /* End-of-list marker */
3091         {
3092                 {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL
3093         }
3094 };
3095
3096
3097 static struct config_enum ConfigureNamesEnum[] =
3098 {
3099         {
3100                 {"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
3101                         gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
3102                         NULL
3103                 },
3104                 &backslash_quote,
3105                 BACKSLASH_QUOTE_SAFE_ENCODING, backslash_quote_options,
3106                 NULL, NULL, NULL
3107         },
3108
3109         {
3110                 {"bytea_output", PGC_USERSET, CLIENT_CONN_STATEMENT,
3111                         gettext_noop("Sets the output format for bytea."),
3112                         NULL
3113                 },
3114                 &bytea_output,
3115                 BYTEA_OUTPUT_HEX, bytea_output_options,
3116                 NULL, NULL, NULL
3117         },
3118
3119         {
3120                 {"client_min_messages", PGC_USERSET, LOGGING_WHEN,
3121                         gettext_noop("Sets the message levels that are sent to the client."),
3122                         gettext_noop("Each level includes all the levels that follow it. The later"
3123                                                  " the level, the fewer messages are sent.")
3124                 },
3125                 &client_min_messages,
3126                 NOTICE, client_message_level_options,
3127                 NULL, NULL, NULL
3128         },
3129
3130         {
3131                 {"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
3132                         gettext_noop("Enables the planner to use constraints to optimize queries."),
3133                         gettext_noop("Table scans will be skipped if their constraints"
3134                                                  " guarantee that no rows match the query.")
3135                 },
3136                 &constraint_exclusion,
3137                 CONSTRAINT_EXCLUSION_PARTITION, constraint_exclusion_options,
3138                 NULL, NULL, NULL
3139         },
3140
3141         {
3142                 {"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
3143                         gettext_noop("Sets the transaction isolation level of each new transaction."),
3144                         NULL
3145                 },
3146                 &DefaultXactIsoLevel,
3147                 XACT_READ_COMMITTED, isolation_level_options,
3148                 NULL, NULL, NULL
3149         },
3150
3151         {
3152                 {"IntervalStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
3153                         gettext_noop("Sets the display format for interval values."),
3154                         NULL,
3155                         GUC_REPORT
3156                 },
3157                 &IntervalStyle,
3158                 INTSTYLE_POSTGRES, intervalstyle_options,
3159                 NULL, NULL, NULL
3160         },
3161
3162         {
3163                 {"log_error_verbosity", PGC_SUSET, LOGGING_WHAT,
3164                         gettext_noop("Sets the verbosity of logged messages."),
3165                         NULL
3166                 },
3167                 &Log_error_verbosity,
3168                 PGERROR_DEFAULT, log_error_verbosity_options,
3169                 NULL, NULL, NULL
3170         },
3171
3172         {
3173                 {"log_min_messages", PGC_SUSET, LOGGING_WHEN,
3174                         gettext_noop("Sets the message levels that are logged."),
3175                         gettext_noop("Each level includes all the levels that follow it. The later"
3176                                                  " the level, the fewer messages are sent.")
3177                 },
3178                 &log_min_messages,
3179                 WARNING, server_message_level_options,
3180                 NULL, NULL, NULL
3181         },
3182
3183         {
3184                 {"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
3185                         gettext_noop("Causes all statements generating error at or above this level to be logged."),
3186                         gettext_noop("Each level includes all the levels that follow it. The later"
3187                                                  " the level, the fewer messages are sent.")
3188                 },
3189                 &log_min_error_statement,
3190                 ERROR, server_message_level_options,
3191                 NULL, NULL, NULL
3192         },
3193
3194         {
3195                 {"log_statement", PGC_SUSET, LOGGING_WHAT,
3196                         gettext_noop("Sets the type of statements logged."),
3197                         NULL
3198                 },
3199                 &log_statement,
3200                 LOGSTMT_NONE, log_statement_options,
3201                 NULL, NULL, NULL
3202         },
3203
3204         {
3205                 {"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
3206                         gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
3207                         NULL
3208                 },
3209                 &syslog_facility,
3210 #ifdef HAVE_SYSLOG
3211                 LOG_LOCAL0,
3212 #else
3213                 0,
3214 #endif
3215                 syslog_facility_options,
3216                 NULL, assign_syslog_facility, NULL
3217         },
3218
3219         {
3220                 {"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
3221                         gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
3222                         NULL
3223                 },
3224                 &SessionReplicationRole,
3225                 SESSION_REPLICATION_ROLE_ORIGIN, session_replication_role_options,
3226                 NULL, assign_session_replication_role, NULL
3227         },
3228
3229         {
3230                 {"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
3231                         gettext_noop("Sets the current transaction's synchronization level."),
3232                         NULL
3233                 },
3234                 &synchronous_commit,
3235                 SYNCHRONOUS_COMMIT_ON, synchronous_commit_options,
3236                 NULL, assign_synchronous_commit, NULL
3237         },
3238
3239         {
3240                 {"trace_recovery_messages", PGC_SIGHUP, DEVELOPER_OPTIONS,
3241                         gettext_noop("Enables logging of recovery-related debugging information."),
3242                         gettext_noop("Each level includes all the levels that follow it. The later"
3243                                                  " the level, the fewer messages are sent.")
3244                 },
3245                 &trace_recovery_messages,
3246
3247                 /*
3248                  * client_message_level_options allows too many values, really, but
3249                  * it's not worth having a separate options array for this.
3250                  */
3251                 LOG, client_message_level_options,
3252                 NULL, NULL, NULL
3253         },
3254
3255         {
3256                 {"track_functions", PGC_SUSET, STATS_COLLECTOR,
3257                         gettext_noop("Collects function-level statistics on database activity."),
3258                         NULL
3259                 },
3260                 &pgstat_track_functions,
3261                 TRACK_FUNC_OFF, track_function_options,
3262                 NULL, NULL, NULL
3263         },
3264
3265         {
3266                 {"wal_level", PGC_POSTMASTER, WAL_SETTINGS,
3267                         gettext_noop("Set the level of information written to the WAL."),
3268                         NULL
3269                 },
3270                 &wal_level,
3271                 WAL_LEVEL_MINIMAL, wal_level_options,
3272                 NULL, NULL, NULL
3273         },
3274
3275         {
3276                 {"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
3277                         gettext_noop("Selects the method used for forcing WAL updates to disk."),
3278                         NULL
3279                 },
3280                 &sync_method,
3281                 DEFAULT_SYNC_METHOD, sync_method_options,
3282                 NULL, assign_xlog_sync_method, NULL
3283         },
3284
3285         {
3286                 {"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
3287                         gettext_noop("Sets how binary values are to be encoded in XML."),
3288                         NULL
3289                 },
3290                 &xmlbinary,
3291                 XMLBINARY_BASE64, xmlbinary_options,
3292                 NULL, NULL, NULL
3293         },
3294
3295         {
3296                 {"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
3297                         gettext_noop("Sets whether XML data in implicit parsing and serialization "
3298                                                  "operations is to be considered as documents or content fragments."),
3299                         NULL
3300                 },
3301                 &xmloption,
3302                 XMLOPTION_CONTENT, xmloption_options,
3303                 NULL, NULL, NULL
3304         },
3305
3306
3307         /* End-of-list marker */
3308         {
3309                 {NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL
3310         }
3311 };
3312
3313 /******** end of options list ********/
3314
3315
3316 /*
3317  * To allow continued support of obsolete names for GUC variables, we apply
3318  * the following mappings to any unrecognized name.  Note that an old name
3319  * should be mapped to a new one only if the new variable has very similar
3320  * semantics to the old.
3321  */
3322 static const char *const map_old_guc_names[] = {
3323         "sort_mem", "work_mem",
3324         "vacuum_mem", "maintenance_work_mem",
3325         NULL
3326 };
3327
3328
3329 /*
3330  * Actual lookup of variables is done through this single, sorted array.
3331  */
3332 static struct config_generic **guc_variables;
3333
3334 /* Current number of variables contained in the vector */
3335 static int      num_guc_variables;
3336
3337 /* Vector capacity */
3338 static int      size_guc_variables;
3339
3340
3341 static bool guc_dirty;                  /* TRUE if need to do commit/abort work */
3342
3343 static bool reporting_enabled;  /* TRUE to enable GUC_REPORT */
3344
3345 static int      GUCNestLevel = 0;       /* 1 when in main transaction */
3346
3347
3348 static int      guc_var_compare(const void *a, const void *b);
3349 static int      guc_name_compare(const char *namea, const char *nameb);
3350 static void InitializeGUCOptionsFromEnvironment(void);
3351 static void InitializeOneGUCOption(struct config_generic * gconf);
3352 static void push_old_value(struct config_generic * gconf, GucAction action);
3353 static void ReportGUCOption(struct config_generic * record);
3354 static void reapply_stacked_values(struct config_generic * variable,
3355                                            struct config_string * pHolder,
3356                                            GucStack *stack,
3357                                            const char *curvalue,
3358                                            GucContext curscontext, GucSource cursource);
3359 static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
3360 static void ShowAllGUCConfig(DestReceiver *dest);
3361 static char *_ShowOption(struct config_generic * record, bool use_units);
3362 static bool validate_option_array_item(const char *name, const char *value,
3363                                                    bool skipIfNoPermissions);
3364
3365
3366 /*
3367  * Some infrastructure for checking malloc/strdup/realloc calls
3368  */
3369 static void *
3370 guc_malloc(int elevel, size_t size)
3371 {
3372         void       *data;
3373
3374         /* Avoid unportable behavior of malloc(0) */
3375         if (size == 0)
3376                 size = 1;
3377         data = malloc(size);
3378         if (data == NULL)
3379                 ereport(elevel,
3380                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3381                                  errmsg("out of memory")));
3382         return data;
3383 }
3384
3385 static void *
3386 guc_realloc(int elevel, void *old, size_t size)
3387 {
3388         void       *data;
3389
3390         /* Avoid unportable behavior of realloc(NULL, 0) */
3391         if (old == NULL && size == 0)
3392                 size = 1;
3393         data = realloc(old, size);
3394         if (data == NULL)
3395                 ereport(elevel,
3396                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3397                                  errmsg("out of memory")));
3398         return data;
3399 }
3400
3401 static char *
3402 guc_strdup(int elevel, const char *src)
3403 {
3404         char       *data;
3405
3406         data = strdup(src);
3407         if (data == NULL)
3408                 ereport(elevel,
3409                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3410                                  errmsg("out of memory")));
3411         return data;
3412 }
3413
3414
3415 /*
3416  * Detect whether strval is referenced anywhere in a GUC string item
3417  */
3418 static bool
3419 string_field_used(struct config_string * conf, char *strval)
3420 {
3421         GucStack   *stack;
3422
3423         if (strval == *(conf->variable) ||
3424                 strval == conf->reset_val ||
3425                 strval == conf->boot_val)
3426                 return true;
3427         for (stack = conf->gen.stack; stack; stack = stack->prev)
3428         {
3429                 if (strval == stack->prior.val.stringval ||
3430                         strval == stack->masked.val.stringval)
3431                         return true;
3432         }
3433         return false;
3434 }
3435
3436 /*
3437  * Support for assigning to a field of a string GUC item.  Free the prior
3438  * value if it's not referenced anywhere else in the item (including stacked
3439  * states).
3440  */
3441 static void
3442 set_string_field(struct config_string * conf, char **field, char *newval)
3443 {
3444         char       *oldval = *field;
3445
3446         /* Do the assignment */
3447         *field = newval;
3448
3449         /* Free old value if it's not NULL and isn't referenced anymore */
3450         if (oldval && !string_field_used(conf, oldval))
3451                 free(oldval);
3452 }
3453
3454 /*
3455  * Detect whether an "extra" struct is referenced anywhere in a GUC item
3456  */
3457 static bool
3458 extra_field_used(struct config_generic * gconf, void *extra)
3459 {
3460         GucStack   *stack;
3461
3462         if (extra == gconf->extra)
3463                 return true;
3464         switch (gconf->vartype)
3465         {
3466                 case PGC_BOOL:
3467                         if (extra == ((struct config_bool *) gconf)->reset_extra)
3468                                 return true;
3469                         break;
3470                 case PGC_INT:
3471                         if (extra == ((struct config_int *) gconf)->reset_extra)
3472                                 return true;
3473                         break;
3474                 case PGC_REAL:
3475                         if (extra == ((struct config_real *) gconf)->reset_extra)
3476                                 return true;
3477                         break;
3478                 case PGC_STRING:
3479                         if (extra == ((struct config_string *) gconf)->reset_extra)
3480                                 return true;
3481                         break;
3482                 case PGC_ENUM:
3483                         if (extra == ((struct config_enum *) gconf)->reset_extra)
3484                                 return true;
3485                         break;
3486         }
3487         for (stack = gconf->stack; stack; stack = stack->prev)
3488         {
3489                 if (extra == stack->prior.extra ||
3490                         extra == stack->masked.extra)
3491                         return true;
3492         }
3493
3494         return false;
3495 }
3496
3497 /*
3498  * Support for assigning to an "extra" field of a GUC item.  Free the prior
3499  * value if it's not referenced anywhere else in the item (including stacked
3500  * states).
3501  */
3502 static void
3503 set_extra_field(struct config_generic * gconf, void **field, void *newval)
3504 {
3505         void       *oldval = *field;
3506
3507         /* Do the assignment */
3508         *field = newval;
3509
3510         /* Free old value if it's not NULL and isn't referenced anymore */
3511         if (oldval && !extra_field_used(gconf, oldval))
3512                 free(oldval);
3513 }
3514
3515 /*
3516  * Support for copying a variable's active value into a stack entry.
3517  * The "extra" field associated with the active value is copied, too.
3518  *
3519  * NB: be sure stringval and extra fields of a new stack entry are
3520  * initialized to NULL before this is used, else we'll try to free() them.
3521  */
3522 static void
3523 set_stack_value(struct config_generic * gconf, config_var_value *val)
3524 {
3525         switch (gconf->vartype)
3526         {
3527                 case PGC_BOOL:
3528                         val->val.boolval =
3529                                 *((struct config_bool *) gconf)->variable;
3530                         break;
3531                 case PGC_INT:
3532                         val->val.intval =
3533                                 *((struct config_int *) gconf)->variable;
3534                         break;
3535                 case PGC_REAL:
3536                         val->val.realval =
3537                                 *((struct config_real *) gconf)->variable;
3538                         break;
3539                 case PGC_STRING:
3540                         set_string_field((struct config_string *) gconf,
3541                                                          &(val->val.stringval),
3542                                                          *((struct config_string *) gconf)->variable);
3543                         break;
3544                 case PGC_ENUM:
3545                         val->val.enumval =
3546                                 *((struct config_enum *) gconf)->variable;
3547                         break;
3548         }
3549         set_extra_field(gconf, &(val->extra), gconf->extra);
3550 }
3551
3552 /*
3553  * Support for discarding a no-longer-needed value in a stack entry.
3554  * The "extra" field associated with the stack entry is cleared, too.
3555  */
3556 static void
3557 discard_stack_value(struct config_generic * gconf, config_var_value *val)
3558 {
3559         switch (gconf->vartype)
3560         {
3561                 case PGC_BOOL:
3562                 case PGC_INT:
3563                 case PGC_REAL:
3564                 case PGC_ENUM:
3565                         /* no need to do anything */
3566                         break;
3567                 case PGC_STRING:
3568                         set_string_field((struct config_string *) gconf,
3569                                                          &(val->val.stringval),
3570                                                          NULL);
3571                         break;
3572         }
3573         set_extra_field(gconf, &(val->extra), NULL);
3574 }
3575
3576
3577 /*
3578  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
3579  */
3580 struct config_generic **
3581 get_guc_variables(void)
3582 {
3583         return guc_variables;
3584 }
3585
3586
3587 /*
3588  * Build the sorted array.      This is split out so that it could be
3589  * re-executed after startup (eg, we could allow loadable modules to
3590  * add vars, and then we'd need to re-sort).
3591  */
3592 void
3593 build_guc_variables(void)
3594 {
3595         int                     size_vars;
3596         int                     num_vars = 0;
3597         struct config_generic **guc_vars;
3598         int                     i;
3599
3600         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3601         {
3602                 struct config_bool *conf = &ConfigureNamesBool[i];
3603
3604                 /* Rather than requiring vartype to be filled in by hand, do this: */
3605                 conf->gen.vartype = PGC_BOOL;
3606                 num_vars++;
3607         }
3608
3609         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3610         {
3611                 struct config_int *conf = &ConfigureNamesInt[i];
3612
3613                 conf->gen.vartype = PGC_INT;
3614                 num_vars++;
3615         }
3616
3617         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3618         {
3619                 struct config_real *conf = &ConfigureNamesReal[i];
3620
3621                 conf->gen.vartype = PGC_REAL;
3622                 num_vars++;
3623         }
3624
3625         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3626         {
3627                 struct config_string *conf = &ConfigureNamesString[i];
3628
3629                 conf->gen.vartype = PGC_STRING;
3630                 num_vars++;
3631         }
3632
3633         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3634         {
3635                 struct config_enum *conf = &ConfigureNamesEnum[i];
3636
3637                 conf->gen.vartype = PGC_ENUM;
3638                 num_vars++;
3639         }
3640
3641         /*
3642          * Create table with 20% slack
3643          */
3644         size_vars = num_vars + num_vars / 4;
3645
3646         guc_vars = (struct config_generic **)
3647                 guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
3648
3649         num_vars = 0;
3650
3651         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3652                 guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
3653
3654         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3655                 guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
3656
3657         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3658                 guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
3659
3660         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3661                 guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
3662
3663         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3664                 guc_vars[num_vars++] = &ConfigureNamesEnum[i].gen;
3665
3666         if (guc_variables)
3667                 free(guc_variables);
3668         guc_variables = guc_vars;
3669         num_guc_variables = num_vars;
3670         size_guc_variables = size_vars;
3671         qsort((void *) guc_variables, num_guc_variables,
3672                   sizeof(struct config_generic *), guc_var_compare);
3673 }
3674
3675 /*
3676  * Add a new GUC variable to the list of known variables. The
3677  * list is expanded if needed.
3678  */
3679 static bool
3680 add_guc_variable(struct config_generic * var, int elevel)
3681 {
3682         if (num_guc_variables + 1 >= size_guc_variables)
3683         {
3684                 /*
3685                  * Increase the vector by 25%
3686                  */
3687                 int                     size_vars = size_guc_variables + size_guc_variables / 4;
3688                 struct config_generic **guc_vars;
3689
3690                 if (size_vars == 0)
3691                 {
3692                         size_vars = 100;
3693                         guc_vars = (struct config_generic **)
3694                                 guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
3695                 }
3696                 else
3697                 {
3698                         guc_vars = (struct config_generic **)
3699                                 guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
3700                 }
3701
3702                 if (guc_vars == NULL)
3703                         return false;           /* out of memory */
3704
3705                 guc_variables = guc_vars;
3706                 size_guc_variables = size_vars;
3707         }
3708         guc_variables[num_guc_variables++] = var;
3709         qsort((void *) guc_variables, num_guc_variables,
3710                   sizeof(struct config_generic *), guc_var_compare);
3711         return true;
3712 }
3713
3714 /*
3715  * Create and add a placeholder variable for a custom variable name.
3716  */
3717 static struct config_generic *
3718 add_placeholder_variable(const char *name, int elevel)
3719 {
3720         size_t          sz = sizeof(struct config_string) + sizeof(char *);
3721         struct config_string *var;
3722         struct config_generic *gen;
3723
3724         var = (struct config_string *) guc_malloc(elevel, sz);
3725         if (var == NULL)
3726                 return NULL;
3727         memset(var, 0, sz);
3728         gen = &var->gen;
3729
3730         gen->name = guc_strdup(elevel, name);
3731         if (gen->name == NULL)
3732         {
3733                 free(var);
3734                 return NULL;
3735         }
3736
3737         gen->context = PGC_USERSET;
3738         gen->group = CUSTOM_OPTIONS;
3739         gen->short_desc = "GUC placeholder variable";
3740         gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
3741         gen->vartype = PGC_STRING;
3742
3743         /*
3744          * The char* is allocated at the end of the struct since we have no
3745          * 'static' place to point to.  Note that the current value, as well as
3746          * the boot and reset values, start out NULL.
3747          */
3748         var->variable = (char **) (var + 1);
3749
3750         if (!add_guc_variable((struct config_generic *) var, elevel))
3751         {
3752                 free((void *) gen->name);
3753                 free(var);
3754                 return NULL;
3755         }
3756
3757         return gen;
3758 }
3759
3760 /*
3761  * Look up option NAME.  If it exists, return a pointer to its record,
3762  * else return NULL.  If create_placeholders is TRUE, we'll create a
3763  * placeholder record for a valid-looking custom variable name.
3764  */
3765 static struct config_generic *
3766 find_option(const char *name, bool create_placeholders, int elevel)
3767 {
3768         const char **key = &name;
3769         struct config_generic **res;
3770         int                     i;
3771
3772         Assert(name);
3773
3774         /*
3775          * By equating const char ** with struct config_generic *, we are assuming
3776          * the name field is first in config_generic.
3777          */
3778         res = (struct config_generic **) bsearch((void *) &key,
3779                                                                                          (void *) guc_variables,
3780                                                                                          num_guc_variables,
3781                                                                                          sizeof(struct config_generic *),
3782                                                                                          guc_var_compare);
3783         if (res)
3784                 return *res;
3785
3786         /*
3787          * See if the name is an obsolete name for a variable.  We assume that the
3788          * set of supported old names is short enough that a brute-force search is
3789          * the best way.
3790          */
3791         for (i = 0; map_old_guc_names[i] != NULL; i += 2)
3792         {
3793                 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
3794                         return find_option(map_old_guc_names[i + 1], false, elevel);
3795         }
3796
3797         if (create_placeholders)
3798         {
3799                 /*
3800                  * Check if the name is qualified, and if so, add a placeholder.
3801                  */
3802                 if (strchr(name, GUC_QUALIFIER_SEPARATOR) != NULL)
3803                         return add_placeholder_variable(name, elevel);
3804         }
3805
3806         /* Unknown name */
3807         return NULL;
3808 }
3809
3810
3811 /*
3812  * comparator for qsorting and bsearching guc_variables array
3813  */
3814 static int
3815 guc_var_compare(const void *a, const void *b)
3816 {
3817         const struct config_generic *confa = *(struct config_generic * const *) a;
3818         const struct config_generic *confb = *(struct config_generic * const *) b;
3819
3820         return guc_name_compare(confa->name, confb->name);
3821 }
3822
3823 /*
3824  * the bare comparison function for GUC names
3825  */
3826 static int
3827 guc_name_compare(const char *namea, const char *nameb)
3828 {
3829         /*
3830          * The temptation to use strcasecmp() here must be resisted, because the
3831          * array ordering has to remain stable across setlocale() calls. So, build
3832          * our own with a simple ASCII-only downcasing.
3833          */
3834         while (*namea && *nameb)
3835         {
3836                 char            cha = *namea++;
3837                 char            chb = *nameb++;
3838
3839                 if (cha >= 'A' && cha <= 'Z')
3840                         cha += 'a' - 'A';
3841                 if (chb >= 'A' && chb <= 'Z')
3842                         chb += 'a' - 'A';
3843                 if (cha != chb)
3844                         return cha - chb;
3845         }
3846         if (*namea)
3847                 return 1;                               /* a is longer */
3848         if (*nameb)
3849                 return -1;                              /* b is longer */
3850         return 0;
3851 }
3852
3853
3854 /*
3855  * Initialize GUC options during program startup.
3856  *
3857  * Note that we cannot read the config file yet, since we have not yet
3858  * processed command-line switches.
3859  */
3860 void
3861 InitializeGUCOptions(void)
3862 {
3863         int                     i;
3864
3865         /*
3866          * Before log_line_prefix could possibly receive a nonempty setting, make
3867          * sure that timezone processing is minimally alive (see elog.c).
3868          */
3869         pg_timezone_initialize();
3870
3871         /*
3872          * Build sorted array of all GUC variables.
3873          */
3874         build_guc_variables();
3875
3876         /*
3877          * Load all variables with their compiled-in defaults, and initialize
3878          * status fields as needed.
3879          */
3880         for (i = 0; i < num_guc_variables; i++)
3881         {
3882                 InitializeOneGUCOption(guc_variables[i]);
3883         }
3884
3885         guc_dirty = false;
3886
3887         reporting_enabled = false;
3888
3889         /*
3890          * Prevent any attempt to override the transaction modes from
3891          * non-interactive sources.
3892          */
3893         SetConfigOption("transaction_isolation", "default",
3894                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3895         SetConfigOption("transaction_read_only", "no",
3896                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3897         SetConfigOption("transaction_deferrable", "no",
3898                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3899
3900         /*
3901          * For historical reasons, some GUC parameters can receive defaults from
3902          * environment variables.  Process those settings.
3903          */
3904         InitializeGUCOptionsFromEnvironment();
3905 }
3906
3907 /*
3908  * Assign any GUC values that can come from the server's environment.
3909  *
3910  * This is called from InitializeGUCOptions, and also from ProcessConfigFile
3911  * to deal with the possibility that a setting has been removed from
3912  * postgresql.conf and should now get a value from the environment.
3913  * (The latter is a kludge that should probably go away someday; if so,
3914  * fold this back into InitializeGUCOptions.)
3915  */
3916 static void
3917 InitializeGUCOptionsFromEnvironment(void)
3918 {
3919         char       *env;
3920         long            stack_rlimit;
3921
3922         env = getenv("PGPORT");
3923         if (env != NULL)
3924                 SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3925
3926         env = getenv("PGDATESTYLE");
3927         if (env != NULL)
3928                 SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3929
3930         env = getenv("PGCLIENTENCODING");
3931         if (env != NULL)
3932                 SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3933
3934         /*
3935          * rlimit isn't exactly an "environment variable", but it behaves about
3936          * the same.  If we can identify the platform stack depth rlimit, increase
3937          * default stack depth setting up to whatever is safe (but at most 2MB).
3938          */
3939         stack_rlimit = get_stack_depth_rlimit();
3940         if (stack_rlimit > 0)
3941         {
3942                 long            new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
3943
3944                 if (new_limit > 100)
3945                 {
3946                         char            limbuf[16];
3947
3948                         new_limit = Min(new_limit, 2048);
3949                         sprintf(limbuf, "%ld", new_limit);
3950                         SetConfigOption("max_stack_depth", limbuf,
3951                                                         PGC_POSTMASTER, PGC_S_ENV_VAR);
3952                 }
3953         }
3954 }
3955
3956 /*
3957  * Initialize one GUC option variable to its compiled-in default.
3958  *
3959  * Note: the reason for calling check_hooks is not that we think the boot_val
3960  * might fail, but that the hooks might wish to compute an "extra" struct.
3961  */
3962 static void
3963 InitializeOneGUCOption(struct config_generic * gconf)
3964 {
3965         gconf->status = 0;
3966         gconf->source = PGC_S_DEFAULT;
3967         gconf->reset_source = PGC_S_DEFAULT;
3968         gconf->scontext = PGC_INTERNAL;
3969         gconf->reset_scontext = PGC_INTERNAL;
3970         gconf->stack = NULL;
3971         gconf->extra = NULL;
3972         gconf->sourcefile = NULL;
3973         gconf->sourceline = 0;
3974
3975         switch (gconf->vartype)
3976         {
3977                 case PGC_BOOL:
3978                         {
3979                                 struct config_bool *conf = (struct config_bool *) gconf;
3980                                 bool            newval = conf->boot_val;
3981                                 void       *extra = NULL;
3982
3983                                 if (!call_bool_check_hook(conf, &newval, &extra,
3984                                                                                   PGC_S_DEFAULT, LOG))
3985                                         elog(FATAL, "failed to initialize %s to %d",
3986                                                  conf->gen.name, (int) newval);
3987                                 if (conf->assign_hook)
3988                                         (*conf->assign_hook) (newval, extra);
3989                                 *conf->variable = conf->reset_val = newval;
3990                                 conf->gen.extra = conf->reset_extra = extra;
3991                                 break;
3992                         }
3993                 case PGC_INT:
3994                         {
3995                                 struct config_int *conf = (struct config_int *) gconf;
3996                                 int                     newval = conf->boot_val;
3997                                 void       *extra = NULL;
3998
3999                                 Assert(newval >= conf->min);
4000                                 Assert(newval <= conf->max);
4001                                 if (!call_int_check_hook(conf, &newval, &extra,
4002                                                                                  PGC_S_DEFAULT, LOG))
4003                                         elog(FATAL, "failed to initialize %s to %d",
4004                                                  conf->gen.name, newval);
4005                                 if (conf->assign_hook)
4006                                         (*conf->assign_hook) (newval, extra);
4007                                 *conf->variable = conf->reset_val = newval;
4008                                 conf->gen.extra = conf->reset_extra = extra;
4009                                 break;
4010                         }
4011                 case PGC_REAL:
4012                         {
4013                                 struct config_real *conf = (struct config_real *) gconf;
4014                                 double          newval = conf->boot_val;
4015                                 void       *extra = NULL;
4016
4017                                 Assert(newval >= conf->min);
4018                                 Assert(newval <= conf->max);
4019                                 if (!call_real_check_hook(conf, &newval, &extra,
4020                                                                                   PGC_S_DEFAULT, LOG))
4021                                         elog(FATAL, "failed to initialize %s to %g",
4022                                                  conf->gen.name, newval);
4023                                 if (conf->assign_hook)
4024                                         (*conf->assign_hook) (newval, extra);
4025                                 *conf->variable = conf->reset_val = newval;
4026                                 conf->gen.extra = conf->reset_extra = extra;
4027                                 break;
4028                         }
4029                 case PGC_STRING:
4030                         {
4031                                 struct config_string *conf = (struct config_string *) gconf;
4032                                 char       *newval;
4033                                 void       *extra = NULL;
4034
4035                                 /* non-NULL boot_val must always get strdup'd */
4036                                 if (conf->boot_val != NULL)
4037                                         newval = guc_strdup(FATAL, conf->boot_val);
4038                                 else
4039                                         newval = NULL;
4040
4041                                 if (!call_string_check_hook(conf, &newval, &extra,
4042                                                                                         PGC_S_DEFAULT, LOG))
4043                                         elog(FATAL, "failed to initialize %s to \"%s\"",
4044                                                  conf->gen.name, newval ? newval : "");
4045                                 if (conf->assign_hook)
4046                                         (*conf->assign_hook) (newval, extra);
4047                                 *conf->variable = conf->reset_val = newval;
4048                                 conf->gen.extra = conf->reset_extra = extra;
4049                                 break;
4050                         }
4051                 case PGC_ENUM:
4052                         {
4053                                 struct config_enum *conf = (struct config_enum *) gconf;
4054                                 int                     newval = conf->boot_val;
4055                                 void       *extra = NULL;
4056
4057                                 if (!call_enum_check_hook(conf, &newval, &extra,
4058                                                                                   PGC_S_DEFAULT, LOG))
4059                                         elog(FATAL, "failed to initialize %s to %d",
4060                                                  conf->gen.name, newval);
4061                                 if (conf->assign_hook)
4062                                         (*conf->assign_hook) (newval, extra);
4063                                 *conf->variable = conf->reset_val = newval;
4064                                 conf->gen.extra = conf->reset_extra = extra;
4065                                 break;
4066                         }
4067         }
4068 }
4069
4070
4071 /*
4072  * Select the configuration files and data directory to be used, and
4073  * do the initial read of postgresql.conf.
4074  *
4075  * This is called after processing command-line switches.
4076  *              userDoption is the -D switch value if any (NULL if unspecified).
4077  *              progname is just for use in error messages.
4078  *
4079  * Returns true on success; on failure, prints a suitable error message
4080  * to stderr and returns false.
4081  */
4082 bool
4083 SelectConfigFiles(const char *userDoption, const char *progname)
4084 {
4085         char       *configdir;
4086         char       *fname;
4087         struct stat stat_buf;
4088
4089         /* configdir is -D option, or $PGDATA if no -D */
4090         if (userDoption)
4091                 configdir = make_absolute_path(userDoption);
4092         else
4093                 configdir = make_absolute_path(getenv("PGDATA"));
4094
4095         /*
4096          * Find the configuration file: if config_file was specified on the
4097          * command line, use it, else use configdir/postgresql.conf.  In any case
4098          * ensure the result is an absolute path, so that it will be interpreted
4099          * the same way by future backends.
4100          */
4101         if (ConfigFileName)
4102                 fname = make_absolute_path(ConfigFileName);
4103         else if (configdir)
4104         {
4105                 fname = guc_malloc(FATAL,
4106                                                    strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
4107                 sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
4108         }
4109         else
4110         {
4111                 write_stderr("%s does not know where to find the server configuration file.\n"
4112                                          "You must specify the --config-file or -D invocation "
4113                                          "option or set the PGDATA environment variable.\n",
4114                                          progname);
4115                 return false;
4116         }
4117
4118         /*
4119          * Set the ConfigFileName GUC variable to its final value, ensuring that
4120          * it can't be overridden later.
4121          */
4122         SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4123         free(fname);
4124
4125         /*
4126          * Now read the config file for the first time.
4127          */
4128         if (stat(ConfigFileName, &stat_buf) != 0)
4129         {
4130                 write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
4131                                          progname, ConfigFileName, strerror(errno));
4132                 free(configdir);
4133                 return false;
4134         }
4135
4136         ProcessConfigFile(PGC_POSTMASTER);
4137
4138         /*
4139          * If the data_directory GUC variable has been set, use that as DataDir;
4140          * otherwise use configdir if set; else punt.
4141          *
4142          * Note: SetDataDir will copy and absolute-ize its argument, so we don't
4143          * have to.
4144          */
4145         if (data_directory)
4146                 SetDataDir(data_directory);
4147         else if (configdir)
4148                 SetDataDir(configdir);
4149         else
4150         {
4151                 write_stderr("%s does not know where to find the database system data.\n"
4152                                          "This can be specified as \"data_directory\" in \"%s\", "
4153                                          "or by the -D invocation option, or by the "
4154                                          "PGDATA environment variable.\n",
4155                                          progname, ConfigFileName);
4156                 return false;
4157         }
4158
4159         /*
4160          * Reflect the final DataDir value back into the data_directory GUC var.
4161          * (If you are wondering why we don't just make them a single variable,
4162          * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
4163          * child backends specially.  XXX is that still true?  Given that we now
4164          * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
4165          * DataDir in advance.)
4166          */
4167         SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
4168
4169         /*
4170          * If timezone_abbreviations wasn't set in the configuration file, install
4171          * the default value.  We do it this way because we can't safely install a
4172          * "real" value until my_exec_path is set, which may not have happened
4173          * when InitializeGUCOptions runs, so the bootstrap default value cannot
4174          * be the real desired default.
4175          */
4176         pg_timezone_abbrev_initialize();
4177
4178         /*
4179          * Figure out where pg_hba.conf is, and make sure the path is absolute.
4180          */
4181         if (HbaFileName)
4182                 fname = make_absolute_path(HbaFileName);
4183         else if (configdir)
4184         {
4185                 fname = guc_malloc(FATAL,
4186                                                    strlen(configdir) + strlen(HBA_FILENAME) + 2);
4187                 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
4188         }
4189         else
4190         {
4191                 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
4192                                          "This can be specified as \"hba_file\" in \"%s\", "
4193                                          "or by the -D invocation option, or by the "
4194                                          "PGDATA environment variable.\n",
4195                                          progname, ConfigFileName);
4196                 return false;
4197         }
4198         SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4199         free(fname);
4200
4201         /*
4202          * Likewise for pg_ident.conf.
4203          */
4204         if (IdentFileName)
4205                 fname = make_absolute_path(IdentFileName);
4206         else if (configdir)
4207         {
4208                 fname = guc_malloc(FATAL,
4209                                                    strlen(configdir) + strlen(IDENT_FILENAME) + 2);
4210                 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
4211         }
4212         else
4213         {
4214                 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
4215                                          "This can be specified as \"ident_file\" in \"%s\", "
4216                                          "or by the -D invocation option, or by the "
4217                                          "PGDATA environment variable.\n",
4218                                          progname, ConfigFileName);
4219                 return false;
4220         }
4221         SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4222         free(fname);
4223
4224         free(configdir);
4225
4226         return true;
4227 }
4228
4229
4230 /*
4231  * Reset all options to their saved default values (implements RESET ALL)
4232  */
4233 void
4234 ResetAllOptions(void)
4235 {
4236         int                     i;
4237
4238         for (i = 0; i < num_guc_variables; i++)
4239         {
4240                 struct config_generic *gconf = guc_variables[i];
4241
4242                 /* Don't reset non-SET-able values */
4243                 if (gconf->context != PGC_SUSET &&
4244                         gconf->context != PGC_USERSET)
4245                         continue;
4246                 /* Don't reset if special exclusion from RESET ALL */
4247                 if (gconf->flags & GUC_NO_RESET_ALL)
4248                         continue;
4249                 /* No need to reset if wasn't SET */
4250                 if (gconf->source <= PGC_S_OVERRIDE)
4251                         continue;
4252
4253                 /* Save old value to support transaction abort */
4254                 push_old_value(gconf, GUC_ACTION_SET);
4255
4256                 switch (gconf->vartype)
4257                 {
4258                         case PGC_BOOL:
4259                                 {
4260                                         struct config_bool *conf = (struct config_bool *) gconf;
4261
4262                                         if (conf->assign_hook)
4263                                                 (*conf->assign_hook) (conf->reset_val,
4264                                                                                           conf->reset_extra);
4265                                         *conf->variable = conf->reset_val;
4266                                         set_extra_field(&conf->gen, &conf->gen.extra,
4267                                                                         conf->reset_extra);
4268                                         break;
4269                                 }
4270                         case PGC_INT:
4271                                 {
4272                                         struct config_int *conf = (struct config_int *) gconf;
4273
4274                                         if (conf->assign_hook)
4275                                                 (*conf->assign_hook) (conf->reset_val,
4276                                                                                           conf->reset_extra);
4277                                         *conf->variable = conf->reset_val;
4278                                         set_extra_field(&conf->gen, &conf->gen.extra,
4279                                                                         conf->reset_extra);
4280                                         break;
4281                                 }
4282                         case PGC_REAL:
4283                                 {
4284                                         struct config_real *conf = (struct config_real *) gconf;
4285
4286                                         if (conf->assign_hook)
4287                                                 (*conf->assign_hook) (conf->reset_val,
4288                                                                                           conf->reset_extra);
4289                                         *conf->variable = conf->reset_val;
4290                                         set_extra_field(&conf->gen, &conf->gen.extra,
4291                                                                         conf->reset_extra);
4292                                         break;
4293                                 }
4294                         case PGC_STRING:
4295                                 {
4296                                         struct config_string *conf = (struct config_string *) gconf;
4297
4298                                         if (conf->assign_hook)
4299                                                 (*conf->assign_hook) (conf->reset_val,
4300                                                                                           conf->reset_extra);
4301                                         set_string_field(conf, conf->variable, conf->reset_val);
4302                                         set_extra_field(&conf->gen, &conf->gen.extra,
4303                                                                         conf->reset_extra);
4304                                         break;
4305                                 }
4306                         case PGC_ENUM:
4307                                 {
4308                                         struct config_enum *conf = (struct config_enum *) gconf;
4309
4310                                         if (conf->assign_hook)
4311                                                 (*conf->assign_hook) (conf->reset_val,
4312                                                                                           conf->reset_extra);
4313                                         *conf->variable = conf->reset_val;
4314                                         set_extra_field(&conf->gen, &conf->gen.extra,
4315                                                                         conf->reset_extra);
4316                                         break;
4317                                 }
4318                 }
4319
4320                 gconf->source = gconf->reset_source;
4321                 gconf->scontext = gconf->reset_scontext;
4322
4323                 if (gconf->flags & GUC_REPORT)
4324                         ReportGUCOption(gconf);
4325         }
4326 }
4327
4328
4329 /*
4330  * push_old_value
4331  *              Push previous state during transactional assignment to a GUC variable.
4332  */
4333 static void
4334 push_old_value(struct config_generic * gconf, GucAction action)
4335 {
4336         GucStack   *stack;
4337
4338         /* If we're not inside a nest level, do nothing */
4339         if (GUCNestLevel == 0)
4340                 return;
4341
4342         /* Do we already have a stack entry of the current nest level? */
4343         stack = gconf->stack;
4344         if (stack && stack->nest_level >= GUCNestLevel)
4345         {
4346                 /* Yes, so adjust its state if necessary */
4347                 Assert(stack->nest_level == GUCNestLevel);
4348                 switch (action)
4349                 {
4350                         case GUC_ACTION_SET:
4351                                 /* SET overrides any prior action at same nest level */
4352                                 if (stack->state == GUC_SET_LOCAL)
4353                                 {
4354                                         /* must discard old masked value */
4355                                         discard_stack_value(gconf, &stack->masked);
4356                                 }
4357                                 stack->state = GUC_SET;
4358                                 break;
4359                         case GUC_ACTION_LOCAL:
4360                                 if (stack->state == GUC_SET)
4361                                 {
4362                                         /* SET followed by SET LOCAL, remember SET's value */
4363                                         stack->masked_scontext = gconf->scontext;
4364                                         set_stack_value(gconf, &stack->masked);
4365                                         stack->state = GUC_SET_LOCAL;
4366                                 }
4367                                 /* in all other cases, no change to stack entry */
4368                                 break;
4369                         case GUC_ACTION_SAVE:
4370                                 /* Could only have a prior SAVE of same variable */
4371                                 Assert(stack->state == GUC_SAVE);
4372                                 break;
4373                 }
4374                 Assert(guc_dirty);              /* must be set already */
4375                 return;
4376         }
4377
4378         /*
4379          * Push a new stack entry
4380          *
4381          * We keep all the stack entries in TopTransactionContext for simplicity.
4382          */
4383         stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
4384                                                                                                 sizeof(GucStack));
4385
4386         stack->prev = gconf->stack;
4387         stack->nest_level = GUCNestLevel;
4388         switch (action)
4389         {
4390                 case GUC_ACTION_SET:
4391                         stack->state = GUC_SET;
4392                         break;
4393                 case GUC_ACTION_LOCAL:
4394                         stack->state = GUC_LOCAL;
4395                         break;
4396                 case GUC_ACTION_SAVE:
4397                         stack->state = GUC_SAVE;
4398                         break;
4399         }
4400         stack->source = gconf->source;
4401         stack->scontext = gconf->scontext;
4402         set_stack_value(gconf, &stack->prior);
4403
4404         gconf->stack = stack;
4405
4406         /* Ensure we remember to pop at end of xact */
4407         guc_dirty = true;
4408 }
4409
4410
4411 /*
4412  * Do GUC processing at main transaction start.
4413  */
4414 void
4415 AtStart_GUC(void)
4416 {
4417         /*
4418          * The nest level should be 0 between transactions; if it isn't, somebody
4419          * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
4420          * throw a warning but make no other effort to clean up.
4421          */
4422         if (GUCNestLevel != 0)
4423                 elog(WARNING, "GUC nest level = %d at transaction start",
4424                          GUCNestLevel);
4425         GUCNestLevel = 1;
4426 }
4427
4428 /*
4429  * Enter a new nesting level for GUC values.  This is called at subtransaction
4430  * start, and when entering a function that has proconfig settings, and in
4431  * some other places where we want to set GUC variables transiently.
4432  * NOTE we must not risk error here, else subtransaction start will be unhappy.
4433  */
4434 int
4435 NewGUCNestLevel(void)
4436 {
4437         return ++GUCNestLevel;
4438 }
4439
4440 /*
4441  * Do GUC processing at transaction or subtransaction commit or abort, or
4442  * when exiting a function that has proconfig settings, or when undoing a
4443  * transient assignment to some GUC variables.  (The name is thus a bit of
4444  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
4445  * During abort, we discard all GUC settings that were applied at nesting
4446  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
4447  */
4448 void
4449 AtEOXact_GUC(bool isCommit, int nestLevel)
4450 {
4451         bool            still_dirty;
4452         int                     i;
4453
4454         /*
4455          * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
4456          * abort, if there is a failure during transaction start before
4457          * AtStart_GUC is called.
4458          */
4459         Assert(nestLevel > 0 &&
4460                    (nestLevel <= GUCNestLevel ||
4461                         (nestLevel == GUCNestLevel + 1 && !isCommit)));
4462
4463         /* Quick exit if nothing's changed in this transaction */
4464         if (!guc_dirty)
4465         {
4466                 GUCNestLevel = nestLevel - 1;
4467                 return;
4468         }
4469
4470         still_dirty = false;
4471         for (i = 0; i < num_guc_variables; i++)
4472         {
4473                 struct config_generic *gconf = guc_variables[i];
4474                 GucStack   *stack;
4475
4476                 /*
4477                  * Process and pop each stack entry within the nest level. To simplify
4478                  * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
4479                  * we allow failure exit from code that uses a local nest level to be
4480                  * recovered at the surrounding transaction or subtransaction abort;
4481                  * so there could be more than one stack entry to pop.
4482                  */
4483                 while ((stack = gconf->stack) != NULL &&
4484                            stack->nest_level >= nestLevel)
4485                 {
4486                         GucStack   *prev = stack->prev;
4487                         bool            restorePrior = false;
4488                         bool            restoreMasked = false;
4489                         bool            changed;
4490
4491                         /*
4492                          * In this next bit, if we don't set either restorePrior or
4493                          * restoreMasked, we must "discard" any unwanted fields of the
4494                          * stack entries to avoid leaking memory.  If we do set one of
4495                          * those flags, unused fields will be cleaned up after restoring.
4496                          */
4497                         if (!isCommit)          /* if abort, always restore prior value */
4498                                 restorePrior = true;
4499                         else if (stack->state == GUC_SAVE)
4500                                 restorePrior = true;
4501                         else if (stack->nest_level == 1)
4502                         {
4503                                 /* transaction commit */
4504                                 if (stack->state == GUC_SET_LOCAL)
4505                                         restoreMasked = true;
4506                                 else if (stack->state == GUC_SET)
4507                                 {
4508                                         /* we keep the current active value */
4509                                         discard_stack_value(gconf, &stack->prior);
4510                                 }
4511                                 else    /* must be GUC_LOCAL */
4512                                         restorePrior = true;
4513                         }
4514                         else if (prev == NULL ||
4515                                          prev->nest_level < stack->nest_level - 1)
4516                         {
4517                                 /* decrement entry's level and do not pop it */
4518                                 stack->nest_level--;
4519                                 continue;
4520                         }
4521                         else
4522                         {
4523                                 /*
4524                                  * We have to merge this stack entry into prev. See README for
4525                                  * discussion of this bit.
4526                                  */
4527                                 switch (stack->state)
4528                                 {
4529                                         case GUC_SAVE:
4530                                                 Assert(false);  /* can't get here */
4531
4532                                         case GUC_SET:
4533                                                 /* next level always becomes SET */
4534                                                 discard_stack_value(gconf, &stack->prior);
4535                                                 if (prev->state == GUC_SET_LOCAL)
4536                                                         discard_stack_value(gconf, &prev->masked);
4537                                                 prev->state = GUC_SET;
4538                                                 break;
4539
4540                                         case GUC_LOCAL:
4541                                                 if (prev->state == GUC_SET)
4542                                                 {
4543                                                         /* LOCAL migrates down */
4544                                                         prev->masked_scontext = stack->scontext;
4545                                                         prev->masked = stack->prior;
4546                                                         prev->state = GUC_SET_LOCAL;
4547                                                 }
4548                                                 else
4549                                                 {
4550                                                         /* else just forget this stack level */
4551                                                         discard_stack_value(gconf, &stack->prior);
4552                                                 }
4553                                                 break;
4554
4555                                         case GUC_SET_LOCAL:
4556                                                 /* prior state at this level no longer wanted */
4557                                                 discard_stack_value(gconf, &stack->prior);
4558                                                 /* copy down the masked state */
4559                                                 prev->masked_scontext = stack->masked_scontext;
4560                                                 if (prev->state == GUC_SET_LOCAL)
4561                                                         discard_stack_value(gconf, &prev->masked);
4562                                                 prev->masked = stack->masked;
4563                                                 prev->state = GUC_SET_LOCAL;
4564                                                 break;
4565                                 }
4566                         }
4567
4568                         changed = false;
4569
4570                         if (restorePrior || restoreMasked)
4571                         {
4572                                 /* Perform appropriate restoration of the stacked value */
4573                                 config_var_value newvalue;
4574                                 GucSource       newsource;
4575                                 GucContext      newscontext;
4576
4577                                 if (restoreMasked)
4578                                 {
4579                                         newvalue = stack->masked;
4580                                         newsource = PGC_S_SESSION;
4581                                         newscontext = stack->masked_scontext;
4582                                 }
4583                                 else
4584                                 {
4585                                         newvalue = stack->prior;
4586                                         newsource = stack->source;
4587                                         newscontext = stack->scontext;
4588                                 }
4589
4590                                 switch (gconf->vartype)
4591                                 {
4592                                         case PGC_BOOL:
4593                                                 {
4594                                                         struct config_bool *conf = (struct config_bool *) gconf;
4595                                                         bool            newval = newvalue.val.boolval;
4596                                                         void       *newextra = newvalue.extra;
4597
4598                                                         if (*conf->variable != newval ||
4599                                                                 conf->gen.extra != newextra)
4600                                                         {
4601                                                                 if (conf->assign_hook)
4602                                                                         (*conf->assign_hook) (newval, newextra);
4603                                                                 *conf->variable = newval;
4604                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4605                                                                                                 newextra);
4606                                                                 changed = true;
4607                                                         }
4608                                                         break;
4609                                                 }
4610                                         case PGC_INT:
4611                                                 {
4612                                                         struct config_int *conf = (struct config_int *) gconf;
4613                                                         int                     newval = newvalue.val.intval;
4614                                                         void       *newextra = newvalue.extra;
4615
4616                                                         if (*conf->variable != newval ||
4617                                                                 conf->gen.extra != newextra)
4618                                                         {
4619                                                                 if (conf->assign_hook)
4620                                                                         (*conf->assign_hook) (newval, newextra);
4621                                                                 *conf->variable = newval;
4622                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4623                                                                                                 newextra);
4624                                                                 changed = true;
4625                                                         }
4626                                                         break;
4627                                                 }
4628                                         case PGC_REAL:
4629                                                 {
4630                                                         struct config_real *conf = (struct config_real *) gconf;
4631                                                         double          newval = newvalue.val.realval;
4632                                                         void       *newextra = newvalue.extra;
4633
4634                                                         if (*conf->variable != newval ||
4635                                                                 conf->gen.extra != newextra)
4636                                                         {
4637                                                                 if (conf->assign_hook)
4638                                                                         (*conf->assign_hook) (newval, newextra);
4639                                                                 *conf->variable = newval;
4640                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4641                                                                                                 newextra);
4642                                                                 changed = true;
4643                                                         }
4644                                                         break;
4645                                                 }
4646                                         case PGC_STRING:
4647                                                 {
4648                                                         struct config_string *conf = (struct config_string *) gconf;
4649                                                         char       *newval = newvalue.val.stringval;
4650                                                         void       *newextra = newvalue.extra;
4651
4652                                                         if (*conf->variable != newval ||
4653                                                                 conf->gen.extra != newextra)
4654                                                         {
4655                                                                 if (conf->assign_hook)
4656                                                                         (*conf->assign_hook) (newval, newextra);
4657                                                                 set_string_field(conf, conf->variable, newval);
4658                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4659                                                                                                 newextra);
4660                                                                 changed = true;
4661                                                         }
4662
4663                                                         /*
4664                                                          * Release stacked values if not used anymore. We
4665                                                          * could use discard_stack_value() here, but since
4666                                                          * we have type-specific code anyway, might as
4667                                                          * well inline it.
4668                                                          */
4669                                                         set_string_field(conf, &stack->prior.val.stringval, NULL);
4670                                                         set_string_field(conf, &stack->masked.val.stringval, NULL);
4671                                                         break;
4672                                                 }
4673                                         case PGC_ENUM:
4674                                                 {
4675                                                         struct config_enum *conf = (struct config_enum *) gconf;
4676                                                         int                     newval = newvalue.val.enumval;
4677                                                         void       *newextra = newvalue.extra;
4678
4679                                                         if (*conf->variable != newval ||
4680                                                                 conf->gen.extra != newextra)
4681                                                         {
4682                                                                 if (conf->assign_hook)
4683                                                                         (*conf->assign_hook) (newval, newextra);
4684                                                                 *conf->variable = newval;
4685                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4686                                                                                                 newextra);
4687                                                                 changed = true;
4688                                                         }
4689                                                         break;
4690                                                 }
4691                                 }
4692
4693                                 /*
4694                                  * Release stacked extra values if not used anymore.
4695                                  */
4696                                 set_extra_field(gconf, &(stack->prior.extra), NULL);
4697                                 set_extra_field(gconf, &(stack->masked.extra), NULL);
4698
4699                                 /* And restore source information */
4700                                 gconf->source = newsource;
4701                                 gconf->scontext = newscontext;
4702                         }
4703
4704                         /* Finish popping the state stack */
4705                         gconf->stack = prev;
4706                         pfree(stack);
4707
4708                         /* Report new value if we changed it */
4709                         if (changed && (gconf->flags & GUC_REPORT))
4710                                 ReportGUCOption(gconf);
4711                 }                                               /* end of stack-popping loop */
4712
4713                 if (stack != NULL)
4714                         still_dirty = true;
4715         }
4716
4717         /* If there are no remaining stack entries, we can reset guc_dirty */
4718         guc_dirty = still_dirty;
4719
4720         /* Update nesting level */
4721         GUCNestLevel = nestLevel - 1;
4722 }
4723
4724
4725 /*
4726  * Start up automatic reporting of changes to variables marked GUC_REPORT.
4727  * This is executed at completion of backend startup.
4728  */
4729 void
4730 BeginReportingGUCOptions(void)
4731 {
4732         int                     i;
4733
4734         /*
4735          * Don't do anything unless talking to an interactive frontend of protocol
4736          * 3.0 or later.
4737          */
4738         if (whereToSendOutput != DestRemote ||
4739                 PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
4740                 return;
4741
4742         reporting_enabled = true;
4743
4744         /* Transmit initial values of interesting variables */
4745         for (i = 0; i < num_guc_variables; i++)
4746         {
4747                 struct config_generic *conf = guc_variables[i];
4748
4749                 if (conf->flags & GUC_REPORT)
4750                         ReportGUCOption(conf);
4751         }
4752 }
4753
4754 /*
4755  * ReportGUCOption: if appropriate, transmit option value to frontend
4756  */
4757 static void
4758 ReportGUCOption(struct config_generic * record)
4759 {
4760         if (reporting_enabled && (record->flags & GUC_REPORT))
4761         {
4762                 char       *val = _ShowOption(record, false);
4763                 StringInfoData msgbuf;
4764
4765                 pq_beginmessage(&msgbuf, 'S');
4766                 pq_sendstring(&msgbuf, record->name);
4767                 pq_sendstring(&msgbuf, val);
4768                 pq_endmessage(&msgbuf);
4769
4770                 pfree(val);
4771         }
4772 }
4773
4774 /*
4775  * Try to parse value as an integer.  The accepted formats are the
4776  * usual decimal, octal, or hexadecimal formats, optionally followed by
4777  * a unit name if "flags" indicates a unit is allowed.
4778  *
4779  * If the string parses okay, return true, else false.
4780  * If okay and result is not NULL, return the value in *result.
4781  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
4782  *      HINT message, or NULL if no hint provided.
4783  */
4784 bool
4785 parse_int(const char *value, int *result, int flags, const char **hintmsg)
4786 {
4787         int64           val;
4788         char       *endptr;
4789
4790         /* To suppress compiler warnings, always set output params */
4791         if (result)
4792                 *result = 0;
4793         if (hintmsg)
4794                 *hintmsg = NULL;
4795
4796         /* We assume here that int64 is at least as wide as long */
4797         errno = 0;
4798         val = strtol(value, &endptr, 0);
4799
4800         if (endptr == value)
4801                 return false;                   /* no HINT for integer syntax error */
4802
4803         if (errno == ERANGE || val != (int64) ((int32) val))
4804         {
4805                 if (hintmsg)
4806                         *hintmsg = gettext_noop("Value exceeds integer range.");
4807                 return false;
4808         }
4809
4810         /* allow whitespace between integer and unit */
4811         while (isspace((unsigned char) *endptr))
4812                 endptr++;
4813
4814         /* Handle possible unit */
4815         if (*endptr != '\0')
4816         {
4817                 /*
4818                  * Note: the multiple-switch coding technique here is a bit tedious,
4819                  * but seems necessary to avoid intermediate-value overflows.
4820                  */
4821                 if (flags & GUC_UNIT_MEMORY)
4822                 {
4823                         /* Set hint for use if no match or trailing garbage */
4824                         if (hintmsg)
4825                                 *hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");
4826
4827 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
4828 #error BLCKSZ must be between 1KB and 1MB
4829 #endif
4830 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
4831 #error XLOG_BLCKSZ must be between 1KB and 1MB
4832 #endif
4833
4834                         if (strncmp(endptr, "kB", 2) == 0)
4835                         {
4836                                 endptr += 2;
4837                                 switch (flags & GUC_UNIT_MEMORY)
4838                                 {
4839                                         case GUC_UNIT_BLOCKS:
4840                                                 val /= (BLCKSZ / 1024);
4841                                                 break;
4842                                         case GUC_UNIT_XBLOCKS:
4843                                                 val /= (XLOG_BLCKSZ / 1024);
4844                                                 break;
4845                                 }
4846                         }
4847                         else if (strncmp(endptr, "MB", 2) == 0)
4848                         {
4849                                 endptr += 2;
4850                                 switch (flags & GUC_UNIT_MEMORY)
4851                                 {
4852                                         case GUC_UNIT_KB:
4853                                                 val *= KB_PER_MB;
4854                                                 break;
4855                                         case GUC_UNIT_BLOCKS:
4856                                                 val *= KB_PER_MB / (BLCKSZ / 1024);
4857                                                 break;
4858                                         case GUC_UNIT_XBLOCKS:
4859                                                 val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
4860                                                 break;
4861                                 }
4862                         }
4863                         else if (strncmp(endptr, "GB", 2) == 0)
4864                         {
4865                                 endptr += 2;
4866                                 switch (flags & GUC_UNIT_MEMORY)
4867                                 {
4868                                         case GUC_UNIT_KB:
4869                                                 val *= KB_PER_GB;
4870                                                 break;
4871                                         case GUC_UNIT_BLOCKS:
4872                                                 val *= KB_PER_GB / (BLCKSZ / 1024);
4873                                                 break;
4874                                         case GUC_UNIT_XBLOCKS:
4875                                                 val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
4876                                                 break;
4877                                 }
4878                         }
4879                 }
4880                 else if (flags & GUC_UNIT_TIME)
4881                 {
4882                         /* Set hint for use if no match or trailing garbage */
4883                         if (hintmsg)
4884                                 *hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
4885
4886                         if (strncmp(endptr, "ms", 2) == 0)
4887                         {
4888                                 endptr += 2;
4889                                 switch (flags & GUC_UNIT_TIME)
4890                                 {
4891                                         case GUC_UNIT_S:
4892                                                 val /= MS_PER_S;
4893                                                 break;
4894                                         case GUC_UNIT_MIN:
4895                                                 val /= MS_PER_MIN;
4896                                                 break;
4897                                 }
4898                         }
4899                         else if (strncmp(endptr, "s", 1) == 0)
4900                         {
4901                                 endptr += 1;
4902                                 switch (flags & GUC_UNIT_TIME)
4903                                 {
4904                                         case GUC_UNIT_MS:
4905                                                 val *= MS_PER_S;
4906                                                 break;
4907                                         case GUC_UNIT_MIN:
4908                                                 val /= S_PER_MIN;
4909                                                 break;
4910                                 }
4911                         }
4912                         else if (strncmp(endptr, "min", 3) == 0)
4913                         {
4914                                 endptr += 3;
4915                                 switch (flags & GUC_UNIT_TIME)
4916                                 {
4917                                         case GUC_UNIT_MS:
4918                                                 val *= MS_PER_MIN;
4919                                                 break;
4920                                         case GUC_UNIT_S:
4921                                                 val *= S_PER_MIN;
4922                                                 break;
4923                                 }
4924                         }
4925                         else if (strncmp(endptr, "h", 1) == 0)
4926                         {
4927                                 endptr += 1;
4928                                 switch (flags & GUC_UNIT_TIME)
4929                                 {
4930                                         case GUC_UNIT_MS:
4931                                                 val *= MS_PER_H;
4932                                                 break;
4933                                         case GUC_UNIT_S:
4934                                                 val *= S_PER_H;
4935                                                 break;
4936                                         case GUC_UNIT_MIN:
4937                                                 val *= MIN_PER_H;
4938                                                 break;
4939                                 }
4940                         }
4941                         else if (strncmp(endptr, "d", 1) == 0)
4942                         {
4943                                 endptr += 1;
4944                                 switch (flags & GUC_UNIT_TIME)
4945                                 {
4946                                         case GUC_UNIT_MS:
4947                                                 val *= MS_PER_D;
4948                                                 break;
4949                                         case GUC_UNIT_S:
4950                                                 val *= S_PER_D;
4951                                                 break;
4952                                         case GUC_UNIT_MIN:
4953                                                 val *= MIN_PER_D;
4954                                                 break;
4955                                 }
4956                         }
4957                 }
4958
4959                 /* allow whitespace after unit */
4960                 while (isspace((unsigned char) *endptr))
4961                         endptr++;
4962
4963                 if (*endptr != '\0')
4964                         return false;           /* appropriate hint, if any, already set */
4965
4966                 /* Check for overflow due to units conversion */
4967                 if (val != (int64) ((int32) val))
4968                 {
4969                         if (hintmsg)
4970                                 *hintmsg = gettext_noop("Value exceeds integer range.");
4971                         return false;
4972                 }
4973         }
4974
4975         if (result)
4976                 *result = (int) val;
4977         return true;
4978 }
4979
4980
4981
4982 /*
4983  * Try to parse value as a floating point number in the usual format.
4984  * If the string parses okay, return true, else false.
4985  * If okay and result is not NULL, return the value in *result.
4986  */
4987 bool
4988 parse_real(const char *value, double *result)
4989 {
4990         double          val;
4991         char       *endptr;
4992
4993         if (result)
4994                 *result = 0;                    /* suppress compiler warning */
4995
4996         errno = 0;
4997         val = strtod(value, &endptr);
4998         if (endptr == value || errno == ERANGE)
4999                 return false;
5000
5001         /* allow whitespace after number */
5002         while (isspace((unsigned char) *endptr))
5003                 endptr++;
5004         if (*endptr != '\0')
5005                 return false;
5006
5007         if (result)
5008                 *result = val;
5009         return true;
5010 }
5011
5012
5013 /*
5014  * Lookup the name for an enum option with the selected value.
5015  * Should only ever be called with known-valid values, so throws
5016  * an elog(ERROR) if the enum option is not found.
5017  *
5018  * The returned string is a pointer to static data and not
5019  * allocated for modification.
5020  */
5021 const char *
5022 config_enum_lookup_by_value(struct config_enum * record, int val)
5023 {
5024         const struct config_enum_entry *entry;
5025
5026         for (entry = record->options; entry && entry->name; entry++)
5027         {
5028                 if (entry->val == val)
5029                         return entry->name;
5030         }
5031
5032         elog(ERROR, "could not find enum option %d for %s",
5033                  val, record->gen.name);
5034         return NULL;                            /* silence compiler */
5035 }
5036
5037
5038 /*
5039  * Lookup the value for an enum option with the selected name
5040  * (case-insensitive).
5041  * If the enum option is found, sets the retval value and returns
5042  * true. If it's not found, return FALSE and retval is set to 0.
5043  */
5044 bool
5045 config_enum_lookup_by_name(struct config_enum * record, const char *value,
5046                                                    int *retval)
5047 {
5048         const struct config_enum_entry *entry;
5049
5050         for (entry = record->options; entry && entry->name; entry++)
5051         {
5052                 if (pg_strcasecmp(value, entry->name) == 0)
5053                 {
5054                         *retval = entry->val;
5055                         return TRUE;
5056                 }
5057         }
5058
5059         *retval = 0;
5060         return FALSE;
5061 }
5062
5063
5064 /*
5065  * Return a list of all available options for an enum, excluding
5066  * hidden ones, separated by the given separator.
5067  * If prefix is non-NULL, it is added before the first enum value.
5068  * If suffix is non-NULL, it is added to the end of the string.
5069  */
5070 static char *
5071 config_enum_get_options(struct config_enum * record, const char *prefix,
5072                                                 const char *suffix, const char *separator)
5073 {
5074         const struct config_enum_entry *entry;
5075         StringInfoData retstr;
5076         int                     seplen;
5077
5078         initStringInfo(&retstr);
5079         appendStringInfoString(&retstr, prefix);
5080
5081         seplen = strlen(separator);
5082         for (entry = record->options; entry && entry->name; entry++)
5083         {
5084                 if (!entry->hidden)
5085                 {
5086                         appendStringInfoString(&retstr, entry->name);
5087                         appendBinaryStringInfo(&retstr, separator, seplen);
5088                 }
5089         }
5090
5091         /*
5092          * All the entries may have been hidden, leaving the string empty if no
5093          * prefix was given. This indicates a broken GUC setup, since there is no
5094          * use for an enum without any values, so we just check to make sure we
5095          * don't write to invalid memory instead of actually trying to do
5096          * something smart with it.
5097          */
5098         if (retstr.len >= seplen)
5099         {
5100                 /* Replace final separator */
5101                 retstr.data[retstr.len - seplen] = '\0';
5102                 retstr.len -= seplen;
5103         }
5104
5105         appendStringInfoString(&retstr, suffix);
5106
5107         return retstr.data;
5108 }
5109
5110
5111 /*
5112  * Sets option `name' to given value.
5113  *
5114  * The value should be a string, which will be parsed and converted to
5115  * the appropriate data type.  The context and source parameters indicate
5116  * in which context this function is being called, so that it can apply the
5117  * access restrictions properly.
5118  *
5119  * If value is NULL, set the option to its default value (normally the
5120  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
5121  *
5122  * action indicates whether to set the value globally in the session, locally
5123  * to the current top transaction, or just for the duration of a function call.
5124  *
5125  * If changeVal is false then don't really set the option but do all
5126  * the checks to see if it would work.
5127  *
5128  * elevel should normally be passed as zero, allowing this function to make
5129  * its standard choice of ereport level.  However some callers need to be
5130  * able to override that choice; they should pass the ereport level to use.
5131  *
5132  * Return value:
5133  *      +1: the value is valid and was successfully applied.
5134  *      0:      the name or value is invalid (but see below).
5135  *      -1: the value was not applied because of context, priority, or changeVal.
5136  *
5137  * If there is an error (non-existing option, invalid value) then an
5138  * ereport(ERROR) is thrown *unless* this is called for a source for which
5139  * we don't want an ERROR (currently, those are defaults, the config file,
5140  * and per-database or per-user settings, as well as callers who specify
5141  * a less-than-ERROR elevel).  In those cases we write a suitable error
5142  * message via ereport() and return 0.
5143  *
5144  * See also SetConfigOption for an external interface.
5145  */
5146 int
5147 set_config_option(const char *name, const char *value,
5148                                   GucContext context, GucSource source,
5149                                   GucAction action, bool changeVal, int elevel)
5150 {
5151         struct config_generic *record;
5152         bool            prohibitValueChange = false;
5153         bool            makeDefault;
5154
5155         if (elevel == 0)
5156         {
5157                 if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
5158                 {
5159                         /*
5160                          * To avoid cluttering the log, only the postmaster bleats loudly
5161                          * about problems with the config file.
5162                          */
5163                         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5164                 }
5165                 else if (source == PGC_S_DATABASE || source == PGC_S_USER ||
5166                                  source == PGC_S_DATABASE_USER)
5167                         elevel = WARNING;
5168                 else
5169                         elevel = ERROR;
5170         }
5171
5172         record = find_option(name, true, elevel);
5173         if (record == NULL)
5174         {
5175                 ereport(elevel,
5176                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5177                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5178                 return 0;
5179         }
5180
5181         /*
5182          * Check if the option can be set at this time. See guc.h for the precise
5183          * rules.
5184          */
5185         switch (record->context)
5186         {
5187                 case PGC_INTERNAL:
5188                         if (context != PGC_INTERNAL)
5189                         {
5190                                 ereport(elevel,
5191                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5192                                                  errmsg("parameter \"%s\" cannot be changed",
5193                                                                 name)));
5194                                 return 0;
5195                         }
5196                         break;
5197                 case PGC_POSTMASTER:
5198                         if (context == PGC_SIGHUP)
5199                         {
5200                                 /*
5201                                  * We are re-reading a PGC_POSTMASTER variable from
5202                                  * postgresql.conf.  We can't change the setting, so we should
5203                                  * give a warning if the DBA tries to change it.  However,
5204                                  * because of variant formats, canonicalization by check
5205                                  * hooks, etc, we can't just compare the given string directly
5206                                  * to what's stored.  Set a flag to check below after we have
5207                                  * the final storable value.
5208                                  */
5209                                 prohibitValueChange = true;
5210                         }
5211                         else if (context != PGC_POSTMASTER)
5212                         {
5213                                 ereport(elevel,
5214                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5215                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5216                                                                 name)));
5217                                 return 0;
5218                         }
5219                         break;
5220                 case PGC_SIGHUP:
5221                         if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
5222                         {
5223                                 ereport(elevel,
5224                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5225                                                  errmsg("parameter \"%s\" cannot be changed now",
5226                                                                 name)));
5227                                 return 0;
5228                         }
5229
5230                         /*
5231                          * Hmm, the idea of the SIGHUP context is "ought to be global, but
5232                          * can be changed after postmaster start". But there's nothing
5233                          * that prevents a crafty administrator from sending SIGHUP
5234                          * signals to individual backends only.
5235                          */
5236                         break;
5237                 case PGC_BACKEND:
5238                         if (context == PGC_SIGHUP)
5239                         {
5240                                 /*
5241                                  * If a PGC_BACKEND parameter is changed in the config file,
5242                                  * we want to accept the new value in the postmaster (whence
5243                                  * it will propagate to subsequently-started backends), but
5244                                  * ignore it in existing backends.      This is a tad klugy, but
5245                                  * necessary because we don't re-read the config file during
5246                                  * backend start.
5247                                  */
5248                                 if (IsUnderPostmaster)
5249                                         return -1;
5250                         }
5251                         else if (context != PGC_POSTMASTER && context != PGC_BACKEND &&
5252                                          source != PGC_S_CLIENT)
5253                         {
5254                                 ereport(elevel,
5255                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5256                                                  errmsg("parameter \"%s\" cannot be set after connection start",
5257                                                                 name)));
5258                                 return 0;
5259                         }
5260                         break;
5261                 case PGC_SUSET:
5262                         if (context == PGC_USERSET || context == PGC_BACKEND)
5263                         {
5264                                 ereport(elevel,
5265                                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5266                                                  errmsg("permission denied to set parameter \"%s\"",
5267                                                                 name)));
5268                                 return 0;
5269                         }
5270                         break;
5271                 case PGC_USERSET:
5272                         /* always okay */
5273                         break;
5274         }
5275
5276         /*
5277          * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
5278          * security restriction context.  We can reject this regardless of the GUC
5279          * context or source, mainly because sources that it might be reasonable
5280          * to override for won't be seen while inside a function.
5281          *
5282          * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
5283          * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
5284          * An exception might be made if the reset value is assumed to be "safe".
5285          *
5286          * Note: this flag is currently used for "session_authorization" and
5287          * "role".      We need to prohibit changing these inside a local userid
5288          * context because when we exit it, GUC won't be notified, leaving things
5289          * out of sync.  (This could be fixed by forcing a new GUC nesting level,
5290          * but that would change behavior in possibly-undesirable ways.)  Also, we
5291          * prohibit changing these in a security-restricted operation because
5292          * otherwise RESET could be used to regain the session user's privileges.
5293          */
5294         if (record->flags & GUC_NOT_WHILE_SEC_REST)
5295         {
5296                 if (InLocalUserIdChange())
5297                 {
5298                         /*
5299                          * Phrasing of this error message is historical, but it's the most
5300                          * common case.
5301                          */
5302                         ereport(elevel,
5303                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5304                                          errmsg("cannot set parameter \"%s\" within security-definer function",
5305                                                         name)));
5306                         return 0;
5307                 }
5308                 if (InSecurityRestrictedOperation())
5309                 {
5310                         ereport(elevel,
5311                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5312                                          errmsg("cannot set parameter \"%s\" within security-restricted operation",
5313                                                         name)));
5314                         return 0;
5315                 }
5316         }
5317
5318         /*
5319          * Should we set reset/stacked values?  (If so, the behavior is not
5320          * transactional.)      This is done either when we get a default value from
5321          * the database's/user's/client's default settings or when we reset a
5322          * value to its default.
5323          */
5324         makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
5325                 ((value != NULL) || source == PGC_S_DEFAULT);
5326
5327         /*
5328          * Ignore attempted set if overridden by previously processed setting.
5329          * However, if changeVal is false then plow ahead anyway since we are
5330          * trying to find out if the value is potentially good, not actually use
5331          * it. Also keep going if makeDefault is true, since we may want to set
5332          * the reset/stacked values even if we can't set the variable itself.
5333          */
5334         if (record->source > source)
5335         {
5336                 if (changeVal && !makeDefault)
5337                 {
5338                         elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
5339                                  name);
5340                         return -1;
5341                 }
5342                 changeVal = false;
5343         }
5344
5345         /*
5346          * Evaluate value and set variable.
5347          */
5348         switch (record->vartype)
5349         {
5350                 case PGC_BOOL:
5351                         {
5352                                 struct config_bool *conf = (struct config_bool *) record;
5353                                 bool            newval;
5354                                 void       *newextra = NULL;
5355
5356                                 if (value)
5357                                 {
5358                                         if (!parse_bool(value, &newval))
5359                                         {
5360                                                 ereport(elevel,
5361                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5362                                                   errmsg("parameter \"%s\" requires a Boolean value",
5363                                                                  name)));
5364                                                 return 0;
5365                                         }
5366                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5367                                                                                           source, elevel))
5368                                                 return 0;
5369                                 }
5370                                 else if (source == PGC_S_DEFAULT)
5371                                 {
5372                                         newval = conf->boot_val;
5373                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5374                                                                                           source, elevel))
5375                                                 return 0;
5376                                 }
5377                                 else
5378                                 {
5379                                         newval = conf->reset_val;
5380                                         newextra = conf->reset_extra;
5381                                         source = conf->gen.reset_source;
5382                                         context = conf->gen.reset_scontext;
5383                                 }
5384
5385                                 if (prohibitValueChange)
5386                                 {
5387                                         if (*conf->variable != newval)
5388                                         {
5389                                                 ereport(elevel,
5390                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5391                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5392                                                                                 name)));
5393                                                 return 0;
5394                                         }
5395                                         return -1;
5396                                 }
5397
5398                                 if (changeVal)
5399                                 {
5400                                         /* Save old value to support transaction abort */
5401                                         if (!makeDefault)
5402                                                 push_old_value(&conf->gen, action);
5403
5404                                         if (conf->assign_hook)
5405                                                 (*conf->assign_hook) (newval, newextra);
5406                                         *conf->variable = newval;
5407                                         set_extra_field(&conf->gen, &conf->gen.extra,
5408                                                                         newextra);
5409                                         conf->gen.source = source;
5410                                         conf->gen.scontext = context;
5411                                 }
5412                                 if (makeDefault)
5413                                 {
5414                                         GucStack   *stack;
5415
5416                                         if (conf->gen.reset_source <= source)
5417                                         {
5418                                                 conf->reset_val = newval;
5419                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5420                                                                                 newextra);
5421                                                 conf->gen.reset_source = source;
5422                                                 conf->gen.reset_scontext = context;
5423                                         }
5424                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5425                                         {
5426                                                 if (stack->source <= source)
5427                                                 {
5428                                                         stack->prior.val.boolval = newval;
5429                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5430                                                                                         newextra);
5431                                                         stack->source = source;
5432                                                         stack->scontext = context;
5433                                                 }
5434                                         }
5435                                 }
5436
5437                                 /* Perhaps we didn't install newextra anywhere */
5438                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5439                                         free(newextra);
5440                                 break;
5441                         }
5442
5443                 case PGC_INT:
5444                         {
5445                                 struct config_int *conf = (struct config_int *) record;
5446                                 int                     newval;
5447                                 void       *newextra = NULL;
5448
5449                                 if (value)
5450                                 {
5451                                         const char *hintmsg;
5452
5453                                         if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
5454                                         {
5455                                                 ereport(elevel,
5456                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5457                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5458                                                                 name, value),
5459                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5460                                                 return 0;
5461                                         }
5462                                         if (newval < conf->min || newval > conf->max)
5463                                         {
5464                                                 ereport(elevel,
5465                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5466                                                                  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
5467                                                                                 newval, name, conf->min, conf->max)));
5468                                                 return 0;
5469                                         }
5470                                         if (!call_int_check_hook(conf, &newval, &newextra,
5471                                                                                          source, elevel))
5472                                                 return 0;
5473                                 }
5474                                 else if (source == PGC_S_DEFAULT)
5475                                 {
5476                                         newval = conf->boot_val;
5477                                         if (!call_int_check_hook(conf, &newval, &newextra,
5478                                                                                          source, elevel))
5479                                                 return 0;
5480                                 }
5481                                 else
5482                                 {
5483                                         newval = conf->reset_val;
5484                                         newextra = conf->reset_extra;
5485                                         source = conf->gen.reset_source;
5486                                         context = conf->gen.reset_scontext;
5487                                 }
5488
5489                                 if (prohibitValueChange)
5490                                 {
5491                                         if (*conf->variable != newval)
5492                                         {
5493                                                 ereport(elevel,
5494                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5495                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5496                                                                                 name)));
5497                                                 return 0;
5498                                         }
5499                                         return -1;
5500                                 }
5501
5502                                 if (changeVal)
5503                                 {
5504                                         /* Save old value to support transaction abort */
5505                                         if (!makeDefault)
5506                                                 push_old_value(&conf->gen, action);
5507
5508                                         if (conf->assign_hook)
5509                                                 (*conf->assign_hook) (newval, newextra);
5510                                         *conf->variable = newval;
5511                                         set_extra_field(&conf->gen, &conf->gen.extra,
5512                                                                         newextra);
5513                                         conf->gen.source = source;
5514                                         conf->gen.scontext = context;
5515                                 }
5516                                 if (makeDefault)
5517                                 {
5518                                         GucStack   *stack;
5519
5520                                         if (conf->gen.reset_source <= source)
5521                                         {
5522                                                 conf->reset_val = newval;
5523                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5524                                                                                 newextra);
5525                                                 conf->gen.reset_source = source;
5526                                                 conf->gen.reset_scontext = context;
5527                                         }
5528                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5529                                         {
5530                                                 if (stack->source <= source)
5531                                                 {
5532                                                         stack->prior.val.intval = newval;
5533                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5534                                                                                         newextra);
5535                                                         stack->source = source;
5536                                                         stack->scontext = context;
5537                                                 }
5538                                         }
5539                                 }
5540
5541                                 /* Perhaps we didn't install newextra anywhere */
5542                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5543                                         free(newextra);
5544                                 break;
5545                         }
5546
5547                 case PGC_REAL:
5548                         {
5549                                 struct config_real *conf = (struct config_real *) record;
5550                                 double          newval;
5551                                 void       *newextra = NULL;
5552
5553                                 if (value)
5554                                 {
5555                                         if (!parse_real(value, &newval))
5556                                         {
5557                                                 ereport(elevel,
5558                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5559                                                   errmsg("parameter \"%s\" requires a numeric value",
5560                                                                  name)));
5561                                                 return 0;
5562                                         }
5563                                         if (newval < conf->min || newval > conf->max)
5564                                         {
5565                                                 ereport(elevel,
5566                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5567                                                                  errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
5568                                                                                 newval, name, conf->min, conf->max)));
5569                                                 return 0;
5570                                         }
5571                                         if (!call_real_check_hook(conf, &newval, &newextra,
5572                                                                                           source, elevel))
5573                                                 return 0;
5574                                 }
5575                                 else if (source == PGC_S_DEFAULT)
5576                                 {
5577                                         newval = conf->boot_val;
5578                                         if (!call_real_check_hook(conf, &newval, &newextra,
5579                                                                                           source, elevel))
5580                                                 return 0;
5581                                 }
5582                                 else
5583                                 {
5584                                         newval = conf->reset_val;
5585                                         newextra = conf->reset_extra;
5586                                         source = conf->gen.reset_source;
5587                                         context = conf->gen.reset_scontext;
5588                                 }
5589
5590                                 if (prohibitValueChange)
5591                                 {
5592                                         if (*conf->variable != newval)
5593                                         {
5594                                                 ereport(elevel,
5595                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5596                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5597                                                                                 name)));
5598                                                 return 0;
5599                                         }
5600                                         return -1;
5601                                 }
5602
5603                                 if (changeVal)
5604                                 {
5605                                         /* Save old value to support transaction abort */
5606                                         if (!makeDefault)
5607                                                 push_old_value(&conf->gen, action);
5608
5609                                         if (conf->assign_hook)
5610                                                 (*conf->assign_hook) (newval, newextra);
5611                                         *conf->variable = newval;
5612                                         set_extra_field(&conf->gen, &conf->gen.extra,
5613                                                                         newextra);
5614                                         conf->gen.source = source;
5615                                         conf->gen.scontext = context;
5616                                 }
5617                                 if (makeDefault)
5618                                 {
5619                                         GucStack   *stack;
5620
5621                                         if (conf->gen.reset_source <= source)
5622                                         {
5623                                                 conf->reset_val = newval;
5624                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5625                                                                                 newextra);
5626                                                 conf->gen.reset_source = source;
5627                                                 conf->gen.reset_scontext = context;
5628                                         }
5629                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5630                                         {
5631                                                 if (stack->source <= source)
5632                                                 {
5633                                                         stack->prior.val.realval = newval;
5634                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5635                                                                                         newextra);
5636                                                         stack->source = source;
5637                                                         stack->scontext = context;
5638                                                 }
5639                                         }
5640                                 }
5641
5642                                 /* Perhaps we didn't install newextra anywhere */
5643                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5644                                         free(newextra);
5645                                 break;
5646                         }
5647
5648                 case PGC_STRING:
5649                         {
5650                                 struct config_string *conf = (struct config_string *) record;
5651                                 char       *newval;
5652                                 void       *newextra = NULL;
5653
5654                                 if (value)
5655                                 {
5656                                         /*
5657                                          * The value passed by the caller could be transient, so
5658                                          * we always strdup it.
5659                                          */
5660                                         newval = guc_strdup(elevel, value);
5661                                         if (newval == NULL)
5662                                                 return 0;
5663
5664                                         /*
5665                                          * The only built-in "parsing" check we have is to apply
5666                                          * truncation if GUC_IS_NAME.
5667                                          */
5668                                         if (conf->gen.flags & GUC_IS_NAME)
5669                                                 truncate_identifier(newval, strlen(newval), true);
5670
5671                                         if (!call_string_check_hook(conf, &newval, &newextra,
5672                                                                                                 source, elevel))
5673                                         {
5674                                                 free(newval);
5675                                                 return 0;
5676                                         }
5677                                 }
5678                                 else if (source == PGC_S_DEFAULT)
5679                                 {
5680                                         /* non-NULL boot_val must always get strdup'd */
5681                                         if (conf->boot_val != NULL)
5682                                         {
5683                                                 newval = guc_strdup(elevel, conf->boot_val);
5684                                                 if (newval == NULL)
5685                                                         return 0;
5686                                         }
5687                                         else
5688                                                 newval = NULL;
5689
5690                                         if (!call_string_check_hook(conf, &newval, &newextra,
5691                                                                                                 source, elevel))
5692                                         {
5693                                                 free(newval);
5694                                                 return 0;
5695                                         }
5696                                 }
5697                                 else
5698                                 {
5699                                         /*
5700                                          * strdup not needed, since reset_val is already under
5701                                          * guc.c's control
5702                                          */
5703                                         newval = conf->reset_val;
5704                                         newextra = conf->reset_extra;
5705                                         source = conf->gen.reset_source;
5706                                         context = conf->gen.reset_scontext;
5707                                 }
5708
5709                                 if (prohibitValueChange)
5710                                 {
5711                                         /* newval shouldn't be NULL, so we're a bit sloppy here */
5712                                         if (*conf->variable == NULL || newval == NULL ||
5713                                                 strcmp(*conf->variable, newval) != 0)
5714                                         {
5715                                                 ereport(elevel,
5716                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5717                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5718                                                                                 name)));
5719                                                 return 0;
5720                                         }
5721                                         return -1;
5722                                 }
5723
5724                                 if (changeVal)
5725                                 {
5726                                         /* Save old value to support transaction abort */
5727                                         if (!makeDefault)
5728                                                 push_old_value(&conf->gen, action);
5729
5730                                         if (conf->assign_hook)
5731                                                 (*conf->assign_hook) (newval, newextra);
5732                                         set_string_field(conf, conf->variable, newval);
5733                                         set_extra_field(&conf->gen, &conf->gen.extra,
5734                                                                         newextra);
5735                                         conf->gen.source = source;
5736                                         conf->gen.scontext = context;
5737                                 }
5738
5739                                 if (makeDefault)
5740                                 {
5741                                         GucStack   *stack;
5742
5743                                         if (conf->gen.reset_source <= source)
5744                                         {
5745                                                 set_string_field(conf, &conf->reset_val, newval);
5746                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5747                                                                                 newextra);
5748                                                 conf->gen.reset_source = source;
5749                                                 conf->gen.reset_scontext = context;
5750                                         }
5751                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5752                                         {
5753                                                 if (stack->source <= source)
5754                                                 {
5755                                                         set_string_field(conf, &stack->prior.val.stringval,
5756                                                                                          newval);
5757                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5758                                                                                         newextra);
5759                                                         stack->source = source;
5760                                                         stack->scontext = context;
5761                                                 }
5762                                         }
5763                                 }
5764
5765                                 /* Perhaps we didn't install newval anywhere */
5766                                 if (newval && !string_field_used(conf, newval))
5767                                         free(newval);
5768                                 /* Perhaps we didn't install newextra anywhere */
5769                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5770                                         free(newextra);
5771                                 break;
5772                         }
5773
5774                 case PGC_ENUM:
5775                         {
5776                                 struct config_enum *conf = (struct config_enum *) record;
5777                                 int                     newval;
5778                                 void       *newextra = NULL;
5779
5780                                 if (value)
5781                                 {
5782                                         if (!config_enum_lookup_by_name(conf, value, &newval))
5783                                         {
5784                                                 char       *hintmsg;
5785
5786                                                 hintmsg = config_enum_get_options(conf,
5787                                                                                                                 "Available values: ",
5788                                                                                                                   ".", ", ");
5789
5790                                                 ereport(elevel,
5791                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5792                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5793                                                                 name, value),
5794                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5795
5796                                                 if (hintmsg)
5797                                                         pfree(hintmsg);
5798                                                 return 0;
5799                                         }
5800                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5801                                                                                           source, elevel))
5802                                                 return 0;
5803                                 }
5804                                 else if (source == PGC_S_DEFAULT)
5805                                 {
5806                                         newval = conf->boot_val;
5807                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5808                                                                                           source, elevel))
5809                                                 return 0;
5810                                 }
5811                                 else
5812                                 {
5813                                         newval = conf->reset_val;
5814                                         newextra = conf->reset_extra;
5815                                         source = conf->gen.reset_source;
5816                                         context = conf->gen.reset_scontext;
5817                                 }
5818
5819                                 if (prohibitValueChange)
5820                                 {
5821                                         if (*conf->variable != newval)
5822                                         {
5823                                                 ereport(elevel,
5824                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5825                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5826                                                                                 name)));
5827                                                 return 0;
5828                                         }
5829                                         return -1;
5830                                 }
5831
5832                                 if (changeVal)
5833                                 {
5834                                         /* Save old value to support transaction abort */
5835                                         if (!makeDefault)
5836                                                 push_old_value(&conf->gen, action);
5837
5838                                         if (conf->assign_hook)
5839                                                 (*conf->assign_hook) (newval, newextra);
5840                                         *conf->variable = newval;
5841                                         set_extra_field(&conf->gen, &conf->gen.extra,
5842                                                                         newextra);
5843                                         conf->gen.source = source;
5844                                         conf->gen.scontext = context;
5845                                 }
5846                                 if (makeDefault)
5847                                 {
5848                                         GucStack   *stack;
5849
5850                                         if (conf->gen.reset_source <= source)
5851                                         {
5852                                                 conf->reset_val = newval;
5853                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5854                                                                                 newextra);
5855                                                 conf->gen.reset_source = source;
5856                                                 conf->gen.reset_scontext = context;
5857                                         }
5858                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5859                                         {
5860                                                 if (stack->source <= source)
5861                                                 {
5862                                                         stack->prior.val.enumval = newval;
5863                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5864                                                                                         newextra);
5865                                                         stack->source = source;
5866                                                         stack->scontext = context;
5867                                                 }
5868                                         }
5869                                 }
5870
5871                                 /* Perhaps we didn't install newextra anywhere */
5872                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5873                                         free(newextra);
5874                                 break;
5875                         }
5876         }
5877
5878         if (changeVal && (record->flags & GUC_REPORT))
5879                 ReportGUCOption(record);
5880
5881         return changeVal ? 1 : -1;
5882 }
5883
5884
5885 /*
5886  * Set the fields for source file and line number the setting came from.
5887  */
5888 static void
5889 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
5890 {
5891         struct config_generic *record;
5892         int                     elevel;
5893
5894         /*
5895          * To avoid cluttering the log, only the postmaster bleats loudly about
5896          * problems with the config file.
5897          */
5898         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5899
5900         record = find_option(name, true, elevel);
5901         /* should not happen */
5902         if (record == NULL)
5903                 elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
5904
5905         sourcefile = guc_strdup(elevel, sourcefile);
5906         if (record->sourcefile)
5907                 free(record->sourcefile);
5908         record->sourcefile = sourcefile;
5909         record->sourceline = sourceline;
5910 }
5911
5912 /*
5913  * Set a config option to the given value.
5914  *
5915  * See also set_config_option; this is just the wrapper to be called from
5916  * outside GUC.  (This function should be used when possible, because its API
5917  * is more stable than set_config_option's.)
5918  *
5919  * Note: there is no support here for setting source file/line, as it
5920  * is currently not needed.
5921  */
5922 void
5923 SetConfigOption(const char *name, const char *value,
5924                                 GucContext context, GucSource source)
5925 {
5926         (void) set_config_option(name, value, context, source,
5927                                                          GUC_ACTION_SET, true, 0);
5928 }
5929
5930
5931
5932 /*
5933  * Fetch the current value of the option `name', as a string.
5934  *
5935  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
5936  * this cannot be distinguished from a string variable with a NULL value!),
5937  * otherwise throw an ereport and don't return.
5938  *
5939  * If restrict_superuser is true, we also enforce that only superusers can
5940  * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
5941  * in user-driven calls.
5942  *
5943  * The string is *not* allocated for modification and is really only
5944  * valid until the next call to configuration related functions.
5945  */
5946 const char *
5947 GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
5948 {
5949         struct config_generic *record;
5950         static char buffer[256];
5951
5952         record = find_option(name, false, ERROR);
5953         if (record == NULL)
5954         {
5955                 if (missing_ok)
5956                         return NULL;
5957                 ereport(ERROR,
5958                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5959                                  errmsg("unrecognized configuration parameter \"%s\"",
5960                                                 name)));
5961         }
5962         if (restrict_superuser &&
5963                 (record->flags & GUC_SUPERUSER_ONLY) &&
5964                 !superuser())
5965                 ereport(ERROR,
5966                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5967                                  errmsg("must be superuser to examine \"%s\"", name)));
5968
5969         switch (record->vartype)
5970         {
5971                 case PGC_BOOL:
5972                         return *((struct config_bool *) record)->variable ? "on" : "off";
5973
5974                 case PGC_INT:
5975                         snprintf(buffer, sizeof(buffer), "%d",
5976                                          *((struct config_int *) record)->variable);
5977                         return buffer;
5978
5979                 case PGC_REAL:
5980                         snprintf(buffer, sizeof(buffer), "%g",
5981                                          *((struct config_real *) record)->variable);
5982                         return buffer;
5983
5984                 case PGC_STRING:
5985                         return *((struct config_string *) record)->variable;
5986
5987                 case PGC_ENUM:
5988                         return config_enum_lookup_by_value((struct config_enum *) record,
5989                                                                  *((struct config_enum *) record)->variable);
5990         }
5991         return NULL;
5992 }
5993
5994 /*
5995  * Get the RESET value associated with the given option.
5996  *
5997  * Note: this is not re-entrant, due to use of static result buffer;
5998  * not to mention that a string variable could have its reset_val changed.
5999  * Beware of assuming the result value is good for very long.
6000  */
6001 const char *
6002 GetConfigOptionResetString(const char *name)
6003 {
6004         struct config_generic *record;
6005         static char buffer[256];
6006
6007         record = find_option(name, false, ERROR);
6008         if (record == NULL)
6009                 ereport(ERROR,
6010                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6011                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6012         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6013                 ereport(ERROR,
6014                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6015                                  errmsg("must be superuser to examine \"%s\"", name)));
6016
6017         switch (record->vartype)
6018         {
6019                 case PGC_BOOL:
6020                         return ((struct config_bool *) record)->reset_val ? "on" : "off";
6021
6022                 case PGC_INT:
6023                         snprintf(buffer, sizeof(buffer), "%d",
6024                                          ((struct config_int *) record)->reset_val);
6025                         return buffer;
6026
6027                 case PGC_REAL:
6028                         snprintf(buffer, sizeof(buffer), "%g",
6029                                          ((struct config_real *) record)->reset_val);
6030                         return buffer;
6031
6032                 case PGC_STRING:
6033                         return ((struct config_string *) record)->reset_val;
6034
6035                 case PGC_ENUM:
6036                         return config_enum_lookup_by_value((struct config_enum *) record,
6037                                                                  ((struct config_enum *) record)->reset_val);
6038         }
6039         return NULL;
6040 }
6041
6042
6043 /*
6044  * flatten_set_variable_args
6045  *              Given a parsenode List as emitted by the grammar for SET,
6046  *              convert to the flat string representation used by GUC.
6047  *
6048  * We need to be told the name of the variable the args are for, because
6049  * the flattening rules vary (ugh).
6050  *
6051  * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
6052  * a palloc'd string.
6053  */
6054 static char *
6055 flatten_set_variable_args(const char *name, List *args)
6056 {
6057         struct config_generic *record;
6058         int                     flags;
6059         StringInfoData buf;
6060         ListCell   *l;
6061
6062         /* Fast path if just DEFAULT */
6063         if (args == NIL)
6064                 return NULL;
6065
6066         /*
6067          * Get flags for the variable; if it's not known, use default flags.
6068          * (Caller might throw error later, but not our business to do so here.)
6069          */
6070         record = find_option(name, false, WARNING);
6071         if (record)
6072                 flags = record->flags;
6073         else
6074                 flags = 0;
6075
6076         /* Complain if list input and non-list variable */
6077         if ((flags & GUC_LIST_INPUT) == 0 &&
6078                 list_length(args) != 1)
6079                 ereport(ERROR,
6080                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6081                                  errmsg("SET %s takes only one argument", name)));
6082
6083         initStringInfo(&buf);
6084
6085         /*
6086          * Each list member may be a plain A_Const node, or an A_Const within a
6087          * TypeCast; the latter case is supported only for ConstInterval arguments
6088          * (for SET TIME ZONE).
6089          */
6090         foreach(l, args)
6091         {
6092                 Node       *arg = (Node *) lfirst(l);
6093                 char       *val;
6094                 TypeName   *typeName = NULL;
6095                 A_Const    *con;
6096
6097                 if (l != list_head(args))
6098                         appendStringInfo(&buf, ", ");
6099
6100                 if (IsA(arg, TypeCast))
6101                 {
6102                         TypeCast   *tc = (TypeCast *) arg;
6103
6104                         arg = tc->arg;
6105                         typeName = tc->typeName;
6106                 }
6107
6108                 if (!IsA(arg, A_Const))
6109                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
6110                 con = (A_Const *) arg;
6111
6112                 switch (nodeTag(&con->val))
6113                 {
6114                         case T_Integer:
6115                                 appendStringInfo(&buf, "%ld", intVal(&con->val));
6116                                 break;
6117                         case T_Float:
6118                                 /* represented as a string, so just copy it */
6119                                 appendStringInfoString(&buf, strVal(&con->val));
6120                                 break;
6121                         case T_String:
6122                                 val = strVal(&con->val);
6123                                 if (typeName != NULL)
6124                                 {
6125                                         /*
6126                                          * Must be a ConstInterval argument for TIME ZONE. Coerce
6127                                          * to interval and back to normalize the value and account
6128                                          * for any typmod.
6129                                          */
6130                                         Oid                     typoid;
6131                                         int32           typmod;
6132                                         Datum           interval;
6133                                         char       *intervalout;
6134
6135                                         typenameTypeIdAndMod(NULL, typeName, &typoid, &typmod);
6136                                         Assert(typoid == INTERVALOID);
6137
6138                                         interval =
6139                                                 DirectFunctionCall3(interval_in,
6140                                                                                         CStringGetDatum(val),
6141                                                                                         ObjectIdGetDatum(InvalidOid),
6142                                                                                         Int32GetDatum(typmod));
6143
6144                                         intervalout =
6145                                                 DatumGetCString(DirectFunctionCall1(interval_out,
6146                                                                                                                         interval));
6147                                         appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
6148                                 }
6149                                 else
6150                                 {
6151                                         /*
6152                                          * Plain string literal or identifier.  For quote mode,
6153                                          * quote it if it's not a vanilla identifier.
6154                                          */
6155                                         if (flags & GUC_LIST_QUOTE)
6156                                                 appendStringInfoString(&buf, quote_identifier(val));
6157                                         else
6158                                                 appendStringInfoString(&buf, val);
6159                                 }
6160                                 break;
6161                         default:
6162                                 elog(ERROR, "unrecognized node type: %d",
6163                                          (int) nodeTag(&con->val));
6164                                 break;
6165                 }
6166         }
6167
6168         return buf.data;
6169 }
6170
6171
6172 /*
6173  * SET command
6174  */
6175 void
6176 ExecSetVariableStmt(VariableSetStmt *stmt)
6177 {
6178         GucAction       action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
6179
6180         switch (stmt->kind)
6181         {
6182                 case VAR_SET_VALUE:
6183                 case VAR_SET_CURRENT:
6184                         (void) set_config_option(stmt->name,
6185                                                                          ExtractSetVariableArgs(stmt),
6186                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6187                                                                          PGC_S_SESSION,
6188                                                                          action,
6189                                                                          true,
6190                                                                          0);
6191                         break;
6192                 case VAR_SET_MULTI:
6193
6194                         /*
6195                          * Special-case SQL syntaxes.  The TRANSACTION and SESSION
6196                          * CHARACTERISTICS cases effectively set more than one variable
6197                          * per statement.  TRANSACTION SNAPSHOT only takes one argument,
6198                          * but we put it here anyway since it's a special case and not
6199                          * related to any GUC variable.
6200                          */
6201                         if (strcmp(stmt->name, "TRANSACTION") == 0)
6202                         {
6203                                 ListCell   *head;
6204
6205                                 foreach(head, stmt->args)
6206                                 {
6207                                         DefElem    *item = (DefElem *) lfirst(head);
6208
6209                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6210                                                 SetPGVariable("transaction_isolation",
6211                                                                           list_make1(item->arg), stmt->is_local);
6212                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6213                                                 SetPGVariable("transaction_read_only",
6214                                                                           list_make1(item->arg), stmt->is_local);
6215                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6216                                                 SetPGVariable("transaction_deferrable",
6217                                                                           list_make1(item->arg), stmt->is_local);
6218                                         else
6219                                                 elog(ERROR, "unexpected SET TRANSACTION element: %s",
6220                                                          item->defname);
6221                                 }
6222                         }
6223                         else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
6224                         {
6225                                 ListCell   *head;
6226
6227                                 foreach(head, stmt->args)
6228                                 {
6229                                         DefElem    *item = (DefElem *) lfirst(head);
6230
6231                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6232                                                 SetPGVariable("default_transaction_isolation",
6233                                                                           list_make1(item->arg), stmt->is_local);
6234                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6235                                                 SetPGVariable("default_transaction_read_only",
6236                                                                           list_make1(item->arg), stmt->is_local);
6237                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6238                                                 SetPGVariable("default_transaction_deferrable",
6239                                                                           list_make1(item->arg), stmt->is_local);
6240                                         else
6241                                                 elog(ERROR, "unexpected SET SESSION element: %s",
6242                                                          item->defname);
6243                                 }
6244                         }
6245                         else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
6246                         {
6247                                 A_Const    *con = (A_Const *) linitial(stmt->args);
6248
6249                                 if (stmt->is_local)
6250                                         ereport(ERROR,
6251                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6252                                                          errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
6253                                 Assert(IsA(con, A_Const));
6254                                 Assert(nodeTag(&con->val) == T_String);
6255                                 ImportSnapshot(strVal(&con->val));
6256                         }
6257                         else
6258                                 elog(ERROR, "unexpected SET MULTI element: %s",
6259                                          stmt->name);
6260                         break;
6261                 case VAR_SET_DEFAULT:
6262                 case VAR_RESET:
6263                         (void) set_config_option(stmt->name,
6264                                                                          NULL,
6265                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6266                                                                          PGC_S_SESSION,
6267                                                                          action,
6268                                                                          true,
6269                                                                          0);
6270                         break;
6271                 case VAR_RESET_ALL:
6272                         ResetAllOptions();
6273                         break;
6274         }
6275 }
6276
6277 /*
6278  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
6279  * The result is palloc'd.
6280  *
6281  * This is exported for use by actions such as ALTER ROLE SET.
6282  */
6283 char *
6284 ExtractSetVariableArgs(VariableSetStmt *stmt)
6285 {
6286         switch (stmt->kind)
6287         {
6288                 case VAR_SET_VALUE:
6289                         return flatten_set_variable_args(stmt->name, stmt->args);
6290                 case VAR_SET_CURRENT:
6291                         return GetConfigOptionByName(stmt->name, NULL);
6292                 default:
6293                         return NULL;
6294         }
6295 }
6296
6297 /*
6298  * SetPGVariable - SET command exported as an easily-C-callable function.
6299  *
6300  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
6301  * by passing args == NIL), but not SET FROM CURRENT functionality.
6302  */
6303 void
6304 SetPGVariable(const char *name, List *args, bool is_local)
6305 {
6306         char       *argstring = flatten_set_variable_args(name, args);
6307
6308         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6309         (void) set_config_option(name,
6310                                                          argstring,
6311                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6312                                                          PGC_S_SESSION,
6313                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6314                                                          true,
6315                                                          0);
6316 }
6317
6318 /*
6319  * SET command wrapped as a SQL callable function.
6320  */
6321 Datum
6322 set_config_by_name(PG_FUNCTION_ARGS)
6323 {
6324         char       *name;
6325         char       *value;
6326         char       *new_value;
6327         bool            is_local;
6328
6329         if (PG_ARGISNULL(0))
6330                 ereport(ERROR,
6331                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6332                                  errmsg("SET requires parameter name")));
6333
6334         /* Get the GUC variable name */
6335         name = TextDatumGetCString(PG_GETARG_DATUM(0));
6336
6337         /* Get the desired value or set to NULL for a reset request */
6338         if (PG_ARGISNULL(1))
6339                 value = NULL;
6340         else
6341                 value = TextDatumGetCString(PG_GETARG_DATUM(1));
6342
6343         /*
6344          * Get the desired state of is_local. Default to false if provided value
6345          * is NULL
6346          */
6347         if (PG_ARGISNULL(2))
6348                 is_local = false;
6349         else
6350                 is_local = PG_GETARG_BOOL(2);
6351
6352         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6353         (void) set_config_option(name,
6354                                                          value,
6355                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6356                                                          PGC_S_SESSION,
6357                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6358                                                          true,
6359                                                          0);
6360
6361         /* get the new current value */
6362         new_value = GetConfigOptionByName(name, NULL);
6363
6364         /* Convert return string to text */
6365         PG_RETURN_TEXT_P(cstring_to_text(new_value));
6366 }
6367
6368
6369 /*
6370  * Common code for DefineCustomXXXVariable subroutines: allocate the
6371  * new variable's config struct and fill in generic fields.
6372  */
6373 static struct config_generic *
6374 init_custom_variable(const char *name,
6375                                          const char *short_desc,
6376                                          const char *long_desc,
6377                                          GucContext context,
6378                                          int flags,
6379                                          enum config_type type,
6380                                          size_t sz)
6381 {
6382         struct config_generic *gen;
6383
6384         /*
6385          * Only allow custom PGC_POSTMASTER variables to be created during shared
6386          * library preload; any later than that, we can't ensure that the value
6387          * doesn't change after startup.  This is a fatal elog if it happens; just
6388          * erroring out isn't safe because we don't know what the calling loadable
6389          * module might already have hooked into.
6390          */
6391         if (context == PGC_POSTMASTER &&
6392                 !process_shared_preload_libraries_in_progress)
6393                 elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
6394
6395         gen = (struct config_generic *) guc_malloc(ERROR, sz);
6396         memset(gen, 0, sz);
6397
6398         gen->name = guc_strdup(ERROR, name);
6399         gen->context = context;
6400         gen->group = CUSTOM_OPTIONS;
6401         gen->short_desc = short_desc;
6402         gen->long_desc = long_desc;
6403         gen->flags = flags;
6404         gen->vartype = type;
6405
6406         return gen;
6407 }
6408
6409 /*
6410  * Common code for DefineCustomXXXVariable subroutines: insert the new
6411  * variable into the GUC variable array, replacing any placeholder.
6412  */
6413 static void
6414 define_custom_variable(struct config_generic * variable)
6415 {
6416         const char *name = variable->name;
6417         const char **nameAddr = &name;
6418         struct config_string *pHolder;
6419         struct config_generic **res;
6420
6421         /*
6422          * See if there's a placeholder by the same name.
6423          */
6424         res = (struct config_generic **) bsearch((void *) &nameAddr,
6425                                                                                          (void *) guc_variables,
6426                                                                                          num_guc_variables,
6427                                                                                          sizeof(struct config_generic *),
6428                                                                                          guc_var_compare);
6429         if (res == NULL)
6430         {
6431                 /*
6432                  * No placeholder to replace, so we can just add it ... but first,
6433                  * make sure it's initialized to its default value.
6434                  */
6435                 InitializeOneGUCOption(variable);
6436                 add_guc_variable(variable, ERROR);
6437                 return;
6438         }
6439
6440         /*
6441          * This better be a placeholder
6442          */
6443         if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
6444                 ereport(ERROR,
6445                                 (errcode(ERRCODE_INTERNAL_ERROR),
6446                                  errmsg("attempt to redefine parameter \"%s\"", name)));
6447
6448         Assert((*res)->vartype == PGC_STRING);
6449         pHolder = (struct config_string *) (*res);
6450
6451         /*
6452          * First, set the variable to its default value.  We must do this even
6453          * though we intend to immediately apply a new value, since it's possible
6454          * that the new value is invalid.
6455          */
6456         InitializeOneGUCOption(variable);
6457
6458         /*
6459          * Replace the placeholder. We aren't changing the name, so no re-sorting
6460          * is necessary
6461          */
6462         *res = variable;
6463
6464         /*
6465          * Assign the string value(s) stored in the placeholder to the real
6466          * variable.  Essentially, we need to duplicate all the active and stacked
6467          * values, but with appropriate validation and datatype adjustment.
6468          *
6469          * If an assignment fails, we report a WARNING and keep going.  We don't
6470          * want to throw ERROR for bad values, because it'd bollix the add-on
6471          * module that's presumably halfway through getting loaded.  In such cases
6472          * the default or previous state will become active instead.
6473          */
6474
6475         /* First, apply the reset value if any */
6476         if (pHolder->reset_val)
6477                 (void) set_config_option(name, pHolder->reset_val,
6478                                                                  pHolder->gen.reset_scontext,
6479                                                                  pHolder->gen.reset_source,
6480                                                                  GUC_ACTION_SET, true, WARNING);
6481         /* That should not have resulted in stacking anything */
6482         Assert(variable->stack == NULL);
6483
6484         /* Now, apply current and stacked values, in the order they were stacked */
6485         reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
6486                                                    *(pHolder->variable),
6487                                                    pHolder->gen.scontext, pHolder->gen.source);
6488
6489         /* Also copy over any saved source-location information */
6490         if (pHolder->gen.sourcefile)
6491                 set_config_sourcefile(name, pHolder->gen.sourcefile,
6492                                                           pHolder->gen.sourceline);
6493
6494         /*
6495          * Free up as much as we conveniently can of the placeholder structure.
6496          * (This neglects any stack items, so it's possible for some memory to be
6497          * leaked.      Since this can only happen once per session per variable, it
6498          * doesn't seem worth spending much code on.)
6499          */
6500         set_string_field(pHolder, pHolder->variable, NULL);
6501         set_string_field(pHolder, &pHolder->reset_val, NULL);
6502
6503         free(pHolder);
6504 }
6505
6506 /*
6507  * Recursive subroutine for define_custom_variable: reapply non-reset values
6508  *
6509  * We recurse so that the values are applied in the same order as originally.
6510  * At each recursion level, apply the upper-level value (passed in) in the
6511  * fashion implied by the stack entry.
6512  */
6513 static void
6514 reapply_stacked_values(struct config_generic * variable,
6515                                            struct config_string * pHolder,
6516                                            GucStack *stack,
6517                                            const char *curvalue,
6518                                            GucContext curscontext, GucSource cursource)
6519 {
6520         const char *name = variable->name;
6521         GucStack   *oldvarstack = variable->stack;
6522
6523         if (stack != NULL)
6524         {
6525                 /* First, recurse, so that stack items are processed bottom to top */
6526                 reapply_stacked_values(variable, pHolder, stack->prev,
6527                                                            stack->prior.val.stringval,
6528                                                            stack->scontext, stack->source);
6529
6530                 /* See how to apply the passed-in value */
6531                 switch (stack->state)
6532                 {
6533                         case GUC_SAVE:
6534                                 (void) set_config_option(name, curvalue,
6535                                                                                  curscontext, cursource,
6536                                                                                  GUC_ACTION_SAVE, true, WARNING);
6537                                 break;
6538
6539                         case GUC_SET:
6540                                 (void) set_config_option(name, curvalue,
6541                                                                                  curscontext, cursource,
6542                                                                                  GUC_ACTION_SET, true, WARNING);
6543                                 break;
6544
6545                         case GUC_LOCAL:
6546                                 (void) set_config_option(name, curvalue,
6547                                                                                  curscontext, cursource,
6548                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6549                                 break;
6550
6551                         case GUC_SET_LOCAL:
6552                                 /* first, apply the masked value as SET */
6553                                 (void) set_config_option(name, stack->masked.val.stringval,
6554                                                                            stack->masked_scontext, PGC_S_SESSION,
6555                                                                                  GUC_ACTION_SET, true, WARNING);
6556                                 /* then apply the current value as LOCAL */
6557                                 (void) set_config_option(name, curvalue,
6558                                                                                  curscontext, cursource,
6559                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6560                                 break;
6561                 }
6562
6563                 /* If we successfully made a stack entry, adjust its nest level */
6564                 if (variable->stack != oldvarstack)
6565                         variable->stack->nest_level = stack->nest_level;
6566         }
6567         else
6568         {
6569                 /*
6570                  * We are at the end of the stack.      If the active/previous value is
6571                  * different from the reset value, it must represent a previously
6572                  * committed session value.  Apply it, and then drop the stack entry
6573                  * that set_config_option will have created under the impression that
6574                  * this is to be just a transactional assignment.  (We leak the stack
6575                  * entry.)
6576                  */
6577                 if (curvalue != pHolder->reset_val ||
6578                         curscontext != pHolder->gen.reset_scontext ||
6579                         cursource != pHolder->gen.reset_source)
6580                 {
6581                         (void) set_config_option(name, curvalue,
6582                                                                          curscontext, cursource,
6583                                                                          GUC_ACTION_SET, true, WARNING);
6584                         variable->stack = NULL;
6585                 }
6586         }
6587 }
6588
6589 void
6590 DefineCustomBoolVariable(const char *name,
6591                                                  const char *short_desc,
6592                                                  const char *long_desc,
6593                                                  bool *valueAddr,
6594                                                  bool bootValue,
6595                                                  GucContext context,
6596                                                  int flags,
6597                                                  GucBoolCheckHook check_hook,
6598                                                  GucBoolAssignHook assign_hook,
6599                                                  GucShowHook show_hook)
6600 {
6601         struct config_bool *var;
6602
6603         var = (struct config_bool *)
6604                 init_custom_variable(name, short_desc, long_desc, context, flags,
6605                                                          PGC_BOOL, sizeof(struct config_bool));
6606         var->variable = valueAddr;
6607         var->boot_val = bootValue;
6608         var->reset_val = bootValue;
6609         var->check_hook = check_hook;
6610         var->assign_hook = assign_hook;
6611         var->show_hook = show_hook;
6612         define_custom_variable(&var->gen);
6613 }
6614
6615 void
6616 DefineCustomIntVariable(const char *name,
6617                                                 const char *short_desc,
6618                                                 const char *long_desc,
6619                                                 int *valueAddr,
6620                                                 int bootValue,
6621                                                 int minValue,
6622                                                 int maxValue,
6623                                                 GucContext context,
6624                                                 int flags,
6625                                                 GucIntCheckHook check_hook,
6626                                                 GucIntAssignHook assign_hook,
6627                                                 GucShowHook show_hook)
6628 {
6629         struct config_int *var;
6630
6631         var = (struct config_int *)
6632                 init_custom_variable(name, short_desc, long_desc, context, flags,
6633                                                          PGC_INT, sizeof(struct config_int));
6634         var->variable = valueAddr;
6635         var->boot_val = bootValue;
6636         var->reset_val = bootValue;
6637         var->min = minValue;
6638         var->max = maxValue;
6639         var->check_hook = check_hook;
6640         var->assign_hook = assign_hook;
6641         var->show_hook = show_hook;
6642         define_custom_variable(&var->gen);
6643 }
6644
6645 void
6646 DefineCustomRealVariable(const char *name,
6647                                                  const char *short_desc,
6648                                                  const char *long_desc,
6649                                                  double *valueAddr,
6650                                                  double bootValue,
6651                                                  double minValue,
6652                                                  double maxValue,
6653                                                  GucContext context,
6654                                                  int flags,
6655                                                  GucRealCheckHook check_hook,
6656                                                  GucRealAssignHook assign_hook,
6657                                                  GucShowHook show_hook)
6658 {
6659         struct config_real *var;
6660
6661         var = (struct config_real *)
6662                 init_custom_variable(name, short_desc, long_desc, context, flags,
6663                                                          PGC_REAL, sizeof(struct config_real));
6664         var->variable = valueAddr;
6665         var->boot_val = bootValue;
6666         var->reset_val = bootValue;
6667         var->min = minValue;
6668         var->max = maxValue;
6669         var->check_hook = check_hook;
6670         var->assign_hook = assign_hook;
6671         var->show_hook = show_hook;
6672         define_custom_variable(&var->gen);
6673 }
6674
6675 void
6676 DefineCustomStringVariable(const char *name,
6677                                                    const char *short_desc,
6678                                                    const char *long_desc,
6679                                                    char **valueAddr,
6680                                                    const char *bootValue,
6681                                                    GucContext context,
6682                                                    int flags,
6683                                                    GucStringCheckHook check_hook,
6684                                                    GucStringAssignHook assign_hook,
6685                                                    GucShowHook show_hook)
6686 {
6687         struct config_string *var;
6688
6689         var = (struct config_string *)
6690                 init_custom_variable(name, short_desc, long_desc, context, flags,
6691                                                          PGC_STRING, sizeof(struct config_string));
6692         var->variable = valueAddr;
6693         var->boot_val = bootValue;
6694         var->check_hook = check_hook;
6695         var->assign_hook = assign_hook;
6696         var->show_hook = show_hook;
6697         define_custom_variable(&var->gen);
6698 }
6699
6700 void
6701 DefineCustomEnumVariable(const char *name,
6702                                                  const char *short_desc,
6703                                                  const char *long_desc,
6704                                                  int *valueAddr,
6705                                                  int bootValue,
6706                                                  const struct config_enum_entry * options,
6707                                                  GucContext context,
6708                                                  int flags,
6709                                                  GucEnumCheckHook check_hook,
6710                                                  GucEnumAssignHook assign_hook,
6711                                                  GucShowHook show_hook)
6712 {
6713         struct config_enum *var;
6714
6715         var = (struct config_enum *)
6716                 init_custom_variable(name, short_desc, long_desc, context, flags,
6717                                                          PGC_ENUM, sizeof(struct config_enum));
6718         var->variable = valueAddr;
6719         var->boot_val = bootValue;
6720         var->reset_val = bootValue;
6721         var->options = options;
6722         var->check_hook = check_hook;
6723         var->assign_hook = assign_hook;
6724         var->show_hook = show_hook;
6725         define_custom_variable(&var->gen);
6726 }
6727
6728 void
6729 EmitWarningsOnPlaceholders(const char *className)
6730 {
6731         int                     classLen = strlen(className);
6732         int                     i;
6733
6734         for (i = 0; i < num_guc_variables; i++)
6735         {
6736                 struct config_generic *var = guc_variables[i];
6737
6738                 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
6739                         strncmp(className, var->name, classLen) == 0 &&
6740                         var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
6741                 {
6742                         ereport(WARNING,
6743                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
6744                                          errmsg("unrecognized configuration parameter \"%s\"",
6745                                                         var->name)));
6746                 }
6747         }
6748 }
6749
6750
6751 /*
6752  * SHOW command
6753  */
6754 void
6755 GetPGVariable(const char *name, DestReceiver *dest)
6756 {
6757         if (guc_name_compare(name, "all") == 0)
6758                 ShowAllGUCConfig(dest);
6759         else
6760                 ShowGUCConfigOption(name, dest);
6761 }
6762
6763 TupleDesc
6764 GetPGVariableResultDesc(const char *name)
6765 {
6766         TupleDesc       tupdesc;
6767
6768         if (guc_name_compare(name, "all") == 0)
6769         {
6770                 /* need a tuple descriptor representing three TEXT columns */
6771                 tupdesc = CreateTemplateTupleDesc(3, false);
6772                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6773                                                    TEXTOID, -1, 0);
6774                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6775                                                    TEXTOID, -1, 0);
6776                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6777                                                    TEXTOID, -1, 0);
6778         }
6779         else
6780         {
6781                 const char *varname;
6782
6783                 /* Get the canonical spelling of name */
6784                 (void) GetConfigOptionByName(name, &varname);
6785
6786                 /* need a tuple descriptor representing a single TEXT column */
6787                 tupdesc = CreateTemplateTupleDesc(1, false);
6788                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6789                                                    TEXTOID, -1, 0);
6790         }
6791         return tupdesc;
6792 }
6793
6794
6795 /*
6796  * SHOW command
6797  */
6798 static void
6799 ShowGUCConfigOption(const char *name, DestReceiver *dest)
6800 {
6801         TupOutputState *tstate;
6802         TupleDesc       tupdesc;
6803         const char *varname;
6804         char       *value;
6805
6806         /* Get the value and canonical spelling of name */
6807         value = GetConfigOptionByName(name, &varname);
6808
6809         /* need a tuple descriptor representing a single TEXT column */
6810         tupdesc = CreateTemplateTupleDesc(1, false);
6811         TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6812                                            TEXTOID, -1, 0);
6813
6814         /* prepare for projection of tuples */
6815         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6816
6817         /* Send it */
6818         do_text_output_oneline(tstate, value);
6819
6820         end_tup_output(tstate);
6821 }
6822
6823 /*
6824  * SHOW ALL command
6825  */
6826 static void
6827 ShowAllGUCConfig(DestReceiver *dest)
6828 {
6829         bool            am_superuser = superuser();
6830         int                     i;
6831         TupOutputState *tstate;
6832         TupleDesc       tupdesc;
6833         Datum           values[3];
6834         bool            isnull[3] = {false, false, false};
6835
6836         /* need a tuple descriptor representing three TEXT columns */
6837         tupdesc = CreateTemplateTupleDesc(3, false);
6838         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6839                                            TEXTOID, -1, 0);
6840         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6841                                            TEXTOID, -1, 0);
6842         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6843                                            TEXTOID, -1, 0);
6844
6845         /* prepare for projection of tuples */
6846         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6847
6848         for (i = 0; i < num_guc_variables; i++)
6849         {
6850                 struct config_generic *conf = guc_variables[i];
6851                 char       *setting;
6852
6853                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6854                         ((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
6855                         continue;
6856
6857                 /* assign to the values array */
6858                 values[0] = PointerGetDatum(cstring_to_text(conf->name));
6859
6860                 setting = _ShowOption(conf, true);
6861                 if (setting)
6862                 {
6863                         values[1] = PointerGetDatum(cstring_to_text(setting));
6864                         isnull[1] = false;
6865                 }
6866                 else
6867                 {
6868                         values[1] = PointerGetDatum(NULL);
6869                         isnull[1] = true;
6870                 }
6871
6872                 values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
6873
6874                 /* send it to dest */
6875                 do_tup_output(tstate, values, isnull);
6876
6877                 /* clean up */
6878                 pfree(DatumGetPointer(values[0]));
6879                 if (setting)
6880                 {
6881                         pfree(setting);
6882                         pfree(DatumGetPointer(values[1]));
6883                 }
6884                 pfree(DatumGetPointer(values[2]));
6885         }
6886
6887         end_tup_output(tstate);
6888 }
6889
6890 /*
6891  * Return GUC variable value by name; optionally return canonical
6892  * form of name.  Return value is palloc'd.
6893  */
6894 char *
6895 GetConfigOptionByName(const char *name, const char **varname)
6896 {
6897         struct config_generic *record;
6898
6899         record = find_option(name, false, ERROR);
6900         if (record == NULL)
6901                 ereport(ERROR,
6902                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6903                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6904         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6905                 ereport(ERROR,
6906                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6907                                  errmsg("must be superuser to examine \"%s\"", name)));
6908
6909         if (varname)
6910                 *varname = record->name;
6911
6912         return _ShowOption(record, true);
6913 }
6914
6915 /*
6916  * Return GUC variable value by variable number; optionally return canonical
6917  * form of name.  Return value is palloc'd.
6918  */
6919 void
6920 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
6921 {
6922         char            buffer[256];
6923         struct config_generic *conf;
6924
6925         /* check requested variable number valid */
6926         Assert((varnum >= 0) && (varnum < num_guc_variables));
6927
6928         conf = guc_variables[varnum];
6929
6930         if (noshow)
6931         {
6932                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6933                         ((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
6934                         *noshow = true;
6935                 else
6936                         *noshow = false;
6937         }
6938
6939         /* first get the generic attributes */
6940
6941         /* name */
6942         values[0] = conf->name;
6943
6944         /* setting : use _ShowOption in order to avoid duplicating the logic */
6945         values[1] = _ShowOption(conf, false);
6946
6947         /* unit */
6948         if (conf->vartype == PGC_INT)
6949         {
6950                 static char buf[8];
6951
6952                 switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
6953                 {
6954                         case GUC_UNIT_KB:
6955                                 values[2] = "kB";
6956                                 break;
6957                         case GUC_UNIT_BLOCKS:
6958                                 snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
6959                                 values[2] = buf;
6960                                 break;
6961                         case GUC_UNIT_XBLOCKS:
6962                                 snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
6963                                 values[2] = buf;
6964                                 break;
6965                         case GUC_UNIT_MS:
6966                                 values[2] = "ms";
6967                                 break;
6968                         case GUC_UNIT_S:
6969                                 values[2] = "s";
6970                                 break;
6971                         case GUC_UNIT_MIN:
6972                                 values[2] = "min";
6973                                 break;
6974                         default:
6975                                 values[2] = "";
6976                                 break;
6977                 }
6978         }
6979         else
6980                 values[2] = NULL;
6981
6982         /* group */
6983         values[3] = config_group_names[conf->group];
6984
6985         /* short_desc */
6986         values[4] = conf->short_desc;
6987
6988         /* extra_desc */
6989         values[5] = conf->long_desc;
6990
6991         /* context */
6992         values[6] = GucContext_Names[conf->context];
6993
6994         /* vartype */
6995         values[7] = config_type_names[conf->vartype];
6996
6997         /* source */
6998         values[8] = GucSource_Names[conf->source];
6999
7000         /* now get the type specifc attributes */
7001         switch (conf->vartype)
7002         {
7003                 case PGC_BOOL:
7004                         {
7005                                 struct config_bool *lconf = (struct config_bool *) conf;
7006
7007                                 /* min_val */
7008                                 values[9] = NULL;
7009
7010                                 /* max_val */
7011                                 values[10] = NULL;
7012
7013                                 /* enumvals */
7014                                 values[11] = NULL;
7015
7016                                 /* boot_val */
7017                                 values[12] = pstrdup(lconf->boot_val ? "on" : "off");
7018
7019                                 /* reset_val */
7020                                 values[13] = pstrdup(lconf->reset_val ? "on" : "off");
7021                         }
7022                         break;
7023
7024                 case PGC_INT:
7025                         {
7026                                 struct config_int *lconf = (struct config_int *) conf;
7027
7028                                 /* min_val */
7029                                 snprintf(buffer, sizeof(buffer), "%d", lconf->min);
7030                                 values[9] = pstrdup(buffer);
7031
7032                                 /* max_val */
7033                                 snprintf(buffer, sizeof(buffer), "%d", lconf->max);
7034                                 values[10] = pstrdup(buffer);
7035
7036                                 /* enumvals */
7037                                 values[11] = NULL;
7038
7039                                 /* boot_val */
7040                                 snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
7041                                 values[12] = pstrdup(buffer);
7042
7043                                 /* reset_val */
7044                                 snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
7045                                 values[13] = pstrdup(buffer);
7046                         }
7047                         break;
7048
7049                 case PGC_REAL:
7050                         {
7051                                 struct config_real *lconf = (struct config_real *) conf;
7052
7053                                 /* min_val */
7054                                 snprintf(buffer, sizeof(buffer), "%g", lconf->min);
7055                                 values[9] = pstrdup(buffer);
7056
7057                                 /* max_val */
7058                                 snprintf(buffer, sizeof(buffer), "%g", lconf->max);
7059                                 values[10] = pstrdup(buffer);
7060
7061                                 /* enumvals */
7062                                 values[11] = NULL;
7063
7064                                 /* boot_val */
7065                                 snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
7066                                 values[12] = pstrdup(buffer);
7067
7068                                 /* reset_val */
7069                                 snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
7070                                 values[13] = pstrdup(buffer);
7071                         }
7072                         break;
7073
7074                 case PGC_STRING:
7075                         {
7076                                 struct config_string *lconf = (struct config_string *) conf;
7077
7078                                 /* min_val */
7079                                 values[9] = NULL;
7080
7081                                 /* max_val */
7082                                 values[10] = NULL;
7083
7084                                 /* enumvals */
7085                                 values[11] = NULL;
7086
7087                                 /* boot_val */
7088                                 if (lconf->boot_val == NULL)
7089                                         values[12] = NULL;
7090                                 else
7091                                         values[12] = pstrdup(lconf->boot_val);
7092
7093                                 /* reset_val */
7094                                 if (lconf->reset_val == NULL)
7095                                         values[13] = NULL;
7096                                 else
7097                                         values[13] = pstrdup(lconf->reset_val);
7098                         }
7099                         break;
7100
7101                 case PGC_ENUM:
7102                         {
7103                                 struct config_enum *lconf = (struct config_enum *) conf;
7104
7105                                 /* min_val */
7106                                 values[9] = NULL;
7107
7108                                 /* max_val */
7109                                 values[10] = NULL;
7110
7111                                 /* enumvals */
7112
7113                                 /*
7114                                  * NOTE! enumvals with double quotes in them are not
7115                                  * supported!
7116                                  */
7117                                 values[11] = config_enum_get_options((struct config_enum *) conf,
7118                                                                                                          "{\"", "\"}", "\",\"");
7119
7120                                 /* boot_val */
7121                                 values[12] = pstrdup(config_enum_lookup_by_value(lconf,
7122                                                                                                                    lconf->boot_val));
7123
7124                                 /* reset_val */
7125                                 values[13] = pstrdup(config_enum_lookup_by_value(lconf,
7126                                                                                                                   lconf->reset_val));
7127                         }
7128                         break;
7129
7130                 default:
7131                         {
7132                                 /*
7133                                  * should never get here, but in case we do, set 'em to NULL
7134                                  */
7135
7136                                 /* min_val */
7137                                 values[9] = NULL;
7138
7139                                 /* max_val */
7140                                 values[10] = NULL;
7141
7142                                 /* enumvals */
7143                                 values[11] = NULL;
7144
7145                                 /* boot_val */
7146                                 values[12] = NULL;
7147
7148                                 /* reset_val */
7149                                 values[13] = NULL;
7150                         }
7151                         break;
7152         }
7153
7154         /*
7155          * If the setting came from a config file, set the source location. For
7156          * security reasons, we don't show source file/line number for
7157          * non-superusers.
7158          */
7159         if (conf->source == PGC_S_FILE && superuser())
7160         {
7161                 values[14] = conf->sourcefile;
7162                 snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
7163                 values[15] = pstrdup(buffer);
7164         }
7165         else
7166         {
7167                 values[14] = NULL;
7168                 values[15] = NULL;
7169         }
7170 }
7171
7172 /*
7173  * Return the total number of GUC variables
7174  */
7175 int
7176 GetNumConfigOptions(void)
7177 {
7178         return num_guc_variables;
7179 }
7180
7181 /*
7182  * show_config_by_name - equiv to SHOW X command but implemented as
7183  * a function.
7184  */
7185 Datum
7186 show_config_by_name(PG_FUNCTION_ARGS)
7187 {
7188         char       *varname;
7189         char       *varval;
7190
7191         /* Get the GUC variable name */
7192         varname = TextDatumGetCString(PG_GETARG_DATUM(0));
7193
7194         /* Get the value */
7195         varval = GetConfigOptionByName(varname, NULL);
7196
7197         /* Convert to text */
7198         PG_RETURN_TEXT_P(cstring_to_text(varval));
7199 }
7200
7201 /*
7202  * show_all_settings - equiv to SHOW ALL command but implemented as
7203  * a Table Function.
7204  */
7205 #define NUM_PG_SETTINGS_ATTS    16
7206
7207 Datum
7208 show_all_settings(PG_FUNCTION_ARGS)
7209 {
7210         FuncCallContext *funcctx;
7211         TupleDesc       tupdesc;
7212         int                     call_cntr;
7213         int                     max_calls;
7214         AttInMetadata *attinmeta;
7215         MemoryContext oldcontext;
7216
7217         /* stuff done only on the first call of the function */
7218         if (SRF_IS_FIRSTCALL())
7219         {
7220                 /* create a function context for cross-call persistence */
7221                 funcctx = SRF_FIRSTCALL_INIT();
7222
7223                 /*
7224                  * switch to memory context appropriate for multiple function calls
7225                  */
7226                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
7227
7228                 /*
7229                  * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
7230                  * of the appropriate types
7231                  */
7232                 tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
7233                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7234                                                    TEXTOID, -1, 0);
7235                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7236                                                    TEXTOID, -1, 0);
7237                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
7238                                                    TEXTOID, -1, 0);
7239                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
7240                                                    TEXTOID, -1, 0);
7241                 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
7242                                                    TEXTOID, -1, 0);
7243                 TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
7244                                                    TEXTOID, -1, 0);
7245                 TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
7246                                                    TEXTOID, -1, 0);
7247                 TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
7248                                                    TEXTOID, -1, 0);
7249                 TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
7250                                                    TEXTOID, -1, 0);
7251                 TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
7252                                                    TEXTOID, -1, 0);
7253                 TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
7254                                                    TEXTOID, -1, 0);
7255                 TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
7256                                                    TEXTARRAYOID, -1, 0);
7257                 TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
7258                                                    TEXTOID, -1, 0);
7259                 TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
7260                                                    TEXTOID, -1, 0);
7261                 TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
7262                                                    TEXTOID, -1, 0);
7263                 TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
7264                                                    INT4OID, -1, 0);
7265
7266                 /*
7267                  * Generate attribute metadata needed later to produce tuples from raw
7268                  * C strings
7269                  */
7270                 attinmeta = TupleDescGetAttInMetadata(tupdesc);
7271                 funcctx->attinmeta = attinmeta;
7272
7273                 /* total number of tuples to be returned */
7274                 funcctx->max_calls = GetNumConfigOptions();
7275
7276                 MemoryContextSwitchTo(oldcontext);
7277         }
7278
7279         /* stuff done on every call of the function */
7280         funcctx = SRF_PERCALL_SETUP();
7281
7282         call_cntr = funcctx->call_cntr;
7283         max_calls = funcctx->max_calls;
7284         attinmeta = funcctx->attinmeta;
7285
7286         if (call_cntr < max_calls)      /* do when there is more left to send */
7287         {
7288                 char       *values[NUM_PG_SETTINGS_ATTS];
7289                 bool            noshow;
7290                 HeapTuple       tuple;
7291                 Datum           result;
7292
7293                 /*
7294                  * Get the next visible GUC variable name and value
7295                  */
7296                 do
7297                 {
7298                         GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
7299                         if (noshow)
7300                         {
7301                                 /* bump the counter and get the next config setting */
7302                                 call_cntr = ++funcctx->call_cntr;
7303
7304                                 /* make sure we haven't gone too far now */
7305                                 if (call_cntr >= max_calls)
7306                                         SRF_RETURN_DONE(funcctx);
7307                         }
7308                 } while (noshow);
7309
7310                 /* build a tuple */
7311                 tuple = BuildTupleFromCStrings(attinmeta, values);
7312
7313                 /* make the tuple into a datum */
7314                 result = HeapTupleGetDatum(tuple);
7315
7316                 SRF_RETURN_NEXT(funcctx, result);
7317         }
7318         else
7319         {
7320                 /* do when there is no more left */
7321                 SRF_RETURN_DONE(funcctx);
7322         }
7323 }
7324
7325 static char *
7326 _ShowOption(struct config_generic * record, bool use_units)
7327 {
7328         char            buffer[256];
7329         const char *val;
7330
7331         switch (record->vartype)
7332         {
7333                 case PGC_BOOL:
7334                         {
7335                                 struct config_bool *conf = (struct config_bool *) record;
7336
7337                                 if (conf->show_hook)
7338                                         val = (*conf->show_hook) ();
7339                                 else
7340                                         val = *conf->variable ? "on" : "off";
7341                         }
7342                         break;
7343
7344                 case PGC_INT:
7345                         {
7346                                 struct config_int *conf = (struct config_int *) record;
7347
7348                                 if (conf->show_hook)
7349                                         val = (*conf->show_hook) ();
7350                                 else
7351                                 {
7352                                         /*
7353                                          * Use int64 arithmetic to avoid overflows in units
7354                                          * conversion.
7355                                          */
7356                                         int64           result = *conf->variable;
7357                                         const char *unit;
7358
7359                                         if (use_units && result > 0 &&
7360                                                 (record->flags & GUC_UNIT_MEMORY))
7361                                         {
7362                                                 switch (record->flags & GUC_UNIT_MEMORY)
7363                                                 {
7364                                                         case GUC_UNIT_BLOCKS:
7365                                                                 result *= BLCKSZ / 1024;
7366                                                                 break;
7367                                                         case GUC_UNIT_XBLOCKS:
7368                                                                 result *= XLOG_BLCKSZ / 1024;
7369                                                                 break;
7370                                                 }
7371
7372                                                 if (result % KB_PER_GB == 0)
7373                                                 {
7374                                                         result /= KB_PER_GB;
7375                                                         unit = "GB";
7376                                                 }
7377                                                 else if (result % KB_PER_MB == 0)
7378                                                 {
7379                                                         result /= KB_PER_MB;
7380                                                         unit = "MB";
7381                                                 }
7382                                                 else
7383                                                 {
7384                                                         unit = "kB";
7385                                                 }
7386                                         }
7387                                         else if (use_units && result > 0 &&
7388                                                          (record->flags & GUC_UNIT_TIME))
7389                                         {
7390                                                 switch (record->flags & GUC_UNIT_TIME)
7391                                                 {
7392                                                         case GUC_UNIT_S:
7393                                                                 result *= MS_PER_S;
7394                                                                 break;
7395                                                         case GUC_UNIT_MIN:
7396                                                                 result *= MS_PER_MIN;
7397                                                                 break;
7398                                                 }
7399
7400                                                 if (result % MS_PER_D == 0)
7401                                                 {
7402                                                         result /= MS_PER_D;
7403                                                         unit = "d";
7404                                                 }
7405                                                 else if (result % MS_PER_H == 0)
7406                                                 {
7407                                                         result /= MS_PER_H;
7408                                                         unit = "h";
7409                                                 }
7410                                                 else if (result % MS_PER_MIN == 0)
7411                                                 {
7412                                                         result /= MS_PER_MIN;
7413                                                         unit = "min";
7414                                                 }
7415                                                 else if (result % MS_PER_S == 0)
7416                                                 {
7417                                                         result /= MS_PER_S;
7418                                                         unit = "s";
7419                                                 }
7420                                                 else
7421                                                 {
7422                                                         unit = "ms";
7423                                                 }
7424                                         }
7425                                         else
7426                                                 unit = "";
7427
7428                                         snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
7429                                                          result, unit);
7430                                         val = buffer;
7431                                 }
7432                         }
7433                         break;
7434
7435                 case PGC_REAL:
7436                         {
7437                                 struct config_real *conf = (struct config_real *) record;
7438
7439                                 if (conf->show_hook)
7440                                         val = (*conf->show_hook) ();
7441                                 else
7442                                 {
7443                                         snprintf(buffer, sizeof(buffer), "%g",
7444                                                          *conf->variable);
7445                                         val = buffer;
7446                                 }
7447                         }
7448                         break;
7449
7450                 case PGC_STRING:
7451                         {
7452                                 struct config_string *conf = (struct config_string *) record;
7453
7454                                 if (conf->show_hook)
7455                                         val = (*conf->show_hook) ();
7456                                 else if (*conf->variable && **conf->variable)
7457                                         val = *conf->variable;
7458                                 else
7459                                         val = "";
7460                         }
7461                         break;
7462
7463                 case PGC_ENUM:
7464                         {
7465                                 struct config_enum *conf = (struct config_enum *) record;
7466
7467                                 if (conf->show_hook)
7468                                         val = (*conf->show_hook) ();
7469                                 else
7470                                         val = config_enum_lookup_by_value(conf, *conf->variable);
7471                         }
7472                         break;
7473
7474                 default:
7475                         /* just to keep compiler quiet */
7476                         val = "???";
7477                         break;
7478         }
7479
7480         return pstrdup(val);
7481 }
7482
7483
7484 #ifdef EXEC_BACKEND
7485
7486 /*
7487  *      These routines dump out all non-default GUC options into a binary
7488  *      file that is read by all exec'ed backends.  The format is:
7489  *
7490  *              variable name, string, null terminated
7491  *              variable value, string, null terminated
7492  *              variable sourcefile, string, null terminated (empty if none)
7493  *              variable sourceline, integer
7494  *              variable source, integer
7495  *              variable scontext, integer
7496  */
7497 static void
7498 write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
7499 {
7500         if (gconf->source == PGC_S_DEFAULT)
7501                 return;
7502
7503         fprintf(fp, "%s", gconf->name);
7504         fputc(0, fp);
7505
7506         switch (gconf->vartype)
7507         {
7508                 case PGC_BOOL:
7509                         {
7510                                 struct config_bool *conf = (struct config_bool *) gconf;
7511
7512                                 if (*conf->variable)
7513                                         fprintf(fp, "true");
7514                                 else
7515                                         fprintf(fp, "false");
7516                         }
7517                         break;
7518
7519                 case PGC_INT:
7520                         {
7521                                 struct config_int *conf = (struct config_int *) gconf;
7522
7523                                 fprintf(fp, "%d", *conf->variable);
7524                         }
7525                         break;
7526
7527                 case PGC_REAL:
7528                         {
7529                                 struct config_real *conf = (struct config_real *) gconf;
7530
7531                                 fprintf(fp, "%.17g", *conf->variable);
7532                         }
7533                         break;
7534
7535                 case PGC_STRING:
7536                         {
7537                                 struct config_string *conf = (struct config_string *) gconf;
7538
7539                                 fprintf(fp, "%s", *conf->variable);
7540                         }
7541                         break;
7542
7543                 case PGC_ENUM:
7544                         {
7545                                 struct config_enum *conf = (struct config_enum *) gconf;
7546
7547                                 fprintf(fp, "%s",
7548                                                 config_enum_lookup_by_value(conf, *conf->variable));
7549                         }
7550                         break;
7551         }
7552
7553         fputc(0, fp);
7554
7555         if (gconf->sourcefile)
7556                 fprintf(fp, "%s", gconf->sourcefile);
7557         fputc(0, fp);
7558
7559         fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
7560         fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
7561         fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
7562 }
7563
7564 void
7565 write_nondefault_variables(GucContext context)
7566 {
7567         int                     elevel;
7568         FILE       *fp;
7569         int                     i;
7570
7571         Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
7572
7573         elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
7574
7575         /*
7576          * Open file
7577          */
7578         fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
7579         if (!fp)
7580         {
7581                 ereport(elevel,
7582                                 (errcode_for_file_access(),
7583                                  errmsg("could not write to file \"%s\": %m",
7584                                                 CONFIG_EXEC_PARAMS_NEW)));
7585                 return;
7586         }
7587
7588         for (i = 0; i < num_guc_variables; i++)
7589         {
7590                 write_one_nondefault_variable(fp, guc_variables[i]);
7591         }
7592
7593         if (FreeFile(fp))
7594         {
7595                 ereport(elevel,
7596                                 (errcode_for_file_access(),
7597                                  errmsg("could not write to file \"%s\": %m",
7598                                                 CONFIG_EXEC_PARAMS_NEW)));
7599                 return;
7600         }
7601
7602         /*
7603          * Put new file in place.  This could delay on Win32, but we don't hold
7604          * any exclusive locks.
7605          */
7606         rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
7607 }
7608
7609
7610 /*
7611  *      Read string, including null byte from file
7612  *
7613  *      Return NULL on EOF and nothing read
7614  */
7615 static char *
7616 read_string_with_null(FILE *fp)
7617 {
7618         int                     i = 0,
7619                                 ch,
7620                                 maxlen = 256;
7621         char       *str = NULL;
7622
7623         do
7624         {
7625                 if ((ch = fgetc(fp)) == EOF)
7626                 {
7627                         if (i == 0)
7628                                 return NULL;
7629                         else
7630                                 elog(FATAL, "invalid format of exec config params file");
7631                 }
7632                 if (i == 0)
7633                         str = guc_malloc(FATAL, maxlen);
7634                 else if (i == maxlen)
7635                         str = guc_realloc(FATAL, str, maxlen *= 2);
7636                 str[i++] = ch;
7637         } while (ch != 0);
7638
7639         return str;
7640 }
7641
7642
7643 /*
7644  *      This routine loads a previous postmaster dump of its non-default
7645  *      settings.
7646  */
7647 void
7648 read_nondefault_variables(void)
7649 {
7650         FILE       *fp;
7651         char       *varname,
7652                            *varvalue,
7653                            *varsourcefile;
7654         int                     varsourceline;
7655         GucSource       varsource;
7656         GucContext      varscontext;
7657
7658         /*
7659          * Open file
7660          */
7661         fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
7662         if (!fp)
7663         {
7664                 /* File not found is fine */
7665                 if (errno != ENOENT)
7666                         ereport(FATAL,
7667                                         (errcode_for_file_access(),
7668                                          errmsg("could not read from file \"%s\": %m",
7669                                                         CONFIG_EXEC_PARAMS)));
7670                 return;
7671         }
7672
7673         for (;;)
7674         {
7675                 struct config_generic *record;
7676
7677                 if ((varname = read_string_with_null(fp)) == NULL)
7678                         break;
7679
7680                 if ((record = find_option(varname, true, FATAL)) == NULL)
7681                         elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
7682
7683                 if ((varvalue = read_string_with_null(fp)) == NULL)
7684                         elog(FATAL, "invalid format of exec config params file");
7685                 if ((varsourcefile = read_string_with_null(fp)) == NULL)
7686                         elog(FATAL, "invalid format of exec config params file");
7687                 if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
7688                         elog(FATAL, "invalid format of exec config params file");
7689                 if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
7690                         elog(FATAL, "invalid format of exec config params file");
7691                 if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
7692                         elog(FATAL, "invalid format of exec config params file");
7693
7694                 (void) set_config_option(varname, varvalue,
7695                                                                  varscontext, varsource,
7696                                                                  GUC_ACTION_SET, true, 0);
7697                 if (varsourcefile[0])
7698                         set_config_sourcefile(varname, varsourcefile, varsourceline);
7699
7700                 free(varname);
7701                 free(varvalue);
7702                 free(varsourcefile);
7703         }
7704
7705         FreeFile(fp);
7706 }
7707 #endif   /* EXEC_BACKEND */
7708
7709
7710 /*
7711  * A little "long argument" simulation, although not quite GNU
7712  * compliant. Takes a string of the form "some-option=some value" and
7713  * returns name = "some_option" and value = "some value" in malloc'ed
7714  * storage. Note that '-' is converted to '_' in the option name. If
7715  * there is no '=' in the input string then value will be NULL.
7716  */
7717 void
7718 ParseLongOption(const char *string, char **name, char **value)
7719 {
7720         size_t          equal_pos;
7721         char       *cp;
7722
7723         AssertArg(string);
7724         AssertArg(name);
7725         AssertArg(value);
7726
7727         equal_pos = strcspn(string, "=");
7728
7729         if (string[equal_pos] == '=')
7730         {
7731                 *name = guc_malloc(FATAL, equal_pos + 1);
7732                 strlcpy(*name, string, equal_pos + 1);
7733
7734                 *value = guc_strdup(FATAL, &string[equal_pos + 1]);
7735         }
7736         else
7737         {
7738                 /* no equal sign in string */
7739                 *name = guc_strdup(FATAL, string);
7740                 *value = NULL;
7741         }
7742
7743         for (cp = *name; *cp; cp++)
7744                 if (*cp == '-')
7745                         *cp = '_';
7746 }
7747
7748
7749 /*
7750  * Handle options fetched from pg_db_role_setting.setconfig,
7751  * pg_proc.proconfig, etc.      Caller must specify proper context/source/action.
7752  *
7753  * The array parameter must be an array of TEXT (it must not be NULL).
7754  */
7755 void
7756 ProcessGUCArray(ArrayType *array,
7757                                 GucContext context, GucSource source, GucAction action)
7758 {
7759         int                     i;
7760
7761         Assert(array != NULL);
7762         Assert(ARR_ELEMTYPE(array) == TEXTOID);
7763         Assert(ARR_NDIM(array) == 1);
7764         Assert(ARR_LBOUND(array)[0] == 1);
7765
7766         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7767         {
7768                 Datum           d;
7769                 bool            isnull;
7770                 char       *s;
7771                 char       *name;
7772                 char       *value;
7773
7774                 d = array_ref(array, 1, &i,
7775                                           -1 /* varlenarray */ ,
7776                                           -1 /* TEXT's typlen */ ,
7777                                           false /* TEXT's typbyval */ ,
7778                                           'i' /* TEXT's typalign */ ,
7779                                           &isnull);
7780
7781                 if (isnull)
7782                         continue;
7783
7784                 s = TextDatumGetCString(d);
7785
7786                 ParseLongOption(s, &name, &value);
7787                 if (!value)
7788                 {
7789                         ereport(WARNING,
7790                                         (errcode(ERRCODE_SYNTAX_ERROR),
7791                                          errmsg("could not parse setting for parameter \"%s\"",
7792                                                         name)));
7793                         free(name);
7794                         continue;
7795                 }
7796
7797                 (void) set_config_option(name, value,
7798                                                                  context, source,
7799                                                                  action, true, 0);
7800
7801                 free(name);
7802                 if (value)
7803                         free(value);
7804                 pfree(s);
7805         }
7806 }
7807
7808
7809 /*
7810  * Add an entry to an option array.  The array parameter may be NULL
7811  * to indicate the current table entry is NULL.
7812  */
7813 ArrayType *
7814 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
7815 {
7816         struct config_generic *record;
7817         Datum           datum;
7818         char       *newval;
7819         ArrayType  *a;
7820
7821         Assert(name);
7822         Assert(value);
7823
7824         /* test if the option is valid and we're allowed to set it */
7825         (void) validate_option_array_item(name, value, false);
7826
7827         /* normalize name (converts obsolete GUC names to modern spellings) */
7828         record = find_option(name, false, WARNING);
7829         if (record)
7830                 name = record->name;
7831
7832         /* build new item for array */
7833         newval = palloc(strlen(name) + 1 + strlen(value) + 1);
7834         sprintf(newval, "%s=%s", name, value);
7835         datum = CStringGetTextDatum(newval);
7836
7837         if (array)
7838         {
7839                 int                     index;
7840                 bool            isnull;
7841                 int                     i;
7842
7843                 Assert(ARR_ELEMTYPE(array) == TEXTOID);
7844                 Assert(ARR_NDIM(array) == 1);
7845                 Assert(ARR_LBOUND(array)[0] == 1);
7846
7847                 index = ARR_DIMS(array)[0] + 1; /* add after end */
7848
7849                 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7850                 {
7851                         Datum           d;
7852                         char       *current;
7853
7854                         d = array_ref(array, 1, &i,
7855                                                   -1 /* varlenarray */ ,
7856                                                   -1 /* TEXT's typlen */ ,
7857                                                   false /* TEXT's typbyval */ ,
7858                                                   'i' /* TEXT's typalign */ ,
7859                                                   &isnull);
7860                         if (isnull)
7861                                 continue;
7862                         current = TextDatumGetCString(d);
7863
7864                         /* check for match up through and including '=' */
7865                         if (strncmp(current, newval, strlen(name) + 1) == 0)
7866                         {
7867                                 index = i;
7868                                 break;
7869                         }
7870                 }
7871
7872                 a = array_set(array, 1, &index,
7873                                           datum,
7874                                           false,
7875                                           -1 /* varlena array */ ,
7876                                           -1 /* TEXT's typlen */ ,
7877                                           false /* TEXT's typbyval */ ,
7878                                           'i' /* TEXT's typalign */ );
7879         }
7880         else
7881                 a = construct_array(&datum, 1,
7882                                                         TEXTOID,
7883                                                         -1, false, 'i');
7884
7885         return a;
7886 }
7887
7888
7889 /*
7890  * Delete an entry from an option array.  The array parameter may be NULL
7891  * to indicate the current table entry is NULL.  Also, if the return value
7892  * is NULL then a null should be stored.
7893  */
7894 ArrayType *
7895 GUCArrayDelete(ArrayType *array, const char *name)
7896 {
7897         struct config_generic *record;
7898         ArrayType  *newarray;
7899         int                     i;
7900         int                     index;
7901
7902         Assert(name);
7903
7904         /* test if the option is valid and we're allowed to set it */
7905         (void) validate_option_array_item(name, NULL, false);
7906
7907         /* normalize name (converts obsolete GUC names to modern spellings) */
7908         record = find_option(name, false, WARNING);
7909         if (record)
7910                 name = record->name;
7911
7912         /* if array is currently null, then surely nothing to delete */
7913         if (!array)
7914                 return NULL;
7915
7916         newarray = NULL;
7917         index = 1;
7918
7919         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7920         {
7921                 Datum           d;
7922                 char       *val;
7923                 bool            isnull;
7924
7925                 d = array_ref(array, 1, &i,
7926                                           -1 /* varlenarray */ ,
7927                                           -1 /* TEXT's typlen */ ,
7928                                           false /* TEXT's typbyval */ ,
7929                                           'i' /* TEXT's typalign */ ,
7930                                           &isnull);
7931                 if (isnull)
7932                         continue;
7933                 val = TextDatumGetCString(d);
7934
7935                 /* ignore entry if it's what we want to delete */
7936                 if (strncmp(val, name, strlen(name)) == 0
7937                         && val[strlen(name)] == '=')
7938                         continue;
7939
7940                 /* else add it to the output array */
7941                 if (newarray)
7942                         newarray = array_set(newarray, 1, &index,
7943                                                                  d,
7944                                                                  false,
7945                                                                  -1 /* varlenarray */ ,
7946                                                                  -1 /* TEXT's typlen */ ,
7947                                                                  false /* TEXT's typbyval */ ,
7948                                                                  'i' /* TEXT's typalign */ );
7949                 else
7950                         newarray = construct_array(&d, 1,
7951                                                                            TEXTOID,
7952                                                                            -1, false, 'i');
7953
7954                 index++;
7955         }
7956
7957         return newarray;
7958 }
7959
7960
7961 /*
7962  * Given a GUC array, delete all settings from it that our permission
7963  * level allows: if superuser, delete them all; if regular user, only
7964  * those that are PGC_USERSET
7965  */
7966 ArrayType *
7967 GUCArrayReset(ArrayType *array)
7968 {
7969         ArrayType  *newarray;
7970         int                     i;
7971         int                     index;
7972
7973         /* if array is currently null, nothing to do */
7974         if (!array)
7975                 return NULL;
7976
7977         /* if we're superuser, we can delete everything, so just do it */
7978         if (superuser())
7979                 return NULL;
7980
7981         newarray = NULL;
7982         index = 1;
7983
7984         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7985         {
7986                 Datum           d;
7987                 char       *val;
7988                 char       *eqsgn;
7989                 bool            isnull;
7990
7991                 d = array_ref(array, 1, &i,
7992                                           -1 /* varlenarray */ ,
7993                                           -1 /* TEXT's typlen */ ,
7994                                           false /* TEXT's typbyval */ ,
7995                                           'i' /* TEXT's typalign */ ,
7996                                           &isnull);
7997                 if (isnull)
7998                         continue;
7999                 val = TextDatumGetCString(d);
8000
8001                 eqsgn = strchr(val, '=');
8002                 *eqsgn = '\0';
8003
8004                 /* skip if we have permission to delete it */
8005                 if (validate_option_array_item(val, NULL, true))
8006                         continue;
8007
8008                 /* else add it to the output array */
8009                 if (newarray)
8010                         newarray = array_set(newarray, 1, &index,
8011                                                                  d,
8012                                                                  false,
8013                                                                  -1 /* varlenarray */ ,
8014                                                                  -1 /* TEXT's typlen */ ,
8015                                                                  false /* TEXT's typbyval */ ,
8016                                                                  'i' /* TEXT's typalign */ );
8017                 else
8018                         newarray = construct_array(&d, 1,
8019                                                                            TEXTOID,
8020                                                                            -1, false, 'i');
8021
8022                 index++;
8023                 pfree(val);
8024         }
8025
8026         return newarray;
8027 }
8028
8029 /*
8030  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
8031  *
8032  * name is the option name.  value is the proposed value for the Add case,
8033  * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
8034  * not an error to have no permissions to set the option.
8035  *
8036  * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
8037  * have permission to change this option (all other error cases result in an
8038  * error being thrown).
8039  */
8040 static bool
8041 validate_option_array_item(const char *name, const char *value,
8042                                                    bool skipIfNoPermissions)
8043
8044 {
8045         struct config_generic *gconf;
8046
8047         /*
8048          * There are three cases to consider:
8049          *
8050          * name is a known GUC variable.  Check the value normally, check
8051          * permissions normally (ie, allow if variable is USERSET, or if it's
8052          * SUSET and user is superuser).
8053          *
8054          * name is not known, but exists or can be created as a placeholder (i.e.,
8055          * it has a prefixed name).  We allow this case if you're a superuser,
8056          * otherwise not.  Superusers are assumed to know what they're doing. We
8057          * can't allow it for other users, because when the placeholder is
8058          * resolved it might turn out to be a SUSET variable;
8059          * define_custom_variable assumes we checked that.
8060          *
8061          * name is not known and can't be created as a placeholder.  Throw error,
8062          * unless skipIfNoPermissions is true, in which case return FALSE.
8063          */
8064         gconf = find_option(name, true, WARNING);
8065         if (!gconf)
8066         {
8067                 /* not known, failed to make a placeholder */
8068                 if (skipIfNoPermissions)
8069                         return false;
8070                 ereport(ERROR,
8071                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
8072                                  errmsg("unrecognized configuration parameter \"%s\"",
8073                                                 name)));
8074         }
8075
8076         if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
8077         {
8078                 /*
8079                  * We cannot do any meaningful check on the value, so only permissions
8080                  * are useful to check.
8081                  */
8082                 if (superuser())
8083                         return true;
8084                 if (skipIfNoPermissions)
8085                         return false;
8086                 ereport(ERROR,
8087                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8088                                  errmsg("permission denied to set parameter \"%s\"", name)));
8089         }
8090
8091         /* manual permissions check so we can avoid an error being thrown */
8092         if (gconf->context == PGC_USERSET)
8093                  /* ok */ ;
8094         else if (gconf->context == PGC_SUSET && superuser())
8095                  /* ok */ ;
8096         else if (skipIfNoPermissions)
8097                 return false;
8098         /* if a permissions error should be thrown, let set_config_option do it */
8099
8100         /* test for permissions and valid option value */
8101         (void) set_config_option(name, value,
8102                                                          superuser() ? PGC_SUSET : PGC_USERSET,
8103                                                          PGC_S_TEST, GUC_ACTION_SET, false, 0);
8104
8105         return true;
8106 }
8107
8108
8109 /*
8110  * Called by check_hooks that want to override the normal
8111  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
8112  *
8113  * Note that GUC_check_errmsg() etc are just macros that result in a direct
8114  * assignment to the associated variables.      That is ugly, but forced by the
8115  * limitations of C's macro mechanisms.
8116  */
8117 void
8118 GUC_check_errcode(int sqlerrcode)
8119 {
8120         GUC_check_errcode_value = sqlerrcode;
8121 }
8122
8123
8124 /*
8125  * Convenience functions to manage calling a variable's check_hook.
8126  * These mostly take care of the protocol for letting check hooks supply
8127  * portions of the error report on failure.
8128  */
8129
8130 static bool
8131 call_bool_check_hook(struct config_bool * conf, bool *newval, void **extra,
8132                                          GucSource source, int elevel)
8133 {
8134         /* Quick success if no hook */
8135         if (!conf->check_hook)
8136                 return true;
8137
8138         /* Reset variables that might be set by hook */
8139         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8140         GUC_check_errmsg_string = NULL;
8141         GUC_check_errdetail_string = NULL;
8142         GUC_check_errhint_string = NULL;
8143
8144         if (!(*conf->check_hook) (newval, extra, source))
8145         {
8146                 ereport(elevel,
8147                                 (errcode(GUC_check_errcode_value),
8148                                  GUC_check_errmsg_string ?
8149                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8150                                  errmsg("invalid value for parameter \"%s\": %d",
8151                                                 conf->gen.name, (int) *newval),
8152                                  GUC_check_errdetail_string ?
8153                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8154                                  GUC_check_errhint_string ?
8155                                  errhint("%s", GUC_check_errhint_string) : 0));
8156                 /* Flush any strings created in ErrorContext */
8157                 FlushErrorState();
8158                 return false;
8159         }
8160
8161         return true;
8162 }
8163
8164 static bool
8165 call_int_check_hook(struct config_int * conf, int *newval, void **extra,
8166                                         GucSource source, int elevel)
8167 {
8168         /* Quick success if no hook */
8169         if (!conf->check_hook)
8170                 return true;
8171
8172         /* Reset variables that might be set by hook */
8173         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8174         GUC_check_errmsg_string = NULL;
8175         GUC_check_errdetail_string = NULL;
8176         GUC_check_errhint_string = NULL;
8177
8178         if (!(*conf->check_hook) (newval, extra, source))
8179         {
8180                 ereport(elevel,
8181                                 (errcode(GUC_check_errcode_value),
8182                                  GUC_check_errmsg_string ?
8183                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8184                                  errmsg("invalid value for parameter \"%s\": %d",
8185                                                 conf->gen.name, *newval),
8186                                  GUC_check_errdetail_string ?
8187                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8188                                  GUC_check_errhint_string ?
8189                                  errhint("%s", GUC_check_errhint_string) : 0));
8190                 /* Flush any strings created in ErrorContext */
8191                 FlushErrorState();
8192                 return false;
8193         }
8194
8195         return true;
8196 }
8197
8198 static bool
8199 call_real_check_hook(struct config_real * conf, double *newval, void **extra,
8200                                          GucSource source, int elevel)
8201 {
8202         /* Quick success if no hook */
8203         if (!conf->check_hook)
8204                 return true;
8205
8206         /* Reset variables that might be set by hook */
8207         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8208         GUC_check_errmsg_string = NULL;
8209         GUC_check_errdetail_string = NULL;
8210         GUC_check_errhint_string = NULL;
8211
8212         if (!(*conf->check_hook) (newval, extra, source))
8213         {
8214                 ereport(elevel,
8215                                 (errcode(GUC_check_errcode_value),
8216                                  GUC_check_errmsg_string ?
8217                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8218                                  errmsg("invalid value for parameter \"%s\": %g",
8219                                                 conf->gen.name, *newval),
8220                                  GUC_check_errdetail_string ?
8221                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8222                                  GUC_check_errhint_string ?
8223                                  errhint("%s", GUC_check_errhint_string) : 0));
8224                 /* Flush any strings created in ErrorContext */
8225                 FlushErrorState();
8226                 return false;
8227         }
8228
8229         return true;
8230 }
8231
8232 static bool
8233 call_string_check_hook(struct config_string * conf, char **newval, void **extra,
8234                                            GucSource source, int elevel)
8235 {
8236         /* Quick success if no hook */
8237         if (!conf->check_hook)
8238                 return true;
8239
8240         /* Reset variables that might be set by hook */
8241         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8242         GUC_check_errmsg_string = NULL;
8243         GUC_check_errdetail_string = NULL;
8244         GUC_check_errhint_string = NULL;
8245
8246         if (!(*conf->check_hook) (newval, extra, source))
8247         {
8248                 ereport(elevel,
8249                                 (errcode(GUC_check_errcode_value),
8250                                  GUC_check_errmsg_string ?
8251                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8252                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8253                                                 conf->gen.name, *newval ? *newval : ""),
8254                                  GUC_check_errdetail_string ?
8255                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8256                                  GUC_check_errhint_string ?
8257                                  errhint("%s", GUC_check_errhint_string) : 0));
8258                 /* Flush any strings created in ErrorContext */
8259                 FlushErrorState();
8260                 return false;
8261         }
8262
8263         return true;
8264 }
8265
8266 static bool
8267 call_enum_check_hook(struct config_enum * conf, int *newval, void **extra,
8268                                          GucSource source, int elevel)
8269 {
8270         /* Quick success if no hook */
8271         if (!conf->check_hook)
8272                 return true;
8273
8274         /* Reset variables that might be set by hook */
8275         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8276         GUC_check_errmsg_string = NULL;
8277         GUC_check_errdetail_string = NULL;
8278         GUC_check_errhint_string = NULL;
8279
8280         if (!(*conf->check_hook) (newval, extra, source))
8281         {
8282                 ereport(elevel,
8283                                 (errcode(GUC_check_errcode_value),
8284                                  GUC_check_errmsg_string ?
8285                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8286                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8287                                                 conf->gen.name,
8288                                                 config_enum_lookup_by_value(conf, *newval)),
8289                                  GUC_check_errdetail_string ?
8290                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8291                                  GUC_check_errhint_string ?
8292                                  errhint("%s", GUC_check_errhint_string) : 0));
8293                 /* Flush any strings created in ErrorContext */
8294                 FlushErrorState();
8295                 return false;
8296         }
8297
8298         return true;
8299 }
8300
8301
8302 /*
8303  * check_hook, assign_hook and show_hook subroutines
8304  */
8305
8306 static bool
8307 check_log_destination(char **newval, void **extra, GucSource source)
8308 {
8309         char       *rawstring;
8310         List       *elemlist;
8311         ListCell   *l;
8312         int                     newlogdest = 0;
8313         int                *myextra;
8314
8315         /* Need a modifiable copy of string */
8316         rawstring = pstrdup(*newval);
8317
8318         /* Parse string into list of identifiers */
8319         if (!SplitIdentifierString(rawstring, ',', &elemlist))
8320         {
8321                 /* syntax error in list */
8322                 GUC_check_errdetail("List syntax is invalid.");
8323                 pfree(rawstring);
8324                 list_free(elemlist);
8325                 return false;
8326         }
8327
8328         foreach(l, elemlist)
8329         {
8330                 char       *tok = (char *) lfirst(l);
8331
8332                 if (pg_strcasecmp(tok, "stderr") == 0)
8333                         newlogdest |= LOG_DESTINATION_STDERR;
8334                 else if (pg_strcasecmp(tok, "csvlog") == 0)
8335                         newlogdest |= LOG_DESTINATION_CSVLOG;
8336 #ifdef HAVE_SYSLOG
8337                 else if (pg_strcasecmp(tok, "syslog") == 0)
8338                         newlogdest |= LOG_DESTINATION_SYSLOG;
8339 #endif
8340 #ifdef WIN32
8341                 else if (pg_strcasecmp(tok, "eventlog") == 0)
8342                         newlogdest |= LOG_DESTINATION_EVENTLOG;
8343 #endif
8344                 else
8345                 {
8346                         GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
8347                         pfree(rawstring);
8348                         list_free(elemlist);
8349                         return false;
8350                 }
8351         }
8352
8353         pfree(rawstring);
8354         list_free(elemlist);
8355
8356         myextra = (int *) guc_malloc(ERROR, sizeof(int));
8357         *myextra = newlogdest;
8358         *extra = (void *) myextra;
8359
8360         return true;
8361 }
8362
8363 static void
8364 assign_log_destination(const char *newval, void *extra)
8365 {
8366         Log_destination = *((int *) extra);
8367 }
8368
8369 static void
8370 assign_syslog_facility(int newval, void *extra)
8371 {
8372 #ifdef HAVE_SYSLOG
8373         set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
8374                                                   newval);
8375 #endif
8376         /* Without syslog support, just ignore it */
8377 }
8378
8379 static void
8380 assign_syslog_ident(const char *newval, void *extra)
8381 {
8382 #ifdef HAVE_SYSLOG
8383         set_syslog_parameters(newval, syslog_facility);
8384 #endif
8385         /* Without syslog support, it will always be set to "none", so ignore */
8386 }
8387
8388
8389 static void
8390 assign_session_replication_role(int newval, void *extra)
8391 {
8392         /*
8393          * Must flush the plan cache when changing replication role; but don't
8394          * flush unnecessarily.
8395          */
8396         if (SessionReplicationRole != newval)
8397                 ResetPlanCache();
8398 }
8399
8400 static bool
8401 check_temp_buffers(int *newval, void **extra, GucSource source)
8402 {
8403         /*
8404          * Once local buffers have been initialized, it's too late to change this.
8405          */
8406         if (NLocBuffer && NLocBuffer != *newval)
8407         {
8408                 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
8409                 return false;
8410         }
8411         return true;
8412 }
8413
8414 static bool
8415 check_phony_autocommit(bool *newval, void **extra, GucSource source)
8416 {
8417         if (!*newval)
8418         {
8419                 GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
8420                 GUC_check_errmsg("SET AUTOCOMMIT TO OFF is no longer supported");
8421                 return false;
8422         }
8423         return true;
8424 }
8425
8426 static bool
8427 check_debug_assertions(bool *newval, void **extra, GucSource source)
8428 {
8429 #ifndef USE_ASSERT_CHECKING
8430         if (*newval)
8431         {
8432                 GUC_check_errmsg("assertion checking is not supported by this build");
8433                 return false;
8434         }
8435 #endif
8436         return true;
8437 }
8438
8439 static bool
8440 check_bonjour(bool *newval, void **extra, GucSource source)
8441 {
8442 #ifndef USE_BONJOUR
8443         if (*newval)
8444         {
8445                 GUC_check_errmsg("Bonjour is not supported by this build");
8446                 return false;
8447         }
8448 #endif
8449         return true;
8450 }
8451
8452 static bool
8453 check_ssl(bool *newval, void **extra, GucSource source)
8454 {
8455 #ifndef USE_SSL
8456         if (*newval)
8457         {
8458                 GUC_check_errmsg("SSL is not supported by this build");
8459                 return false;
8460         }
8461 #endif
8462         return true;
8463 }
8464
8465 static bool
8466 check_stage_log_stats(bool *newval, void **extra, GucSource source)
8467 {
8468         if (*newval && log_statement_stats)
8469         {
8470                 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
8471                 return false;
8472         }
8473         return true;
8474 }
8475
8476 static bool
8477 check_log_stats(bool *newval, void **extra, GucSource source)
8478 {
8479         if (*newval &&
8480                 (log_parser_stats || log_planner_stats || log_executor_stats))
8481         {
8482                 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
8483                                                         "\"log_parser_stats\", \"log_planner_stats\", "
8484                                                         "or \"log_executor_stats\" is true.");
8485                 return false;
8486         }
8487         return true;
8488 }
8489
8490 static bool
8491 check_canonical_path(char **newval, void **extra, GucSource source)
8492 {
8493         /*
8494          * Since canonicalize_path never enlarges the string, we can just modify
8495          * newval in-place.  But watch out for NULL, which is the default value
8496          * for external_pid_file.
8497          */
8498         if (*newval)
8499                 canonicalize_path(*newval);
8500         return true;
8501 }
8502
8503 static bool
8504 check_timezone_abbreviations(char **newval, void **extra, GucSource source)
8505 {
8506         /*
8507          * The boot_val given above for timezone_abbreviations is NULL. When we
8508          * see this we just do nothing.  If this value isn't overridden from the
8509          * config file then pg_timezone_abbrev_initialize() will eventually
8510          * replace it with "Default".  This hack has two purposes: to avoid
8511          * wasting cycles loading values that might soon be overridden from the
8512          * config file, and to avoid trying to read the timezone abbrev files
8513          * during InitializeGUCOptions().  The latter doesn't work in an
8514          * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
8515          * we can't locate PGSHAREDIR.
8516          */
8517         if (*newval == NULL)
8518         {
8519                 Assert(source == PGC_S_DEFAULT);
8520                 return true;
8521         }
8522
8523         /* OK, load the file and produce a malloc'd TimeZoneAbbrevTable */
8524         *extra = load_tzoffsets(*newval);
8525
8526         /* tzparser.c returns NULL on failure, reporting via GUC_check_errmsg */
8527         if (!*extra)
8528                 return false;
8529
8530         return true;
8531 }
8532
8533 static void
8534 assign_timezone_abbreviations(const char *newval, void *extra)
8535 {
8536         /* Do nothing for the boot_val default of NULL */
8537         if (!extra)
8538                 return;
8539
8540         InstallTimeZoneAbbrevs((TimeZoneAbbrevTable *) extra);
8541 }
8542
8543 /*
8544  * pg_timezone_abbrev_initialize --- set default value if not done already
8545  *
8546  * This is called after initial loading of postgresql.conf.  If no
8547  * timezone_abbreviations setting was found therein, select default.
8548  * If a non-default value is already installed, nothing will happen.
8549  *
8550  * This can also be called from ProcessConfigFile to establish the default
8551  * value after a postgresql.conf entry for it is removed.
8552  */
8553 static void
8554 pg_timezone_abbrev_initialize(void)
8555 {
8556         SetConfigOption("timezone_abbreviations", "Default",
8557                                         PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
8558 }
8559
8560 static const char *
8561 show_archive_command(void)
8562 {
8563         if (XLogArchivingActive())
8564                 return XLogArchiveCommand;
8565         else
8566                 return "(disabled)";
8567 }
8568
8569 static void
8570 assign_tcp_keepalives_idle(int newval, void *extra)
8571 {
8572         /*
8573          * The kernel API provides no way to test a value without setting it; and
8574          * once we set it we might fail to unset it.  So there seems little point
8575          * in fully implementing the check-then-assign GUC API for these
8576          * variables.  Instead we just do the assignment on demand.  pqcomm.c
8577          * reports any problems via elog(LOG).
8578          *
8579          * This approach means that the GUC value might have little to do with the
8580          * actual kernel value, so we use a show_hook that retrieves the kernel
8581          * value rather than trusting GUC's copy.
8582          */
8583         (void) pq_setkeepalivesidle(newval, MyProcPort);
8584 }
8585
8586 static const char *
8587 show_tcp_keepalives_idle(void)
8588 {
8589         /* See comments in assign_tcp_keepalives_idle */
8590         static char nbuf[16];
8591
8592         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
8593         return nbuf;
8594 }
8595
8596 static void
8597 assign_tcp_keepalives_interval(int newval, void *extra)
8598 {
8599         /* See comments in assign_tcp_keepalives_idle */
8600         (void) pq_setkeepalivesinterval(newval, MyProcPort);
8601 }
8602
8603 static const char *
8604 show_tcp_keepalives_interval(void)
8605 {
8606         /* See comments in assign_tcp_keepalives_idle */
8607         static char nbuf[16];
8608
8609         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
8610         return nbuf;
8611 }
8612
8613 static void
8614 assign_tcp_keepalives_count(int newval, void *extra)
8615 {
8616         /* See comments in assign_tcp_keepalives_idle */
8617         (void) pq_setkeepalivescount(newval, MyProcPort);
8618 }
8619
8620 static const char *
8621 show_tcp_keepalives_count(void)
8622 {
8623         /* See comments in assign_tcp_keepalives_idle */
8624         static char nbuf[16];
8625
8626         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
8627         return nbuf;
8628 }
8629
8630 static bool
8631 check_maxconnections(int *newval, void **extra, GucSource source)
8632 {
8633         if (*newval + GetNumShmemAttachedBgworkers() + autovacuum_max_workers + 1 >
8634                 MAX_BACKENDS)
8635                 return false;
8636         return true;
8637 }
8638
8639 static void
8640 assign_maxconnections(int newval, void *extra)
8641 {
8642         MaxBackends = newval + autovacuum_max_workers + 1 +
8643                 GetNumShmemAttachedBgworkers();
8644 }
8645
8646 static bool
8647 check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
8648 {
8649         if (MaxConnections + *newval + 1 + GetNumShmemAttachedBgworkers() >
8650                 MAX_BACKENDS)
8651                 return false;
8652         return true;
8653 }
8654
8655 static void
8656 assign_autovacuum_max_workers(int newval, void *extra)
8657 {
8658         MaxBackends = MaxConnections + newval + 1 + GetNumShmemAttachedBgworkers();
8659 }
8660
8661 static bool
8662 check_effective_io_concurrency(int *newval, void **extra, GucSource source)
8663 {
8664 #ifdef USE_PREFETCH
8665         double          new_prefetch_pages = 0.0;
8666         int                     i;
8667
8668         /*----------
8669          * The user-visible GUC parameter is the number of drives (spindles),
8670          * which we need to translate to a number-of-pages-to-prefetch target.
8671          * The target value is stashed in *extra and then assigned to the actual
8672          * variable by assign_effective_io_concurrency.
8673          *
8674          * The expected number of prefetch pages needed to keep N drives busy is:
8675          *
8676          * drives |   I/O requests
8677          * -------+----------------
8678          *              1 |   1
8679          *              2 |   2/1 + 2/2 = 3
8680          *              3 |   3/1 + 3/2 + 3/3 = 5 1/2
8681          *              4 |   4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
8682          *              n |   n * H(n)
8683          *
8684          * This is called the "coupon collector problem" and H(n) is called the
8685          * harmonic series.  This could be approximated by n * ln(n), but for
8686          * reasonable numbers of drives we might as well just compute the series.
8687          *
8688          * Alternatively we could set the target to the number of pages necessary
8689          * so that the expected number of active spindles is some arbitrary
8690          * percentage of the total.  This sounds the same but is actually slightly
8691          * different.  The result ends up being ln(1-P)/ln((n-1)/n) where P is
8692          * that desired fraction.
8693          *
8694          * Experimental results show that both of these formulas aren't aggressive
8695          * enough, but we don't really have any better proposals.
8696          *
8697          * Note that if *newval = 0 (disabled), we must set target = 0.
8698          *----------
8699          */
8700
8701         for (i = 1; i <= *newval; i++)
8702                 new_prefetch_pages += (double) *newval / (double) i;
8703
8704         /* This range check shouldn't fail, but let's be paranoid */
8705         if (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX)
8706         {
8707                 int                *myextra = (int *) guc_malloc(ERROR, sizeof(int));
8708
8709                 *myextra = (int) rint(new_prefetch_pages);
8710                 *extra = (void *) myextra;
8711
8712                 return true;
8713         }
8714         else
8715                 return false;
8716 #else
8717         return true;
8718 #endif   /* USE_PREFETCH */
8719 }
8720
8721 static void
8722 assign_effective_io_concurrency(int newval, void *extra)
8723 {
8724 #ifdef USE_PREFETCH
8725         target_prefetch_pages = *((int *) extra);
8726 #endif   /* USE_PREFETCH */
8727 }
8728
8729 static void
8730 assign_pgstat_temp_directory(const char *newval, void *extra)
8731 {
8732         /* check_canonical_path already canonicalized newval for us */
8733         char       *tname;
8734         char       *fname;
8735
8736         tname = guc_malloc(ERROR, strlen(newval) + 12);         /* /pgstat.tmp */
8737         sprintf(tname, "%s/pgstat.tmp", newval);
8738         fname = guc_malloc(ERROR, strlen(newval) + 13);         /* /pgstat.stat */
8739         sprintf(fname, "%s/pgstat.stat", newval);
8740
8741         if (pgstat_stat_tmpname)
8742                 free(pgstat_stat_tmpname);
8743         pgstat_stat_tmpname = tname;
8744         if (pgstat_stat_filename)
8745                 free(pgstat_stat_filename);
8746         pgstat_stat_filename = fname;
8747 }
8748
8749 static bool
8750 check_application_name(char **newval, void **extra, GucSource source)
8751 {
8752         /* Only allow clean ASCII chars in the application name */
8753         char       *p;
8754
8755         for (p = *newval; *p; p++)
8756         {
8757                 if (*p < 32 || *p > 126)
8758                         *p = '?';
8759         }
8760
8761         return true;
8762 }
8763
8764 static void
8765 assign_application_name(const char *newval, void *extra)
8766 {
8767         /* Update the pg_stat_activity view */
8768         pgstat_report_appname(newval);
8769 }
8770
8771 static const char *
8772 show_unix_socket_permissions(void)
8773 {
8774         static char buf[8];
8775
8776         snprintf(buf, sizeof(buf), "%04o", Unix_socket_permissions);
8777         return buf;
8778 }
8779
8780 static const char *
8781 show_log_file_mode(void)
8782 {
8783         static char buf[8];
8784
8785         snprintf(buf, sizeof(buf), "%04o", Log_file_mode);
8786         return buf;
8787 }
8788
8789 #include "guc-file.c"