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