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