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