]> granicus.if.org Git - postgresql/blob - src/backend/utils/misc/guc.c
Support configurable eventlog application names on Windows
[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/snapmgr.h"
76 #include "utils/tzparser.h"
77 #include "utils/xml.h"
78
79 #ifndef PG_KRB_SRVTAB
80 #define PG_KRB_SRVTAB ""
81 #endif
82 #ifndef PG_KRB_SRVNAM
83 #define PG_KRB_SRVNAM ""
84 #endif
85
86 #define CONFIG_FILENAME "postgresql.conf"
87 #define HBA_FILENAME    "pg_hba.conf"
88 #define IDENT_FILENAME  "pg_ident.conf"
89
90 #ifdef EXEC_BACKEND
91 #define CONFIG_EXEC_PARAMS "global/config_exec_params"
92 #define CONFIG_EXEC_PARAMS_NEW "global/config_exec_params.new"
93 #endif
94
95 /* upper limit for GUC variables measured in kilobytes of memory */
96 /* note that various places assume the byte size fits in a "long" variable */
97 #if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
98 #define MAX_KILOBYTES   INT_MAX
99 #else
100 #define MAX_KILOBYTES   (INT_MAX / 1024)
101 #endif
102
103 /*
104  * Note: MAX_BACKENDS is limited to 2^23-1 because inval.c stores the
105  * backend ID as a 3-byte signed integer.  Even if that limitation were
106  * removed, we still could not exceed INT_MAX/4 because some places compute
107  * 4*MaxBackends without any overflow check.  This is rechecked in
108  * check_maxconnections, since MaxBackends is computed as MaxConnections
109  * plus autovacuum_max_workers plus one (for the autovacuum launcher).
110  */
111 #define MAX_BACKENDS    0x7fffff
112
113 #define KB_PER_MB (1024)
114 #define KB_PER_GB (1024*1024)
115
116 #define MS_PER_S 1000
117 #define S_PER_MIN 60
118 #define MS_PER_MIN (1000 * 60)
119 #define MIN_PER_H 60
120 #define S_PER_H (60 * 60)
121 #define MS_PER_H (1000 * 60 * 60)
122 #define MIN_PER_D (60 * 24)
123 #define S_PER_D (60 * 60 * 24)
124 #define MS_PER_D (1000 * 60 * 60 * 24)
125
126 /* XXX these should appear in other modules' header files */
127 extern bool Log_disconnections;
128 extern int      CommitDelay;
129 extern int      CommitSiblings;
130 extern char *default_tablespace;
131 extern char *temp_tablespaces;
132 extern bool synchronize_seqscans;
133 extern bool fullPageWrites;
134 extern int      ssl_renegotiation_limit;
135 extern char *SSLCipherSuites;
136
137 #ifdef TRACE_SORT
138 extern bool trace_sort;
139 #endif
140 #ifdef TRACE_SYNCSCAN
141 extern bool trace_syncscan;
142 #endif
143 #ifdef DEBUG_BOUNDED_SORT
144 extern bool optimize_bounded_sort;
145 #endif
146
147 static int      GUC_check_errcode_value;
148
149 /* global variables for check hook support */
150 char       *GUC_check_errmsg_string;
151 char       *GUC_check_errdetail_string;
152 char       *GUC_check_errhint_string;
153
154
155 static void set_config_sourcefile(const char *name, char *sourcefile,
156                                           int sourceline);
157 static bool call_bool_check_hook(struct config_bool * conf, bool *newval,
158                                          void **extra, GucSource source, int elevel);
159 static bool call_int_check_hook(struct config_int * conf, int *newval,
160                                         void **extra, GucSource source, int elevel);
161 static bool call_real_check_hook(struct config_real * conf, double *newval,
162                                          void **extra, GucSource source, int elevel);
163 static bool call_string_check_hook(struct config_string * conf, char **newval,
164                                            void **extra, GucSource source, int elevel);
165 static bool call_enum_check_hook(struct config_enum * conf, int *newval,
166                                          void **extra, GucSource source, int elevel);
167
168 static bool check_log_destination(char **newval, void **extra, GucSource source);
169 static void assign_log_destination(const char *newval, void *extra);
170
171 #ifdef HAVE_SYSLOG
172 static int      syslog_facility = LOG_LOCAL0;
173 #else
174 static int      syslog_facility = 0;
175 #endif
176
177 static void assign_syslog_facility(int newval, void *extra);
178 static void assign_syslog_ident(const char *newval, void *extra);
179 static void assign_session_replication_role(int newval, void *extra);
180 static bool check_temp_buffers(int *newval, void **extra, GucSource source);
181 static bool check_phony_autocommit(bool *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 void pg_timezone_abbrev_initialize(void);
191 static const char *show_archive_command(void);
192 static void assign_tcp_keepalives_idle(int newval, void *extra);
193 static void assign_tcp_keepalives_interval(int newval, void *extra);
194 static void assign_tcp_keepalives_count(int newval, void *extra);
195 static const char *show_tcp_keepalives_idle(void);
196 static const char *show_tcp_keepalives_interval(void);
197 static const char *show_tcp_keepalives_count(void);
198 static bool check_maxconnections(int *newval, void **extra, GucSource source);
199 static void assign_maxconnections(int newval, void *extra);
200 static bool check_autovacuum_max_workers(int *newval, void **extra, GucSource source);
201 static void assign_autovacuum_max_workers(int newval, void *extra);
202 static bool check_effective_io_concurrency(int *newval, void **extra, GucSource source);
203 static void assign_effective_io_concurrency(int newval, void *extra);
204 static void assign_pgstat_temp_directory(const char *newval, void *extra);
205 static bool check_application_name(char **newval, void **extra, GucSource source);
206 static void assign_application_name(const char *newval, void *extra);
207 static const char *show_unix_socket_permissions(void);
208 static const char *show_log_file_mode(void);
209
210 static char *config_enum_get_options(struct config_enum * record,
211                                                 const char *prefix, const char *suffix,
212                                                 const char *separator);
213
214
215 /*
216  * Options for enum values defined in this module.
217  *
218  * NOTE! Option values may not contain double quotes!
219  */
220
221 static const struct config_enum_entry bytea_output_options[] = {
222         {"escape", BYTEA_OUTPUT_ESCAPE, false},
223         {"hex", BYTEA_OUTPUT_HEX, false},
224         {NULL, 0, false}
225 };
226
227 /*
228  * We have different sets for client and server message level options because
229  * they sort slightly different (see "log" level)
230  */
231 static const struct config_enum_entry client_message_level_options[] = {
232         {"debug", DEBUG2, true},
233         {"debug5", DEBUG5, false},
234         {"debug4", DEBUG4, false},
235         {"debug3", DEBUG3, false},
236         {"debug2", DEBUG2, false},
237         {"debug1", DEBUG1, false},
238         {"log", LOG, false},
239         {"info", INFO, true},
240         {"notice", NOTICE, false},
241         {"warning", WARNING, false},
242         {"error", ERROR, false},
243         {"fatal", FATAL, true},
244         {"panic", PANIC, true},
245         {NULL, 0, false}
246 };
247
248 static const struct config_enum_entry server_message_level_options[] = {
249         {"debug", DEBUG2, true},
250         {"debug5", DEBUG5, false},
251         {"debug4", DEBUG4, false},
252         {"debug3", DEBUG3, false},
253         {"debug2", DEBUG2, false},
254         {"debug1", DEBUG1, false},
255         {"info", INFO, false},
256         {"notice", NOTICE, false},
257         {"warning", WARNING, false},
258         {"error", ERROR, false},
259         {"log", LOG, false},
260         {"fatal", FATAL, false},
261         {"panic", PANIC, false},
262         {NULL, 0, false}
263 };
264
265 static const struct config_enum_entry intervalstyle_options[] = {
266         {"postgres", INTSTYLE_POSTGRES, false},
267         {"postgres_verbose", INTSTYLE_POSTGRES_VERBOSE, false},
268         {"sql_standard", INTSTYLE_SQL_STANDARD, false},
269         {"iso_8601", INTSTYLE_ISO_8601, false},
270         {NULL, 0, false}
271 };
272
273 static const struct config_enum_entry log_error_verbosity_options[] = {
274         {"terse", PGERROR_TERSE, false},
275         {"default", PGERROR_DEFAULT, false},
276         {"verbose", PGERROR_VERBOSE, false},
277         {NULL, 0, false}
278 };
279
280 static const struct config_enum_entry log_statement_options[] = {
281         {"none", LOGSTMT_NONE, false},
282         {"ddl", LOGSTMT_DDL, false},
283         {"mod", LOGSTMT_MOD, false},
284         {"all", LOGSTMT_ALL, false},
285         {NULL, 0, false}
286 };
287
288 static const struct config_enum_entry isolation_level_options[] = {
289         {"serializable", XACT_SERIALIZABLE, false},
290         {"repeatable read", XACT_REPEATABLE_READ, false},
291         {"read committed", XACT_READ_COMMITTED, false},
292         {"read uncommitted", XACT_READ_UNCOMMITTED, false},
293         {NULL, 0}
294 };
295
296 static const struct config_enum_entry session_replication_role_options[] = {
297         {"origin", SESSION_REPLICATION_ROLE_ORIGIN, false},
298         {"replica", SESSION_REPLICATION_ROLE_REPLICA, false},
299         {"local", SESSION_REPLICATION_ROLE_LOCAL, false},
300         {NULL, 0, false}
301 };
302
303 static const struct config_enum_entry syslog_facility_options[] = {
304 #ifdef HAVE_SYSLOG
305         {"local0", LOG_LOCAL0, false},
306         {"local1", LOG_LOCAL1, false},
307         {"local2", LOG_LOCAL2, false},
308         {"local3", LOG_LOCAL3, false},
309         {"local4", LOG_LOCAL4, false},
310         {"local5", LOG_LOCAL5, false},
311         {"local6", LOG_LOCAL6, false},
312         {"local7", LOG_LOCAL7, false},
313 #else
314         {"none", 0, false},
315 #endif
316         {NULL, 0}
317 };
318
319 static const struct config_enum_entry track_function_options[] = {
320         {"none", TRACK_FUNC_OFF, false},
321         {"pl", TRACK_FUNC_PL, false},
322         {"all", TRACK_FUNC_ALL, false},
323         {NULL, 0, false}
324 };
325
326 static const struct config_enum_entry xmlbinary_options[] = {
327         {"base64", XMLBINARY_BASE64, false},
328         {"hex", XMLBINARY_HEX, false},
329         {NULL, 0, false}
330 };
331
332 static const struct config_enum_entry xmloption_options[] = {
333         {"content", XMLOPTION_CONTENT, false},
334         {"document", XMLOPTION_DOCUMENT, false},
335         {NULL, 0, false}
336 };
337
338 /*
339  * Although only "on", "off", and "safe_encoding" are documented, we
340  * accept all the likely variants of "on" and "off".
341  */
342 static const struct config_enum_entry backslash_quote_options[] = {
343         {"safe_encoding", BACKSLASH_QUOTE_SAFE_ENCODING, false},
344         {"on", BACKSLASH_QUOTE_ON, false},
345         {"off", BACKSLASH_QUOTE_OFF, false},
346         {"true", BACKSLASH_QUOTE_ON, true},
347         {"false", BACKSLASH_QUOTE_OFF, true},
348         {"yes", BACKSLASH_QUOTE_ON, true},
349         {"no", BACKSLASH_QUOTE_OFF, true},
350         {"1", BACKSLASH_QUOTE_ON, true},
351         {"0", BACKSLASH_QUOTE_OFF, true},
352         {NULL, 0, false}
353 };
354
355 /*
356  * Although only "on", "off", and "partition" are documented, we
357  * accept all the likely variants of "on" and "off".
358  */
359 static const struct config_enum_entry constraint_exclusion_options[] = {
360         {"partition", CONSTRAINT_EXCLUSION_PARTITION, false},
361         {"on", CONSTRAINT_EXCLUSION_ON, false},
362         {"off", CONSTRAINT_EXCLUSION_OFF, false},
363         {"true", CONSTRAINT_EXCLUSION_ON, true},
364         {"false", CONSTRAINT_EXCLUSION_OFF, true},
365         {"yes", CONSTRAINT_EXCLUSION_ON, true},
366         {"no", CONSTRAINT_EXCLUSION_OFF, true},
367         {"1", CONSTRAINT_EXCLUSION_ON, true},
368         {"0", CONSTRAINT_EXCLUSION_OFF, true},
369         {NULL, 0, false}
370 };
371
372 /*
373  * Although only "on", "off", and "local" are documented, we
374  * accept all the likely variants of "on" and "off".
375  */
376 static const struct config_enum_entry synchronous_commit_options[] = {
377         {"local", SYNCHRONOUS_COMMIT_LOCAL_FLUSH, false},
378         {"on", SYNCHRONOUS_COMMIT_ON, false},
379         {"off", SYNCHRONOUS_COMMIT_OFF, false},
380         {"true", SYNCHRONOUS_COMMIT_ON, true},
381         {"false", SYNCHRONOUS_COMMIT_OFF, true},
382         {"yes", SYNCHRONOUS_COMMIT_ON, true},
383         {"no", SYNCHRONOUS_COMMIT_OFF, true},
384         {"1", SYNCHRONOUS_COMMIT_ON, true},
385         {"0", SYNCHRONOUS_COMMIT_OFF, true},
386         {NULL, 0, false}
387 };
388
389 /*
390  * Options for enum values stored in other modules
391  */
392 extern const struct config_enum_entry wal_level_options[];
393 extern const struct config_enum_entry sync_method_options[];
394
395 /*
396  * GUC option variables that are exported from this module
397  */
398 #ifdef USE_ASSERT_CHECKING
399 bool            assert_enabled = true;
400 #else
401 bool            assert_enabled = false;
402 #endif
403 bool            log_duration = false;
404 bool            Debug_print_plan = false;
405 bool            Debug_print_parse = false;
406 bool            Debug_print_rewritten = false;
407 bool            Debug_pretty_print = true;
408
409 bool            log_parser_stats = false;
410 bool            log_planner_stats = false;
411 bool            log_executor_stats = false;
412 bool            log_statement_stats = false;            /* this is sort of all three
413                                                                                                  * above together */
414 bool            log_btree_build_stats = false;
415 char       *event_source;
416
417 bool            check_function_bodies = true;
418 bool            default_with_oids = false;
419 bool            SQL_inheritance = true;
420
421 bool            Password_encryption = true;
422
423 int                     log_min_error_statement = ERROR;
424 int                     log_min_messages = WARNING;
425 int                     client_min_messages = NOTICE;
426 int                     log_min_duration_statement = -1;
427 int                     log_temp_files = -1;
428 int                     trace_recovery_messages = LOG;
429
430 int                     temp_file_limit = -1;
431
432 int                     num_temp_buffers = 1024;
433
434 char       *data_directory;
435 char       *ConfigFileName;
436 char       *HbaFileName;
437 char       *IdentFileName;
438 char       *external_pid_file;
439
440 char       *pgstat_temp_directory;
441
442 char       *application_name;
443
444 int                     tcp_keepalives_idle;
445 int                     tcp_keepalives_interval;
446 int                     tcp_keepalives_count;
447
448 /*
449  * These variables are all dummies that don't do anything, except in some
450  * cases provide the value for SHOW to display.  The real state is elsewhere
451  * and is kept in sync by assign_hooks.
452  */
453 static char *log_destination_string;
454
455 static char *syslog_ident_str;
456 static bool phony_autocommit;
457 static bool session_auth_is_superuser;
458 static double phony_random_seed;
459 static char *client_encoding_string;
460 static char *datestyle_string;
461 static char *locale_collate;
462 static char *locale_ctype;
463 static char *server_encoding_string;
464 static char *server_version_string;
465 static int      server_version_num;
466 static char *timezone_string;
467 static char *log_timezone_string;
468 static char *timezone_abbreviations_string;
469 static char *XactIsoLevel_string;
470 static char *session_authorization_string;
471 static int      max_function_args;
472 static int      max_index_keys;
473 static int      max_identifier_length;
474 static int      block_size;
475 static int      segment_size;
476 static int      wal_block_size;
477 static int      wal_segment_size;
478 static bool integer_datetimes;
479 static int      effective_io_concurrency;
480
481 /* should be static, but commands/variable.c needs to get at this */
482 char       *role_string;
483
484
485 /*
486  * Displayable names for context types (enum GucContext)
487  *
488  * Note: these strings are deliberately not localized.
489  */
490 const char *const GucContext_Names[] =
491 {
492          /* PGC_INTERNAL */ "internal",
493          /* PGC_POSTMASTER */ "postmaster",
494          /* PGC_SIGHUP */ "sighup",
495          /* PGC_BACKEND */ "backend",
496          /* PGC_SUSET */ "superuser",
497          /* PGC_USERSET */ "user"
498 };
499
500 /*
501  * Displayable names for source types (enum GucSource)
502  *
503  * Note: these strings are deliberately not localized.
504  */
505 const char *const GucSource_Names[] =
506 {
507          /* PGC_S_DEFAULT */ "default",
508          /* PGC_S_DYNAMIC_DEFAULT */ "default",
509          /* PGC_S_ENV_VAR */ "environment variable",
510          /* PGC_S_FILE */ "configuration file",
511          /* PGC_S_ARGV */ "command line",
512          /* PGC_S_DATABASE */ "database",
513          /* PGC_S_USER */ "user",
514          /* PGC_S_DATABASE_USER */ "database user",
515          /* PGC_S_CLIENT */ "client",
516          /* PGC_S_OVERRIDE */ "override",
517          /* PGC_S_INTERACTIVE */ "interactive",
518          /* PGC_S_TEST */ "test",
519          /* PGC_S_SESSION */ "session"
520 };
521
522 /*
523  * Displayable names for the groupings defined in enum config_group
524  */
525 const char *const config_group_names[] =
526 {
527         /* UNGROUPED */
528         gettext_noop("Ungrouped"),
529         /* FILE_LOCATIONS */
530         gettext_noop("File Locations"),
531         /* CONN_AUTH */
532         gettext_noop("Connections and Authentication"),
533         /* CONN_AUTH_SETTINGS */
534         gettext_noop("Connections and Authentication / Connection Settings"),
535         /* CONN_AUTH_SECURITY */
536         gettext_noop("Connections and Authentication / Security and Authentication"),
537         /* RESOURCES */
538         gettext_noop("Resource Usage"),
539         /* RESOURCES_MEM */
540         gettext_noop("Resource Usage / Memory"),
541         /* RESOURCES_DISK */
542         gettext_noop("Resource Usage / Disk"),
543         /* RESOURCES_KERNEL */
544         gettext_noop("Resource Usage / Kernel Resources"),
545         /* RESOURCES_VACUUM_DELAY */
546         gettext_noop("Resource Usage / Cost-Based Vacuum Delay"),
547         /* RESOURCES_BGWRITER */
548         gettext_noop("Resource Usage / Background Writer"),
549         /* RESOURCES_ASYNCHRONOUS */
550         gettext_noop("Resource Usage / Asynchronous Behavior"),
551         /* WAL */
552         gettext_noop("Write-Ahead Log"),
553         /* WAL_SETTINGS */
554         gettext_noop("Write-Ahead Log / Settings"),
555         /* WAL_CHECKPOINTS */
556         gettext_noop("Write-Ahead Log / Checkpoints"),
557         /* WAL_ARCHIVING */
558         gettext_noop("Write-Ahead Log / Archiving"),
559         /* REPLICATION */
560         gettext_noop("Replication"),
561         /* REPLICATION_SENDING */
562         gettext_noop("Replication / Sending Servers"),
563         /* REPLICATION_MASTER */
564         gettext_noop("Replication / Master Server"),
565         /* REPLICATION_STANDBY */
566         gettext_noop("Replication / Standby Servers"),
567         /* QUERY_TUNING */
568         gettext_noop("Query Tuning"),
569         /* QUERY_TUNING_METHOD */
570         gettext_noop("Query Tuning / Planner Method Configuration"),
571         /* QUERY_TUNING_COST */
572         gettext_noop("Query Tuning / Planner Cost Constants"),
573         /* QUERY_TUNING_GEQO */
574         gettext_noop("Query Tuning / Genetic Query Optimizer"),
575         /* QUERY_TUNING_OTHER */
576         gettext_noop("Query Tuning / Other Planner Options"),
577         /* LOGGING */
578         gettext_noop("Reporting and Logging"),
579         /* LOGGING_WHERE */
580         gettext_noop("Reporting and Logging / Where to Log"),
581         /* LOGGING_WHEN */
582         gettext_noop("Reporting and Logging / When to Log"),
583         /* LOGGING_WHAT */
584         gettext_noop("Reporting and Logging / What to Log"),
585         /* STATS */
586         gettext_noop("Statistics"),
587         /* STATS_MONITORING */
588         gettext_noop("Statistics / Monitoring"),
589         /* STATS_COLLECTOR */
590         gettext_noop("Statistics / Query and Index Statistics Collector"),
591         /* AUTOVACUUM */
592         gettext_noop("Autovacuum"),
593         /* CLIENT_CONN */
594         gettext_noop("Client Connection Defaults"),
595         /* CLIENT_CONN_STATEMENT */
596         gettext_noop("Client Connection Defaults / Statement Behavior"),
597         /* CLIENT_CONN_LOCALE */
598         gettext_noop("Client Connection Defaults / Locale and Formatting"),
599         /* CLIENT_CONN_OTHER */
600         gettext_noop("Client Connection Defaults / Other Defaults"),
601         /* LOCK_MANAGEMENT */
602         gettext_noop("Lock Management"),
603         /* COMPAT_OPTIONS */
604         gettext_noop("Version and Platform Compatibility"),
605         /* COMPAT_OPTIONS_PREVIOUS */
606         gettext_noop("Version and Platform Compatibility / Previous PostgreSQL Versions"),
607         /* COMPAT_OPTIONS_CLIENT */
608         gettext_noop("Version and Platform Compatibility / Other Platforms and Clients"),
609         /* ERROR_HANDLING */
610         gettext_noop("Error Handling"),
611         /* PRESET_OPTIONS */
612         gettext_noop("Preset Options"),
613         /* CUSTOM_OPTIONS */
614         gettext_noop("Customized Options"),
615         /* DEVELOPER_OPTIONS */
616         gettext_noop("Developer Options"),
617         /* help_config wants this array to be null-terminated */
618         NULL
619 };
620
621 /*
622  * Displayable names for GUC variable types (enum config_type)
623  *
624  * Note: these strings are deliberately not localized.
625  */
626 const char *const config_type_names[] =
627 {
628          /* PGC_BOOL */ "bool",
629          /* PGC_INT */ "integer",
630          /* PGC_REAL */ "real",
631          /* PGC_STRING */ "string",
632          /* PGC_ENUM */ "enum"
633 };
634
635
636 /*
637  * Contents of GUC tables
638  *
639  * See src/backend/utils/misc/README for design notes.
640  *
641  * TO ADD AN OPTION:
642  *
643  * 1. Declare a global variable of type bool, int, double, or char*
644  *        and make use of it.
645  *
646  * 2. Decide at what times it's safe to set the option. See guc.h for
647  *        details.
648  *
649  * 3. Decide on a name, a default value, upper and lower bounds (if
650  *        applicable), etc.
651  *
652  * 4. Add a record below.
653  *
654  * 5. Add it to src/backend/utils/misc/postgresql.conf.sample, if
655  *        appropriate.
656  *
657  * 6. Don't forget to document the option (at least in config.sgml).
658  *
659  * 7. If it's a new GUC_LIST option you must edit pg_dumpall.c to ensure
660  *        it is not single quoted at dump time.
661  */
662
663
664 /******** option records follow ********/
665
666 static struct config_bool ConfigureNamesBool[] =
667 {
668         {
669                 {"enable_seqscan", PGC_USERSET, QUERY_TUNING_METHOD,
670                         gettext_noop("Enables the planner's use of sequential-scan plans."),
671                         NULL
672                 },
673                 &enable_seqscan,
674                 true,
675                 NULL, NULL, NULL
676         },
677         {
678                 {"enable_indexscan", PGC_USERSET, QUERY_TUNING_METHOD,
679                         gettext_noop("Enables the planner's use of index-scan plans."),
680                         NULL
681                 },
682                 &enable_indexscan,
683                 true,
684                 NULL, NULL, NULL
685         },
686         {
687                 {"enable_indexonlyscan", PGC_USERSET, QUERY_TUNING_METHOD,
688                         gettext_noop("Enables the planner's use of index-only-scan plans."),
689                         NULL
690                 },
691                 &enable_indexonlyscan,
692                 true,
693                 NULL, NULL, NULL
694         },
695         {
696                 {"enable_bitmapscan", PGC_USERSET, QUERY_TUNING_METHOD,
697                         gettext_noop("Enables the planner's use of bitmap-scan plans."),
698                         NULL
699                 },
700                 &enable_bitmapscan,
701                 true,
702                 NULL, NULL, NULL
703         },
704         {
705                 {"enable_tidscan", PGC_USERSET, QUERY_TUNING_METHOD,
706                         gettext_noop("Enables the planner's use of TID scan plans."),
707                         NULL
708                 },
709                 &enable_tidscan,
710                 true,
711                 NULL, NULL, NULL
712         },
713         {
714                 {"enable_sort", PGC_USERSET, QUERY_TUNING_METHOD,
715                         gettext_noop("Enables the planner's use of explicit sort steps."),
716                         NULL
717                 },
718                 &enable_sort,
719                 true,
720                 NULL, NULL, NULL
721         },
722         {
723                 {"enable_hashagg", PGC_USERSET, QUERY_TUNING_METHOD,
724                         gettext_noop("Enables the planner's use of hashed aggregation plans."),
725                         NULL
726                 },
727                 &enable_hashagg,
728                 true,
729                 NULL, NULL, NULL
730         },
731         {
732                 {"enable_material", PGC_USERSET, QUERY_TUNING_METHOD,
733                         gettext_noop("Enables the planner's use of materialization."),
734                         NULL
735                 },
736                 &enable_material,
737                 true,
738                 NULL, NULL, NULL
739         },
740         {
741                 {"enable_nestloop", PGC_USERSET, QUERY_TUNING_METHOD,
742                         gettext_noop("Enables the planner's use of nested-loop join plans."),
743                         NULL
744                 },
745                 &enable_nestloop,
746                 true,
747                 NULL, NULL, NULL
748         },
749         {
750                 {"enable_mergejoin", PGC_USERSET, QUERY_TUNING_METHOD,
751                         gettext_noop("Enables the planner's use of merge join plans."),
752                         NULL
753                 },
754                 &enable_mergejoin,
755                 true,
756                 NULL, NULL, NULL
757         },
758         {
759                 {"enable_hashjoin", PGC_USERSET, QUERY_TUNING_METHOD,
760                         gettext_noop("Enables the planner's use of hash join plans."),
761                         NULL
762                 },
763                 &enable_hashjoin,
764                 true,
765                 NULL, NULL, NULL
766         },
767         {
768                 {"geqo", PGC_USERSET, QUERY_TUNING_GEQO,
769                         gettext_noop("Enables genetic query optimization."),
770                         gettext_noop("This algorithm attempts to do planning without "
771                                                  "exhaustive searching.")
772                 },
773                 &enable_geqo,
774                 true,
775                 NULL, NULL, NULL
776         },
777         {
778                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
779                 {"is_superuser", PGC_INTERNAL, UNGROUPED,
780                         gettext_noop("Shows whether the current user is a superuser."),
781                         NULL,
782                         GUC_REPORT | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
783                 },
784                 &session_auth_is_superuser,
785                 false,
786                 NULL, NULL, NULL
787         },
788         {
789                 {"bonjour", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
790                         gettext_noop("Enables advertising the server via Bonjour."),
791                         NULL
792                 },
793                 &enable_bonjour,
794                 false,
795                 check_bonjour, NULL, NULL
796         },
797         {
798                 {"ssl", PGC_POSTMASTER, CONN_AUTH_SECURITY,
799                         gettext_noop("Enables SSL connections."),
800                         NULL
801                 },
802                 &EnableSSL,
803                 false,
804                 check_ssl, NULL, NULL
805         },
806         {
807                 {"fsync", PGC_SIGHUP, WAL_SETTINGS,
808                         gettext_noop("Forces synchronization of updates to disk."),
809                         gettext_noop("The server will use the fsync() system call in several places to make "
810                         "sure that updates are physically written to disk. This insures "
811                                                  "that a database cluster will recover to a consistent state after "
812                                                  "an operating system or hardware crash.")
813                 },
814                 &enableFsync,
815                 true,
816                 NULL, NULL, NULL
817         },
818         {
819                 {"zero_damaged_pages", PGC_SUSET, DEVELOPER_OPTIONS,
820                         gettext_noop("Continues processing past damaged page headers."),
821                         gettext_noop("Detection of a damaged page header normally causes PostgreSQL to "
822                                 "report an error, aborting the current transaction. Setting "
823                                                  "zero_damaged_pages to true causes the system to instead report a "
824                                                  "warning, zero out the damaged page, and continue processing. This "
825                                                  "behavior will destroy data, namely all the rows on the damaged page."),
826                         GUC_NOT_IN_SAMPLE
827                 },
828                 &zero_damaged_pages,
829                 false,
830                 NULL, NULL, NULL
831         },
832         {
833                 {"full_page_writes", PGC_SIGHUP, WAL_SETTINGS,
834                         gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
835                         gettext_noop("A page write in process during an operating system crash might be "
836                                                  "only partially written to disk.  During recovery, the row changes "
837                           "stored in WAL are not enough to recover.  This option writes "
838                                                  "pages when first modified after a checkpoint to WAL so full recovery "
839                                                  "is possible.")
840                 },
841                 &fullPageWrites,
842                 true,
843                 NULL, NULL, NULL
844         },
845         {
846                 {"log_checkpoints", PGC_SIGHUP, LOGGING_WHAT,
847                         gettext_noop("Logs each checkpoint."),
848                         NULL
849                 },
850                 &log_checkpoints,
851                 false,
852                 NULL, NULL, NULL
853         },
854         {
855                 {"log_connections", PGC_BACKEND, LOGGING_WHAT,
856                         gettext_noop("Logs each successful connection."),
857                         NULL
858                 },
859                 &Log_connections,
860                 false,
861                 NULL, NULL, NULL
862         },
863         {
864                 {"log_disconnections", PGC_BACKEND, LOGGING_WHAT,
865                         gettext_noop("Logs end of a session, including duration."),
866                         NULL
867                 },
868                 &Log_disconnections,
869                 false,
870                 NULL, NULL, NULL
871         },
872         {
873                 {"debug_assertions", PGC_USERSET, DEVELOPER_OPTIONS,
874                         gettext_noop("Turns on various assertion checks."),
875                         gettext_noop("This is a debugging aid."),
876                         GUC_NOT_IN_SAMPLE
877                 },
878                 &assert_enabled,
879 #ifdef USE_ASSERT_CHECKING
880                 true,
881 #else
882                 false,
883 #endif
884                 check_debug_assertions, NULL, NULL
885         },
886
887         {
888                 {"exit_on_error", PGC_USERSET, ERROR_HANDLING_OPTIONS,
889                         gettext_noop("Terminate session on any error."),
890                         NULL
891                 },
892                 &ExitOnAnyError,
893                 false,
894                 NULL, NULL, NULL
895         },
896         {
897                 {"restart_after_crash", PGC_SIGHUP, ERROR_HANDLING_OPTIONS,
898                         gettext_noop("Reinitialize server after backend crash."),
899                         NULL
900                 },
901                 &restart_after_crash,
902                 true,
903                 NULL, NULL, NULL
904         },
905
906         {
907                 {"log_duration", PGC_SUSET, LOGGING_WHAT,
908                         gettext_noop("Logs the duration of each completed SQL statement."),
909                         NULL
910                 },
911                 &log_duration,
912                 false,
913                 NULL, NULL, NULL
914         },
915         {
916                 {"debug_print_parse", PGC_USERSET, LOGGING_WHAT,
917                         gettext_noop("Logs each query's parse tree."),
918                         NULL
919                 },
920                 &Debug_print_parse,
921                 false,
922                 NULL, NULL, NULL
923         },
924         {
925                 {"debug_print_rewritten", PGC_USERSET, LOGGING_WHAT,
926                         gettext_noop("Logs each query's rewritten parse tree."),
927                         NULL
928                 },
929                 &Debug_print_rewritten,
930                 false,
931                 NULL, NULL, NULL
932         },
933         {
934                 {"debug_print_plan", PGC_USERSET, LOGGING_WHAT,
935                         gettext_noop("Logs each query's execution plan."),
936                         NULL
937                 },
938                 &Debug_print_plan,
939                 false,
940                 NULL, NULL, NULL
941         },
942         {
943                 {"debug_pretty_print", PGC_USERSET, LOGGING_WHAT,
944                         gettext_noop("Indents parse and plan tree displays."),
945                         NULL
946                 },
947                 &Debug_pretty_print,
948                 true,
949                 NULL, NULL, NULL
950         },
951         {
952                 {"log_parser_stats", PGC_SUSET, STATS_MONITORING,
953                         gettext_noop("Writes parser performance statistics to the server log."),
954                         NULL
955                 },
956                 &log_parser_stats,
957                 false,
958                 check_stage_log_stats, NULL, NULL
959         },
960         {
961                 {"log_planner_stats", PGC_SUSET, STATS_MONITORING,
962                         gettext_noop("Writes planner performance statistics to the server log."),
963                         NULL
964                 },
965                 &log_planner_stats,
966                 false,
967                 check_stage_log_stats, NULL, NULL
968         },
969         {
970                 {"log_executor_stats", PGC_SUSET, STATS_MONITORING,
971                         gettext_noop("Writes executor performance statistics to the server log."),
972                         NULL
973                 },
974                 &log_executor_stats,
975                 false,
976                 check_stage_log_stats, NULL, NULL
977         },
978         {
979                 {"log_statement_stats", PGC_SUSET, STATS_MONITORING,
980                         gettext_noop("Writes cumulative performance statistics to the server log."),
981                         NULL
982                 },
983                 &log_statement_stats,
984                 false,
985                 check_log_stats, NULL, NULL
986         },
987 #ifdef BTREE_BUILD_STATS
988         {
989                 {"log_btree_build_stats", PGC_SUSET, DEVELOPER_OPTIONS,
990                         gettext_noop("No description available."),
991                         NULL,
992                         GUC_NOT_IN_SAMPLE
993                 },
994                 &log_btree_build_stats,
995                 false,
996                 NULL, NULL, NULL
997         },
998 #endif
999
1000         {
1001                 {"track_activities", PGC_SUSET, STATS_COLLECTOR,
1002                         gettext_noop("Collects information about executing commands."),
1003                         gettext_noop("Enables the collection of information on the currently "
1004                                                  "executing command of each session, along with "
1005                                                  "the time at which that command began execution.")
1006                 },
1007                 &pgstat_track_activities,
1008                 true,
1009                 NULL, NULL, NULL
1010         },
1011         {
1012                 {"track_counts", PGC_SUSET, STATS_COLLECTOR,
1013                         gettext_noop("Collects statistics on database activity."),
1014                         NULL
1015                 },
1016                 &pgstat_track_counts,
1017                 true,
1018                 NULL, NULL, NULL
1019         },
1020
1021         {
1022                 {"update_process_title", PGC_SUSET, STATS_COLLECTOR,
1023                         gettext_noop("Updates the process title to show the active SQL command."),
1024                         gettext_noop("Enables updating of the process title every time a new SQL command is received by the server.")
1025                 },
1026                 &update_process_title,
1027                 true,
1028                 NULL, NULL, NULL
1029         },
1030
1031         {
1032                 {"autovacuum", PGC_SIGHUP, AUTOVACUUM,
1033                         gettext_noop("Starts the autovacuum subprocess."),
1034                         NULL
1035                 },
1036                 &autovacuum_start_daemon,
1037                 true,
1038                 NULL, NULL, NULL
1039         },
1040
1041         {
1042                 {"trace_notify", PGC_USERSET, DEVELOPER_OPTIONS,
1043                         gettext_noop("Generates debugging output for LISTEN and NOTIFY."),
1044                         NULL,
1045                         GUC_NOT_IN_SAMPLE
1046                 },
1047                 &Trace_notify,
1048                 false,
1049                 NULL, NULL, NULL
1050         },
1051
1052 #ifdef LOCK_DEBUG
1053         {
1054                 {"trace_locks", PGC_SUSET, DEVELOPER_OPTIONS,
1055                         gettext_noop("No description available."),
1056                         NULL,
1057                         GUC_NOT_IN_SAMPLE
1058                 },
1059                 &Trace_locks,
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                 "GMT",
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 #ifdef WIN32
2824         {
2825                 {"event_source", PGC_POSTMASTER, LOGGING_WHERE,
2826                         gettext_noop("Sets the application name used to identify"
2827                                                  "PostgreSQL messages in the event log."),
2828                         NULL
2829                 },
2830                 &event_source,
2831                 "PostgreSQL",
2832                 NULL, NULL, NULL
2833         },
2834 #endif
2835
2836         {
2837                 {"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
2838                         gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
2839                         NULL,
2840                         GUC_REPORT
2841                 },
2842                 &timezone_string,
2843                 "GMT",
2844                 check_timezone, assign_timezone, show_timezone
2845         },
2846         {
2847                 {"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
2848                         gettext_noop("Selects a file of time zone abbreviations."),
2849                         NULL
2850                 },
2851                 &timezone_abbreviations_string,
2852                 NULL,
2853                 check_timezone_abbreviations, assign_timezone_abbreviations, NULL
2854         },
2855
2856         {
2857                 {"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2858                         gettext_noop("Sets the current transaction's isolation level."),
2859                         NULL,
2860                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2861                 },
2862                 &XactIsoLevel_string,
2863                 "default",
2864                 check_XactIsoLevel, assign_XactIsoLevel, show_XactIsoLevel
2865         },
2866
2867         {
2868                 {"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2869                         gettext_noop("Sets the owning group of the Unix-domain socket."),
2870                         gettext_noop("The owning user of the socket is always the user "
2871                                                  "that starts the server.")
2872                 },
2873                 &Unix_socket_group,
2874                 "",
2875                 NULL, NULL, NULL
2876         },
2877
2878         {
2879                 {"unix_socket_directory", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2880                         gettext_noop("Sets the directory where the Unix-domain socket will be created."),
2881                         NULL,
2882                         GUC_SUPERUSER_ONLY
2883                 },
2884                 &UnixSocketDir,
2885                 "",
2886                 check_canonical_path, NULL, NULL
2887         },
2888
2889         {
2890                 {"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2891                         gettext_noop("Sets the host name or IP address(es) to listen to."),
2892                         NULL,
2893                         GUC_LIST_INPUT
2894                 },
2895                 &ListenAddresses,
2896                 "localhost",
2897                 NULL, NULL, NULL
2898         },
2899
2900         {
2901                 {"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
2902                         gettext_noop("Sets the server's data directory."),
2903                         NULL,
2904                         GUC_SUPERUSER_ONLY
2905                 },
2906                 &data_directory,
2907                 NULL,
2908                 NULL, NULL, NULL
2909         },
2910
2911         {
2912                 {"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
2913                         gettext_noop("Sets the server's main configuration file."),
2914                         NULL,
2915                         GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
2916                 },
2917                 &ConfigFileName,
2918                 NULL,
2919                 NULL, NULL, NULL
2920         },
2921
2922         {
2923                 {"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
2924                         gettext_noop("Sets the server's \"hba\" configuration file."),
2925                         NULL,
2926                         GUC_SUPERUSER_ONLY
2927                 },
2928                 &HbaFileName,
2929                 NULL,
2930                 NULL, NULL, NULL
2931         },
2932
2933         {
2934                 {"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
2935                         gettext_noop("Sets the server's \"ident\" configuration file."),
2936                         NULL,
2937                         GUC_SUPERUSER_ONLY
2938                 },
2939                 &IdentFileName,
2940                 NULL,
2941                 NULL, NULL, NULL
2942         },
2943
2944         {
2945                 {"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
2946                         gettext_noop("Writes the postmaster PID to the specified file."),
2947                         NULL,
2948                         GUC_SUPERUSER_ONLY
2949                 },
2950                 &external_pid_file,
2951                 NULL,
2952                 check_canonical_path, NULL, NULL
2953         },
2954
2955         {
2956                 {"stats_temp_directory", PGC_SIGHUP, STATS_COLLECTOR,
2957                         gettext_noop("Writes temporary statistics files to the specified directory."),
2958                         NULL,
2959                         GUC_SUPERUSER_ONLY
2960                 },
2961                 &pgstat_temp_directory,
2962                 "pg_stat_tmp",
2963                 check_canonical_path, assign_pgstat_temp_directory, NULL
2964         },
2965
2966         {
2967                 {"synchronous_standby_names", PGC_SIGHUP, REPLICATION_MASTER,
2968                         gettext_noop("List of names of potential synchronous standbys."),
2969                         NULL,
2970                         GUC_LIST_INPUT
2971                 },
2972                 &SyncRepStandbyNames,
2973                 "",
2974                 check_synchronous_standby_names, NULL, NULL
2975         },
2976
2977         {
2978                 {"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
2979                         gettext_noop("Sets default text search configuration."),
2980                         NULL
2981                 },
2982                 &TSCurrentConfig,
2983                 "pg_catalog.simple",
2984                 check_TSCurrentConfig, assign_TSCurrentConfig, NULL
2985         },
2986
2987         {
2988                 {"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2989                         gettext_noop("Sets the list of allowed SSL ciphers."),
2990                         NULL,
2991                         GUC_SUPERUSER_ONLY
2992                 },
2993                 &SSLCipherSuites,
2994 #ifdef USE_SSL
2995                 "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH",
2996 #else
2997                 "none",
2998 #endif
2999                 NULL, NULL, NULL
3000         },
3001
3002         {
3003                 {"application_name", PGC_USERSET, LOGGING_WHAT,
3004                         gettext_noop("Sets the application name to be reported in statistics and logs."),
3005                         NULL,
3006                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE
3007                 },
3008                 &application_name,
3009                 "",
3010                 check_application_name, assign_application_name, NULL
3011         },
3012
3013         /* End-of-list marker */
3014         {
3015                 {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL
3016         }
3017 };
3018
3019
3020 static struct config_enum ConfigureNamesEnum[] =
3021 {
3022         {
3023                 {"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
3024                         gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
3025                         NULL
3026                 },
3027                 &backslash_quote,
3028                 BACKSLASH_QUOTE_SAFE_ENCODING, backslash_quote_options,
3029                 NULL, NULL, NULL
3030         },
3031
3032         {
3033                 {"bytea_output", PGC_USERSET, CLIENT_CONN_STATEMENT,
3034                         gettext_noop("Sets the output format for bytea."),
3035                         NULL
3036                 },
3037                 &bytea_output,
3038                 BYTEA_OUTPUT_HEX, bytea_output_options,
3039                 NULL, NULL, NULL
3040         },
3041
3042         {
3043                 {"client_min_messages", PGC_USERSET, LOGGING_WHEN,
3044                         gettext_noop("Sets the message levels that are sent to the client."),
3045                         gettext_noop("Each level includes all the levels that follow it. The later"
3046                                                  " the level, the fewer messages are sent.")
3047                 },
3048                 &client_min_messages,
3049                 NOTICE, client_message_level_options,
3050                 NULL, NULL, NULL
3051         },
3052
3053         {
3054                 {"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
3055                         gettext_noop("Enables the planner to use constraints to optimize queries."),
3056                         gettext_noop("Table scans will be skipped if their constraints"
3057                                                  " guarantee that no rows match the query.")
3058                 },
3059                 &constraint_exclusion,
3060                 CONSTRAINT_EXCLUSION_PARTITION, constraint_exclusion_options,
3061                 NULL, NULL, NULL
3062         },
3063
3064         {
3065                 {"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
3066                         gettext_noop("Sets the transaction isolation level of each new transaction."),
3067                         NULL
3068                 },
3069                 &DefaultXactIsoLevel,
3070                 XACT_READ_COMMITTED, isolation_level_options,
3071                 NULL, NULL, NULL
3072         },
3073
3074         {
3075                 {"IntervalStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
3076                         gettext_noop("Sets the display format for interval values."),
3077                         NULL,
3078                         GUC_REPORT
3079                 },
3080                 &IntervalStyle,
3081                 INTSTYLE_POSTGRES, intervalstyle_options,
3082                 NULL, NULL, NULL
3083         },
3084
3085         {
3086                 {"log_error_verbosity", PGC_SUSET, LOGGING_WHAT,
3087                         gettext_noop("Sets the verbosity of logged messages."),
3088                         NULL
3089                 },
3090                 &Log_error_verbosity,
3091                 PGERROR_DEFAULT, log_error_verbosity_options,
3092                 NULL, NULL, NULL
3093         },
3094
3095         {
3096                 {"log_min_messages", PGC_SUSET, LOGGING_WHEN,
3097                         gettext_noop("Sets the message levels that are logged."),
3098                         gettext_noop("Each level includes all the levels that follow it. The later"
3099                                                  " the level, the fewer messages are sent.")
3100                 },
3101                 &log_min_messages,
3102                 WARNING, server_message_level_options,
3103                 NULL, NULL, NULL
3104         },
3105
3106         {
3107                 {"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
3108                         gettext_noop("Causes all statements generating error at or above this level to be logged."),
3109                         gettext_noop("Each level includes all the levels that follow it. The later"
3110                                                  " the level, the fewer messages are sent.")
3111                 },
3112                 &log_min_error_statement,
3113                 ERROR, server_message_level_options,
3114                 NULL, NULL, NULL
3115         },
3116
3117         {
3118                 {"log_statement", PGC_SUSET, LOGGING_WHAT,
3119                         gettext_noop("Sets the type of statements logged."),
3120                         NULL
3121                 },
3122                 &log_statement,
3123                 LOGSTMT_NONE, log_statement_options,
3124                 NULL, NULL, NULL
3125         },
3126
3127         {
3128                 {"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
3129                         gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
3130                         NULL
3131                 },
3132                 &syslog_facility,
3133 #ifdef HAVE_SYSLOG
3134                 LOG_LOCAL0,
3135 #else
3136                 0,
3137 #endif
3138                 syslog_facility_options,
3139                 NULL, assign_syslog_facility, NULL
3140         },
3141
3142         {
3143                 {"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
3144                         gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
3145                         NULL
3146                 },
3147                 &SessionReplicationRole,
3148                 SESSION_REPLICATION_ROLE_ORIGIN, session_replication_role_options,
3149                 NULL, assign_session_replication_role, NULL
3150         },
3151
3152         {
3153                 {"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
3154                         gettext_noop("Sets the current transaction's synchronization level."),
3155                         NULL
3156                 },
3157                 &synchronous_commit,
3158                 SYNCHRONOUS_COMMIT_ON, synchronous_commit_options,
3159                 NULL, NULL, NULL
3160         },
3161
3162         {
3163                 {"trace_recovery_messages", PGC_SIGHUP, DEVELOPER_OPTIONS,
3164                         gettext_noop("Enables logging of recovery-related debugging information."),
3165                         gettext_noop("Each level includes all the levels that follow it. The later"
3166                                                  " the level, the fewer messages are sent.")
3167                 },
3168                 &trace_recovery_messages,
3169
3170                 /*
3171                  * client_message_level_options allows too many values, really, but
3172                  * it's not worth having a separate options array for this.
3173                  */
3174                 LOG, client_message_level_options,
3175                 NULL, NULL, NULL
3176         },
3177
3178         {
3179                 {"track_functions", PGC_SUSET, STATS_COLLECTOR,
3180                         gettext_noop("Collects function-level statistics on database activity."),
3181                         NULL
3182                 },
3183                 &pgstat_track_functions,
3184                 TRACK_FUNC_OFF, track_function_options,
3185                 NULL, NULL, NULL
3186         },
3187
3188         {
3189                 {"wal_level", PGC_POSTMASTER, WAL_SETTINGS,
3190                         gettext_noop("Set the level of information written to the WAL."),
3191                         NULL
3192                 },
3193                 &wal_level,
3194                 WAL_LEVEL_MINIMAL, wal_level_options,
3195                 NULL, NULL, NULL
3196         },
3197
3198         {
3199                 {"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
3200                         gettext_noop("Selects the method used for forcing WAL updates to disk."),
3201                         NULL
3202                 },
3203                 &sync_method,
3204                 DEFAULT_SYNC_METHOD, sync_method_options,
3205                 NULL, assign_xlog_sync_method, NULL
3206         },
3207
3208         {
3209                 {"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
3210                         gettext_noop("Sets how binary values are to be encoded in XML."),
3211                         NULL
3212                 },
3213                 &xmlbinary,
3214                 XMLBINARY_BASE64, xmlbinary_options,
3215                 NULL, NULL, NULL
3216         },
3217
3218         {
3219                 {"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
3220                         gettext_noop("Sets whether XML data in implicit parsing and serialization "
3221                                                  "operations is to be considered as documents or content fragments."),
3222                         NULL
3223                 },
3224                 &xmloption,
3225                 XMLOPTION_CONTENT, xmloption_options,
3226                 NULL, NULL, NULL
3227         },
3228
3229
3230         /* End-of-list marker */
3231         {
3232                 {NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL
3233         }
3234 };
3235
3236 /******** end of options list ********/
3237
3238
3239 /*
3240  * To allow continued support of obsolete names for GUC variables, we apply
3241  * the following mappings to any unrecognized name.  Note that an old name
3242  * should be mapped to a new one only if the new variable has very similar
3243  * semantics to the old.
3244  */
3245 static const char *const map_old_guc_names[] = {
3246         "sort_mem", "work_mem",
3247         "vacuum_mem", "maintenance_work_mem",
3248         NULL
3249 };
3250
3251
3252 /*
3253  * Actual lookup of variables is done through this single, sorted array.
3254  */
3255 static struct config_generic **guc_variables;
3256
3257 /* Current number of variables contained in the vector */
3258 static int      num_guc_variables;
3259
3260 /* Vector capacity */
3261 static int      size_guc_variables;
3262
3263
3264 static bool guc_dirty;                  /* TRUE if need to do commit/abort work */
3265
3266 static bool reporting_enabled;  /* TRUE to enable GUC_REPORT */
3267
3268 static int      GUCNestLevel = 0;       /* 1 when in main transaction */
3269
3270
3271 static int      guc_var_compare(const void *a, const void *b);
3272 static int      guc_name_compare(const char *namea, const char *nameb);
3273 static void InitializeGUCOptionsFromEnvironment(void);
3274 static void InitializeOneGUCOption(struct config_generic * gconf);
3275 static void push_old_value(struct config_generic * gconf, GucAction action);
3276 static void ReportGUCOption(struct config_generic * record);
3277 static void reapply_stacked_values(struct config_generic * variable,
3278                                            struct config_string *pHolder,
3279                                            GucStack *stack,
3280                                            const char *curvalue,
3281                                            GucContext curscontext, GucSource cursource);
3282 static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
3283 static void ShowAllGUCConfig(DestReceiver *dest);
3284 static char *_ShowOption(struct config_generic * record, bool use_units);
3285 static bool validate_option_array_item(const char *name, const char *value,
3286                                                    bool skipIfNoPermissions);
3287
3288
3289 /*
3290  * Some infrastructure for checking malloc/strdup/realloc calls
3291  */
3292 static void *
3293 guc_malloc(int elevel, size_t size)
3294 {
3295         void       *data;
3296
3297         data = malloc(size);
3298         if (data == NULL)
3299                 ereport(elevel,
3300                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3301                                  errmsg("out of memory")));
3302         return data;
3303 }
3304
3305 static void *
3306 guc_realloc(int elevel, void *old, size_t size)
3307 {
3308         void       *data;
3309
3310         data = realloc(old, size);
3311         if (data == NULL)
3312                 ereport(elevel,
3313                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3314                                  errmsg("out of memory")));
3315         return data;
3316 }
3317
3318 static char *
3319 guc_strdup(int elevel, const char *src)
3320 {
3321         char       *data;
3322
3323         data = strdup(src);
3324         if (data == NULL)
3325                 ereport(elevel,
3326                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3327                                  errmsg("out of memory")));
3328         return data;
3329 }
3330
3331
3332 /*
3333  * Detect whether strval is referenced anywhere in a GUC string item
3334  */
3335 static bool
3336 string_field_used(struct config_string * conf, char *strval)
3337 {
3338         GucStack   *stack;
3339
3340         if (strval == *(conf->variable) ||
3341                 strval == conf->reset_val ||
3342                 strval == conf->boot_val)
3343                 return true;
3344         for (stack = conf->gen.stack; stack; stack = stack->prev)
3345         {
3346                 if (strval == stack->prior.val.stringval ||
3347                         strval == stack->masked.val.stringval)
3348                         return true;
3349         }
3350         return false;
3351 }
3352
3353 /*
3354  * Support for assigning to a field of a string GUC item.  Free the prior
3355  * value if it's not referenced anywhere else in the item (including stacked
3356  * states).
3357  */
3358 static void
3359 set_string_field(struct config_string * conf, char **field, char *newval)
3360 {
3361         char       *oldval = *field;
3362
3363         /* Do the assignment */
3364         *field = newval;
3365
3366         /* Free old value if it's not NULL and isn't referenced anymore */
3367         if (oldval && !string_field_used(conf, oldval))
3368                 free(oldval);
3369 }
3370
3371 /*
3372  * Detect whether an "extra" struct is referenced anywhere in a GUC item
3373  */
3374 static bool
3375 extra_field_used(struct config_generic * gconf, void *extra)
3376 {
3377         GucStack   *stack;
3378
3379         if (extra == gconf->extra)
3380                 return true;
3381         switch (gconf->vartype)
3382         {
3383                 case PGC_BOOL:
3384                         if (extra == ((struct config_bool *) gconf)->reset_extra)
3385                                 return true;
3386                         break;
3387                 case PGC_INT:
3388                         if (extra == ((struct config_int *) gconf)->reset_extra)
3389                                 return true;
3390                         break;
3391                 case PGC_REAL:
3392                         if (extra == ((struct config_real *) gconf)->reset_extra)
3393                                 return true;
3394                         break;
3395                 case PGC_STRING:
3396                         if (extra == ((struct config_string *) gconf)->reset_extra)
3397                                 return true;
3398                         break;
3399                 case PGC_ENUM:
3400                         if (extra == ((struct config_enum *) gconf)->reset_extra)
3401                                 return true;
3402                         break;
3403         }
3404         for (stack = gconf->stack; stack; stack = stack->prev)
3405         {
3406                 if (extra == stack->prior.extra ||
3407                         extra == stack->masked.extra)
3408                         return true;
3409         }
3410
3411         return false;
3412 }
3413
3414 /*
3415  * Support for assigning to an "extra" field of a GUC item.  Free the prior
3416  * value if it's not referenced anywhere else in the item (including stacked
3417  * states).
3418  */
3419 static void
3420 set_extra_field(struct config_generic * gconf, void **field, void *newval)
3421 {
3422         void       *oldval = *field;
3423
3424         /* Do the assignment */
3425         *field = newval;
3426
3427         /* Free old value if it's not NULL and isn't referenced anymore */
3428         if (oldval && !extra_field_used(gconf, oldval))
3429                 free(oldval);
3430 }
3431
3432 /*
3433  * Support for copying a variable's active value into a stack entry.
3434  * The "extra" field associated with the active value is copied, too.
3435  *
3436  * NB: be sure stringval and extra fields of a new stack entry are
3437  * initialized to NULL before this is used, else we'll try to free() them.
3438  */
3439 static void
3440 set_stack_value(struct config_generic * gconf, config_var_value *val)
3441 {
3442         switch (gconf->vartype)
3443         {
3444                 case PGC_BOOL:
3445                         val->val.boolval =
3446                                 *((struct config_bool *) gconf)->variable;
3447                         break;
3448                 case PGC_INT:
3449                         val->val.intval =
3450                                 *((struct config_int *) gconf)->variable;
3451                         break;
3452                 case PGC_REAL:
3453                         val->val.realval =
3454                                 *((struct config_real *) gconf)->variable;
3455                         break;
3456                 case PGC_STRING:
3457                         set_string_field((struct config_string *) gconf,
3458                                                          &(val->val.stringval),
3459                                                          *((struct config_string *) gconf)->variable);
3460                         break;
3461                 case PGC_ENUM:
3462                         val->val.enumval =
3463                                 *((struct config_enum *) gconf)->variable;
3464                         break;
3465         }
3466         set_extra_field(gconf, &(val->extra), gconf->extra);
3467 }
3468
3469 /*
3470  * Support for discarding a no-longer-needed value in a stack entry.
3471  * The "extra" field associated with the stack entry is cleared, too.
3472  */
3473 static void
3474 discard_stack_value(struct config_generic * gconf, config_var_value *val)
3475 {
3476         switch (gconf->vartype)
3477         {
3478                 case PGC_BOOL:
3479                 case PGC_INT:
3480                 case PGC_REAL:
3481                 case PGC_ENUM:
3482                         /* no need to do anything */
3483                         break;
3484                 case PGC_STRING:
3485                         set_string_field((struct config_string *) gconf,
3486                                                          &(val->val.stringval),
3487                                                          NULL);
3488                         break;
3489         }
3490         set_extra_field(gconf, &(val->extra), NULL);
3491 }
3492
3493
3494 /*
3495  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
3496  */
3497 struct config_generic **
3498 get_guc_variables(void)
3499 {
3500         return guc_variables;
3501 }
3502
3503
3504 /*
3505  * Build the sorted array.      This is split out so that it could be
3506  * re-executed after startup (eg, we could allow loadable modules to
3507  * add vars, and then we'd need to re-sort).
3508  */
3509 void
3510 build_guc_variables(void)
3511 {
3512         int                     size_vars;
3513         int                     num_vars = 0;
3514         struct config_generic **guc_vars;
3515         int                     i;
3516
3517         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3518         {
3519                 struct config_bool *conf = &ConfigureNamesBool[i];
3520
3521                 /* Rather than requiring vartype to be filled in by hand, do this: */
3522                 conf->gen.vartype = PGC_BOOL;
3523                 num_vars++;
3524         }
3525
3526         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3527         {
3528                 struct config_int *conf = &ConfigureNamesInt[i];
3529
3530                 conf->gen.vartype = PGC_INT;
3531                 num_vars++;
3532         }
3533
3534         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3535         {
3536                 struct config_real *conf = &ConfigureNamesReal[i];
3537
3538                 conf->gen.vartype = PGC_REAL;
3539                 num_vars++;
3540         }
3541
3542         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3543         {
3544                 struct config_string *conf = &ConfigureNamesString[i];
3545
3546                 conf->gen.vartype = PGC_STRING;
3547                 num_vars++;
3548         }
3549
3550         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3551         {
3552                 struct config_enum *conf = &ConfigureNamesEnum[i];
3553
3554                 conf->gen.vartype = PGC_ENUM;
3555                 num_vars++;
3556         }
3557
3558         /*
3559          * Create table with 20% slack
3560          */
3561         size_vars = num_vars + num_vars / 4;
3562
3563         guc_vars = (struct config_generic **)
3564                 guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
3565
3566         num_vars = 0;
3567
3568         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3569                 guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
3570
3571         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3572                 guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
3573
3574         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3575                 guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
3576
3577         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3578                 guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
3579
3580         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3581                 guc_vars[num_vars++] = &ConfigureNamesEnum[i].gen;
3582
3583         if (guc_variables)
3584                 free(guc_variables);
3585         guc_variables = guc_vars;
3586         num_guc_variables = num_vars;
3587         size_guc_variables = size_vars;
3588         qsort((void *) guc_variables, num_guc_variables,
3589                   sizeof(struct config_generic *), guc_var_compare);
3590 }
3591
3592 /*
3593  * Add a new GUC variable to the list of known variables. The
3594  * list is expanded if needed.
3595  */
3596 static bool
3597 add_guc_variable(struct config_generic * var, int elevel)
3598 {
3599         if (num_guc_variables + 1 >= size_guc_variables)
3600         {
3601                 /*
3602                  * Increase the vector by 25%
3603                  */
3604                 int                     size_vars = size_guc_variables + size_guc_variables / 4;
3605                 struct config_generic **guc_vars;
3606
3607                 if (size_vars == 0)
3608                 {
3609                         size_vars = 100;
3610                         guc_vars = (struct config_generic **)
3611                                 guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
3612                 }
3613                 else
3614                 {
3615                         guc_vars = (struct config_generic **)
3616                                 guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
3617                 }
3618
3619                 if (guc_vars == NULL)
3620                         return false;           /* out of memory */
3621
3622                 guc_variables = guc_vars;
3623                 size_guc_variables = size_vars;
3624         }
3625         guc_variables[num_guc_variables++] = var;
3626         qsort((void *) guc_variables, num_guc_variables,
3627                   sizeof(struct config_generic *), guc_var_compare);
3628         return true;
3629 }
3630
3631 /*
3632  * Create and add a placeholder variable for a custom variable name.
3633  */
3634 static struct config_generic *
3635 add_placeholder_variable(const char *name, int elevel)
3636 {
3637         size_t          sz = sizeof(struct config_string) + sizeof(char *);
3638         struct config_string *var;
3639         struct config_generic *gen;
3640
3641         var = (struct config_string *) guc_malloc(elevel, sz);
3642         if (var == NULL)
3643                 return NULL;
3644         memset(var, 0, sz);
3645         gen = &var->gen;
3646
3647         gen->name = guc_strdup(elevel, name);
3648         if (gen->name == NULL)
3649         {
3650                 free(var);
3651                 return NULL;
3652         }
3653
3654         gen->context = PGC_USERSET;
3655         gen->group = CUSTOM_OPTIONS;
3656         gen->short_desc = "GUC placeholder variable";
3657         gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
3658         gen->vartype = PGC_STRING;
3659
3660         /*
3661          * The char* is allocated at the end of the struct since we have no
3662          * 'static' place to point to.  Note that the current value, as well as
3663          * the boot and reset values, start out NULL.
3664          */
3665         var->variable = (char **) (var + 1);
3666
3667         if (!add_guc_variable((struct config_generic *) var, elevel))
3668         {
3669                 free((void *) gen->name);
3670                 free(var);
3671                 return NULL;
3672         }
3673
3674         return gen;
3675 }
3676
3677 /*
3678  * Look up option NAME.  If it exists, return a pointer to its record,
3679  * else return NULL.  If create_placeholders is TRUE, we'll create a
3680  * placeholder record for a valid-looking custom variable name.
3681  */
3682 static struct config_generic *
3683 find_option(const char *name, bool create_placeholders, int elevel)
3684 {
3685         const char **key = &name;
3686         struct config_generic **res;
3687         int                     i;
3688
3689         Assert(name);
3690
3691         /*
3692          * By equating const char ** with struct config_generic *, we are assuming
3693          * the name field is first in config_generic.
3694          */
3695         res = (struct config_generic **) bsearch((void *) &key,
3696                                                                                          (void *) guc_variables,
3697                                                                                          num_guc_variables,
3698                                                                                          sizeof(struct config_generic *),
3699                                                                                          guc_var_compare);
3700         if (res)
3701                 return *res;
3702
3703         /*
3704          * See if the name is an obsolete name for a variable.  We assume that the
3705          * set of supported old names is short enough that a brute-force search is
3706          * the best way.
3707          */
3708         for (i = 0; map_old_guc_names[i] != NULL; i += 2)
3709         {
3710                 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
3711                         return find_option(map_old_guc_names[i + 1], false, elevel);
3712         }
3713
3714         if (create_placeholders)
3715         {
3716                 /*
3717                  * Check if the name is qualified, and if so, add a placeholder.
3718                  */
3719                 if (strchr(name, GUC_QUALIFIER_SEPARATOR) != NULL)
3720                         return add_placeholder_variable(name, elevel);
3721         }
3722
3723         /* Unknown name */
3724         return NULL;
3725 }
3726
3727
3728 /*
3729  * comparator for qsorting and bsearching guc_variables array
3730  */
3731 static int
3732 guc_var_compare(const void *a, const void *b)
3733 {
3734         struct config_generic *confa = *(struct config_generic **) a;
3735         struct config_generic *confb = *(struct config_generic **) b;
3736
3737         return guc_name_compare(confa->name, confb->name);
3738 }
3739
3740 /*
3741  * the bare comparison function for GUC names
3742  */
3743 static int
3744 guc_name_compare(const char *namea, const char *nameb)
3745 {
3746         /*
3747          * The temptation to use strcasecmp() here must be resisted, because the
3748          * array ordering has to remain stable across setlocale() calls. So, build
3749          * our own with a simple ASCII-only downcasing.
3750          */
3751         while (*namea && *nameb)
3752         {
3753                 char            cha = *namea++;
3754                 char            chb = *nameb++;
3755
3756                 if (cha >= 'A' && cha <= 'Z')
3757                         cha += 'a' - 'A';
3758                 if (chb >= 'A' && chb <= 'Z')
3759                         chb += 'a' - 'A';
3760                 if (cha != chb)
3761                         return cha - chb;
3762         }
3763         if (*namea)
3764                 return 1;                               /* a is longer */
3765         if (*nameb)
3766                 return -1;                              /* b is longer */
3767         return 0;
3768 }
3769
3770
3771 /*
3772  * Initialize GUC options during program startup.
3773  *
3774  * Note that we cannot read the config file yet, since we have not yet
3775  * processed command-line switches.
3776  */
3777 void
3778 InitializeGUCOptions(void)
3779 {
3780         int                     i;
3781
3782         /*
3783          * Before log_line_prefix could possibly receive a nonempty setting, make
3784          * sure that timezone processing is minimally alive (see elog.c).
3785          */
3786         pg_timezone_initialize();
3787
3788         /*
3789          * Build sorted array of all GUC variables.
3790          */
3791         build_guc_variables();
3792
3793         /*
3794          * Load all variables with their compiled-in defaults, and initialize
3795          * status fields as needed.
3796          */
3797         for (i = 0; i < num_guc_variables; i++)
3798         {
3799                 InitializeOneGUCOption(guc_variables[i]);
3800         }
3801
3802         guc_dirty = false;
3803
3804         reporting_enabled = false;
3805
3806         /*
3807          * Prevent any attempt to override the transaction modes from
3808          * non-interactive sources.
3809          */
3810         SetConfigOption("transaction_isolation", "default",
3811                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3812         SetConfigOption("transaction_read_only", "no",
3813                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3814         SetConfigOption("transaction_deferrable", "no",
3815                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3816
3817         /*
3818          * For historical reasons, some GUC parameters can receive defaults from
3819          * environment variables.  Process those settings.
3820          */
3821         InitializeGUCOptionsFromEnvironment();
3822 }
3823
3824 /*
3825  * Assign any GUC values that can come from the server's environment.
3826  *
3827  * This is called from InitializeGUCOptions, and also from ProcessConfigFile
3828  * to deal with the possibility that a setting has been removed from
3829  * postgresql.conf and should now get a value from the environment.
3830  * (The latter is a kludge that should probably go away someday; if so,
3831  * fold this back into InitializeGUCOptions.)
3832  */
3833 static void
3834 InitializeGUCOptionsFromEnvironment(void)
3835 {
3836         char       *env;
3837         long            stack_rlimit;
3838
3839         env = getenv("PGPORT");
3840         if (env != NULL)
3841                 SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3842
3843         env = getenv("PGDATESTYLE");
3844         if (env != NULL)
3845                 SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3846
3847         env = getenv("PGCLIENTENCODING");
3848         if (env != NULL)
3849                 SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3850
3851         /*
3852          * rlimit isn't exactly an "environment variable", but it behaves about
3853          * the same.  If we can identify the platform stack depth rlimit, increase
3854          * default stack depth setting up to whatever is safe (but at most 2MB).
3855          */
3856         stack_rlimit = get_stack_depth_rlimit();
3857         if (stack_rlimit > 0)
3858         {
3859                 long            new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
3860
3861                 if (new_limit > 100)
3862                 {
3863                         char            limbuf[16];
3864
3865                         new_limit = Min(new_limit, 2048);
3866                         sprintf(limbuf, "%ld", new_limit);
3867                         SetConfigOption("max_stack_depth", limbuf,
3868                                                         PGC_POSTMASTER, PGC_S_ENV_VAR);
3869                 }
3870         }
3871 }
3872
3873 /*
3874  * Initialize one GUC option variable to its compiled-in default.
3875  *
3876  * Note: the reason for calling check_hooks is not that we think the boot_val
3877  * might fail, but that the hooks might wish to compute an "extra" struct.
3878  */
3879 static void
3880 InitializeOneGUCOption(struct config_generic * gconf)
3881 {
3882         gconf->status = 0;
3883         gconf->source = PGC_S_DEFAULT;
3884         gconf->reset_source = PGC_S_DEFAULT;
3885         gconf->scontext = PGC_INTERNAL;
3886         gconf->reset_scontext = PGC_INTERNAL;
3887         gconf->stack = NULL;
3888         gconf->extra = NULL;
3889         gconf->sourcefile = NULL;
3890         gconf->sourceline = 0;
3891
3892         switch (gconf->vartype)
3893         {
3894                 case PGC_BOOL:
3895                         {
3896                                 struct config_bool *conf = (struct config_bool *) gconf;
3897                                 bool            newval = conf->boot_val;
3898                                 void       *extra = NULL;
3899
3900                                 if (!call_bool_check_hook(conf, &newval, &extra,
3901                                                                                   PGC_S_DEFAULT, LOG))
3902                                         elog(FATAL, "failed to initialize %s to %d",
3903                                                  conf->gen.name, (int) newval);
3904                                 if (conf->assign_hook)
3905                                         (*conf->assign_hook) (newval, extra);
3906                                 *conf->variable = conf->reset_val = newval;
3907                                 conf->gen.extra = conf->reset_extra = extra;
3908                                 break;
3909                         }
3910                 case PGC_INT:
3911                         {
3912                                 struct config_int *conf = (struct config_int *) gconf;
3913                                 int                     newval = conf->boot_val;
3914                                 void       *extra = NULL;
3915
3916                                 Assert(newval >= conf->min);
3917                                 Assert(newval <= conf->max);
3918                                 if (!call_int_check_hook(conf, &newval, &extra,
3919                                                                                  PGC_S_DEFAULT, LOG))
3920                                         elog(FATAL, "failed to initialize %s to %d",
3921                                                  conf->gen.name, newval);
3922                                 if (conf->assign_hook)
3923                                         (*conf->assign_hook) (newval, extra);
3924                                 *conf->variable = conf->reset_val = newval;
3925                                 conf->gen.extra = conf->reset_extra = extra;
3926                                 break;
3927                         }
3928                 case PGC_REAL:
3929                         {
3930                                 struct config_real *conf = (struct config_real *) gconf;
3931                                 double          newval = conf->boot_val;
3932                                 void       *extra = NULL;
3933
3934                                 Assert(newval >= conf->min);
3935                                 Assert(newval <= conf->max);
3936                                 if (!call_real_check_hook(conf, &newval, &extra,
3937                                                                                   PGC_S_DEFAULT, LOG))
3938                                         elog(FATAL, "failed to initialize %s to %g",
3939                                                  conf->gen.name, newval);
3940                                 if (conf->assign_hook)
3941                                         (*conf->assign_hook) (newval, extra);
3942                                 *conf->variable = conf->reset_val = newval;
3943                                 conf->gen.extra = conf->reset_extra = extra;
3944                                 break;
3945                         }
3946                 case PGC_STRING:
3947                         {
3948                                 struct config_string *conf = (struct config_string *) gconf;
3949                                 char       *newval;
3950                                 void       *extra = NULL;
3951
3952                                 /* non-NULL boot_val must always get strdup'd */
3953                                 if (conf->boot_val != NULL)
3954                                         newval = guc_strdup(FATAL, conf->boot_val);
3955                                 else
3956                                         newval = NULL;
3957
3958                                 if (!call_string_check_hook(conf, &newval, &extra,
3959                                                                                         PGC_S_DEFAULT, LOG))
3960                                         elog(FATAL, "failed to initialize %s to \"%s\"",
3961                                                  conf->gen.name, newval ? newval : "");
3962                                 if (conf->assign_hook)
3963                                         (*conf->assign_hook) (newval, extra);
3964                                 *conf->variable = conf->reset_val = newval;
3965                                 conf->gen.extra = conf->reset_extra = extra;
3966                                 break;
3967                         }
3968                 case PGC_ENUM:
3969                         {
3970                                 struct config_enum *conf = (struct config_enum *) gconf;
3971                                 int                     newval = conf->boot_val;
3972                                 void       *extra = NULL;
3973
3974                                 if (!call_enum_check_hook(conf, &newval, &extra,
3975                                                                                   PGC_S_DEFAULT, LOG))
3976                                         elog(FATAL, "failed to initialize %s to %d",
3977                                                  conf->gen.name, newval);
3978                                 if (conf->assign_hook)
3979                                         (*conf->assign_hook) (newval, extra);
3980                                 *conf->variable = conf->reset_val = newval;
3981                                 conf->gen.extra = conf->reset_extra = extra;
3982                                 break;
3983                         }
3984         }
3985 }
3986
3987
3988 /*
3989  * Select the configuration files and data directory to be used, and
3990  * do the initial read of postgresql.conf.
3991  *
3992  * This is called after processing command-line switches.
3993  *              userDoption is the -D switch value if any (NULL if unspecified).
3994  *              progname is just for use in error messages.
3995  *
3996  * Returns true on success; on failure, prints a suitable error message
3997  * to stderr and returns false.
3998  */
3999 bool
4000 SelectConfigFiles(const char *userDoption, const char *progname)
4001 {
4002         char       *configdir;
4003         char       *fname;
4004         struct stat stat_buf;
4005
4006         /* configdir is -D option, or $PGDATA if no -D */
4007         if (userDoption)
4008                 configdir = make_absolute_path(userDoption);
4009         else
4010                 configdir = make_absolute_path(getenv("PGDATA"));
4011
4012         /*
4013          * Find the configuration file: if config_file was specified on the
4014          * command line, use it, else use configdir/postgresql.conf.  In any case
4015          * ensure the result is an absolute path, so that it will be interpreted
4016          * the same way by future backends.
4017          */
4018         if (ConfigFileName)
4019                 fname = make_absolute_path(ConfigFileName);
4020         else if (configdir)
4021         {
4022                 fname = guc_malloc(FATAL,
4023                                                    strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
4024                 sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
4025         }
4026         else
4027         {
4028                 write_stderr("%s does not know where to find the server configuration file.\n"
4029                                          "You must specify the --config-file or -D invocation "
4030                                          "option or set the PGDATA environment variable.\n",
4031                                          progname);
4032                 return false;
4033         }
4034
4035         /*
4036          * Set the ConfigFileName GUC variable to its final value, ensuring that
4037          * it can't be overridden later.
4038          */
4039         SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4040         free(fname);
4041
4042         /*
4043          * Now read the config file for the first time.
4044          */
4045         if (stat(ConfigFileName, &stat_buf) != 0)
4046         {
4047                 write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
4048                                          progname, ConfigFileName, strerror(errno));
4049                 return false;
4050         }
4051
4052         ProcessConfigFile(PGC_POSTMASTER);
4053
4054         /*
4055          * If the data_directory GUC variable has been set, use that as DataDir;
4056          * otherwise use configdir if set; else punt.
4057          *
4058          * Note: SetDataDir will copy and absolute-ize its argument, so we don't
4059          * have to.
4060          */
4061         if (data_directory)
4062                 SetDataDir(data_directory);
4063         else if (configdir)
4064                 SetDataDir(configdir);
4065         else
4066         {
4067                 write_stderr("%s does not know where to find the database system data.\n"
4068                                          "This can be specified as \"data_directory\" in \"%s\", "
4069                                          "or by the -D invocation option, or by the "
4070                                          "PGDATA environment variable.\n",
4071                                          progname, ConfigFileName);
4072                 return false;
4073         }
4074
4075         /*
4076          * Reflect the final DataDir value back into the data_directory GUC var.
4077          * (If you are wondering why we don't just make them a single variable,
4078          * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
4079          * child backends specially.  XXX is that still true?  Given that we now
4080          * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
4081          * DataDir in advance.)
4082          */
4083         SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
4084
4085         /*
4086          * If timezone_abbreviations wasn't set in the configuration file, install
4087          * the default value.  We do it this way because we can't safely install
4088          * a "real" value until my_exec_path is set, which may not have happened
4089          * when InitializeGUCOptions runs, so the bootstrap default value cannot
4090          * be the real desired default.
4091          */
4092         pg_timezone_abbrev_initialize();
4093
4094         /*
4095          * Figure out where pg_hba.conf is, and make sure the path is absolute.
4096          */
4097         if (HbaFileName)
4098                 fname = make_absolute_path(HbaFileName);
4099         else if (configdir)
4100         {
4101                 fname = guc_malloc(FATAL,
4102                                                    strlen(configdir) + strlen(HBA_FILENAME) + 2);
4103                 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
4104         }
4105         else
4106         {
4107                 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
4108                                          "This can be specified as \"hba_file\" in \"%s\", "
4109                                          "or by the -D invocation option, or by the "
4110                                          "PGDATA environment variable.\n",
4111                                          progname, ConfigFileName);
4112                 return false;
4113         }
4114         SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4115         free(fname);
4116
4117         /*
4118          * Likewise for pg_ident.conf.
4119          */
4120         if (IdentFileName)
4121                 fname = make_absolute_path(IdentFileName);
4122         else if (configdir)
4123         {
4124                 fname = guc_malloc(FATAL,
4125                                                    strlen(configdir) + strlen(IDENT_FILENAME) + 2);
4126                 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
4127         }
4128         else
4129         {
4130                 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
4131                                          "This can be specified as \"ident_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("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4138         free(fname);
4139
4140         free(configdir);
4141
4142         return true;
4143 }
4144
4145
4146 /*
4147  * Reset all options to their saved default values (implements RESET ALL)
4148  */
4149 void
4150 ResetAllOptions(void)
4151 {
4152         int                     i;
4153
4154         for (i = 0; i < num_guc_variables; i++)
4155         {
4156                 struct config_generic *gconf = guc_variables[i];
4157
4158                 /* Don't reset non-SET-able values */
4159                 if (gconf->context != PGC_SUSET &&
4160                         gconf->context != PGC_USERSET)
4161                         continue;
4162                 /* Don't reset if special exclusion from RESET ALL */
4163                 if (gconf->flags & GUC_NO_RESET_ALL)
4164                         continue;
4165                 /* No need to reset if wasn't SET */
4166                 if (gconf->source <= PGC_S_OVERRIDE)
4167                         continue;
4168
4169                 /* Save old value to support transaction abort */
4170                 push_old_value(gconf, GUC_ACTION_SET);
4171
4172                 switch (gconf->vartype)
4173                 {
4174                         case PGC_BOOL:
4175                                 {
4176                                         struct config_bool *conf = (struct config_bool *) gconf;
4177
4178                                         if (conf->assign_hook)
4179                                                 (*conf->assign_hook) (conf->reset_val,
4180                                                                                           conf->reset_extra);
4181                                         *conf->variable = conf->reset_val;
4182                                         set_extra_field(&conf->gen, &conf->gen.extra,
4183                                                                         conf->reset_extra);
4184                                         break;
4185                                 }
4186                         case PGC_INT:
4187                                 {
4188                                         struct config_int *conf = (struct config_int *) gconf;
4189
4190                                         if (conf->assign_hook)
4191                                                 (*conf->assign_hook) (conf->reset_val,
4192                                                                                           conf->reset_extra);
4193                                         *conf->variable = conf->reset_val;
4194                                         set_extra_field(&conf->gen, &conf->gen.extra,
4195                                                                         conf->reset_extra);
4196                                         break;
4197                                 }
4198                         case PGC_REAL:
4199                                 {
4200                                         struct config_real *conf = (struct config_real *) gconf;
4201
4202                                         if (conf->assign_hook)
4203                                                 (*conf->assign_hook) (conf->reset_val,
4204                                                                                           conf->reset_extra);
4205                                         *conf->variable = conf->reset_val;
4206                                         set_extra_field(&conf->gen, &conf->gen.extra,
4207                                                                         conf->reset_extra);
4208                                         break;
4209                                 }
4210                         case PGC_STRING:
4211                                 {
4212                                         struct config_string *conf = (struct config_string *) gconf;
4213
4214                                         if (conf->assign_hook)
4215                                                 (*conf->assign_hook) (conf->reset_val,
4216                                                                                           conf->reset_extra);
4217                                         set_string_field(conf, conf->variable, conf->reset_val);
4218                                         set_extra_field(&conf->gen, &conf->gen.extra,
4219                                                                         conf->reset_extra);
4220                                         break;
4221                                 }
4222                         case PGC_ENUM:
4223                                 {
4224                                         struct config_enum *conf = (struct config_enum *) gconf;
4225
4226                                         if (conf->assign_hook)
4227                                                 (*conf->assign_hook) (conf->reset_val,
4228                                                                                           conf->reset_extra);
4229                                         *conf->variable = conf->reset_val;
4230                                         set_extra_field(&conf->gen, &conf->gen.extra,
4231                                                                         conf->reset_extra);
4232                                         break;
4233                                 }
4234                 }
4235
4236                 gconf->source = gconf->reset_source;
4237                 gconf->scontext = gconf->reset_scontext;
4238
4239                 if (gconf->flags & GUC_REPORT)
4240                         ReportGUCOption(gconf);
4241         }
4242 }
4243
4244
4245 /*
4246  * push_old_value
4247  *              Push previous state during transactional assignment to a GUC variable.
4248  */
4249 static void
4250 push_old_value(struct config_generic * gconf, GucAction action)
4251 {
4252         GucStack   *stack;
4253
4254         /* If we're not inside a nest level, do nothing */
4255         if (GUCNestLevel == 0)
4256                 return;
4257
4258         /* Do we already have a stack entry of the current nest level? */
4259         stack = gconf->stack;
4260         if (stack && stack->nest_level >= GUCNestLevel)
4261         {
4262                 /* Yes, so adjust its state if necessary */
4263                 Assert(stack->nest_level == GUCNestLevel);
4264                 switch (action)
4265                 {
4266                         case GUC_ACTION_SET:
4267                                 /* SET overrides any prior action at same nest level */
4268                                 if (stack->state == GUC_SET_LOCAL)
4269                                 {
4270                                         /* must discard old masked value */
4271                                         discard_stack_value(gconf, &stack->masked);
4272                                 }
4273                                 stack->state = GUC_SET;
4274                                 break;
4275                         case GUC_ACTION_LOCAL:
4276                                 if (stack->state == GUC_SET)
4277                                 {
4278                                         /* SET followed by SET LOCAL, remember SET's value */
4279                                         stack->masked_scontext = gconf->scontext;
4280                                         set_stack_value(gconf, &stack->masked);
4281                                         stack->state = GUC_SET_LOCAL;
4282                                 }
4283                                 /* in all other cases, no change to stack entry */
4284                                 break;
4285                         case GUC_ACTION_SAVE:
4286                                 /* Could only have a prior SAVE of same variable */
4287                                 Assert(stack->state == GUC_SAVE);
4288                                 break;
4289                 }
4290                 Assert(guc_dirty);              /* must be set already */
4291                 return;
4292         }
4293
4294         /*
4295          * Push a new stack entry
4296          *
4297          * We keep all the stack entries in TopTransactionContext for simplicity.
4298          */
4299         stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
4300                                                                                                 sizeof(GucStack));
4301
4302         stack->prev = gconf->stack;
4303         stack->nest_level = GUCNestLevel;
4304         switch (action)
4305         {
4306                 case GUC_ACTION_SET:
4307                         stack->state = GUC_SET;
4308                         break;
4309                 case GUC_ACTION_LOCAL:
4310                         stack->state = GUC_LOCAL;
4311                         break;
4312                 case GUC_ACTION_SAVE:
4313                         stack->state = GUC_SAVE;
4314                         break;
4315         }
4316         stack->source = gconf->source;
4317         stack->scontext = gconf->scontext;
4318         set_stack_value(gconf, &stack->prior);
4319
4320         gconf->stack = stack;
4321
4322         /* Ensure we remember to pop at end of xact */
4323         guc_dirty = true;
4324 }
4325
4326
4327 /*
4328  * Do GUC processing at main transaction start.
4329  */
4330 void
4331 AtStart_GUC(void)
4332 {
4333         /*
4334          * The nest level should be 0 between transactions; if it isn't, somebody
4335          * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
4336          * throw a warning but make no other effort to clean up.
4337          */
4338         if (GUCNestLevel != 0)
4339                 elog(WARNING, "GUC nest level = %d at transaction start",
4340                          GUCNestLevel);
4341         GUCNestLevel = 1;
4342 }
4343
4344 /*
4345  * Enter a new nesting level for GUC values.  This is called at subtransaction
4346  * start, and when entering a function that has proconfig settings, and in
4347  * some other places where we want to set GUC variables transiently.
4348  * NOTE we must not risk error here, else subtransaction start will be unhappy.
4349  */
4350 int
4351 NewGUCNestLevel(void)
4352 {
4353         return ++GUCNestLevel;
4354 }
4355
4356 /*
4357  * Do GUC processing at transaction or subtransaction commit or abort, or
4358  * when exiting a function that has proconfig settings, or when undoing a
4359  * transient assignment to some GUC variables.  (The name is thus a bit of
4360  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
4361  * During abort, we discard all GUC settings that were applied at nesting
4362  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
4363  */
4364 void
4365 AtEOXact_GUC(bool isCommit, int nestLevel)
4366 {
4367         bool            still_dirty;
4368         int                     i;
4369
4370         /*
4371          * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
4372          * abort, if there is a failure during transaction start before
4373          * AtStart_GUC is called.
4374          */
4375         Assert(nestLevel > 0 &&
4376                    (nestLevel <= GUCNestLevel ||
4377                         (nestLevel == GUCNestLevel + 1 && !isCommit)));
4378
4379         /* Quick exit if nothing's changed in this transaction */
4380         if (!guc_dirty)
4381         {
4382                 GUCNestLevel = nestLevel - 1;
4383                 return;
4384         }
4385
4386         still_dirty = false;
4387         for (i = 0; i < num_guc_variables; i++)
4388         {
4389                 struct config_generic *gconf = guc_variables[i];
4390                 GucStack   *stack;
4391
4392                 /*
4393                  * Process and pop each stack entry within the nest level. To simplify
4394                  * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
4395                  * we allow failure exit from code that uses a local nest level to be
4396                  * recovered at the surrounding transaction or subtransaction abort;
4397                  * so there could be more than one stack entry to pop.
4398                  */
4399                 while ((stack = gconf->stack) != NULL &&
4400                            stack->nest_level >= nestLevel)
4401                 {
4402                         GucStack   *prev = stack->prev;
4403                         bool            restorePrior = false;
4404                         bool            restoreMasked = false;
4405                         bool            changed;
4406
4407                         /*
4408                          * In this next bit, if we don't set either restorePrior or
4409                          * restoreMasked, we must "discard" any unwanted fields of the
4410                          * stack entries to avoid leaking memory.  If we do set one of
4411                          * those flags, unused fields will be cleaned up after restoring.
4412                          */
4413                         if (!isCommit)          /* if abort, always restore prior value */
4414                                 restorePrior = true;
4415                         else if (stack->state == GUC_SAVE)
4416                                 restorePrior = true;
4417                         else if (stack->nest_level == 1)
4418                         {
4419                                 /* transaction commit */
4420                                 if (stack->state == GUC_SET_LOCAL)
4421                                         restoreMasked = true;
4422                                 else if (stack->state == GUC_SET)
4423                                 {
4424                                         /* we keep the current active value */
4425                                         discard_stack_value(gconf, &stack->prior);
4426                                 }
4427                                 else    /* must be GUC_LOCAL */
4428                                         restorePrior = true;
4429                         }
4430                         else if (prev == NULL ||
4431                                          prev->nest_level < stack->nest_level - 1)
4432                         {
4433                                 /* decrement entry's level and do not pop it */
4434                                 stack->nest_level--;
4435                                 continue;
4436                         }
4437                         else
4438                         {
4439                                 /*
4440                                  * We have to merge this stack entry into prev. See README for
4441                                  * discussion of this bit.
4442                                  */
4443                                 switch (stack->state)
4444                                 {
4445                                         case GUC_SAVE:
4446                                                 Assert(false);  /* can't get here */
4447
4448                                         case GUC_SET:
4449                                                 /* next level always becomes SET */
4450                                                 discard_stack_value(gconf, &stack->prior);
4451                                                 if (prev->state == GUC_SET_LOCAL)
4452                                                         discard_stack_value(gconf, &prev->masked);
4453                                                 prev->state = GUC_SET;
4454                                                 break;
4455
4456                                         case GUC_LOCAL:
4457                                                 if (prev->state == GUC_SET)
4458                                                 {
4459                                                         /* LOCAL migrates down */
4460                                                         prev->masked_scontext = stack->scontext;
4461                                                         prev->masked = stack->prior;
4462                                                         prev->state = GUC_SET_LOCAL;
4463                                                 }
4464                                                 else
4465                                                 {
4466                                                         /* else just forget this stack level */
4467                                                         discard_stack_value(gconf, &stack->prior);
4468                                                 }
4469                                                 break;
4470
4471                                         case GUC_SET_LOCAL:
4472                                                 /* prior state at this level no longer wanted */
4473                                                 discard_stack_value(gconf, &stack->prior);
4474                                                 /* copy down the masked state */
4475                                                 prev->masked_scontext = stack->masked_scontext;
4476                                                 if (prev->state == GUC_SET_LOCAL)
4477                                                         discard_stack_value(gconf, &prev->masked);
4478                                                 prev->masked = stack->masked;
4479                                                 prev->state = GUC_SET_LOCAL;
4480                                                 break;
4481                                 }
4482                         }
4483
4484                         changed = false;
4485
4486                         if (restorePrior || restoreMasked)
4487                         {
4488                                 /* Perform appropriate restoration of the stacked value */
4489                                 config_var_value newvalue;
4490                                 GucSource       newsource;
4491                                 GucContext      newscontext;
4492
4493                                 if (restoreMasked)
4494                                 {
4495                                         newvalue = stack->masked;
4496                                         newsource = PGC_S_SESSION;
4497                                         newscontext = stack->masked_scontext;
4498                                 }
4499                                 else
4500                                 {
4501                                         newvalue = stack->prior;
4502                                         newsource = stack->source;
4503                                         newscontext = stack->scontext;
4504                                 }
4505
4506                                 switch (gconf->vartype)
4507                                 {
4508                                         case PGC_BOOL:
4509                                                 {
4510                                                         struct config_bool *conf = (struct config_bool *) gconf;
4511                                                         bool            newval = newvalue.val.boolval;
4512                                                         void       *newextra = newvalue.extra;
4513
4514                                                         if (*conf->variable != newval ||
4515                                                                 conf->gen.extra != newextra)
4516                                                         {
4517                                                                 if (conf->assign_hook)
4518                                                                         (*conf->assign_hook) (newval, newextra);
4519                                                                 *conf->variable = newval;
4520                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4521                                                                                                 newextra);
4522                                                                 changed = true;
4523                                                         }
4524                                                         break;
4525                                                 }
4526                                         case PGC_INT:
4527                                                 {
4528                                                         struct config_int *conf = (struct config_int *) gconf;
4529                                                         int                     newval = newvalue.val.intval;
4530                                                         void       *newextra = newvalue.extra;
4531
4532                                                         if (*conf->variable != newval ||
4533                                                                 conf->gen.extra != newextra)
4534                                                         {
4535                                                                 if (conf->assign_hook)
4536                                                                         (*conf->assign_hook) (newval, newextra);
4537                                                                 *conf->variable = newval;
4538                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4539                                                                                                 newextra);
4540                                                                 changed = true;
4541                                                         }
4542                                                         break;
4543                                                 }
4544                                         case PGC_REAL:
4545                                                 {
4546                                                         struct config_real *conf = (struct config_real *) gconf;
4547                                                         double          newval = newvalue.val.realval;
4548                                                         void       *newextra = newvalue.extra;
4549
4550                                                         if (*conf->variable != newval ||
4551                                                                 conf->gen.extra != newextra)
4552                                                         {
4553                                                                 if (conf->assign_hook)
4554                                                                         (*conf->assign_hook) (newval, newextra);
4555                                                                 *conf->variable = newval;
4556                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4557                                                                                                 newextra);
4558                                                                 changed = true;
4559                                                         }
4560                                                         break;
4561                                                 }
4562                                         case PGC_STRING:
4563                                                 {
4564                                                         struct config_string *conf = (struct config_string *) gconf;
4565                                                         char       *newval = newvalue.val.stringval;
4566                                                         void       *newextra = newvalue.extra;
4567
4568                                                         if (*conf->variable != newval ||
4569                                                                 conf->gen.extra != newextra)
4570                                                         {
4571                                                                 if (conf->assign_hook)
4572                                                                         (*conf->assign_hook) (newval, newextra);
4573                                                                 set_string_field(conf, conf->variable, newval);
4574                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4575                                                                                                 newextra);
4576                                                                 changed = true;
4577                                                         }
4578
4579                                                         /*
4580                                                          * Release stacked values if not used anymore. We
4581                                                          * could use discard_stack_value() here, but since
4582                                                          * we have type-specific code anyway, might as
4583                                                          * well inline it.
4584                                                          */
4585                                                         set_string_field(conf, &stack->prior.val.stringval, NULL);
4586                                                         set_string_field(conf, &stack->masked.val.stringval, NULL);
4587                                                         break;
4588                                                 }
4589                                         case PGC_ENUM:
4590                                                 {
4591                                                         struct config_enum *conf = (struct config_enum *) gconf;
4592                                                         int                     newval = newvalue.val.enumval;
4593                                                         void       *newextra = newvalue.extra;
4594
4595                                                         if (*conf->variable != newval ||
4596                                                                 conf->gen.extra != newextra)
4597                                                         {
4598                                                                 if (conf->assign_hook)
4599                                                                         (*conf->assign_hook) (newval, newextra);
4600                                                                 *conf->variable = newval;
4601                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4602                                                                                                 newextra);
4603                                                                 changed = true;
4604                                                         }
4605                                                         break;
4606                                                 }
4607                                 }
4608
4609                                 /*
4610                                  * Release stacked extra values if not used anymore.
4611                                  */
4612                                 set_extra_field(gconf, &(stack->prior.extra), NULL);
4613                                 set_extra_field(gconf, &(stack->masked.extra), NULL);
4614
4615                                 /* And restore source information */
4616                                 gconf->source = newsource;
4617                                 gconf->scontext = newscontext;
4618                         }
4619
4620                         /* Finish popping the state stack */
4621                         gconf->stack = prev;
4622                         pfree(stack);
4623
4624                         /* Report new value if we changed it */
4625                         if (changed && (gconf->flags & GUC_REPORT))
4626                                 ReportGUCOption(gconf);
4627                 }                                               /* end of stack-popping loop */
4628
4629                 if (stack != NULL)
4630                         still_dirty = true;
4631         }
4632
4633         /* If there are no remaining stack entries, we can reset guc_dirty */
4634         guc_dirty = still_dirty;
4635
4636         /* Update nesting level */
4637         GUCNestLevel = nestLevel - 1;
4638 }
4639
4640
4641 /*
4642  * Start up automatic reporting of changes to variables marked GUC_REPORT.
4643  * This is executed at completion of backend startup.
4644  */
4645 void
4646 BeginReportingGUCOptions(void)
4647 {
4648         int                     i;
4649
4650         /*
4651          * Don't do anything unless talking to an interactive frontend of protocol
4652          * 3.0 or later.
4653          */
4654         if (whereToSendOutput != DestRemote ||
4655                 PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
4656                 return;
4657
4658         reporting_enabled = true;
4659
4660         /* Transmit initial values of interesting variables */
4661         for (i = 0; i < num_guc_variables; i++)
4662         {
4663                 struct config_generic *conf = guc_variables[i];
4664
4665                 if (conf->flags & GUC_REPORT)
4666                         ReportGUCOption(conf);
4667         }
4668 }
4669
4670 /*
4671  * ReportGUCOption: if appropriate, transmit option value to frontend
4672  */
4673 static void
4674 ReportGUCOption(struct config_generic * record)
4675 {
4676         if (reporting_enabled && (record->flags & GUC_REPORT))
4677         {
4678                 char       *val = _ShowOption(record, false);
4679                 StringInfoData msgbuf;
4680
4681                 pq_beginmessage(&msgbuf, 'S');
4682                 pq_sendstring(&msgbuf, record->name);
4683                 pq_sendstring(&msgbuf, val);
4684                 pq_endmessage(&msgbuf);
4685
4686                 pfree(val);
4687         }
4688 }
4689
4690 /*
4691  * Try to parse value as an integer.  The accepted formats are the
4692  * usual decimal, octal, or hexadecimal formats, optionally followed by
4693  * a unit name if "flags" indicates a unit is allowed.
4694  *
4695  * If the string parses okay, return true, else false.
4696  * If okay and result is not NULL, return the value in *result.
4697  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
4698  *      HINT message, or NULL if no hint provided.
4699  */
4700 bool
4701 parse_int(const char *value, int *result, int flags, const char **hintmsg)
4702 {
4703         int64           val;
4704         char       *endptr;
4705
4706         /* To suppress compiler warnings, always set output params */
4707         if (result)
4708                 *result = 0;
4709         if (hintmsg)
4710                 *hintmsg = NULL;
4711
4712         /* We assume here that int64 is at least as wide as long */
4713         errno = 0;
4714         val = strtol(value, &endptr, 0);
4715
4716         if (endptr == value)
4717                 return false;                   /* no HINT for integer syntax error */
4718
4719         if (errno == ERANGE || val != (int64) ((int32) val))
4720         {
4721                 if (hintmsg)
4722                         *hintmsg = gettext_noop("Value exceeds integer range.");
4723                 return false;
4724         }
4725
4726         /* allow whitespace between integer and unit */
4727         while (isspace((unsigned char) *endptr))
4728                 endptr++;
4729
4730         /* Handle possible unit */
4731         if (*endptr != '\0')
4732         {
4733                 /*
4734                  * Note: the multiple-switch coding technique here is a bit tedious,
4735                  * but seems necessary to avoid intermediate-value overflows.
4736                  */
4737                 if (flags & GUC_UNIT_MEMORY)
4738                 {
4739                         /* Set hint for use if no match or trailing garbage */
4740                         if (hintmsg)
4741                                 *hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");
4742
4743 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
4744 #error BLCKSZ must be between 1KB and 1MB
4745 #endif
4746 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
4747 #error XLOG_BLCKSZ must be between 1KB and 1MB
4748 #endif
4749
4750                         if (strncmp(endptr, "kB", 2) == 0)
4751                         {
4752                                 endptr += 2;
4753                                 switch (flags & GUC_UNIT_MEMORY)
4754                                 {
4755                                         case GUC_UNIT_BLOCKS:
4756                                                 val /= (BLCKSZ / 1024);
4757                                                 break;
4758                                         case GUC_UNIT_XBLOCKS:
4759                                                 val /= (XLOG_BLCKSZ / 1024);
4760                                                 break;
4761                                 }
4762                         }
4763                         else if (strncmp(endptr, "MB", 2) == 0)
4764                         {
4765                                 endptr += 2;
4766                                 switch (flags & GUC_UNIT_MEMORY)
4767                                 {
4768                                         case GUC_UNIT_KB:
4769                                                 val *= KB_PER_MB;
4770                                                 break;
4771                                         case GUC_UNIT_BLOCKS:
4772                                                 val *= KB_PER_MB / (BLCKSZ / 1024);
4773                                                 break;
4774                                         case GUC_UNIT_XBLOCKS:
4775                                                 val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
4776                                                 break;
4777                                 }
4778                         }
4779                         else if (strncmp(endptr, "GB", 2) == 0)
4780                         {
4781                                 endptr += 2;
4782                                 switch (flags & GUC_UNIT_MEMORY)
4783                                 {
4784                                         case GUC_UNIT_KB:
4785                                                 val *= KB_PER_GB;
4786                                                 break;
4787                                         case GUC_UNIT_BLOCKS:
4788                                                 val *= KB_PER_GB / (BLCKSZ / 1024);
4789                                                 break;
4790                                         case GUC_UNIT_XBLOCKS:
4791                                                 val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
4792                                                 break;
4793                                 }
4794                         }
4795                 }
4796                 else if (flags & GUC_UNIT_TIME)
4797                 {
4798                         /* Set hint for use if no match or trailing garbage */
4799                         if (hintmsg)
4800                                 *hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
4801
4802                         if (strncmp(endptr, "ms", 2) == 0)
4803                         {
4804                                 endptr += 2;
4805                                 switch (flags & GUC_UNIT_TIME)
4806                                 {
4807                                         case GUC_UNIT_S:
4808                                                 val /= MS_PER_S;
4809                                                 break;
4810                                         case GUC_UNIT_MIN:
4811                                                 val /= MS_PER_MIN;
4812                                                 break;
4813                                 }
4814                         }
4815                         else if (strncmp(endptr, "s", 1) == 0)
4816                         {
4817                                 endptr += 1;
4818                                 switch (flags & GUC_UNIT_TIME)
4819                                 {
4820                                         case GUC_UNIT_MS:
4821                                                 val *= MS_PER_S;
4822                                                 break;
4823                                         case GUC_UNIT_MIN:
4824                                                 val /= S_PER_MIN;
4825                                                 break;
4826                                 }
4827                         }
4828                         else if (strncmp(endptr, "min", 3) == 0)
4829                         {
4830                                 endptr += 3;
4831                                 switch (flags & GUC_UNIT_TIME)
4832                                 {
4833                                         case GUC_UNIT_MS:
4834                                                 val *= MS_PER_MIN;
4835                                                 break;
4836                                         case GUC_UNIT_S:
4837                                                 val *= S_PER_MIN;
4838                                                 break;
4839                                 }
4840                         }
4841                         else if (strncmp(endptr, "h", 1) == 0)
4842                         {
4843                                 endptr += 1;
4844                                 switch (flags & GUC_UNIT_TIME)
4845                                 {
4846                                         case GUC_UNIT_MS:
4847                                                 val *= MS_PER_H;
4848                                                 break;
4849                                         case GUC_UNIT_S:
4850                                                 val *= S_PER_H;
4851                                                 break;
4852                                         case GUC_UNIT_MIN:
4853                                                 val *= MIN_PER_H;
4854                                                 break;
4855                                 }
4856                         }
4857                         else if (strncmp(endptr, "d", 1) == 0)
4858                         {
4859                                 endptr += 1;
4860                                 switch (flags & GUC_UNIT_TIME)
4861                                 {
4862                                         case GUC_UNIT_MS:
4863                                                 val *= MS_PER_D;
4864                                                 break;
4865                                         case GUC_UNIT_S:
4866                                                 val *= S_PER_D;
4867                                                 break;
4868                                         case GUC_UNIT_MIN:
4869                                                 val *= MIN_PER_D;
4870                                                 break;
4871                                 }
4872                         }
4873                 }
4874
4875                 /* allow whitespace after unit */
4876                 while (isspace((unsigned char) *endptr))
4877                         endptr++;
4878
4879                 if (*endptr != '\0')
4880                         return false;           /* appropriate hint, if any, already set */
4881
4882                 /* Check for overflow due to units conversion */
4883                 if (val != (int64) ((int32) val))
4884                 {
4885                         if (hintmsg)
4886                                 *hintmsg = gettext_noop("Value exceeds integer range.");
4887                         return false;
4888                 }
4889         }
4890
4891         if (result)
4892                 *result = (int) val;
4893         return true;
4894 }
4895
4896
4897
4898 /*
4899  * Try to parse value as a floating point number in the usual format.
4900  * If the string parses okay, return true, else false.
4901  * If okay and result is not NULL, return the value in *result.
4902  */
4903 bool
4904 parse_real(const char *value, double *result)
4905 {
4906         double          val;
4907         char       *endptr;
4908
4909         if (result)
4910                 *result = 0;                    /* suppress compiler warning */
4911
4912         errno = 0;
4913         val = strtod(value, &endptr);
4914         if (endptr == value || errno == ERANGE)
4915                 return false;
4916
4917         /* allow whitespace after number */
4918         while (isspace((unsigned char) *endptr))
4919                 endptr++;
4920         if (*endptr != '\0')
4921                 return false;
4922
4923         if (result)
4924                 *result = val;
4925         return true;
4926 }
4927
4928
4929 /*
4930  * Lookup the name for an enum option with the selected value.
4931  * Should only ever be called with known-valid values, so throws
4932  * an elog(ERROR) if the enum option is not found.
4933  *
4934  * The returned string is a pointer to static data and not
4935  * allocated for modification.
4936  */
4937 const char *
4938 config_enum_lookup_by_value(struct config_enum * record, int val)
4939 {
4940         const struct config_enum_entry *entry;
4941
4942         for (entry = record->options; entry && entry->name; entry++)
4943         {
4944                 if (entry->val == val)
4945                         return entry->name;
4946         }
4947
4948         elog(ERROR, "could not find enum option %d for %s",
4949                  val, record->gen.name);
4950         return NULL;                            /* silence compiler */
4951 }
4952
4953
4954 /*
4955  * Lookup the value for an enum option with the selected name
4956  * (case-insensitive).
4957  * If the enum option is found, sets the retval value and returns
4958  * true. If it's not found, return FALSE and retval is set to 0.
4959  */
4960 bool
4961 config_enum_lookup_by_name(struct config_enum * record, const char *value,
4962                                                    int *retval)
4963 {
4964         const struct config_enum_entry *entry;
4965
4966         for (entry = record->options; entry && entry->name; entry++)
4967         {
4968                 if (pg_strcasecmp(value, entry->name) == 0)
4969                 {
4970                         *retval = entry->val;
4971                         return TRUE;
4972                 }
4973         }
4974
4975         *retval = 0;
4976         return FALSE;
4977 }
4978
4979
4980 /*
4981  * Return a list of all available options for an enum, excluding
4982  * hidden ones, separated by the given separator.
4983  * If prefix is non-NULL, it is added before the first enum value.
4984  * If suffix is non-NULL, it is added to the end of the string.
4985  */
4986 static char *
4987 config_enum_get_options(struct config_enum * record, const char *prefix,
4988                                                 const char *suffix, const char *separator)
4989 {
4990         const struct config_enum_entry *entry;
4991         StringInfoData retstr;
4992         int                     seplen;
4993
4994         initStringInfo(&retstr);
4995         appendStringInfoString(&retstr, prefix);
4996
4997         seplen = strlen(separator);
4998         for (entry = record->options; entry && entry->name; entry++)
4999         {
5000                 if (!entry->hidden)
5001                 {
5002                         appendStringInfoString(&retstr, entry->name);
5003                         appendBinaryStringInfo(&retstr, separator, seplen);
5004                 }
5005         }
5006
5007         /*
5008          * All the entries may have been hidden, leaving the string empty if no
5009          * prefix was given. This indicates a broken GUC setup, since there is no
5010          * use for an enum without any values, so we just check to make sure we
5011          * don't write to invalid memory instead of actually trying to do
5012          * something smart with it.
5013          */
5014         if (retstr.len >= seplen)
5015         {
5016                 /* Replace final separator */
5017                 retstr.data[retstr.len - seplen] = '\0';
5018                 retstr.len -= seplen;
5019         }
5020
5021         appendStringInfoString(&retstr, suffix);
5022
5023         return retstr.data;
5024 }
5025
5026
5027 /*
5028  * Sets option `name' to given value.
5029  *
5030  * The value should be a string, which will be parsed and converted to
5031  * the appropriate data type.  The context and source parameters indicate
5032  * in which context this function is being called, so that it can apply the
5033  * access restrictions properly.
5034  *
5035  * If value is NULL, set the option to its default value (normally the
5036  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
5037  *
5038  * action indicates whether to set the value globally in the session, locally
5039  * to the current top transaction, or just for the duration of a function call.
5040  *
5041  * If changeVal is false then don't really set the option but do all
5042  * the checks to see if it would work.
5043  *
5044  * elevel should normally be passed as zero, allowing this function to make
5045  * its standard choice of ereport level.  However some callers need to be
5046  * able to override that choice; they should pass the ereport level to use.
5047  *
5048  * Return value:
5049  *      +1: the value is valid and was successfully applied.
5050  *      0:  the name or value is invalid (but see below).
5051  *      -1: the value was not applied because of context, priority, or changeVal.
5052  *
5053  * If there is an error (non-existing option, invalid value) then an
5054  * ereport(ERROR) is thrown *unless* this is called for a source for which
5055  * we don't want an ERROR (currently, those are defaults, the config file,
5056  * and per-database or per-user settings, as well as callers who specify
5057  * a less-than-ERROR elevel).  In those cases we write a suitable error
5058  * message via ereport() and return 0.
5059  *
5060  * See also SetConfigOption for an external interface.
5061  */
5062 int
5063 set_config_option(const char *name, const char *value,
5064                                   GucContext context, GucSource source,
5065                                   GucAction action, bool changeVal, int elevel)
5066 {
5067         struct config_generic *record;
5068         bool            prohibitValueChange = false;
5069         bool            makeDefault;
5070
5071         if (elevel == 0)
5072         {
5073                 if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
5074                 {
5075                         /*
5076                          * To avoid cluttering the log, only the postmaster bleats loudly
5077                          * about problems with the config file.
5078                          */
5079                         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5080                 }
5081                 else if (source == PGC_S_DATABASE || source == PGC_S_USER ||
5082                                  source == PGC_S_DATABASE_USER)
5083                         elevel = WARNING;
5084                 else
5085                         elevel = ERROR;
5086         }
5087
5088         record = find_option(name, true, elevel);
5089         if (record == NULL)
5090         {
5091                 ereport(elevel,
5092                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5093                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5094                 return 0;
5095         }
5096
5097         /*
5098          * Check if the option can be set at this time. See guc.h for the precise
5099          * rules.
5100          */
5101         switch (record->context)
5102         {
5103                 case PGC_INTERNAL:
5104                         if (context != PGC_INTERNAL)
5105                         {
5106                                 ereport(elevel,
5107                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5108                                                  errmsg("parameter \"%s\" cannot be changed",
5109                                                                 name)));
5110                                 return 0;
5111                         }
5112                         break;
5113                 case PGC_POSTMASTER:
5114                         if (context == PGC_SIGHUP)
5115                         {
5116                                 /*
5117                                  * We are re-reading a PGC_POSTMASTER variable from
5118                                  * postgresql.conf.  We can't change the setting, so we should
5119                                  * give a warning if the DBA tries to change it.  However,
5120                                  * because of variant formats, canonicalization by check
5121                                  * hooks, etc, we can't just compare the given string directly
5122                                  * to what's stored.  Set a flag to check below after we have
5123                                  * the final storable value.
5124                                  */
5125                                 prohibitValueChange = true;
5126                         }
5127                         else if (context != PGC_POSTMASTER)
5128                         {
5129                                 ereport(elevel,
5130                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5131                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5132                                                                 name)));
5133                                 return 0;
5134                         }
5135                         break;
5136                 case PGC_SIGHUP:
5137                         if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
5138                         {
5139                                 ereport(elevel,
5140                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5141                                                  errmsg("parameter \"%s\" cannot be changed now",
5142                                                                 name)));
5143                                 return 0;
5144                         }
5145
5146                         /*
5147                          * Hmm, the idea of the SIGHUP context is "ought to be global, but
5148                          * can be changed after postmaster start". But there's nothing
5149                          * that prevents a crafty administrator from sending SIGHUP
5150                          * signals to individual backends only.
5151                          */
5152                         break;
5153                 case PGC_BACKEND:
5154                         if (context == PGC_SIGHUP)
5155                         {
5156                                 /*
5157                                  * If a PGC_BACKEND parameter is changed in the config file,
5158                                  * we want to accept the new value in the postmaster (whence
5159                                  * it will propagate to subsequently-started backends), but
5160                                  * ignore it in existing backends.      This is a tad klugy, but
5161                                  * necessary because we don't re-read the config file during
5162                                  * backend start.
5163                                  */
5164                                 if (IsUnderPostmaster)
5165                                         return -1;
5166                         }
5167                         else if (context != PGC_POSTMASTER && context != PGC_BACKEND &&
5168                                          source != PGC_S_CLIENT)
5169                         {
5170                                 ereport(elevel,
5171                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5172                                                  errmsg("parameter \"%s\" cannot be set after connection start",
5173                                                                 name)));
5174                                 return 0;
5175                         }
5176                         break;
5177                 case PGC_SUSET:
5178                         if (context == PGC_USERSET || context == PGC_BACKEND)
5179                         {
5180                                 ereport(elevel,
5181                                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5182                                                  errmsg("permission denied to set parameter \"%s\"",
5183                                                                 name)));
5184                                 return 0;
5185                         }
5186                         break;
5187                 case PGC_USERSET:
5188                         /* always okay */
5189                         break;
5190         }
5191
5192         /*
5193          * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
5194          * security restriction context.  We can reject this regardless of the GUC
5195          * context or source, mainly because sources that it might be reasonable
5196          * to override for won't be seen while inside a function.
5197          *
5198          * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
5199          * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
5200          * An exception might be made if the reset value is assumed to be "safe".
5201          *
5202          * Note: this flag is currently used for "session_authorization" and
5203          * "role".      We need to prohibit changing these inside a local userid
5204          * context because when we exit it, GUC won't be notified, leaving things
5205          * out of sync.  (This could be fixed by forcing a new GUC nesting level,
5206          * but that would change behavior in possibly-undesirable ways.)  Also, we
5207          * prohibit changing these in a security-restricted operation because
5208          * otherwise RESET could be used to regain the session user's privileges.
5209          */
5210         if (record->flags & GUC_NOT_WHILE_SEC_REST)
5211         {
5212                 if (InLocalUserIdChange())
5213                 {
5214                         /*
5215                          * Phrasing of this error message is historical, but it's the most
5216                          * common case.
5217                          */
5218                         ereport(elevel,
5219                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5220                                          errmsg("cannot set parameter \"%s\" within security-definer function",
5221                                                         name)));
5222                         return 0;
5223                 }
5224                 if (InSecurityRestrictedOperation())
5225                 {
5226                         ereport(elevel,
5227                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5228                                          errmsg("cannot set parameter \"%s\" within security-restricted operation",
5229                                                         name)));
5230                         return 0;
5231                 }
5232         }
5233
5234         /*
5235          * Should we set reset/stacked values?  (If so, the behavior is not
5236          * transactional.)      This is done either when we get a default value from
5237          * the database's/user's/client's default settings or when we reset a
5238          * value to its default.
5239          */
5240         makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
5241                 ((value != NULL) || source == PGC_S_DEFAULT);
5242
5243         /*
5244          * Ignore attempted set if overridden by previously processed setting.
5245          * However, if changeVal is false then plow ahead anyway since we are
5246          * trying to find out if the value is potentially good, not actually use
5247          * it. Also keep going if makeDefault is true, since we may want to set
5248          * the reset/stacked values even if we can't set the variable itself.
5249          */
5250         if (record->source > source)
5251         {
5252                 if (changeVal && !makeDefault)
5253                 {
5254                         elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
5255                                  name);
5256                         return -1;
5257                 }
5258                 changeVal = false;
5259         }
5260
5261         /*
5262          * Evaluate value and set variable.
5263          */
5264         switch (record->vartype)
5265         {
5266                 case PGC_BOOL:
5267                         {
5268                                 struct config_bool *conf = (struct config_bool *) record;
5269                                 bool            newval;
5270                                 void       *newextra = NULL;
5271
5272                                 if (value)
5273                                 {
5274                                         if (!parse_bool(value, &newval))
5275                                         {
5276                                                 ereport(elevel,
5277                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5278                                                   errmsg("parameter \"%s\" requires a Boolean value",
5279                                                                  name)));
5280                                                 return 0;
5281                                         }
5282                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5283                                                                                           source, elevel))
5284                                                 return 0;
5285                                 }
5286                                 else if (source == PGC_S_DEFAULT)
5287                                 {
5288                                         newval = conf->boot_val;
5289                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5290                                                                                           source, elevel))
5291                                                 return 0;
5292                                 }
5293                                 else
5294                                 {
5295                                         newval = conf->reset_val;
5296                                         newextra = conf->reset_extra;
5297                                         source = conf->gen.reset_source;
5298                                         context = conf->gen.reset_scontext;
5299                                 }
5300
5301                                 if (prohibitValueChange)
5302                                 {
5303                                         if (*conf->variable != newval)
5304                                         {
5305                                                 ereport(elevel,
5306                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5307                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5308                                                                                 name)));
5309                                                 return 0;
5310                                         }
5311                                         return -1;
5312                                 }
5313
5314                                 if (changeVal)
5315                                 {
5316                                         /* Save old value to support transaction abort */
5317                                         if (!makeDefault)
5318                                                 push_old_value(&conf->gen, action);
5319
5320                                         if (conf->assign_hook)
5321                                                 (*conf->assign_hook) (newval, newextra);
5322                                         *conf->variable = newval;
5323                                         set_extra_field(&conf->gen, &conf->gen.extra,
5324                                                                         newextra);
5325                                         conf->gen.source = source;
5326                                         conf->gen.scontext = context;
5327                                 }
5328                                 if (makeDefault)
5329                                 {
5330                                         GucStack   *stack;
5331
5332                                         if (conf->gen.reset_source <= source)
5333                                         {
5334                                                 conf->reset_val = newval;
5335                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5336                                                                                 newextra);
5337                                                 conf->gen.reset_source = source;
5338                                                 conf->gen.reset_scontext = context;
5339                                         }
5340                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5341                                         {
5342                                                 if (stack->source <= source)
5343                                                 {
5344                                                         stack->prior.val.boolval = newval;
5345                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5346                                                                                         newextra);
5347                                                         stack->source = source;
5348                                                         stack->scontext = context;
5349                                                 }
5350                                         }
5351                                 }
5352
5353                                 /* Perhaps we didn't install newextra anywhere */
5354                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5355                                         free(newextra);
5356                                 break;
5357                         }
5358
5359                 case PGC_INT:
5360                         {
5361                                 struct config_int *conf = (struct config_int *) record;
5362                                 int                     newval;
5363                                 void       *newextra = NULL;
5364
5365                                 if (value)
5366                                 {
5367                                         const char *hintmsg;
5368
5369                                         if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
5370                                         {
5371                                                 ereport(elevel,
5372                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5373                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5374                                                                 name, value),
5375                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5376                                                 return 0;
5377                                         }
5378                                         if (newval < conf->min || newval > conf->max)
5379                                         {
5380                                                 ereport(elevel,
5381                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5382                                                                  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
5383                                                                                 newval, name, conf->min, conf->max)));
5384                                                 return 0;
5385                                         }
5386                                         if (!call_int_check_hook(conf, &newval, &newextra,
5387                                                                                          source, elevel))
5388                                                 return 0;
5389                                 }
5390                                 else if (source == PGC_S_DEFAULT)
5391                                 {
5392                                         newval = conf->boot_val;
5393                                         if (!call_int_check_hook(conf, &newval, &newextra,
5394                                                                                          source, elevel))
5395                                                 return 0;
5396                                 }
5397                                 else
5398                                 {
5399                                         newval = conf->reset_val;
5400                                         newextra = conf->reset_extra;
5401                                         source = conf->gen.reset_source;
5402                                         context = conf->gen.reset_scontext;
5403                                 }
5404
5405                                 if (prohibitValueChange)
5406                                 {
5407                                         if (*conf->variable != newval)
5408                                         {
5409                                                 ereport(elevel,
5410                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5411                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5412                                                                                 name)));
5413                                                 return 0;
5414                                         }
5415                                         return -1;
5416                                 }
5417
5418                                 if (changeVal)
5419                                 {
5420                                         /* Save old value to support transaction abort */
5421                                         if (!makeDefault)
5422                                                 push_old_value(&conf->gen, action);
5423
5424                                         if (conf->assign_hook)
5425                                                 (*conf->assign_hook) (newval, newextra);
5426                                         *conf->variable = newval;
5427                                         set_extra_field(&conf->gen, &conf->gen.extra,
5428                                                                         newextra);
5429                                         conf->gen.source = source;
5430                                         conf->gen.scontext = context;
5431                                 }
5432                                 if (makeDefault)
5433                                 {
5434                                         GucStack   *stack;
5435
5436                                         if (conf->gen.reset_source <= source)
5437                                         {
5438                                                 conf->reset_val = newval;
5439                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5440                                                                                 newextra);
5441                                                 conf->gen.reset_source = source;
5442                                                 conf->gen.reset_scontext = context;
5443                                         }
5444                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5445                                         {
5446                                                 if (stack->source <= source)
5447                                                 {
5448                                                         stack->prior.val.intval = newval;
5449                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5450                                                                                         newextra);
5451                                                         stack->source = source;
5452                                                         stack->scontext = context;
5453                                                 }
5454                                         }
5455                                 }
5456
5457                                 /* Perhaps we didn't install newextra anywhere */
5458                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5459                                         free(newextra);
5460                                 break;
5461                         }
5462
5463                 case PGC_REAL:
5464                         {
5465                                 struct config_real *conf = (struct config_real *) record;
5466                                 double          newval;
5467                                 void       *newextra = NULL;
5468
5469                                 if (value)
5470                                 {
5471                                         if (!parse_real(value, &newval))
5472                                         {
5473                                                 ereport(elevel,
5474                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5475                                                   errmsg("parameter \"%s\" requires a numeric value",
5476                                                                  name)));
5477                                                 return 0;
5478                                         }
5479                                         if (newval < conf->min || newval > conf->max)
5480                                         {
5481                                                 ereport(elevel,
5482                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5483                                                                  errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
5484                                                                                 newval, name, conf->min, conf->max)));
5485                                                 return 0;
5486                                         }
5487                                         if (!call_real_check_hook(conf, &newval, &newextra,
5488                                                                                           source, elevel))
5489                                                 return 0;
5490                                 }
5491                                 else if (source == PGC_S_DEFAULT)
5492                                 {
5493                                         newval = conf->boot_val;
5494                                         if (!call_real_check_hook(conf, &newval, &newextra,
5495                                                                                           source, elevel))
5496                                                 return 0;
5497                                 }
5498                                 else
5499                                 {
5500                                         newval = conf->reset_val;
5501                                         newextra = conf->reset_extra;
5502                                         source = conf->gen.reset_source;
5503                                         context = conf->gen.reset_scontext;
5504                                 }
5505
5506                                 if (prohibitValueChange)
5507                                 {
5508                                         if (*conf->variable != newval)
5509                                         {
5510                                                 ereport(elevel,
5511                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5512                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5513                                                                                 name)));
5514                                                 return 0;
5515                                         }
5516                                         return -1;
5517                                 }
5518
5519                                 if (changeVal)
5520                                 {
5521                                         /* Save old value to support transaction abort */
5522                                         if (!makeDefault)
5523                                                 push_old_value(&conf->gen, action);
5524
5525                                         if (conf->assign_hook)
5526                                                 (*conf->assign_hook) (newval, newextra);
5527                                         *conf->variable = newval;
5528                                         set_extra_field(&conf->gen, &conf->gen.extra,
5529                                                                         newextra);
5530                                         conf->gen.source = source;
5531                                         conf->gen.scontext = context;
5532                                 }
5533                                 if (makeDefault)
5534                                 {
5535                                         GucStack   *stack;
5536
5537                                         if (conf->gen.reset_source <= source)
5538                                         {
5539                                                 conf->reset_val = newval;
5540                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5541                                                                                 newextra);
5542                                                 conf->gen.reset_source = source;
5543                                                 conf->gen.reset_scontext = context;
5544                                         }
5545                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5546                                         {
5547                                                 if (stack->source <= source)
5548                                                 {
5549                                                         stack->prior.val.realval = newval;
5550                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5551                                                                                         newextra);
5552                                                         stack->source = source;
5553                                                         stack->scontext = context;
5554                                                 }
5555                                         }
5556                                 }
5557
5558                                 /* Perhaps we didn't install newextra anywhere */
5559                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5560                                         free(newextra);
5561                                 break;
5562                         }
5563
5564                 case PGC_STRING:
5565                         {
5566                                 struct config_string *conf = (struct config_string *) record;
5567                                 char       *newval;
5568                                 void       *newextra = NULL;
5569
5570                                 if (value)
5571                                 {
5572                                         /*
5573                                          * The value passed by the caller could be transient, so
5574                                          * we always strdup it.
5575                                          */
5576                                         newval = guc_strdup(elevel, value);
5577                                         if (newval == NULL)
5578                                                 return 0;
5579
5580                                         /*
5581                                          * The only built-in "parsing" check we have is to apply
5582                                          * truncation if GUC_IS_NAME.
5583                                          */
5584                                         if (conf->gen.flags & GUC_IS_NAME)
5585                                                 truncate_identifier(newval, strlen(newval), true);
5586
5587                                         if (!call_string_check_hook(conf, &newval, &newextra,
5588                                                                                                 source, elevel))
5589                                         {
5590                                                 free(newval);
5591                                                 return 0;
5592                                         }
5593                                 }
5594                                 else if (source == PGC_S_DEFAULT)
5595                                 {
5596                                         /* non-NULL boot_val must always get strdup'd */
5597                                         if (conf->boot_val != NULL)
5598                                         {
5599                                                 newval = guc_strdup(elevel, conf->boot_val);
5600                                                 if (newval == NULL)
5601                                                         return 0;
5602                                         }
5603                                         else
5604                                                 newval = NULL;
5605
5606                                         if (!call_string_check_hook(conf, &newval, &newextra,
5607                                                                                                 source, elevel))
5608                                         {
5609                                                 free(newval);
5610                                                 return 0;
5611                                         }
5612                                 }
5613                                 else
5614                                 {
5615                                         /*
5616                                          * strdup not needed, since reset_val is already under
5617                                          * guc.c's control
5618                                          */
5619                                         newval = conf->reset_val;
5620                                         newextra = conf->reset_extra;
5621                                         source = conf->gen.reset_source;
5622                                         context = conf->gen.reset_scontext;
5623                                 }
5624
5625                                 if (prohibitValueChange)
5626                                 {
5627                                         /* newval shouldn't be NULL, so we're a bit sloppy here */
5628                                         if (*conf->variable == NULL || newval == NULL ||
5629                                                 strcmp(*conf->variable, newval) != 0)
5630                                         {
5631                                                 ereport(elevel,
5632                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5633                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5634                                                                                 name)));
5635                                                 return 0;
5636                                         }
5637                                         return -1;
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                                         conf->gen.scontext = context;
5653                                 }
5654
5655                                 if (makeDefault)
5656                                 {
5657                                         GucStack   *stack;
5658
5659                                         if (conf->gen.reset_source <= source)
5660                                         {
5661                                                 set_string_field(conf, &conf->reset_val, newval);
5662                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5663                                                                                 newextra);
5664                                                 conf->gen.reset_source = source;
5665                                                 conf->gen.reset_scontext = context;
5666                                         }
5667                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5668                                         {
5669                                                 if (stack->source <= source)
5670                                                 {
5671                                                         set_string_field(conf, &stack->prior.val.stringval,
5672                                                                                          newval);
5673                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5674                                                                                         newextra);
5675                                                         stack->source = source;
5676                                                         stack->scontext = context;
5677                                                 }
5678                                         }
5679                                 }
5680
5681                                 /* Perhaps we didn't install newval anywhere */
5682                                 if (newval && !string_field_used(conf, newval))
5683                                         free(newval);
5684                                 /* Perhaps we didn't install newextra anywhere */
5685                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5686                                         free(newextra);
5687                                 break;
5688                         }
5689
5690                 case PGC_ENUM:
5691                         {
5692                                 struct config_enum *conf = (struct config_enum *) record;
5693                                 int                     newval;
5694                                 void       *newextra = NULL;
5695
5696                                 if (value)
5697                                 {
5698                                         if (!config_enum_lookup_by_name(conf, value, &newval))
5699                                         {
5700                                                 char       *hintmsg;
5701
5702                                                 hintmsg = config_enum_get_options(conf,
5703                                                                                                                 "Available values: ",
5704                                                                                                                   ".", ", ");
5705
5706                                                 ereport(elevel,
5707                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5708                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5709                                                                 name, value),
5710                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5711
5712                                                 if (hintmsg)
5713                                                         pfree(hintmsg);
5714                                                 return 0;
5715                                         }
5716                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5717                                                                                           source, elevel))
5718                                                 return 0;
5719                                 }
5720                                 else if (source == PGC_S_DEFAULT)
5721                                 {
5722                                         newval = conf->boot_val;
5723                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5724                                                                                           source, elevel))
5725                                                 return 0;
5726                                 }
5727                                 else
5728                                 {
5729                                         newval = conf->reset_val;
5730                                         newextra = conf->reset_extra;
5731                                         source = conf->gen.reset_source;
5732                                         context = conf->gen.reset_scontext;
5733                                 }
5734
5735                                 if (prohibitValueChange)
5736                                 {
5737                                         if (*conf->variable != newval)
5738                                         {
5739                                                 ereport(elevel,
5740                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5741                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5742                                                                                 name)));
5743                                                 return 0;
5744                                         }
5745                                         return -1;
5746                                 }
5747
5748                                 if (changeVal)
5749                                 {
5750                                         /* Save old value to support transaction abort */
5751                                         if (!makeDefault)
5752                                                 push_old_value(&conf->gen, action);
5753
5754                                         if (conf->assign_hook)
5755                                                 (*conf->assign_hook) (newval, newextra);
5756                                         *conf->variable = newval;
5757                                         set_extra_field(&conf->gen, &conf->gen.extra,
5758                                                                         newextra);
5759                                         conf->gen.source = source;
5760                                         conf->gen.scontext = context;
5761                                 }
5762                                 if (makeDefault)
5763                                 {
5764                                         GucStack   *stack;
5765
5766                                         if (conf->gen.reset_source <= source)
5767                                         {
5768                                                 conf->reset_val = newval;
5769                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5770                                                                                 newextra);
5771                                                 conf->gen.reset_source = source;
5772                                                 conf->gen.reset_scontext = context;
5773                                         }
5774                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5775                                         {
5776                                                 if (stack->source <= source)
5777                                                 {
5778                                                         stack->prior.val.enumval = newval;
5779                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5780                                                                                         newextra);
5781                                                         stack->source = source;
5782                                                         stack->scontext = context;
5783                                                 }
5784                                         }
5785                                 }
5786
5787                                 /* Perhaps we didn't install newextra anywhere */
5788                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5789                                         free(newextra);
5790                                 break;
5791                         }
5792         }
5793
5794         if (changeVal && (record->flags & GUC_REPORT))
5795                 ReportGUCOption(record);
5796
5797         return changeVal ? 1 : -1;
5798 }
5799
5800
5801 /*
5802  * Set the fields for source file and line number the setting came from.
5803  */
5804 static void
5805 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
5806 {
5807         struct config_generic *record;
5808         int                     elevel;
5809
5810         /*
5811          * To avoid cluttering the log, only the postmaster bleats loudly about
5812          * problems with the config file.
5813          */
5814         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5815
5816         record = find_option(name, true, elevel);
5817         /* should not happen */
5818         if (record == NULL)
5819                 elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
5820
5821         sourcefile = guc_strdup(elevel, sourcefile);
5822         if (record->sourcefile)
5823                 free(record->sourcefile);
5824         record->sourcefile = sourcefile;
5825         record->sourceline = sourceline;
5826 }
5827
5828 /*
5829  * Set a config option to the given value.
5830  *
5831  * See also set_config_option; this is just the wrapper to be called from
5832  * outside GUC.  (This function should be used when possible, because its API
5833  * is more stable than set_config_option's.)
5834  *
5835  * Note: there is no support here for setting source file/line, as it
5836  * is currently not needed.
5837  */
5838 void
5839 SetConfigOption(const char *name, const char *value,
5840                                 GucContext context, GucSource source)
5841 {
5842         (void) set_config_option(name, value, context, source,
5843                                                          GUC_ACTION_SET, true, 0);
5844 }
5845
5846
5847
5848 /*
5849  * Fetch the current value of the option `name', as a string.
5850  *
5851  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
5852  * this cannot be distinguished from a string variable with a NULL value!),
5853  * otherwise throw an ereport and don't return.
5854  *
5855  * If restrict_superuser is true, we also enforce that only superusers can
5856  * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
5857  * in user-driven calls.
5858  *
5859  * The string is *not* allocated for modification and is really only
5860  * valid until the next call to configuration related functions.
5861  */
5862 const char *
5863 GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
5864 {
5865         struct config_generic *record;
5866         static char buffer[256];
5867
5868         record = find_option(name, false, ERROR);
5869         if (record == NULL)
5870         {
5871                 if (missing_ok)
5872                         return NULL;
5873                 ereport(ERROR,
5874                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5875                                  errmsg("unrecognized configuration parameter \"%s\"",
5876                                                 name)));
5877         }
5878         if (restrict_superuser &&
5879                 (record->flags & GUC_SUPERUSER_ONLY) &&
5880                 !superuser())
5881                 ereport(ERROR,
5882                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5883                                  errmsg("must be superuser to examine \"%s\"", name)));
5884
5885         switch (record->vartype)
5886         {
5887                 case PGC_BOOL:
5888                         return *((struct config_bool *) record)->variable ? "on" : "off";
5889
5890                 case PGC_INT:
5891                         snprintf(buffer, sizeof(buffer), "%d",
5892                                          *((struct config_int *) record)->variable);
5893                         return buffer;
5894
5895                 case PGC_REAL:
5896                         snprintf(buffer, sizeof(buffer), "%g",
5897                                          *((struct config_real *) record)->variable);
5898                         return buffer;
5899
5900                 case PGC_STRING:
5901                         return *((struct config_string *) record)->variable;
5902
5903                 case PGC_ENUM:
5904                         return config_enum_lookup_by_value((struct config_enum *) record,
5905                                                                  *((struct config_enum *) record)->variable);
5906         }
5907         return NULL;
5908 }
5909
5910 /*
5911  * Get the RESET value associated with the given option.
5912  *
5913  * Note: this is not re-entrant, due to use of static result buffer;
5914  * not to mention that a string variable could have its reset_val changed.
5915  * Beware of assuming the result value is good for very long.
5916  */
5917 const char *
5918 GetConfigOptionResetString(const char *name)
5919 {
5920         struct config_generic *record;
5921         static char buffer[256];
5922
5923         record = find_option(name, false, ERROR);
5924         if (record == NULL)
5925                 ereport(ERROR,
5926                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5927                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5928         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
5929                 ereport(ERROR,
5930                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5931                                  errmsg("must be superuser to examine \"%s\"", name)));
5932
5933         switch (record->vartype)
5934         {
5935                 case PGC_BOOL:
5936                         return ((struct config_bool *) record)->reset_val ? "on" : "off";
5937
5938                 case PGC_INT:
5939                         snprintf(buffer, sizeof(buffer), "%d",
5940                                          ((struct config_int *) record)->reset_val);
5941                         return buffer;
5942
5943                 case PGC_REAL:
5944                         snprintf(buffer, sizeof(buffer), "%g",
5945                                          ((struct config_real *) record)->reset_val);
5946                         return buffer;
5947
5948                 case PGC_STRING:
5949                         return ((struct config_string *) record)->reset_val;
5950
5951                 case PGC_ENUM:
5952                         return config_enum_lookup_by_value((struct config_enum *) record,
5953                                                                  ((struct config_enum *) record)->reset_val);
5954         }
5955         return NULL;
5956 }
5957
5958
5959 /*
5960  * flatten_set_variable_args
5961  *              Given a parsenode List as emitted by the grammar for SET,
5962  *              convert to the flat string representation used by GUC.
5963  *
5964  * We need to be told the name of the variable the args are for, because
5965  * the flattening rules vary (ugh).
5966  *
5967  * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
5968  * a palloc'd string.
5969  */
5970 static char *
5971 flatten_set_variable_args(const char *name, List *args)
5972 {
5973         struct config_generic *record;
5974         int                     flags;
5975         StringInfoData buf;
5976         ListCell   *l;
5977
5978         /* Fast path if just DEFAULT */
5979         if (args == NIL)
5980                 return NULL;
5981
5982         /*
5983          * Get flags for the variable; if it's not known, use default flags.
5984          * (Caller might throw error later, but not our business to do so here.)
5985          */
5986         record = find_option(name, false, WARNING);
5987         if (record)
5988                 flags = record->flags;
5989         else
5990                 flags = 0;
5991
5992         /* Complain if list input and non-list variable */
5993         if ((flags & GUC_LIST_INPUT) == 0 &&
5994                 list_length(args) != 1)
5995                 ereport(ERROR,
5996                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5997                                  errmsg("SET %s takes only one argument", name)));
5998
5999         initStringInfo(&buf);
6000
6001         /*
6002          * Each list member may be a plain A_Const node, or an A_Const within a
6003          * TypeCast; the latter case is supported only for ConstInterval arguments
6004          * (for SET TIME ZONE).
6005          */
6006         foreach(l, args)
6007         {
6008                 Node       *arg = (Node *) lfirst(l);
6009                 char       *val;
6010                 TypeName   *typeName = NULL;
6011                 A_Const    *con;
6012
6013                 if (l != list_head(args))
6014                         appendStringInfo(&buf, ", ");
6015
6016                 if (IsA(arg, TypeCast))
6017                 {
6018                         TypeCast   *tc = (TypeCast *) arg;
6019
6020                         arg = tc->arg;
6021                         typeName = tc->typeName;
6022                 }
6023
6024                 if (!IsA(arg, A_Const))
6025                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
6026                 con = (A_Const *) arg;
6027
6028                 switch (nodeTag(&con->val))
6029                 {
6030                         case T_Integer:
6031                                 appendStringInfo(&buf, "%ld", intVal(&con->val));
6032                                 break;
6033                         case T_Float:
6034                                 /* represented as a string, so just copy it */
6035                                 appendStringInfoString(&buf, strVal(&con->val));
6036                                 break;
6037                         case T_String:
6038                                 val = strVal(&con->val);
6039                                 if (typeName != NULL)
6040                                 {
6041                                         /*
6042                                          * Must be a ConstInterval argument for TIME ZONE. Coerce
6043                                          * to interval and back to normalize the value and account
6044                                          * for any typmod.
6045                                          */
6046                                         Oid                     typoid;
6047                                         int32           typmod;
6048                                         Datum           interval;
6049                                         char       *intervalout;
6050
6051                                         typenameTypeIdAndMod(NULL, typeName, &typoid, &typmod);
6052                                         Assert(typoid == INTERVALOID);
6053
6054                                         interval =
6055                                                 DirectFunctionCall3(interval_in,
6056                                                                                         CStringGetDatum(val),
6057                                                                                         ObjectIdGetDatum(InvalidOid),
6058                                                                                         Int32GetDatum(typmod));
6059
6060                                         intervalout =
6061                                                 DatumGetCString(DirectFunctionCall1(interval_out,
6062                                                                                                                         interval));
6063                                         appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
6064                                 }
6065                                 else
6066                                 {
6067                                         /*
6068                                          * Plain string literal or identifier.  For quote mode,
6069                                          * quote it if it's not a vanilla identifier.
6070                                          */
6071                                         if (flags & GUC_LIST_QUOTE)
6072                                                 appendStringInfoString(&buf, quote_identifier(val));
6073                                         else
6074                                                 appendStringInfoString(&buf, val);
6075                                 }
6076                                 break;
6077                         default:
6078                                 elog(ERROR, "unrecognized node type: %d",
6079                                          (int) nodeTag(&con->val));
6080                                 break;
6081                 }
6082         }
6083
6084         return buf.data;
6085 }
6086
6087
6088 /*
6089  * SET command
6090  */
6091 void
6092 ExecSetVariableStmt(VariableSetStmt *stmt)
6093 {
6094         GucAction       action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
6095
6096         switch (stmt->kind)
6097         {
6098                 case VAR_SET_VALUE:
6099                 case VAR_SET_CURRENT:
6100                         (void) set_config_option(stmt->name,
6101                                                                          ExtractSetVariableArgs(stmt),
6102                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6103                                                                          PGC_S_SESSION,
6104                                                                          action,
6105                                                                          true,
6106                                                                          0);
6107                         break;
6108                 case VAR_SET_MULTI:
6109
6110                         /*
6111                          * Special-case SQL syntaxes.  The TRANSACTION and SESSION
6112                          * CHARACTERISTICS cases effectively set more than one variable
6113                          * per statement.  TRANSACTION SNAPSHOT only takes one argument,
6114                          * but we put it here anyway since it's a special case and not
6115                          * related to any GUC variable.
6116                          */
6117                         if (strcmp(stmt->name, "TRANSACTION") == 0)
6118                         {
6119                                 ListCell   *head;
6120
6121                                 foreach(head, stmt->args)
6122                                 {
6123                                         DefElem    *item = (DefElem *) lfirst(head);
6124
6125                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6126                                                 SetPGVariable("transaction_isolation",
6127                                                                           list_make1(item->arg), stmt->is_local);
6128                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6129                                                 SetPGVariable("transaction_read_only",
6130                                                                           list_make1(item->arg), stmt->is_local);
6131                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6132                                                 SetPGVariable("transaction_deferrable",
6133                                                                           list_make1(item->arg), stmt->is_local);
6134                                         else
6135                                                 elog(ERROR, "unexpected SET TRANSACTION element: %s",
6136                                                          item->defname);
6137                                 }
6138                         }
6139                         else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
6140                         {
6141                                 ListCell   *head;
6142
6143                                 foreach(head, stmt->args)
6144                                 {
6145                                         DefElem    *item = (DefElem *) lfirst(head);
6146
6147                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6148                                                 SetPGVariable("default_transaction_isolation",
6149                                                                           list_make1(item->arg), stmt->is_local);
6150                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6151                                                 SetPGVariable("default_transaction_read_only",
6152                                                                           list_make1(item->arg), stmt->is_local);
6153                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6154                                                 SetPGVariable("default_transaction_deferrable",
6155                                                                           list_make1(item->arg), stmt->is_local);
6156                                         else
6157                                                 elog(ERROR, "unexpected SET SESSION element: %s",
6158                                                          item->defname);
6159                                 }
6160                         }
6161                         else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
6162                         {
6163                                 A_Const    *con = (A_Const *) linitial(stmt->args);
6164
6165                                 if (stmt->is_local)
6166                                         ereport(ERROR,
6167                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6168                                                          errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
6169                                 Assert(IsA(con, A_Const));
6170                                 Assert(nodeTag(&con->val) == T_String);
6171                                 ImportSnapshot(strVal(&con->val));
6172                         }
6173                         else
6174                                 elog(ERROR, "unexpected SET MULTI element: %s",
6175                                          stmt->name);
6176                         break;
6177                 case VAR_SET_DEFAULT:
6178                 case VAR_RESET:
6179                         (void) set_config_option(stmt->name,
6180                                                                          NULL,
6181                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6182                                                                          PGC_S_SESSION,
6183                                                                          action,
6184                                                                          true,
6185                                                                          0);
6186                         break;
6187                 case VAR_RESET_ALL:
6188                         ResetAllOptions();
6189                         break;
6190         }
6191 }
6192
6193 /*
6194  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
6195  * The result is palloc'd.
6196  *
6197  * This is exported for use by actions such as ALTER ROLE SET.
6198  */
6199 char *
6200 ExtractSetVariableArgs(VariableSetStmt *stmt)
6201 {
6202         switch (stmt->kind)
6203         {
6204                 case VAR_SET_VALUE:
6205                         return flatten_set_variable_args(stmt->name, stmt->args);
6206                 case VAR_SET_CURRENT:
6207                         return GetConfigOptionByName(stmt->name, NULL);
6208                 default:
6209                         return NULL;
6210         }
6211 }
6212
6213 /*
6214  * SetPGVariable - SET command exported as an easily-C-callable function.
6215  *
6216  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
6217  * by passing args == NIL), but not SET FROM CURRENT functionality.
6218  */
6219 void
6220 SetPGVariable(const char *name, List *args, bool is_local)
6221 {
6222         char       *argstring = flatten_set_variable_args(name, args);
6223
6224         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6225         (void) set_config_option(name,
6226                                                          argstring,
6227                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6228                                                          PGC_S_SESSION,
6229                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6230                                                          true,
6231                                                          0);
6232 }
6233
6234 /*
6235  * SET command wrapped as a SQL callable function.
6236  */
6237 Datum
6238 set_config_by_name(PG_FUNCTION_ARGS)
6239 {
6240         char       *name;
6241         char       *value;
6242         char       *new_value;
6243         bool            is_local;
6244
6245         if (PG_ARGISNULL(0))
6246                 ereport(ERROR,
6247                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6248                                  errmsg("SET requires parameter name")));
6249
6250         /* Get the GUC variable name */
6251         name = TextDatumGetCString(PG_GETARG_DATUM(0));
6252
6253         /* Get the desired value or set to NULL for a reset request */
6254         if (PG_ARGISNULL(1))
6255                 value = NULL;
6256         else
6257                 value = TextDatumGetCString(PG_GETARG_DATUM(1));
6258
6259         /*
6260          * Get the desired state of is_local. Default to false if provided value
6261          * is NULL
6262          */
6263         if (PG_ARGISNULL(2))
6264                 is_local = false;
6265         else
6266                 is_local = PG_GETARG_BOOL(2);
6267
6268         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6269         (void) set_config_option(name,
6270                                                          value,
6271                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6272                                                          PGC_S_SESSION,
6273                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6274                                                          true,
6275                                                          0);
6276
6277         /* get the new current value */
6278         new_value = GetConfigOptionByName(name, NULL);
6279
6280         /* Convert return string to text */
6281         PG_RETURN_TEXT_P(cstring_to_text(new_value));
6282 }
6283
6284
6285 /*
6286  * Common code for DefineCustomXXXVariable subroutines: allocate the
6287  * new variable's config struct and fill in generic fields.
6288  */
6289 static struct config_generic *
6290 init_custom_variable(const char *name,
6291                                          const char *short_desc,
6292                                          const char *long_desc,
6293                                          GucContext context,
6294                                          int flags,
6295                                          enum config_type type,
6296                                          size_t sz)
6297 {
6298         struct config_generic *gen;
6299
6300         /*
6301          * Only allow custom PGC_POSTMASTER variables to be created during shared
6302          * library preload; any later than that, we can't ensure that the value
6303          * doesn't change after startup.  This is a fatal elog if it happens; just
6304          * erroring out isn't safe because we don't know what the calling loadable
6305          * module might already have hooked into.
6306          */
6307         if (context == PGC_POSTMASTER &&
6308                 !process_shared_preload_libraries_in_progress)
6309                 elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
6310
6311         gen = (struct config_generic *) guc_malloc(ERROR, sz);
6312         memset(gen, 0, sz);
6313
6314         gen->name = guc_strdup(ERROR, name);
6315         gen->context = context;
6316         gen->group = CUSTOM_OPTIONS;
6317         gen->short_desc = short_desc;
6318         gen->long_desc = long_desc;
6319         gen->flags = flags;
6320         gen->vartype = type;
6321
6322         return gen;
6323 }
6324
6325 /*
6326  * Common code for DefineCustomXXXVariable subroutines: insert the new
6327  * variable into the GUC variable array, replacing any placeholder.
6328  */
6329 static void
6330 define_custom_variable(struct config_generic * variable)
6331 {
6332         const char *name = variable->name;
6333         const char **nameAddr = &name;
6334         struct config_string *pHolder;
6335         struct config_generic **res;
6336
6337         /*
6338          * See if there's a placeholder by the same name.
6339          */
6340         res = (struct config_generic **) bsearch((void *) &nameAddr,
6341                                                                                          (void *) guc_variables,
6342                                                                                          num_guc_variables,
6343                                                                                          sizeof(struct config_generic *),
6344                                                                                          guc_var_compare);
6345         if (res == NULL)
6346         {
6347                 /*
6348                  * No placeholder to replace, so we can just add it ... but first,
6349                  * make sure it's initialized to its default value.
6350                  */
6351                 InitializeOneGUCOption(variable);
6352                 add_guc_variable(variable, ERROR);
6353                 return;
6354         }
6355
6356         /*
6357          * This better be a placeholder
6358          */
6359         if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
6360                 ereport(ERROR,
6361                                 (errcode(ERRCODE_INTERNAL_ERROR),
6362                                  errmsg("attempt to redefine parameter \"%s\"", name)));
6363
6364         Assert((*res)->vartype == PGC_STRING);
6365         pHolder = (struct config_string *) (*res);
6366
6367         /*
6368          * First, set the variable to its default value.  We must do this even
6369          * though we intend to immediately apply a new value, since it's possible
6370          * that the new value is invalid.
6371          */
6372         InitializeOneGUCOption(variable);
6373
6374         /*
6375          * Replace the placeholder. We aren't changing the name, so no re-sorting
6376          * is necessary
6377          */
6378         *res = variable;
6379
6380         /*
6381          * Assign the string value(s) stored in the placeholder to the real
6382          * variable.  Essentially, we need to duplicate all the active and stacked
6383          * values, but with appropriate validation and datatype adjustment.
6384          *
6385          * If an assignment fails, we report a WARNING and keep going.  We don't
6386          * want to throw ERROR for bad values, because it'd bollix the add-on
6387          * module that's presumably halfway through getting loaded.  In such cases
6388          * the default or previous state will become active instead.
6389          */
6390
6391         /* First, apply the reset value if any */
6392         if (pHolder->reset_val)
6393                 (void) set_config_option(name, pHolder->reset_val,
6394                                                                  pHolder->gen.reset_scontext,
6395                                                                  pHolder->gen.reset_source,
6396                                                                  GUC_ACTION_SET, true, WARNING);
6397         /* That should not have resulted in stacking anything */
6398         Assert(variable->stack == NULL);
6399
6400         /* Now, apply current and stacked values, in the order they were stacked */
6401         reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
6402                                                    *(pHolder->variable),
6403                                                    pHolder->gen.scontext, pHolder->gen.source);
6404
6405         /* Also copy over any saved source-location information */
6406         if (pHolder->gen.sourcefile)
6407                 set_config_sourcefile(name, pHolder->gen.sourcefile,
6408                                                           pHolder->gen.sourceline);
6409
6410         /*
6411          * Free up as much as we conveniently can of the placeholder structure.
6412          * (This neglects any stack items, so it's possible for some memory to be
6413          * leaked.  Since this can only happen once per session per variable, it
6414          * doesn't seem worth spending much code on.)
6415          */
6416         set_string_field(pHolder, pHolder->variable, NULL);
6417         set_string_field(pHolder, &pHolder->reset_val, NULL);
6418
6419         free(pHolder);
6420 }
6421
6422 /*
6423  * Recursive subroutine for define_custom_variable: reapply non-reset values
6424  *
6425  * We recurse so that the values are applied in the same order as originally.
6426  * At each recursion level, apply the upper-level value (passed in) in the
6427  * fashion implied by the stack entry.
6428  */
6429 static void
6430 reapply_stacked_values(struct config_generic * variable,
6431                                            struct config_string *pHolder,
6432                                            GucStack *stack,
6433                                            const char *curvalue,
6434                                            GucContext curscontext, GucSource cursource)
6435 {
6436         const char *name = variable->name;
6437         GucStack   *oldvarstack = variable->stack;
6438
6439         if (stack != NULL)
6440         {
6441                 /* First, recurse, so that stack items are processed bottom to top */
6442                 reapply_stacked_values(variable, pHolder, stack->prev,
6443                                                            stack->prior.val.stringval,
6444                                                            stack->scontext, stack->source);
6445
6446                 /* See how to apply the passed-in value */
6447                 switch (stack->state)
6448                 {
6449                         case GUC_SAVE:
6450                                 (void) set_config_option(name, curvalue,
6451                                                                                  curscontext, cursource,
6452                                                                                  GUC_ACTION_SAVE, true, WARNING);
6453                                 break;
6454
6455                         case GUC_SET:
6456                                 (void) set_config_option(name, curvalue,
6457                                                                                  curscontext, cursource,
6458                                                                                  GUC_ACTION_SET, true, WARNING);
6459                                 break;
6460
6461                         case GUC_LOCAL:
6462                                 (void) set_config_option(name, curvalue,
6463                                                                                  curscontext, cursource,
6464                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6465                                 break;
6466
6467                         case GUC_SET_LOCAL:
6468                                 /* first, apply the masked value as SET */
6469                                 (void) set_config_option(name, stack->masked.val.stringval,
6470                                                                                  stack->masked_scontext, PGC_S_SESSION,
6471                                                                                  GUC_ACTION_SET, true, WARNING);
6472                                 /* then apply the current value as LOCAL */
6473                                 (void) set_config_option(name, curvalue,
6474                                                                                  curscontext, cursource,
6475                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6476                                 break;
6477                 }
6478
6479                 /* If we successfully made a stack entry, adjust its nest level */
6480                 if (variable->stack != oldvarstack)
6481                         variable->stack->nest_level = stack->nest_level;
6482         }
6483         else
6484         {
6485                 /*
6486                  * We are at the end of the stack.  If the active/previous value is
6487                  * different from the reset value, it must represent a previously
6488                  * committed session value.  Apply it, and then drop the stack entry
6489                  * that set_config_option will have created under the impression that
6490                  * this is to be just a transactional assignment.  (We leak the stack
6491                  * entry.)
6492                  */
6493                 if (curvalue != pHolder->reset_val ||
6494                         curscontext != pHolder->gen.reset_scontext ||
6495                         cursource != pHolder->gen.reset_source)
6496                 {
6497                         (void) set_config_option(name, curvalue,
6498                                                                          curscontext, cursource,
6499                                                                          GUC_ACTION_SET, true, WARNING);
6500                         variable->stack = NULL;
6501                 }
6502         }
6503 }
6504
6505 void
6506 DefineCustomBoolVariable(const char *name,
6507                                                  const char *short_desc,
6508                                                  const char *long_desc,
6509                                                  bool *valueAddr,
6510                                                  bool bootValue,
6511                                                  GucContext context,
6512                                                  int flags,
6513                                                  GucBoolCheckHook check_hook,
6514                                                  GucBoolAssignHook assign_hook,
6515                                                  GucShowHook show_hook)
6516 {
6517         struct config_bool *var;
6518
6519         var = (struct config_bool *)
6520                 init_custom_variable(name, short_desc, long_desc, context, flags,
6521                                                          PGC_BOOL, sizeof(struct config_bool));
6522         var->variable = valueAddr;
6523         var->boot_val = bootValue;
6524         var->reset_val = bootValue;
6525         var->check_hook = check_hook;
6526         var->assign_hook = assign_hook;
6527         var->show_hook = show_hook;
6528         define_custom_variable(&var->gen);
6529 }
6530
6531 void
6532 DefineCustomIntVariable(const char *name,
6533                                                 const char *short_desc,
6534                                                 const char *long_desc,
6535                                                 int *valueAddr,
6536                                                 int bootValue,
6537                                                 int minValue,
6538                                                 int maxValue,
6539                                                 GucContext context,
6540                                                 int flags,
6541                                                 GucIntCheckHook check_hook,
6542                                                 GucIntAssignHook assign_hook,
6543                                                 GucShowHook show_hook)
6544 {
6545         struct config_int *var;
6546
6547         var = (struct config_int *)
6548                 init_custom_variable(name, short_desc, long_desc, context, flags,
6549                                                          PGC_INT, sizeof(struct config_int));
6550         var->variable = valueAddr;
6551         var->boot_val = bootValue;
6552         var->reset_val = bootValue;
6553         var->min = minValue;
6554         var->max = maxValue;
6555         var->check_hook = check_hook;
6556         var->assign_hook = assign_hook;
6557         var->show_hook = show_hook;
6558         define_custom_variable(&var->gen);
6559 }
6560
6561 void
6562 DefineCustomRealVariable(const char *name,
6563                                                  const char *short_desc,
6564                                                  const char *long_desc,
6565                                                  double *valueAddr,
6566                                                  double bootValue,
6567                                                  double minValue,
6568                                                  double maxValue,
6569                                                  GucContext context,
6570                                                  int flags,
6571                                                  GucRealCheckHook check_hook,
6572                                                  GucRealAssignHook assign_hook,
6573                                                  GucShowHook show_hook)
6574 {
6575         struct config_real *var;
6576
6577         var = (struct config_real *)
6578                 init_custom_variable(name, short_desc, long_desc, context, flags,
6579                                                          PGC_REAL, sizeof(struct config_real));
6580         var->variable = valueAddr;
6581         var->boot_val = bootValue;
6582         var->reset_val = bootValue;
6583         var->min = minValue;
6584         var->max = maxValue;
6585         var->check_hook = check_hook;
6586         var->assign_hook = assign_hook;
6587         var->show_hook = show_hook;
6588         define_custom_variable(&var->gen);
6589 }
6590
6591 void
6592 DefineCustomStringVariable(const char *name,
6593                                                    const char *short_desc,
6594                                                    const char *long_desc,
6595                                                    char **valueAddr,
6596                                                    const char *bootValue,
6597                                                    GucContext context,
6598                                                    int flags,
6599                                                    GucStringCheckHook check_hook,
6600                                                    GucStringAssignHook assign_hook,
6601                                                    GucShowHook show_hook)
6602 {
6603         struct config_string *var;
6604
6605         var = (struct config_string *)
6606                 init_custom_variable(name, short_desc, long_desc, context, flags,
6607                                                          PGC_STRING, sizeof(struct config_string));
6608         var->variable = valueAddr;
6609         var->boot_val = bootValue;
6610         var->check_hook = check_hook;
6611         var->assign_hook = assign_hook;
6612         var->show_hook = show_hook;
6613         define_custom_variable(&var->gen);
6614 }
6615
6616 void
6617 DefineCustomEnumVariable(const char *name,
6618                                                  const char *short_desc,
6619                                                  const char *long_desc,
6620                                                  int *valueAddr,
6621                                                  int bootValue,
6622                                                  const struct config_enum_entry * options,
6623                                                  GucContext context,
6624                                                  int flags,
6625                                                  GucEnumCheckHook check_hook,
6626                                                  GucEnumAssignHook assign_hook,
6627                                                  GucShowHook show_hook)
6628 {
6629         struct config_enum *var;
6630
6631         var = (struct config_enum *)
6632                 init_custom_variable(name, short_desc, long_desc, context, flags,
6633                                                          PGC_ENUM, sizeof(struct config_enum));
6634         var->variable = valueAddr;
6635         var->boot_val = bootValue;
6636         var->reset_val = bootValue;
6637         var->options = options;
6638         var->check_hook = check_hook;
6639         var->assign_hook = assign_hook;
6640         var->show_hook = show_hook;
6641         define_custom_variable(&var->gen);
6642 }
6643
6644 void
6645 EmitWarningsOnPlaceholders(const char *className)
6646 {
6647         int                     classLen = strlen(className);
6648         int                     i;
6649
6650         for (i = 0; i < num_guc_variables; i++)
6651         {
6652                 struct config_generic *var = guc_variables[i];
6653
6654                 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
6655                         strncmp(className, var->name, classLen) == 0 &&
6656                         var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
6657                 {
6658                         ereport(WARNING,
6659                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
6660                                          errmsg("unrecognized configuration parameter \"%s\"",
6661                                                         var->name)));
6662                 }
6663         }
6664 }
6665
6666
6667 /*
6668  * SHOW command
6669  */
6670 void
6671 GetPGVariable(const char *name, DestReceiver *dest)
6672 {
6673         if (guc_name_compare(name, "all") == 0)
6674                 ShowAllGUCConfig(dest);
6675         else
6676                 ShowGUCConfigOption(name, dest);
6677 }
6678
6679 TupleDesc
6680 GetPGVariableResultDesc(const char *name)
6681 {
6682         TupleDesc       tupdesc;
6683
6684         if (guc_name_compare(name, "all") == 0)
6685         {
6686                 /* need a tuple descriptor representing three TEXT columns */
6687                 tupdesc = CreateTemplateTupleDesc(3, false);
6688                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6689                                                    TEXTOID, -1, 0);
6690                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6691                                                    TEXTOID, -1, 0);
6692                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6693                                                    TEXTOID, -1, 0);
6694         }
6695         else
6696         {
6697                 const char *varname;
6698
6699                 /* Get the canonical spelling of name */
6700                 (void) GetConfigOptionByName(name, &varname);
6701
6702                 /* need a tuple descriptor representing a single TEXT column */
6703                 tupdesc = CreateTemplateTupleDesc(1, false);
6704                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6705                                                    TEXTOID, -1, 0);
6706         }
6707         return tupdesc;
6708 }
6709
6710
6711 /*
6712  * SHOW command
6713  */
6714 static void
6715 ShowGUCConfigOption(const char *name, DestReceiver *dest)
6716 {
6717         TupOutputState *tstate;
6718         TupleDesc       tupdesc;
6719         const char *varname;
6720         char       *value;
6721
6722         /* Get the value and canonical spelling of name */
6723         value = GetConfigOptionByName(name, &varname);
6724
6725         /* need a tuple descriptor representing a single TEXT column */
6726         tupdesc = CreateTemplateTupleDesc(1, false);
6727         TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6728                                            TEXTOID, -1, 0);
6729
6730         /* prepare for projection of tuples */
6731         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6732
6733         /* Send it */
6734         do_text_output_oneline(tstate, value);
6735
6736         end_tup_output(tstate);
6737 }
6738
6739 /*
6740  * SHOW ALL command
6741  */
6742 static void
6743 ShowAllGUCConfig(DestReceiver *dest)
6744 {
6745         bool            am_superuser = superuser();
6746         int                     i;
6747         TupOutputState *tstate;
6748         TupleDesc       tupdesc;
6749         Datum           values[3];
6750         bool            isnull[3] = {false, false, false};
6751
6752         /* need a tuple descriptor representing three TEXT columns */
6753         tupdesc = CreateTemplateTupleDesc(3, false);
6754         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6755                                            TEXTOID, -1, 0);
6756         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6757                                            TEXTOID, -1, 0);
6758         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6759                                            TEXTOID, -1, 0);
6760
6761         /* prepare for projection of tuples */
6762         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6763
6764         for (i = 0; i < num_guc_variables; i++)
6765         {
6766                 struct config_generic *conf = guc_variables[i];
6767                 char       *setting;
6768
6769                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6770                         ((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
6771                         continue;
6772
6773                 /* assign to the values array */
6774                 values[0] = PointerGetDatum(cstring_to_text(conf->name));
6775
6776                 setting = _ShowOption(conf, true);
6777                 if (setting)
6778                 {
6779                         values[1] = PointerGetDatum(cstring_to_text(setting));
6780                         isnull[1] = false;
6781                 }
6782                 else
6783                 {
6784                         values[1] = PointerGetDatum(NULL);
6785                         isnull[1] = true;
6786                 }
6787
6788                 values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
6789
6790                 /* send it to dest */
6791                 do_tup_output(tstate, values, isnull);
6792
6793                 /* clean up */
6794                 pfree(DatumGetPointer(values[0]));
6795                 if (setting)
6796                 {
6797                         pfree(setting);
6798                         pfree(DatumGetPointer(values[1]));
6799                 }
6800                 pfree(DatumGetPointer(values[2]));
6801         }
6802
6803         end_tup_output(tstate);
6804 }
6805
6806 /*
6807  * Return GUC variable value by name; optionally return canonical
6808  * form of name.  Return value is palloc'd.
6809  */
6810 char *
6811 GetConfigOptionByName(const char *name, const char **varname)
6812 {
6813         struct config_generic *record;
6814
6815         record = find_option(name, false, ERROR);
6816         if (record == NULL)
6817                 ereport(ERROR,
6818                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6819                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6820         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6821                 ereport(ERROR,
6822                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6823                                  errmsg("must be superuser to examine \"%s\"", name)));
6824
6825         if (varname)
6826                 *varname = record->name;
6827
6828         return _ShowOption(record, true);
6829 }
6830
6831 /*
6832  * Return GUC variable value by variable number; optionally return canonical
6833  * form of name.  Return value is palloc'd.
6834  */
6835 void
6836 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
6837 {
6838         char            buffer[256];
6839         struct config_generic *conf;
6840
6841         /* check requested variable number valid */
6842         Assert((varnum >= 0) && (varnum < num_guc_variables));
6843
6844         conf = guc_variables[varnum];
6845
6846         if (noshow)
6847         {
6848                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6849                         ((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
6850                         *noshow = true;
6851                 else
6852                         *noshow = false;
6853         }
6854
6855         /* first get the generic attributes */
6856
6857         /* name */
6858         values[0] = conf->name;
6859
6860         /* setting : use _ShowOption in order to avoid duplicating the logic */
6861         values[1] = _ShowOption(conf, false);
6862
6863         /* unit */
6864         if (conf->vartype == PGC_INT)
6865         {
6866                 static char buf[8];
6867
6868                 switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
6869                 {
6870                         case GUC_UNIT_KB:
6871                                 values[2] = "kB";
6872                                 break;
6873                         case GUC_UNIT_BLOCKS:
6874                                 snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
6875                                 values[2] = buf;
6876                                 break;
6877                         case GUC_UNIT_XBLOCKS:
6878                                 snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
6879                                 values[2] = buf;
6880                                 break;
6881                         case GUC_UNIT_MS:
6882                                 values[2] = "ms";
6883                                 break;
6884                         case GUC_UNIT_S:
6885                                 values[2] = "s";
6886                                 break;
6887                         case GUC_UNIT_MIN:
6888                                 values[2] = "min";
6889                                 break;
6890                         default:
6891                                 values[2] = "";
6892                                 break;
6893                 }
6894         }
6895         else
6896                 values[2] = NULL;
6897
6898         /* group */
6899         values[3] = config_group_names[conf->group];
6900
6901         /* short_desc */
6902         values[4] = conf->short_desc;
6903
6904         /* extra_desc */
6905         values[5] = conf->long_desc;
6906
6907         /* context */
6908         values[6] = GucContext_Names[conf->context];
6909
6910         /* vartype */
6911         values[7] = config_type_names[conf->vartype];
6912
6913         /* source */
6914         values[8] = GucSource_Names[conf->source];
6915
6916         /* now get the type specifc attributes */
6917         switch (conf->vartype)
6918         {
6919                 case PGC_BOOL:
6920                         {
6921                                 struct config_bool *lconf = (struct config_bool *) conf;
6922
6923                                 /* min_val */
6924                                 values[9] = NULL;
6925
6926                                 /* max_val */
6927                                 values[10] = NULL;
6928
6929                                 /* enumvals */
6930                                 values[11] = NULL;
6931
6932                                 /* boot_val */
6933                                 values[12] = pstrdup(lconf->boot_val ? "on" : "off");
6934
6935                                 /* reset_val */
6936                                 values[13] = pstrdup(lconf->reset_val ? "on" : "off");
6937                         }
6938                         break;
6939
6940                 case PGC_INT:
6941                         {
6942                                 struct config_int *lconf = (struct config_int *) conf;
6943
6944                                 /* min_val */
6945                                 snprintf(buffer, sizeof(buffer), "%d", lconf->min);
6946                                 values[9] = pstrdup(buffer);
6947
6948                                 /* max_val */
6949                                 snprintf(buffer, sizeof(buffer), "%d", lconf->max);
6950                                 values[10] = pstrdup(buffer);
6951
6952                                 /* enumvals */
6953                                 values[11] = NULL;
6954
6955                                 /* boot_val */
6956                                 snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
6957                                 values[12] = pstrdup(buffer);
6958
6959                                 /* reset_val */
6960                                 snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
6961                                 values[13] = pstrdup(buffer);
6962                         }
6963                         break;
6964
6965                 case PGC_REAL:
6966                         {
6967                                 struct config_real *lconf = (struct config_real *) conf;
6968
6969                                 /* min_val */
6970                                 snprintf(buffer, sizeof(buffer), "%g", lconf->min);
6971                                 values[9] = pstrdup(buffer);
6972
6973                                 /* max_val */
6974                                 snprintf(buffer, sizeof(buffer), "%g", lconf->max);
6975                                 values[10] = pstrdup(buffer);
6976
6977                                 /* enumvals */
6978                                 values[11] = NULL;
6979
6980                                 /* boot_val */
6981                                 snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
6982                                 values[12] = pstrdup(buffer);
6983
6984                                 /* reset_val */
6985                                 snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
6986                                 values[13] = pstrdup(buffer);
6987                         }
6988                         break;
6989
6990                 case PGC_STRING:
6991                         {
6992                                 struct config_string *lconf = (struct config_string *) conf;
6993
6994                                 /* min_val */
6995                                 values[9] = NULL;
6996
6997                                 /* max_val */
6998                                 values[10] = NULL;
6999
7000                                 /* enumvals */
7001                                 values[11] = NULL;
7002
7003                                 /* boot_val */
7004                                 if (lconf->boot_val == NULL)
7005                                         values[12] = NULL;
7006                                 else
7007                                         values[12] = pstrdup(lconf->boot_val);
7008
7009                                 /* reset_val */
7010                                 if (lconf->reset_val == NULL)
7011                                         values[13] = NULL;
7012                                 else
7013                                         values[13] = pstrdup(lconf->reset_val);
7014                         }
7015                         break;
7016
7017                 case PGC_ENUM:
7018                         {
7019                                 struct config_enum *lconf = (struct config_enum *) conf;
7020
7021                                 /* min_val */
7022                                 values[9] = NULL;
7023
7024                                 /* max_val */
7025                                 values[10] = NULL;
7026
7027                                 /* enumvals */
7028
7029                                 /*
7030                                  * NOTE! enumvals with double quotes in them are not
7031                                  * supported!
7032                                  */
7033                                 values[11] = config_enum_get_options((struct config_enum *) conf,
7034                                                                                                          "{\"", "\"}", "\",\"");
7035
7036                                 /* boot_val */
7037                                 values[12] = pstrdup(config_enum_lookup_by_value(lconf,
7038                                                                                                                    lconf->boot_val));
7039
7040                                 /* reset_val */
7041                                 values[13] = pstrdup(config_enum_lookup_by_value(lconf,
7042                                                                                                                   lconf->reset_val));
7043                         }
7044                         break;
7045
7046                 default:
7047                         {
7048                                 /*
7049                                  * should never get here, but in case we do, set 'em to NULL
7050                                  */
7051
7052                                 /* min_val */
7053                                 values[9] = NULL;
7054
7055                                 /* max_val */
7056                                 values[10] = NULL;
7057
7058                                 /* enumvals */
7059                                 values[11] = NULL;
7060
7061                                 /* boot_val */
7062                                 values[12] = NULL;
7063
7064                                 /* reset_val */
7065                                 values[13] = NULL;
7066                         }
7067                         break;
7068         }
7069
7070         /*
7071          * If the setting came from a config file, set the source location. For
7072          * security reasons, we don't show source file/line number for
7073          * non-superusers.
7074          */
7075         if (conf->source == PGC_S_FILE && superuser())
7076         {
7077                 values[14] = conf->sourcefile;
7078                 snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
7079                 values[15] = pstrdup(buffer);
7080         }
7081         else
7082         {
7083                 values[14] = NULL;
7084                 values[15] = NULL;
7085         }
7086 }
7087
7088 /*
7089  * Return the total number of GUC variables
7090  */
7091 int
7092 GetNumConfigOptions(void)
7093 {
7094         return num_guc_variables;
7095 }
7096
7097 /*
7098  * show_config_by_name - equiv to SHOW X command but implemented as
7099  * a function.
7100  */
7101 Datum
7102 show_config_by_name(PG_FUNCTION_ARGS)
7103 {
7104         char       *varname;
7105         char       *varval;
7106
7107         /* Get the GUC variable name */
7108         varname = TextDatumGetCString(PG_GETARG_DATUM(0));
7109
7110         /* Get the value */
7111         varval = GetConfigOptionByName(varname, NULL);
7112
7113         /* Convert to text */
7114         PG_RETURN_TEXT_P(cstring_to_text(varval));
7115 }
7116
7117 /*
7118  * show_all_settings - equiv to SHOW ALL command but implemented as
7119  * a Table Function.
7120  */
7121 #define NUM_PG_SETTINGS_ATTS    16
7122
7123 Datum
7124 show_all_settings(PG_FUNCTION_ARGS)
7125 {
7126         FuncCallContext *funcctx;
7127         TupleDesc       tupdesc;
7128         int                     call_cntr;
7129         int                     max_calls;
7130         AttInMetadata *attinmeta;
7131         MemoryContext oldcontext;
7132
7133         /* stuff done only on the first call of the function */
7134         if (SRF_IS_FIRSTCALL())
7135         {
7136                 /* create a function context for cross-call persistence */
7137                 funcctx = SRF_FIRSTCALL_INIT();
7138
7139                 /*
7140                  * switch to memory context appropriate for multiple function calls
7141                  */
7142                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
7143
7144                 /*
7145                  * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
7146                  * of the appropriate types
7147                  */
7148                 tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
7149                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7150                                                    TEXTOID, -1, 0);
7151                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7152                                                    TEXTOID, -1, 0);
7153                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
7154                                                    TEXTOID, -1, 0);
7155                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
7156                                                    TEXTOID, -1, 0);
7157                 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
7158                                                    TEXTOID, -1, 0);
7159                 TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
7160                                                    TEXTOID, -1, 0);
7161                 TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
7162                                                    TEXTOID, -1, 0);
7163                 TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
7164                                                    TEXTOID, -1, 0);
7165                 TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
7166                                                    TEXTOID, -1, 0);
7167                 TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
7168                                                    TEXTOID, -1, 0);
7169                 TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
7170                                                    TEXTOID, -1, 0);
7171                 TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
7172                                                    TEXTARRAYOID, -1, 0);
7173                 TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
7174                                                    TEXTOID, -1, 0);
7175                 TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
7176                                                    TEXTOID, -1, 0);
7177                 TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
7178                                                    TEXTOID, -1, 0);
7179                 TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
7180                                                    INT4OID, -1, 0);
7181
7182                 /*
7183                  * Generate attribute metadata needed later to produce tuples from raw
7184                  * C strings
7185                  */
7186                 attinmeta = TupleDescGetAttInMetadata(tupdesc);
7187                 funcctx->attinmeta = attinmeta;
7188
7189                 /* total number of tuples to be returned */
7190                 funcctx->max_calls = GetNumConfigOptions();
7191
7192                 MemoryContextSwitchTo(oldcontext);
7193         }
7194
7195         /* stuff done on every call of the function */
7196         funcctx = SRF_PERCALL_SETUP();
7197
7198         call_cntr = funcctx->call_cntr;
7199         max_calls = funcctx->max_calls;
7200         attinmeta = funcctx->attinmeta;
7201
7202         if (call_cntr < max_calls)      /* do when there is more left to send */
7203         {
7204                 char       *values[NUM_PG_SETTINGS_ATTS];
7205                 bool            noshow;
7206                 HeapTuple       tuple;
7207                 Datum           result;
7208
7209                 /*
7210                  * Get the next visible GUC variable name and value
7211                  */
7212                 do
7213                 {
7214                         GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
7215                         if (noshow)
7216                         {
7217                                 /* bump the counter and get the next config setting */
7218                                 call_cntr = ++funcctx->call_cntr;
7219
7220                                 /* make sure we haven't gone too far now */
7221                                 if (call_cntr >= max_calls)
7222                                         SRF_RETURN_DONE(funcctx);
7223                         }
7224                 } while (noshow);
7225
7226                 /* build a tuple */
7227                 tuple = BuildTupleFromCStrings(attinmeta, values);
7228
7229                 /* make the tuple into a datum */
7230                 result = HeapTupleGetDatum(tuple);
7231
7232                 SRF_RETURN_NEXT(funcctx, result);
7233         }
7234         else
7235         {
7236                 /* do when there is no more left */
7237                 SRF_RETURN_DONE(funcctx);
7238         }
7239 }
7240
7241 static char *
7242 _ShowOption(struct config_generic * record, bool use_units)
7243 {
7244         char            buffer[256];
7245         const char *val;
7246
7247         switch (record->vartype)
7248         {
7249                 case PGC_BOOL:
7250                         {
7251                                 struct config_bool *conf = (struct config_bool *) record;
7252
7253                                 if (conf->show_hook)
7254                                         val = (*conf->show_hook) ();
7255                                 else
7256                                         val = *conf->variable ? "on" : "off";
7257                         }
7258                         break;
7259
7260                 case PGC_INT:
7261                         {
7262                                 struct config_int *conf = (struct config_int *) record;
7263
7264                                 if (conf->show_hook)
7265                                         val = (*conf->show_hook) ();
7266                                 else
7267                                 {
7268                                         /*
7269                                          * Use int64 arithmetic to avoid overflows in units
7270                                          * conversion.
7271                                          */
7272                                         int64           result = *conf->variable;
7273                                         const char *unit;
7274
7275                                         if (use_units && result > 0 &&
7276                                                 (record->flags & GUC_UNIT_MEMORY))
7277                                         {
7278                                                 switch (record->flags & GUC_UNIT_MEMORY)
7279                                                 {
7280                                                         case GUC_UNIT_BLOCKS:
7281                                                                 result *= BLCKSZ / 1024;
7282                                                                 break;
7283                                                         case GUC_UNIT_XBLOCKS:
7284                                                                 result *= XLOG_BLCKSZ / 1024;
7285                                                                 break;
7286                                                 }
7287
7288                                                 if (result % KB_PER_GB == 0)
7289                                                 {
7290                                                         result /= KB_PER_GB;
7291                                                         unit = "GB";
7292                                                 }
7293                                                 else if (result % KB_PER_MB == 0)
7294                                                 {
7295                                                         result /= KB_PER_MB;
7296                                                         unit = "MB";
7297                                                 }
7298                                                 else
7299                                                 {
7300                                                         unit = "kB";
7301                                                 }
7302                                         }
7303                                         else if (use_units && result > 0 &&
7304                                                          (record->flags & GUC_UNIT_TIME))
7305                                         {
7306                                                 switch (record->flags & GUC_UNIT_TIME)
7307                                                 {
7308                                                         case GUC_UNIT_S:
7309                                                                 result *= MS_PER_S;
7310                                                                 break;
7311                                                         case GUC_UNIT_MIN:
7312                                                                 result *= MS_PER_MIN;
7313                                                                 break;
7314                                                 }
7315
7316                                                 if (result % MS_PER_D == 0)
7317                                                 {
7318                                                         result /= MS_PER_D;
7319                                                         unit = "d";
7320                                                 }
7321                                                 else if (result % MS_PER_H == 0)
7322                                                 {
7323                                                         result /= MS_PER_H;
7324                                                         unit = "h";
7325                                                 }
7326                                                 else if (result % MS_PER_MIN == 0)
7327                                                 {
7328                                                         result /= MS_PER_MIN;
7329                                                         unit = "min";
7330                                                 }
7331                                                 else if (result % MS_PER_S == 0)
7332                                                 {
7333                                                         result /= MS_PER_S;
7334                                                         unit = "s";
7335                                                 }
7336                                                 else
7337                                                 {
7338                                                         unit = "ms";
7339                                                 }
7340                                         }
7341                                         else
7342                                                 unit = "";
7343
7344                                         snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
7345                                                          result, unit);
7346                                         val = buffer;
7347                                 }
7348                         }
7349                         break;
7350
7351                 case PGC_REAL:
7352                         {
7353                                 struct config_real *conf = (struct config_real *) record;
7354
7355                                 if (conf->show_hook)
7356                                         val = (*conf->show_hook) ();
7357                                 else
7358                                 {
7359                                         snprintf(buffer, sizeof(buffer), "%g",
7360                                                          *conf->variable);
7361                                         val = buffer;
7362                                 }
7363                         }
7364                         break;
7365
7366                 case PGC_STRING:
7367                         {
7368                                 struct config_string *conf = (struct config_string *) record;
7369
7370                                 if (conf->show_hook)
7371                                         val = (*conf->show_hook) ();
7372                                 else if (*conf->variable && **conf->variable)
7373                                         val = *conf->variable;
7374                                 else
7375                                         val = "";
7376                         }
7377                         break;
7378
7379                 case PGC_ENUM:
7380                         {
7381                                 struct config_enum *conf = (struct config_enum *) record;
7382
7383                                 if (conf->show_hook)
7384                                         val = (*conf->show_hook) ();
7385                                 else
7386                                         val = config_enum_lookup_by_value(conf, *conf->variable);
7387                         }
7388                         break;
7389
7390                 default:
7391                         /* just to keep compiler quiet */
7392                         val = "???";
7393                         break;
7394         }
7395
7396         return pstrdup(val);
7397 }
7398
7399
7400 #ifdef EXEC_BACKEND
7401
7402 /*
7403  *      These routines dump out all non-default GUC options into a binary
7404  *      file that is read by all exec'ed backends.  The format is:
7405  *
7406  *              variable name, string, null terminated
7407  *              variable value, string, null terminated
7408  *              variable sourcefile, string, null terminated (empty if none)
7409  *              variable sourceline, integer
7410  *              variable source, integer
7411  *              variable scontext, integer
7412  */
7413 static void
7414 write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
7415 {
7416         if (gconf->source == PGC_S_DEFAULT)
7417                 return;
7418
7419         fprintf(fp, "%s", gconf->name);
7420         fputc(0, fp);
7421
7422         switch (gconf->vartype)
7423         {
7424                 case PGC_BOOL:
7425                         {
7426                                 struct config_bool *conf = (struct config_bool *) gconf;
7427
7428                                 if (*conf->variable)
7429                                         fprintf(fp, "true");
7430                                 else
7431                                         fprintf(fp, "false");
7432                         }
7433                         break;
7434
7435                 case PGC_INT:
7436                         {
7437                                 struct config_int *conf = (struct config_int *) gconf;
7438
7439                                 fprintf(fp, "%d", *conf->variable);
7440                         }
7441                         break;
7442
7443                 case PGC_REAL:
7444                         {
7445                                 struct config_real *conf = (struct config_real *) gconf;
7446
7447                                 fprintf(fp, "%.17g", *conf->variable);
7448                         }
7449                         break;
7450
7451                 case PGC_STRING:
7452                         {
7453                                 struct config_string *conf = (struct config_string *) gconf;
7454
7455                                 fprintf(fp, "%s", *conf->variable);
7456                         }
7457                         break;
7458
7459                 case PGC_ENUM:
7460                         {
7461                                 struct config_enum *conf = (struct config_enum *) gconf;
7462
7463                                 fprintf(fp, "%s",
7464                                                 config_enum_lookup_by_value(conf, *conf->variable));
7465                         }
7466                         break;
7467         }
7468
7469         fputc(0, fp);
7470
7471         if (gconf->sourcefile)
7472                 fprintf(fp, "%s", gconf->sourcefile);
7473         fputc(0, fp);
7474
7475         fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
7476         fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
7477         fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
7478 }
7479
7480 void
7481 write_nondefault_variables(GucContext context)
7482 {
7483         int                     elevel;
7484         FILE       *fp;
7485         int                     i;
7486
7487         Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
7488
7489         elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
7490
7491         /*
7492          * Open file
7493          */
7494         fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
7495         if (!fp)
7496         {
7497                 ereport(elevel,
7498                                 (errcode_for_file_access(),
7499                                  errmsg("could not write to file \"%s\": %m",
7500                                                 CONFIG_EXEC_PARAMS_NEW)));
7501                 return;
7502         }
7503
7504         for (i = 0; i < num_guc_variables; i++)
7505         {
7506                 write_one_nondefault_variable(fp, guc_variables[i]);
7507         }
7508
7509         if (FreeFile(fp))
7510         {
7511                 ereport(elevel,
7512                                 (errcode_for_file_access(),
7513                                  errmsg("could not write to file \"%s\": %m",
7514                                                 CONFIG_EXEC_PARAMS_NEW)));
7515                 return;
7516         }
7517
7518         /*
7519          * Put new file in place.  This could delay on Win32, but we don't hold
7520          * any exclusive locks.
7521          */
7522         rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
7523 }
7524
7525
7526 /*
7527  *      Read string, including null byte from file
7528  *
7529  *      Return NULL on EOF and nothing read
7530  */
7531 static char *
7532 read_string_with_null(FILE *fp)
7533 {
7534         int                     i = 0,
7535                                 ch,
7536                                 maxlen = 256;
7537         char       *str = NULL;
7538
7539         do
7540         {
7541                 if ((ch = fgetc(fp)) == EOF)
7542                 {
7543                         if (i == 0)
7544                                 return NULL;
7545                         else
7546                                 elog(FATAL, "invalid format of exec config params file");
7547                 }
7548                 if (i == 0)
7549                         str = guc_malloc(FATAL, maxlen);
7550                 else if (i == maxlen)
7551                         str = guc_realloc(FATAL, str, maxlen *= 2);
7552                 str[i++] = ch;
7553         } while (ch != 0);
7554
7555         return str;
7556 }
7557
7558
7559 /*
7560  *      This routine loads a previous postmaster dump of its non-default
7561  *      settings.
7562  */
7563 void
7564 read_nondefault_variables(void)
7565 {
7566         FILE       *fp;
7567         char       *varname,
7568                            *varvalue,
7569                            *varsourcefile;
7570         int                     varsourceline;
7571         GucSource       varsource;
7572         GucContext      varscontext;
7573
7574         /*
7575          * Open file
7576          */
7577         fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
7578         if (!fp)
7579         {
7580                 /* File not found is fine */
7581                 if (errno != ENOENT)
7582                         ereport(FATAL,
7583                                         (errcode_for_file_access(),
7584                                          errmsg("could not read from file \"%s\": %m",
7585                                                         CONFIG_EXEC_PARAMS)));
7586                 return;
7587         }
7588
7589         for (;;)
7590         {
7591                 struct config_generic *record;
7592
7593                 if ((varname = read_string_with_null(fp)) == NULL)
7594                         break;
7595
7596                 if ((record = find_option(varname, true, FATAL)) == NULL)
7597                         elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
7598
7599                 if ((varvalue = read_string_with_null(fp)) == NULL)
7600                         elog(FATAL, "invalid format of exec config params file");
7601                 if ((varsourcefile = read_string_with_null(fp)) == NULL)
7602                         elog(FATAL, "invalid format of exec config params file");
7603                 if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
7604                         elog(FATAL, "invalid format of exec config params file");
7605                 if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
7606                         elog(FATAL, "invalid format of exec config params file");
7607                 if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
7608                         elog(FATAL, "invalid format of exec config params file");
7609
7610                 (void) set_config_option(varname, varvalue,
7611                                                                  varscontext, varsource,
7612                                                                  GUC_ACTION_SET, true, 0);
7613                 if (varsourcefile[0])
7614                         set_config_sourcefile(varname, varsourcefile, varsourceline);
7615
7616                 free(varname);
7617                 free(varvalue);
7618                 free(varsourcefile);
7619         }
7620
7621         FreeFile(fp);
7622 }
7623 #endif   /* EXEC_BACKEND */
7624
7625
7626 /*
7627  * A little "long argument" simulation, although not quite GNU
7628  * compliant. Takes a string of the form "some-option=some value" and
7629  * returns name = "some_option" and value = "some value" in malloc'ed
7630  * storage. Note that '-' is converted to '_' in the option name. If
7631  * there is no '=' in the input string then value will be NULL.
7632  */
7633 void
7634 ParseLongOption(const char *string, char **name, char **value)
7635 {
7636         size_t          equal_pos;
7637         char       *cp;
7638
7639         AssertArg(string);
7640         AssertArg(name);
7641         AssertArg(value);
7642
7643         equal_pos = strcspn(string, "=");
7644
7645         if (string[equal_pos] == '=')
7646         {
7647                 *name = guc_malloc(FATAL, equal_pos + 1);
7648                 strlcpy(*name, string, equal_pos + 1);
7649
7650                 *value = guc_strdup(FATAL, &string[equal_pos + 1]);
7651         }
7652         else
7653         {
7654                 /* no equal sign in string */
7655                 *name = guc_strdup(FATAL, string);
7656                 *value = NULL;
7657         }
7658
7659         for (cp = *name; *cp; cp++)
7660                 if (*cp == '-')
7661                         *cp = '_';
7662 }
7663
7664
7665 /*
7666  * Handle options fetched from pg_db_role_setting.setconfig,
7667  * pg_proc.proconfig, etc.      Caller must specify proper context/source/action.
7668  *
7669  * The array parameter must be an array of TEXT (it must not be NULL).
7670  */
7671 void
7672 ProcessGUCArray(ArrayType *array,
7673                                 GucContext context, GucSource source, GucAction action)
7674 {
7675         int                     i;
7676
7677         Assert(array != NULL);
7678         Assert(ARR_ELEMTYPE(array) == TEXTOID);
7679         Assert(ARR_NDIM(array) == 1);
7680         Assert(ARR_LBOUND(array)[0] == 1);
7681
7682         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7683         {
7684                 Datum           d;
7685                 bool            isnull;
7686                 char       *s;
7687                 char       *name;
7688                 char       *value;
7689
7690                 d = array_ref(array, 1, &i,
7691                                           -1 /* varlenarray */ ,
7692                                           -1 /* TEXT's typlen */ ,
7693                                           false /* TEXT's typbyval */ ,
7694                                           'i' /* TEXT's typalign */ ,
7695                                           &isnull);
7696
7697                 if (isnull)
7698                         continue;
7699
7700                 s = TextDatumGetCString(d);
7701
7702                 ParseLongOption(s, &name, &value);
7703                 if (!value)
7704                 {
7705                         ereport(WARNING,
7706                                         (errcode(ERRCODE_SYNTAX_ERROR),
7707                                          errmsg("could not parse setting for parameter \"%s\"",
7708                                                         name)));
7709                         free(name);
7710                         continue;
7711                 }
7712
7713                 (void) set_config_option(name, value,
7714                                                                  context, source,
7715                                                                  action, true, 0);
7716
7717                 free(name);
7718                 if (value)
7719                         free(value);
7720                 pfree(s);
7721         }
7722 }
7723
7724
7725 /*
7726  * Add an entry to an option array.  The array parameter may be NULL
7727  * to indicate the current table entry is NULL.
7728  */
7729 ArrayType *
7730 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
7731 {
7732         struct config_generic *record;
7733         Datum           datum;
7734         char       *newval;
7735         ArrayType  *a;
7736
7737         Assert(name);
7738         Assert(value);
7739
7740         /* test if the option is valid and we're allowed to set it */
7741         (void) validate_option_array_item(name, value, false);
7742
7743         /* normalize name (converts obsolete GUC names to modern spellings) */
7744         record = find_option(name, false, WARNING);
7745         if (record)
7746                 name = record->name;
7747
7748         /* build new item for array */
7749         newval = palloc(strlen(name) + 1 + strlen(value) + 1);
7750         sprintf(newval, "%s=%s", name, value);
7751         datum = CStringGetTextDatum(newval);
7752
7753         if (array)
7754         {
7755                 int                     index;
7756                 bool            isnull;
7757                 int                     i;
7758
7759                 Assert(ARR_ELEMTYPE(array) == TEXTOID);
7760                 Assert(ARR_NDIM(array) == 1);
7761                 Assert(ARR_LBOUND(array)[0] == 1);
7762
7763                 index = ARR_DIMS(array)[0] + 1; /* add after end */
7764
7765                 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7766                 {
7767                         Datum           d;
7768                         char       *current;
7769
7770                         d = array_ref(array, 1, &i,
7771                                                   -1 /* varlenarray */ ,
7772                                                   -1 /* TEXT's typlen */ ,
7773                                                   false /* TEXT's typbyval */ ,
7774                                                   'i' /* TEXT's typalign */ ,
7775                                                   &isnull);
7776                         if (isnull)
7777                                 continue;
7778                         current = TextDatumGetCString(d);
7779
7780                         /* check for match up through and including '=' */
7781                         if (strncmp(current, newval, strlen(name) + 1) == 0)
7782                         {
7783                                 index = i;
7784                                 break;
7785                         }
7786                 }
7787
7788                 a = array_set(array, 1, &index,
7789                                           datum,
7790                                           false,
7791                                           -1 /* varlena array */ ,
7792                                           -1 /* TEXT's typlen */ ,
7793                                           false /* TEXT's typbyval */ ,
7794                                           'i' /* TEXT's typalign */ );
7795         }
7796         else
7797                 a = construct_array(&datum, 1,
7798                                                         TEXTOID,
7799                                                         -1, false, 'i');
7800
7801         return a;
7802 }
7803
7804
7805 /*
7806  * Delete an entry from an option array.  The array parameter may be NULL
7807  * to indicate the current table entry is NULL.  Also, if the return value
7808  * is NULL then a null should be stored.
7809  */
7810 ArrayType *
7811 GUCArrayDelete(ArrayType *array, const char *name)
7812 {
7813         struct config_generic *record;
7814         ArrayType  *newarray;
7815         int                     i;
7816         int                     index;
7817
7818         Assert(name);
7819
7820         /* test if the option is valid and we're allowed to set it */
7821         (void) validate_option_array_item(name, NULL, false);
7822
7823         /* normalize name (converts obsolete GUC names to modern spellings) */
7824         record = find_option(name, false, WARNING);
7825         if (record)
7826                 name = record->name;
7827
7828         /* if array is currently null, then surely nothing to delete */
7829         if (!array)
7830                 return NULL;
7831
7832         newarray = NULL;
7833         index = 1;
7834
7835         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7836         {
7837                 Datum           d;
7838                 char       *val;
7839                 bool            isnull;
7840
7841                 d = array_ref(array, 1, &i,
7842                                           -1 /* varlenarray */ ,
7843                                           -1 /* TEXT's typlen */ ,
7844                                           false /* TEXT's typbyval */ ,
7845                                           'i' /* TEXT's typalign */ ,
7846                                           &isnull);
7847                 if (isnull)
7848                         continue;
7849                 val = TextDatumGetCString(d);
7850
7851                 /* ignore entry if it's what we want to delete */
7852                 if (strncmp(val, name, strlen(name)) == 0
7853                         && val[strlen(name)] == '=')
7854                         continue;
7855
7856                 /* else add it to the output array */
7857                 if (newarray)
7858                         newarray = array_set(newarray, 1, &index,
7859                                                                  d,
7860                                                                  false,
7861                                                                  -1 /* varlenarray */ ,
7862                                                                  -1 /* TEXT's typlen */ ,
7863                                                                  false /* TEXT's typbyval */ ,
7864                                                                  'i' /* TEXT's typalign */ );
7865                 else
7866                         newarray = construct_array(&d, 1,
7867                                                                            TEXTOID,
7868                                                                            -1, false, 'i');
7869
7870                 index++;
7871         }
7872
7873         return newarray;
7874 }
7875
7876
7877 /*
7878  * Given a GUC array, delete all settings from it that our permission
7879  * level allows: if superuser, delete them all; if regular user, only
7880  * those that are PGC_USERSET
7881  */
7882 ArrayType *
7883 GUCArrayReset(ArrayType *array)
7884 {
7885         ArrayType  *newarray;
7886         int                     i;
7887         int                     index;
7888
7889         /* if array is currently null, nothing to do */
7890         if (!array)
7891                 return NULL;
7892
7893         /* if we're superuser, we can delete everything, so just do it */
7894         if (superuser())
7895                 return NULL;
7896
7897         newarray = NULL;
7898         index = 1;
7899
7900         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7901         {
7902                 Datum           d;
7903                 char       *val;
7904                 char       *eqsgn;
7905                 bool            isnull;
7906
7907                 d = array_ref(array, 1, &i,
7908                                           -1 /* varlenarray */ ,
7909                                           -1 /* TEXT's typlen */ ,
7910                                           false /* TEXT's typbyval */ ,
7911                                           'i' /* TEXT's typalign */ ,
7912                                           &isnull);
7913                 if (isnull)
7914                         continue;
7915                 val = TextDatumGetCString(d);
7916
7917                 eqsgn = strchr(val, '=');
7918                 *eqsgn = '\0';
7919
7920                 /* skip if we have permission to delete it */
7921                 if (validate_option_array_item(val, NULL, true))
7922                         continue;
7923
7924                 /* else add it to the output array */
7925                 if (newarray)
7926                         newarray = array_set(newarray, 1, &index,
7927                                                                  d,
7928                                                                  false,
7929                                                                  -1 /* varlenarray */ ,
7930                                                                  -1 /* TEXT's typlen */ ,
7931                                                                  false /* TEXT's typbyval */ ,
7932                                                                  'i' /* TEXT's typalign */ );
7933                 else
7934                         newarray = construct_array(&d, 1,
7935                                                                            TEXTOID,
7936                                                                            -1, false, 'i');
7937
7938                 index++;
7939                 pfree(val);
7940         }
7941
7942         return newarray;
7943 }
7944
7945 /*
7946  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
7947  *
7948  * name is the option name.  value is the proposed value for the Add case,
7949  * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
7950  * not an error to have no permissions to set the option.
7951  *
7952  * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
7953  * have permission to change this option (all other error cases result in an
7954  * error being thrown).
7955  */
7956 static bool
7957 validate_option_array_item(const char *name, const char *value,
7958                                                    bool skipIfNoPermissions)
7959
7960 {
7961         struct config_generic *gconf;
7962
7963         /*
7964          * There are three cases to consider:
7965          *
7966          * name is a known GUC variable.  Check the value normally, check
7967          * permissions normally (ie, allow if variable is USERSET, or if it's
7968          * SUSET and user is superuser).
7969          *
7970          * name is not known, but exists or can be created as a placeholder (i.e.,
7971          * it has a prefixed name).  We allow this case if you're a superuser,
7972          * otherwise not.  Superusers are assumed to know what they're doing.
7973          * We can't allow it for other users, because when the placeholder is
7974          * resolved it might turn out to be a SUSET variable;
7975          * define_custom_variable assumes we checked that.
7976          *
7977          * name is not known and can't be created as a placeholder.  Throw error,
7978          * unless skipIfNoPermissions is true, in which case return FALSE.
7979          */
7980         gconf = find_option(name, true, WARNING);
7981         if (!gconf)
7982         {
7983                 /* not known, failed to make a placeholder */
7984                 if (skipIfNoPermissions)
7985                         return false;
7986                 ereport(ERROR,
7987                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
7988                                  errmsg("unrecognized configuration parameter \"%s\"",
7989                                                 name)));
7990         }
7991
7992         if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
7993         {
7994                 /*
7995                  * We cannot do any meaningful check on the value, so only permissions
7996                  * are useful to check.
7997                  */
7998                 if (superuser())
7999                         return true;
8000                 if (skipIfNoPermissions)
8001                         return false;
8002                 ereport(ERROR,
8003                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8004                                  errmsg("permission denied to set parameter \"%s\"", name)));
8005         }
8006
8007         /* manual permissions check so we can avoid an error being thrown */
8008         if (gconf->context == PGC_USERSET)
8009                  /* ok */ ;
8010         else if (gconf->context == PGC_SUSET && superuser())
8011                  /* ok */ ;
8012         else if (skipIfNoPermissions)
8013                 return false;
8014         /* if a permissions error should be thrown, let set_config_option do it */
8015
8016         /* test for permissions and valid option value */
8017         (void) set_config_option(name, value,
8018                                                          superuser() ? PGC_SUSET : PGC_USERSET,
8019                                                          PGC_S_TEST, GUC_ACTION_SET, false, 0);
8020
8021         return true;
8022 }
8023
8024
8025 /*
8026  * Called by check_hooks that want to override the normal
8027  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
8028  *
8029  * Note that GUC_check_errmsg() etc are just macros that result in a direct
8030  * assignment to the associated variables.      That is ugly, but forced by the
8031  * limitations of C's macro mechanisms.
8032  */
8033 void
8034 GUC_check_errcode(int sqlerrcode)
8035 {
8036         GUC_check_errcode_value = sqlerrcode;
8037 }
8038
8039
8040 /*
8041  * Convenience functions to manage calling a variable's check_hook.
8042  * These mostly take care of the protocol for letting check hooks supply
8043  * portions of the error report on failure.
8044  */
8045
8046 static bool
8047 call_bool_check_hook(struct config_bool * conf, bool *newval, void **extra,
8048                                          GucSource source, int elevel)
8049 {
8050         /* Quick success if no hook */
8051         if (!conf->check_hook)
8052                 return true;
8053
8054         /* Reset variables that might be set by hook */
8055         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8056         GUC_check_errmsg_string = NULL;
8057         GUC_check_errdetail_string = NULL;
8058         GUC_check_errhint_string = NULL;
8059
8060         if (!(*conf->check_hook) (newval, extra, source))
8061         {
8062                 ereport(elevel,
8063                                 (errcode(GUC_check_errcode_value),
8064                                  GUC_check_errmsg_string ?
8065                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8066                                  errmsg("invalid value for parameter \"%s\": %d",
8067                                                 conf->gen.name, (int) *newval),
8068                                  GUC_check_errdetail_string ?
8069                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8070                                  GUC_check_errhint_string ?
8071                                  errhint("%s", GUC_check_errhint_string) : 0));
8072                 /* Flush any strings created in ErrorContext */
8073                 FlushErrorState();
8074                 return false;
8075         }
8076
8077         return true;
8078 }
8079
8080 static bool
8081 call_int_check_hook(struct config_int * conf, int *newval, void **extra,
8082                                         GucSource source, int elevel)
8083 {
8084         /* Quick success if no hook */
8085         if (!conf->check_hook)
8086                 return true;
8087
8088         /* Reset variables that might be set by hook */
8089         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8090         GUC_check_errmsg_string = NULL;
8091         GUC_check_errdetail_string = NULL;
8092         GUC_check_errhint_string = NULL;
8093
8094         if (!(*conf->check_hook) (newval, extra, source))
8095         {
8096                 ereport(elevel,
8097                                 (errcode(GUC_check_errcode_value),
8098                                  GUC_check_errmsg_string ?
8099                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8100                                  errmsg("invalid value for parameter \"%s\": %d",
8101                                                 conf->gen.name, *newval),
8102                                  GUC_check_errdetail_string ?
8103                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8104                                  GUC_check_errhint_string ?
8105                                  errhint("%s", GUC_check_errhint_string) : 0));
8106                 /* Flush any strings created in ErrorContext */
8107                 FlushErrorState();
8108                 return false;
8109         }
8110
8111         return true;
8112 }
8113
8114 static bool
8115 call_real_check_hook(struct config_real * conf, double *newval, void **extra,
8116                                          GucSource source, int elevel)
8117 {
8118         /* Quick success if no hook */
8119         if (!conf->check_hook)
8120                 return true;
8121
8122         /* Reset variables that might be set by hook */
8123         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8124         GUC_check_errmsg_string = NULL;
8125         GUC_check_errdetail_string = NULL;
8126         GUC_check_errhint_string = NULL;
8127
8128         if (!(*conf->check_hook) (newval, extra, source))
8129         {
8130                 ereport(elevel,
8131                                 (errcode(GUC_check_errcode_value),
8132                                  GUC_check_errmsg_string ?
8133                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8134                                  errmsg("invalid value for parameter \"%s\": %g",
8135                                                 conf->gen.name, *newval),
8136                                  GUC_check_errdetail_string ?
8137                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8138                                  GUC_check_errhint_string ?
8139                                  errhint("%s", GUC_check_errhint_string) : 0));
8140                 /* Flush any strings created in ErrorContext */
8141                 FlushErrorState();
8142                 return false;
8143         }
8144
8145         return true;
8146 }
8147
8148 static bool
8149 call_string_check_hook(struct config_string * conf, char **newval, void **extra,
8150                                            GucSource source, int elevel)
8151 {
8152         /* Quick success if no hook */
8153         if (!conf->check_hook)
8154                 return true;
8155
8156         /* Reset variables that might be set by hook */
8157         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8158         GUC_check_errmsg_string = NULL;
8159         GUC_check_errdetail_string = NULL;
8160         GUC_check_errhint_string = NULL;
8161
8162         if (!(*conf->check_hook) (newval, extra, source))
8163         {
8164                 ereport(elevel,
8165                                 (errcode(GUC_check_errcode_value),
8166                                  GUC_check_errmsg_string ?
8167                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8168                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8169                                                 conf->gen.name, *newval ? *newval : ""),
8170                                  GUC_check_errdetail_string ?
8171                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8172                                  GUC_check_errhint_string ?
8173                                  errhint("%s", GUC_check_errhint_string) : 0));
8174                 /* Flush any strings created in ErrorContext */
8175                 FlushErrorState();
8176                 return false;
8177         }
8178
8179         return true;
8180 }
8181
8182 static bool
8183 call_enum_check_hook(struct config_enum * conf, int *newval, void **extra,
8184                                          GucSource source, int elevel)
8185 {
8186         /* Quick success if no hook */
8187         if (!conf->check_hook)
8188                 return true;
8189
8190         /* Reset variables that might be set by hook */
8191         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8192         GUC_check_errmsg_string = NULL;
8193         GUC_check_errdetail_string = NULL;
8194         GUC_check_errhint_string = NULL;
8195
8196         if (!(*conf->check_hook) (newval, extra, source))
8197         {
8198                 ereport(elevel,
8199                                 (errcode(GUC_check_errcode_value),
8200                                  GUC_check_errmsg_string ?
8201                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8202                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8203                                                 conf->gen.name,
8204                                                 config_enum_lookup_by_value(conf, *newval)),
8205                                  GUC_check_errdetail_string ?
8206                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8207                                  GUC_check_errhint_string ?
8208                                  errhint("%s", GUC_check_errhint_string) : 0));
8209                 /* Flush any strings created in ErrorContext */
8210                 FlushErrorState();
8211                 return false;
8212         }
8213
8214         return true;
8215 }
8216
8217
8218 /*
8219  * check_hook, assign_hook and show_hook subroutines
8220  */
8221
8222 static bool
8223 check_log_destination(char **newval, void **extra, GucSource source)
8224 {
8225         char       *rawstring;
8226         List       *elemlist;
8227         ListCell   *l;
8228         int                     newlogdest = 0;
8229         int                *myextra;
8230
8231         /* Need a modifiable copy of string */
8232         rawstring = pstrdup(*newval);
8233
8234         /* Parse string into list of identifiers */
8235         if (!SplitIdentifierString(rawstring, ',', &elemlist))
8236         {
8237                 /* syntax error in list */
8238                 GUC_check_errdetail("List syntax is invalid.");
8239                 pfree(rawstring);
8240                 list_free(elemlist);
8241                 return false;
8242         }
8243
8244         foreach(l, elemlist)
8245         {
8246                 char       *tok = (char *) lfirst(l);
8247
8248                 if (pg_strcasecmp(tok, "stderr") == 0)
8249                         newlogdest |= LOG_DESTINATION_STDERR;
8250                 else if (pg_strcasecmp(tok, "csvlog") == 0)
8251                         newlogdest |= LOG_DESTINATION_CSVLOG;
8252 #ifdef HAVE_SYSLOG
8253                 else if (pg_strcasecmp(tok, "syslog") == 0)
8254                         newlogdest |= LOG_DESTINATION_SYSLOG;
8255 #endif
8256 #ifdef WIN32
8257                 else if (pg_strcasecmp(tok, "eventlog") == 0)
8258                         newlogdest |= LOG_DESTINATION_EVENTLOG;
8259 #endif
8260                 else
8261                 {
8262                         GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
8263                         pfree(rawstring);
8264                         list_free(elemlist);
8265                         return false;
8266                 }
8267         }
8268
8269         pfree(rawstring);
8270         list_free(elemlist);
8271
8272         myextra = (int *) guc_malloc(ERROR, sizeof(int));
8273         *myextra = newlogdest;
8274         *extra = (void *) myextra;
8275
8276         return true;
8277 }
8278
8279 static void
8280 assign_log_destination(const char *newval, void *extra)
8281 {
8282         Log_destination = *((int *) extra);
8283 }
8284
8285 static void
8286 assign_syslog_facility(int newval, void *extra)
8287 {
8288 #ifdef HAVE_SYSLOG
8289         set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
8290                                                   newval);
8291 #endif
8292         /* Without syslog support, just ignore it */
8293 }
8294
8295 static void
8296 assign_syslog_ident(const char *newval, void *extra)
8297 {
8298 #ifdef HAVE_SYSLOG
8299         set_syslog_parameters(newval, syslog_facility);
8300 #endif
8301         /* Without syslog support, it will always be set to "none", so ignore */
8302 }
8303
8304
8305 static void
8306 assign_session_replication_role(int newval, void *extra)
8307 {
8308         /*
8309          * Must flush the plan cache when changing replication role; but don't
8310          * flush unnecessarily.
8311          */
8312         if (SessionReplicationRole != newval)
8313                 ResetPlanCache();
8314 }
8315
8316 static bool
8317 check_temp_buffers(int *newval, void **extra, GucSource source)
8318 {
8319         /*
8320          * Once local buffers have been initialized, it's too late to change this.
8321          */
8322         if (NLocBuffer && NLocBuffer != *newval)
8323         {
8324                 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
8325                 return false;
8326         }
8327         return true;
8328 }
8329
8330 static bool
8331 check_phony_autocommit(bool *newval, void **extra, GucSource source)
8332 {
8333         if (!*newval)
8334         {
8335                 GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
8336                 GUC_check_errmsg("SET AUTOCOMMIT TO OFF is no longer supported");
8337                 return false;
8338         }
8339         return true;
8340 }
8341
8342 static bool
8343 check_debug_assertions(bool *newval, void **extra, GucSource source)
8344 {
8345 #ifndef USE_ASSERT_CHECKING
8346         if (*newval)
8347         {
8348                 GUC_check_errmsg("assertion checking is not supported by this build");
8349                 return false;
8350         }
8351 #endif
8352         return true;
8353 }
8354
8355 static bool
8356 check_bonjour(bool *newval, void **extra, GucSource source)
8357 {
8358 #ifndef USE_BONJOUR
8359         if (*newval)
8360         {
8361                 GUC_check_errmsg("Bonjour is not supported by this build");
8362                 return false;
8363         }
8364 #endif
8365         return true;
8366 }
8367
8368 static bool
8369 check_ssl(bool *newval, void **extra, GucSource source)
8370 {
8371 #ifndef USE_SSL
8372         if (*newval)
8373         {
8374                 GUC_check_errmsg("SSL is not supported by this build");
8375                 return false;
8376         }
8377 #endif
8378         return true;
8379 }
8380
8381 static bool
8382 check_stage_log_stats(bool *newval, void **extra, GucSource source)
8383 {
8384         if (*newval && log_statement_stats)
8385         {
8386                 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
8387                 return false;
8388         }
8389         return true;
8390 }
8391
8392 static bool
8393 check_log_stats(bool *newval, void **extra, GucSource source)
8394 {
8395         if (*newval &&
8396                 (log_parser_stats || log_planner_stats || log_executor_stats))
8397         {
8398                 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
8399                                                         "\"log_parser_stats\", \"log_planner_stats\", "
8400                                                         "or \"log_executor_stats\" is true.");
8401                 return false;
8402         }
8403         return true;
8404 }
8405
8406 static bool
8407 check_canonical_path(char **newval, void **extra, GucSource source)
8408 {
8409         /*
8410          * Since canonicalize_path never enlarges the string, we can just modify
8411          * newval in-place.  But watch out for NULL, which is the default value
8412          * for external_pid_file.
8413          */
8414         if (*newval)
8415                 canonicalize_path(*newval);
8416         return true;
8417 }
8418
8419 static bool
8420 check_timezone_abbreviations(char **newval, void **extra, GucSource source)
8421 {
8422         /*
8423          * The boot_val given above for timezone_abbreviations is NULL. When we
8424          * see this we just do nothing.  If this value isn't overridden from the
8425          * config file then pg_timezone_abbrev_initialize() will eventually
8426          * replace it with "Default".  This hack has two purposes: to avoid
8427          * wasting cycles loading values that might soon be overridden from the
8428          * config file, and to avoid trying to read the timezone abbrev files
8429          * during InitializeGUCOptions().  The latter doesn't work in an
8430          * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
8431          * we can't locate PGSHAREDIR.
8432          */
8433         if (*newval == NULL)
8434         {
8435                 Assert(source == PGC_S_DEFAULT);
8436                 return true;
8437         }
8438
8439         /* OK, load the file and produce a malloc'd TimeZoneAbbrevTable */
8440         *extra = load_tzoffsets(*newval);
8441
8442         /* tzparser.c returns NULL on failure, reporting via GUC_check_errmsg */
8443         if (!*extra)
8444                 return false;
8445
8446         return true;
8447 }
8448
8449 static void
8450 assign_timezone_abbreviations(const char *newval, void *extra)
8451 {
8452         /* Do nothing for the boot_val default of NULL */
8453         if (!extra)
8454                 return;
8455
8456         InstallTimeZoneAbbrevs((TimeZoneAbbrevTable *) extra);
8457 }
8458
8459 /*
8460  * pg_timezone_abbrev_initialize --- set default value if not done already
8461  *
8462  * This is called after initial loading of postgresql.conf.  If no
8463  * timezone_abbreviations setting was found therein, select default.
8464  * If a non-default value is already installed, nothing will happen.
8465  *
8466  * This can also be called from ProcessConfigFile to establish the default
8467  * value after a postgresql.conf entry for it is removed.
8468  */
8469 static void
8470 pg_timezone_abbrev_initialize(void)
8471 {
8472         SetConfigOption("timezone_abbreviations", "Default",
8473                                         PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
8474 }
8475
8476 static const char *
8477 show_archive_command(void)
8478 {
8479         if (XLogArchivingActive())
8480                 return XLogArchiveCommand;
8481         else
8482                 return "(disabled)";
8483 }
8484
8485 static void
8486 assign_tcp_keepalives_idle(int newval, void *extra)
8487 {
8488         /*
8489          * The kernel API provides no way to test a value without setting it; and
8490          * once we set it we might fail to unset it.  So there seems little point
8491          * in fully implementing the check-then-assign GUC API for these
8492          * variables.  Instead we just do the assignment on demand.  pqcomm.c
8493          * reports any problems via elog(LOG).
8494          *
8495          * This approach means that the GUC value might have little to do with the
8496          * actual kernel value, so we use a show_hook that retrieves the kernel
8497          * value rather than trusting GUC's copy.
8498          */
8499         (void) pq_setkeepalivesidle(newval, MyProcPort);
8500 }
8501
8502 static const char *
8503 show_tcp_keepalives_idle(void)
8504 {
8505         /* See comments in assign_tcp_keepalives_idle */
8506         static char nbuf[16];
8507
8508         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
8509         return nbuf;
8510 }
8511
8512 static void
8513 assign_tcp_keepalives_interval(int newval, void *extra)
8514 {
8515         /* See comments in assign_tcp_keepalives_idle */
8516         (void) pq_setkeepalivesinterval(newval, MyProcPort);
8517 }
8518
8519 static const char *
8520 show_tcp_keepalives_interval(void)
8521 {
8522         /* See comments in assign_tcp_keepalives_idle */
8523         static char nbuf[16];
8524
8525         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
8526         return nbuf;
8527 }
8528
8529 static void
8530 assign_tcp_keepalives_count(int newval, void *extra)
8531 {
8532         /* See comments in assign_tcp_keepalives_idle */
8533         (void) pq_setkeepalivescount(newval, MyProcPort);
8534 }
8535
8536 static const char *
8537 show_tcp_keepalives_count(void)
8538 {
8539         /* See comments in assign_tcp_keepalives_idle */
8540         static char nbuf[16];
8541
8542         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
8543         return nbuf;
8544 }
8545
8546 static bool
8547 check_maxconnections(int *newval, void **extra, GucSource source)
8548 {
8549         if (*newval + autovacuum_max_workers + 1 > MAX_BACKENDS)
8550                 return false;
8551         return true;
8552 }
8553
8554 static void
8555 assign_maxconnections(int newval, void *extra)
8556 {
8557         MaxBackends = newval + autovacuum_max_workers + 1;
8558 }
8559
8560 static bool
8561 check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
8562 {
8563         if (MaxConnections + *newval + 1 > MAX_BACKENDS)
8564                 return false;
8565         return true;
8566 }
8567
8568 static void
8569 assign_autovacuum_max_workers(int newval, void *extra)
8570 {
8571         MaxBackends = MaxConnections + newval + 1;
8572 }
8573
8574 static bool
8575 check_effective_io_concurrency(int *newval, void **extra, GucSource source)
8576 {
8577 #ifdef USE_PREFETCH
8578         double          new_prefetch_pages = 0.0;
8579         int                     i;
8580
8581         /*----------
8582          * The user-visible GUC parameter is the number of drives (spindles),
8583          * which we need to translate to a number-of-pages-to-prefetch target.
8584          * The target value is stashed in *extra and then assigned to the actual
8585          * variable by assign_effective_io_concurrency.
8586          *
8587          * The expected number of prefetch pages needed to keep N drives busy is:
8588          *
8589          * drives |   I/O requests
8590          * -------+----------------
8591          *              1 |   1
8592          *              2 |   2/1 + 2/2 = 3
8593          *              3 |   3/1 + 3/2 + 3/3 = 5 1/2
8594          *              4 |   4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
8595          *              n |   n * H(n)
8596          *
8597          * This is called the "coupon collector problem" and H(n) is called the
8598          * harmonic series.  This could be approximated by n * ln(n), but for
8599          * reasonable numbers of drives we might as well just compute the series.
8600          *
8601          * Alternatively we could set the target to the number of pages necessary
8602          * so that the expected number of active spindles is some arbitrary
8603          * percentage of the total.  This sounds the same but is actually slightly
8604          * different.  The result ends up being ln(1-P)/ln((n-1)/n) where P is
8605          * that desired fraction.
8606          *
8607          * Experimental results show that both of these formulas aren't aggressive
8608          * enough, but we don't really have any better proposals.
8609          *
8610          * Note that if *newval = 0 (disabled), we must set target = 0.
8611          *----------
8612          */
8613
8614         for (i = 1; i <= *newval; i++)
8615                 new_prefetch_pages += (double) *newval / (double) i;
8616
8617         /* This range check shouldn't fail, but let's be paranoid */
8618         if (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX)
8619         {
8620                 int                *myextra = (int *) guc_malloc(ERROR, sizeof(int));
8621
8622                 *myextra = (int) rint(new_prefetch_pages);
8623                 *extra = (void *) myextra;
8624
8625                 return true;
8626         }
8627         else
8628                 return false;
8629 #else
8630         return true;
8631 #endif   /* USE_PREFETCH */
8632 }
8633
8634 static void
8635 assign_effective_io_concurrency(int newval, void *extra)
8636 {
8637 #ifdef USE_PREFETCH
8638         target_prefetch_pages = *((int *) extra);
8639 #endif   /* USE_PREFETCH */
8640 }
8641
8642 static void
8643 assign_pgstat_temp_directory(const char *newval, void *extra)
8644 {
8645         /* check_canonical_path already canonicalized newval for us */
8646         char       *tname;
8647         char       *fname;
8648
8649         tname = guc_malloc(ERROR, strlen(newval) + 12);         /* /pgstat.tmp */
8650         sprintf(tname, "%s/pgstat.tmp", newval);
8651         fname = guc_malloc(ERROR, strlen(newval) + 13);         /* /pgstat.stat */
8652         sprintf(fname, "%s/pgstat.stat", newval);
8653
8654         if (pgstat_stat_tmpname)
8655                 free(pgstat_stat_tmpname);
8656         pgstat_stat_tmpname = tname;
8657         if (pgstat_stat_filename)
8658                 free(pgstat_stat_filename);
8659         pgstat_stat_filename = fname;
8660 }
8661
8662 static bool
8663 check_application_name(char **newval, void **extra, GucSource source)
8664 {
8665         /* Only allow clean ASCII chars in the application name */
8666         char       *p;
8667
8668         for (p = *newval; *p; p++)
8669         {
8670                 if (*p < 32 || *p > 126)
8671                         *p = '?';
8672         }
8673
8674         return true;
8675 }
8676
8677 static void
8678 assign_application_name(const char *newval, void *extra)
8679 {
8680         /* Update the pg_stat_activity view */
8681         pgstat_report_appname(newval);
8682 }
8683
8684 static const char *
8685 show_unix_socket_permissions(void)
8686 {
8687         static char buf[8];
8688
8689         snprintf(buf, sizeof(buf), "%04o", Unix_socket_permissions);
8690         return buf;
8691 }
8692
8693 static const char *
8694 show_log_file_mode(void)
8695 {
8696         static char buf[8];
8697
8698         snprintf(buf, sizeof(buf), "%04o", Log_file_mode);
8699         return buf;
8700 }
8701
8702 #include "guc-file.c"