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