]> granicus.if.org Git - postgresql/blob - src/backend/utils/misc/guc.c
Revert "commit_delay" change; just add comment that we don't have
[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                         /* we have no microseconds designation, so can't supply units here */
2038                 },
2039                 &CommitDelay,
2040                 0, 0, 100000,
2041                 NULL, NULL, NULL
2042         },
2043
2044         {
2045                 {"commit_siblings", PGC_USERSET, WAL_SETTINGS,
2046                         gettext_noop("Sets the minimum concurrent open transactions before performing "
2047                                                  "commit_delay."),
2048                         NULL
2049                 },
2050                 &CommitSiblings,
2051                 5, 0, 1000,
2052                 NULL, NULL, NULL
2053         },
2054
2055         {
2056                 {"extra_float_digits", PGC_USERSET, CLIENT_CONN_LOCALE,
2057                         gettext_noop("Sets the number of digits displayed for floating-point values."),
2058                         gettext_noop("This affects real, double precision, and geometric data types. "
2059                          "The parameter value is added to the standard number of digits "
2060                                                  "(FLT_DIG or DBL_DIG as appropriate).")
2061                 },
2062                 &extra_float_digits,
2063                 0, -15, 3,
2064                 NULL, NULL, NULL
2065         },
2066
2067         {
2068                 {"log_min_duration_statement", PGC_SUSET, LOGGING_WHEN,
2069                         gettext_noop("Sets the minimum execution time above which "
2070                                                  "statements will be logged."),
2071                         gettext_noop("Zero prints all queries. -1 turns this feature off."),
2072                         GUC_UNIT_MS
2073                 },
2074                 &log_min_duration_statement,
2075                 -1, -1, INT_MAX,
2076                 NULL, NULL, NULL
2077         },
2078
2079         {
2080                 {"log_autovacuum_min_duration", PGC_SIGHUP, LOGGING_WHAT,
2081                         gettext_noop("Sets the minimum execution time above which "
2082                                                  "autovacuum actions will be logged."),
2083                         gettext_noop("Zero prints all actions. -1 turns autovacuum logging off."),
2084                         GUC_UNIT_MS
2085                 },
2086                 &Log_autovacuum_min_duration,
2087                 -1, -1, INT_MAX,
2088                 NULL, NULL, NULL
2089         },
2090
2091         {
2092                 {"bgwriter_delay", PGC_SIGHUP, RESOURCES_BGWRITER,
2093                         gettext_noop("Background writer sleep time between rounds."),
2094                         NULL,
2095                         GUC_UNIT_MS
2096                 },
2097                 &BgWriterDelay,
2098                 200, 10, 10000,
2099                 NULL, NULL, NULL
2100         },
2101
2102         {
2103                 {"bgwriter_lru_maxpages", PGC_SIGHUP, RESOURCES_BGWRITER,
2104                         gettext_noop("Background writer maximum number of LRU pages to flush per round."),
2105                         NULL
2106                 },
2107                 &bgwriter_lru_maxpages,
2108                 100, 0, 1000,
2109                 NULL, NULL, NULL
2110         },
2111
2112         {
2113                 {"effective_io_concurrency",
2114 #ifdef USE_PREFETCH
2115                         PGC_USERSET,
2116 #else
2117                         PGC_INTERNAL,
2118 #endif
2119                         RESOURCES_ASYNCHRONOUS,
2120                         gettext_noop("Number of simultaneous requests that can be handled efficiently by the disk subsystem."),
2121                         gettext_noop("For RAID arrays, this should be approximately the number of drive spindles in the array.")
2122                 },
2123                 &effective_io_concurrency,
2124 #ifdef USE_PREFETCH
2125                 1, 0, 1000,
2126 #else
2127                 0, 0, 0,
2128 #endif
2129                 check_effective_io_concurrency, assign_effective_io_concurrency, NULL
2130         },
2131
2132         {
2133                 {"log_rotation_age", PGC_SIGHUP, LOGGING_WHERE,
2134                         gettext_noop("Automatic log file rotation will occur after N minutes."),
2135                         NULL,
2136                         GUC_UNIT_MIN
2137                 },
2138                 &Log_RotationAge,
2139                 HOURS_PER_DAY * MINS_PER_HOUR, 0, INT_MAX / MINS_PER_HOUR,
2140                 NULL, NULL, NULL
2141         },
2142
2143         {
2144                 {"log_rotation_size", PGC_SIGHUP, LOGGING_WHERE,
2145                         gettext_noop("Automatic log file rotation will occur after N kilobytes."),
2146                         NULL,
2147                         GUC_UNIT_KB
2148                 },
2149                 &Log_RotationSize,
2150                 10 * 1024, 0, INT_MAX / 1024,
2151                 NULL, NULL, NULL
2152         },
2153
2154         {
2155                 {"max_function_args", PGC_INTERNAL, PRESET_OPTIONS,
2156                         gettext_noop("Shows the maximum number of function arguments."),
2157                         NULL,
2158                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2159                 },
2160                 &max_function_args,
2161                 FUNC_MAX_ARGS, FUNC_MAX_ARGS, FUNC_MAX_ARGS,
2162                 NULL, NULL, NULL
2163         },
2164
2165         {
2166                 {"max_index_keys", PGC_INTERNAL, PRESET_OPTIONS,
2167                         gettext_noop("Shows the maximum number of index keys."),
2168                         NULL,
2169                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2170                 },
2171                 &max_index_keys,
2172                 INDEX_MAX_KEYS, INDEX_MAX_KEYS, INDEX_MAX_KEYS,
2173                 NULL, NULL, NULL
2174         },
2175
2176         {
2177                 {"max_identifier_length", PGC_INTERNAL, PRESET_OPTIONS,
2178                         gettext_noop("Shows the maximum identifier length."),
2179                         NULL,
2180                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2181                 },
2182                 &max_identifier_length,
2183                 NAMEDATALEN - 1, NAMEDATALEN - 1, NAMEDATALEN - 1,
2184                 NULL, NULL, NULL
2185         },
2186
2187         {
2188                 {"block_size", PGC_INTERNAL, PRESET_OPTIONS,
2189                         gettext_noop("Shows the size of a disk block."),
2190                         NULL,
2191                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2192                 },
2193                 &block_size,
2194                 BLCKSZ, BLCKSZ, BLCKSZ,
2195                 NULL, NULL, NULL
2196         },
2197
2198         {
2199                 {"segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2200                         gettext_noop("Shows the number of pages per disk file."),
2201                         NULL,
2202                         GUC_UNIT_BLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2203                 },
2204                 &segment_size,
2205                 RELSEG_SIZE, RELSEG_SIZE, RELSEG_SIZE,
2206                 NULL, NULL, NULL
2207         },
2208
2209         {
2210                 {"wal_block_size", PGC_INTERNAL, PRESET_OPTIONS,
2211                         gettext_noop("Shows the block size in the write ahead log."),
2212                         NULL,
2213                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2214                 },
2215                 &wal_block_size,
2216                 XLOG_BLCKSZ, XLOG_BLCKSZ, XLOG_BLCKSZ,
2217                 NULL, NULL, NULL
2218         },
2219
2220         {
2221                 {"wal_segment_size", PGC_INTERNAL, PRESET_OPTIONS,
2222                         gettext_noop("Shows the number of pages per write ahead log segment."),
2223                         NULL,
2224                         GUC_UNIT_XBLOCKS | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2225                 },
2226                 &wal_segment_size,
2227                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2228                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2229                 (XLOG_SEG_SIZE / XLOG_BLCKSZ),
2230                 NULL, NULL, NULL
2231         },
2232
2233         {
2234                 {"autovacuum_naptime", PGC_SIGHUP, AUTOVACUUM,
2235                         gettext_noop("Time to sleep between autovacuum runs."),
2236                         NULL,
2237                         GUC_UNIT_S
2238                 },
2239                 &autovacuum_naptime,
2240                 60, 1, INT_MAX / 1000,
2241                 NULL, NULL, NULL
2242         },
2243         {
2244                 {"autovacuum_vacuum_threshold", PGC_SIGHUP, AUTOVACUUM,
2245                         gettext_noop("Minimum number of tuple updates or deletes prior to vacuum."),
2246                         NULL
2247                 },
2248                 &autovacuum_vac_thresh,
2249                 50, 0, INT_MAX,
2250                 NULL, NULL, NULL
2251         },
2252         {
2253                 {"autovacuum_analyze_threshold", PGC_SIGHUP, AUTOVACUUM,
2254                         gettext_noop("Minimum number of tuple inserts, updates, or deletes prior to analyze."),
2255                         NULL
2256                 },
2257                 &autovacuum_anl_thresh,
2258                 50, 0, INT_MAX,
2259                 NULL, NULL, NULL
2260         },
2261         {
2262                 /* see varsup.c for why this is PGC_POSTMASTER not PGC_SIGHUP */
2263                 {"autovacuum_freeze_max_age", PGC_POSTMASTER, AUTOVACUUM,
2264                         gettext_noop("Age at which to autovacuum a table to prevent transaction ID wraparound."),
2265                         NULL
2266                 },
2267                 &autovacuum_freeze_max_age,
2268                 /* see pg_resetxlog if you change the upper-limit value */
2269                 200000000, 100000000, 2000000000,
2270                 NULL, NULL, NULL
2271         },
2272         {
2273                 /* see max_connections */
2274                 {"autovacuum_max_workers", PGC_POSTMASTER, AUTOVACUUM,
2275                         gettext_noop("Sets the maximum number of simultaneously running autovacuum worker processes."),
2276                         NULL
2277                 },
2278                 &autovacuum_max_workers,
2279                 3, 1, MAX_BACKENDS,
2280                 check_autovacuum_max_workers, assign_autovacuum_max_workers, NULL
2281         },
2282
2283         {
2284                 {"tcp_keepalives_idle", PGC_USERSET, CLIENT_CONN_OTHER,
2285                         gettext_noop("Time between issuing TCP keepalives."),
2286                         gettext_noop("A value of 0 uses the system default."),
2287                         GUC_UNIT_S
2288                 },
2289                 &tcp_keepalives_idle,
2290                 0, 0, INT_MAX,
2291                 NULL, assign_tcp_keepalives_idle, show_tcp_keepalives_idle
2292         },
2293
2294         {
2295                 {"tcp_keepalives_interval", PGC_USERSET, CLIENT_CONN_OTHER,
2296                         gettext_noop("Time between TCP keepalive retransmits."),
2297                         gettext_noop("A value of 0 uses the system default."),
2298                         GUC_UNIT_S
2299                 },
2300                 &tcp_keepalives_interval,
2301                 0, 0, INT_MAX,
2302                 NULL, assign_tcp_keepalives_interval, show_tcp_keepalives_interval
2303         },
2304
2305         {
2306                 {"ssl_renegotiation_limit", PGC_USERSET, CONN_AUTH_SECURITY,
2307                         gettext_noop("Set the amount of traffic to send and receive before renegotiating the encryption keys."),
2308                         NULL,
2309                         GUC_UNIT_KB,
2310                 },
2311                 &ssl_renegotiation_limit,
2312                 512 * 1024, 0, MAX_KILOBYTES,
2313                 NULL, NULL, NULL
2314         },
2315
2316         {
2317                 {"tcp_keepalives_count", PGC_USERSET, CLIENT_CONN_OTHER,
2318                         gettext_noop("Maximum number of TCP keepalive retransmits."),
2319                         gettext_noop("This controls the number of consecutive keepalive retransmits that can be "
2320                                                  "lost before a connection is considered dead. A value of 0 uses the "
2321                                                  "system default."),
2322                 },
2323                 &tcp_keepalives_count,
2324                 0, 0, INT_MAX,
2325                 NULL, assign_tcp_keepalives_count, show_tcp_keepalives_count
2326         },
2327
2328         {
2329                 {"gin_fuzzy_search_limit", PGC_USERSET, CLIENT_CONN_OTHER,
2330                         gettext_noop("Sets the maximum allowed result for exact search by GIN."),
2331                         NULL,
2332                         0
2333                 },
2334                 &GinFuzzySearchLimit,
2335                 0, 0, INT_MAX,
2336                 NULL, NULL, NULL
2337         },
2338
2339         {
2340                 {"effective_cache_size", PGC_USERSET, QUERY_TUNING_COST,
2341                         gettext_noop("Sets the planner's assumption about the size of the disk cache."),
2342                         gettext_noop("That is, the portion of the kernel's disk cache that "
2343                                                  "will be used for PostgreSQL data files. This is measured in disk "
2344                                                  "pages, which are normally 8 kB each."),
2345                         GUC_UNIT_BLOCKS,
2346                 },
2347                 &effective_cache_size,
2348                 DEFAULT_EFFECTIVE_CACHE_SIZE, 1, INT_MAX,
2349                 NULL, NULL, NULL
2350         },
2351
2352         {
2353                 /* Can't be set in postgresql.conf */
2354                 {"server_version_num", PGC_INTERNAL, PRESET_OPTIONS,
2355                         gettext_noop("Shows the server version as an integer."),
2356                         NULL,
2357                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2358                 },
2359                 &server_version_num,
2360                 PG_VERSION_NUM, PG_VERSION_NUM, PG_VERSION_NUM,
2361                 NULL, NULL, NULL
2362         },
2363
2364         {
2365                 {"log_temp_files", PGC_SUSET, LOGGING_WHAT,
2366                         gettext_noop("Log the use of temporary files larger than this number of kilobytes."),
2367                         gettext_noop("Zero logs all files. The default is -1 (turning this feature off)."),
2368                         GUC_UNIT_KB
2369                 },
2370                 &log_temp_files,
2371                 -1, -1, INT_MAX,
2372                 NULL, NULL, NULL
2373         },
2374
2375         {
2376                 {"track_activity_query_size", PGC_POSTMASTER, RESOURCES_MEM,
2377                         gettext_noop("Sets the size reserved for pg_stat_activity.query, in bytes."),
2378                         NULL,
2379                 },
2380                 &pgstat_track_activity_query_size,
2381                 1024, 100, 102400,
2382                 NULL, NULL, NULL
2383         },
2384
2385         /* End-of-list marker */
2386         {
2387                 {NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL, NULL
2388         }
2389 };
2390
2391
2392 static struct config_real ConfigureNamesReal[] =
2393 {
2394         {
2395                 {"seq_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2396                         gettext_noop("Sets the planner's estimate of the cost of a "
2397                                                  "sequentially fetched disk page."),
2398                         NULL
2399                 },
2400                 &seq_page_cost,
2401                 DEFAULT_SEQ_PAGE_COST, 0, DBL_MAX,
2402                 NULL, NULL, NULL
2403         },
2404         {
2405                 {"random_page_cost", PGC_USERSET, QUERY_TUNING_COST,
2406                         gettext_noop("Sets the planner's estimate of the cost of a "
2407                                                  "nonsequentially fetched disk page."),
2408                         NULL
2409                 },
2410                 &random_page_cost,
2411                 DEFAULT_RANDOM_PAGE_COST, 0, DBL_MAX,
2412                 NULL, NULL, NULL
2413         },
2414         {
2415                 {"cpu_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2416                         gettext_noop("Sets the planner's estimate of the cost of "
2417                                                  "processing each tuple (row)."),
2418                         NULL
2419                 },
2420                 &cpu_tuple_cost,
2421                 DEFAULT_CPU_TUPLE_COST, 0, DBL_MAX,
2422                 NULL, NULL, NULL
2423         },
2424         {
2425                 {"cpu_index_tuple_cost", PGC_USERSET, QUERY_TUNING_COST,
2426                         gettext_noop("Sets the planner's estimate of the cost of "
2427                                                  "processing each index entry during an index scan."),
2428                         NULL
2429                 },
2430                 &cpu_index_tuple_cost,
2431                 DEFAULT_CPU_INDEX_TUPLE_COST, 0, DBL_MAX,
2432                 NULL, NULL, NULL
2433         },
2434         {
2435                 {"cpu_operator_cost", PGC_USERSET, QUERY_TUNING_COST,
2436                         gettext_noop("Sets the planner's estimate of the cost of "
2437                                                  "processing each operator or function call."),
2438                         NULL
2439                 },
2440                 &cpu_operator_cost,
2441                 DEFAULT_CPU_OPERATOR_COST, 0, DBL_MAX,
2442                 NULL, NULL, NULL
2443         },
2444
2445         {
2446                 {"cursor_tuple_fraction", PGC_USERSET, QUERY_TUNING_OTHER,
2447                         gettext_noop("Sets the planner's estimate of the fraction of "
2448                                                  "a cursor's rows that will be retrieved."),
2449                         NULL
2450                 },
2451                 &cursor_tuple_fraction,
2452                 DEFAULT_CURSOR_TUPLE_FRACTION, 0.0, 1.0,
2453                 NULL, NULL, NULL
2454         },
2455
2456         {
2457                 {"geqo_selection_bias", PGC_USERSET, QUERY_TUNING_GEQO,
2458                         gettext_noop("GEQO: selective pressure within the population."),
2459                         NULL
2460                 },
2461                 &Geqo_selection_bias,
2462                 DEFAULT_GEQO_SELECTION_BIAS,
2463                 MIN_GEQO_SELECTION_BIAS, MAX_GEQO_SELECTION_BIAS,
2464                 NULL, NULL, NULL
2465         },
2466         {
2467                 {"geqo_seed", PGC_USERSET, QUERY_TUNING_GEQO,
2468                         gettext_noop("GEQO: seed for random path selection."),
2469                         NULL
2470                 },
2471                 &Geqo_seed,
2472                 0.0, 0.0, 1.0,
2473                 NULL, NULL, NULL
2474         },
2475
2476         {
2477                 {"bgwriter_lru_multiplier", PGC_SIGHUP, RESOURCES_BGWRITER,
2478                         gettext_noop("Multiple of the average buffer usage to free per round."),
2479                         NULL
2480                 },
2481                 &bgwriter_lru_multiplier,
2482                 2.0, 0.0, 10.0,
2483                 NULL, NULL, NULL
2484         },
2485
2486         {
2487                 {"seed", PGC_USERSET, UNGROUPED,
2488                         gettext_noop("Sets the seed for random-number generation."),
2489                         NULL,
2490                         GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2491                 },
2492                 &phony_random_seed,
2493                 0.0, -1.0, 1.0,
2494                 check_random_seed, assign_random_seed, show_random_seed
2495         },
2496
2497         {
2498                 {"autovacuum_vacuum_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2499                         gettext_noop("Number of tuple updates or deletes prior to vacuum as a fraction of reltuples."),
2500                         NULL
2501                 },
2502                 &autovacuum_vac_scale,
2503                 0.2, 0.0, 100.0,
2504                 NULL, NULL, NULL
2505         },
2506         {
2507                 {"autovacuum_analyze_scale_factor", PGC_SIGHUP, AUTOVACUUM,
2508                         gettext_noop("Number of tuple inserts, updates, or deletes prior to analyze as a fraction of reltuples."),
2509                         NULL
2510                 },
2511                 &autovacuum_anl_scale,
2512                 0.1, 0.0, 100.0,
2513                 NULL, NULL, NULL
2514         },
2515
2516         {
2517                 {"checkpoint_completion_target", PGC_SIGHUP, WAL_CHECKPOINTS,
2518                         gettext_noop("Time spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval."),
2519                         NULL
2520                 },
2521                 &CheckPointCompletionTarget,
2522                 0.5, 0.0, 1.0,
2523                 NULL, NULL, NULL
2524         },
2525
2526         /* End-of-list marker */
2527         {
2528                 {NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL, NULL
2529         }
2530 };
2531
2532
2533 static struct config_string ConfigureNamesString[] =
2534 {
2535         {
2536                 {"archive_command", PGC_SIGHUP, WAL_ARCHIVING,
2537                         gettext_noop("Sets the shell command that will be called to archive a WAL file."),
2538                         NULL
2539                 },
2540                 &XLogArchiveCommand,
2541                 "",
2542                 NULL, NULL, show_archive_command
2543         },
2544
2545         {
2546                 {"client_encoding", PGC_USERSET, CLIENT_CONN_LOCALE,
2547                         gettext_noop("Sets the client's character set encoding."),
2548                         NULL,
2549                         GUC_IS_NAME | GUC_REPORT
2550                 },
2551                 &client_encoding_string,
2552                 "SQL_ASCII",
2553                 check_client_encoding, assign_client_encoding, NULL
2554         },
2555
2556         {
2557                 {"log_line_prefix", PGC_SIGHUP, LOGGING_WHAT,
2558                         gettext_noop("Controls information prefixed to each log line."),
2559                         gettext_noop("If blank, no prefix is used.")
2560                 },
2561                 &Log_line_prefix,
2562                 "",
2563                 NULL, NULL, NULL
2564         },
2565
2566         {
2567                 {"log_timezone", PGC_SIGHUP, LOGGING_WHAT,
2568                         gettext_noop("Sets the time zone to use in log messages."),
2569                         NULL
2570                 },
2571                 &log_timezone_string,
2572                 "GMT",
2573                 check_log_timezone, assign_log_timezone, show_log_timezone
2574         },
2575
2576         {
2577                 {"DateStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
2578                         gettext_noop("Sets the display format for date and time values."),
2579                         gettext_noop("Also controls interpretation of ambiguous "
2580                                                  "date inputs."),
2581                         GUC_LIST_INPUT | GUC_REPORT
2582                 },
2583                 &datestyle_string,
2584                 "ISO, MDY",
2585                 check_datestyle, assign_datestyle, NULL
2586         },
2587
2588         {
2589                 {"default_tablespace", PGC_USERSET, CLIENT_CONN_STATEMENT,
2590                         gettext_noop("Sets the default tablespace to create tables and indexes in."),
2591                         gettext_noop("An empty string selects the database's default tablespace."),
2592                         GUC_IS_NAME
2593                 },
2594                 &default_tablespace,
2595                 "",
2596                 check_default_tablespace, NULL, NULL
2597         },
2598
2599         {
2600                 {"temp_tablespaces", PGC_USERSET, CLIENT_CONN_STATEMENT,
2601                         gettext_noop("Sets the tablespace(s) to use for temporary tables and sort files."),
2602                         NULL,
2603                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2604                 },
2605                 &temp_tablespaces,
2606                 "",
2607                 check_temp_tablespaces, assign_temp_tablespaces, NULL
2608         },
2609
2610         {
2611                 {"dynamic_library_path", PGC_SUSET, CLIENT_CONN_OTHER,
2612                         gettext_noop("Sets the path for dynamically loadable modules."),
2613                         gettext_noop("If a dynamically loadable module needs to be opened and "
2614                                                  "the specified name does not have a directory component (i.e., the "
2615                                                  "name does not contain a slash), the system will search this path for "
2616                                                  "the specified file."),
2617                         GUC_SUPERUSER_ONLY
2618                 },
2619                 &Dynamic_library_path,
2620                 "$libdir",
2621                 NULL, NULL, NULL
2622         },
2623
2624         {
2625                 {"krb_server_keyfile", PGC_SIGHUP, CONN_AUTH_SECURITY,
2626                         gettext_noop("Sets the location of the Kerberos server key file."),
2627                         NULL,
2628                         GUC_SUPERUSER_ONLY
2629                 },
2630                 &pg_krb_server_keyfile,
2631                 PG_KRB_SRVTAB,
2632                 NULL, NULL, NULL
2633         },
2634
2635         {
2636                 {"krb_srvname", PGC_SIGHUP, CONN_AUTH_SECURITY,
2637                         gettext_noop("Sets the name of the Kerberos service."),
2638                         NULL
2639                 },
2640                 &pg_krb_srvnam,
2641                 PG_KRB_SRVNAM,
2642                 NULL, NULL, NULL
2643         },
2644
2645         {
2646                 {"bonjour_name", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2647                         gettext_noop("Sets the Bonjour service name."),
2648                         NULL
2649                 },
2650                 &bonjour_name,
2651                 "",
2652                 NULL, NULL, NULL
2653         },
2654
2655         /* See main.c about why defaults for LC_foo are not all alike */
2656
2657         {
2658                 {"lc_collate", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2659                         gettext_noop("Shows the collation order locale."),
2660                         NULL,
2661                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2662                 },
2663                 &locale_collate,
2664                 "C",
2665                 NULL, NULL, NULL
2666         },
2667
2668         {
2669                 {"lc_ctype", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2670                         gettext_noop("Shows the character classification and case conversion locale."),
2671                         NULL,
2672                         GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2673                 },
2674                 &locale_ctype,
2675                 "C",
2676                 NULL, NULL, NULL
2677         },
2678
2679         {
2680                 {"lc_messages", PGC_SUSET, CLIENT_CONN_LOCALE,
2681                         gettext_noop("Sets the language in which messages are displayed."),
2682                         NULL
2683                 },
2684                 &locale_messages,
2685                 "",
2686                 check_locale_messages, assign_locale_messages, NULL
2687         },
2688
2689         {
2690                 {"lc_monetary", PGC_USERSET, CLIENT_CONN_LOCALE,
2691                         gettext_noop("Sets the locale for formatting monetary amounts."),
2692                         NULL
2693                 },
2694                 &locale_monetary,
2695                 "C",
2696                 check_locale_monetary, assign_locale_monetary, NULL
2697         },
2698
2699         {
2700                 {"lc_numeric", PGC_USERSET, CLIENT_CONN_LOCALE,
2701                         gettext_noop("Sets the locale for formatting numbers."),
2702                         NULL
2703                 },
2704                 &locale_numeric,
2705                 "C",
2706                 check_locale_numeric, assign_locale_numeric, NULL
2707         },
2708
2709         {
2710                 {"lc_time", PGC_USERSET, CLIENT_CONN_LOCALE,
2711                         gettext_noop("Sets the locale for formatting date and time values."),
2712                         NULL
2713                 },
2714                 &locale_time,
2715                 "C",
2716                 check_locale_time, assign_locale_time, NULL
2717         },
2718
2719         {
2720                 {"shared_preload_libraries", PGC_POSTMASTER, RESOURCES_KERNEL,
2721                         gettext_noop("Lists shared libraries to preload into server."),
2722                         NULL,
2723                         GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY
2724                 },
2725                 &shared_preload_libraries_string,
2726                 "",
2727                 NULL, NULL, NULL
2728         },
2729
2730         {
2731                 {"local_preload_libraries", PGC_BACKEND, CLIENT_CONN_OTHER,
2732                         gettext_noop("Lists shared libraries to preload into each backend."),
2733                         NULL,
2734                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2735                 },
2736                 &local_preload_libraries_string,
2737                 "",
2738                 NULL, NULL, NULL
2739         },
2740
2741         {
2742                 {"search_path", PGC_USERSET, CLIENT_CONN_STATEMENT,
2743                         gettext_noop("Sets the schema search order for names that are not schema-qualified."),
2744                         NULL,
2745                         GUC_LIST_INPUT | GUC_LIST_QUOTE
2746                 },
2747                 &namespace_search_path,
2748                 "\"$user\",public",
2749                 check_search_path, assign_search_path, NULL
2750         },
2751
2752         {
2753                 /* Can't be set in postgresql.conf */
2754                 {"server_encoding", PGC_INTERNAL, CLIENT_CONN_LOCALE,
2755                         gettext_noop("Sets the server (database) character set encoding."),
2756                         NULL,
2757                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2758                 },
2759                 &server_encoding_string,
2760                 "SQL_ASCII",
2761                 NULL, NULL, NULL
2762         },
2763
2764         {
2765                 /* Can't be set in postgresql.conf */
2766                 {"server_version", PGC_INTERNAL, PRESET_OPTIONS,
2767                         gettext_noop("Shows the server version."),
2768                         NULL,
2769                         GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2770                 },
2771                 &server_version_string,
2772                 PG_VERSION,
2773                 NULL, NULL, NULL
2774         },
2775
2776         {
2777                 /* Not for general use --- used by SET ROLE */
2778                 {"role", PGC_USERSET, UNGROUPED,
2779                         gettext_noop("Sets the current role."),
2780                         NULL,
2781                         GUC_IS_NAME | GUC_NO_SHOW_ALL | GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE | GUC_NOT_WHILE_SEC_REST
2782                 },
2783                 &role_string,
2784                 "none",
2785                 check_role, assign_role, show_role
2786         },
2787
2788         {
2789                 /* Not for general use --- used by SET SESSION AUTHORIZATION */
2790                 {"session_authorization", PGC_USERSET, UNGROUPED,
2791                         gettext_noop("Sets the session user name."),
2792                         NULL,
2793                         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
2794                 },
2795                 &session_authorization_string,
2796                 NULL,
2797                 check_session_authorization, assign_session_authorization, NULL
2798         },
2799
2800         {
2801                 {"log_destination", PGC_SIGHUP, LOGGING_WHERE,
2802                         gettext_noop("Sets the destination for server log output."),
2803                         gettext_noop("Valid values are combinations of \"stderr\", "
2804                                                  "\"syslog\", \"csvlog\", and \"eventlog\", "
2805                                                  "depending on the platform."),
2806                         GUC_LIST_INPUT
2807                 },
2808                 &log_destination_string,
2809                 "stderr",
2810                 check_log_destination, assign_log_destination, NULL
2811         },
2812         {
2813                 {"log_directory", PGC_SIGHUP, LOGGING_WHERE,
2814                         gettext_noop("Sets the destination directory for log files."),
2815                         gettext_noop("Can be specified as relative to the data directory "
2816                                                  "or as absolute path."),
2817                         GUC_SUPERUSER_ONLY
2818                 },
2819                 &Log_directory,
2820                 "pg_log",
2821                 check_canonical_path, NULL, NULL
2822         },
2823         {
2824                 {"log_filename", PGC_SIGHUP, LOGGING_WHERE,
2825                         gettext_noop("Sets the file name pattern for log files."),
2826                         NULL,
2827                         GUC_SUPERUSER_ONLY
2828                 },
2829                 &Log_filename,
2830                 "postgresql-%Y-%m-%d_%H%M%S.log",
2831                 NULL, NULL, NULL
2832         },
2833
2834         {
2835                 {"syslog_ident", PGC_SIGHUP, LOGGING_WHERE,
2836                         gettext_noop("Sets the program name used to identify PostgreSQL "
2837                                                  "messages in syslog."),
2838                         NULL
2839                 },
2840                 &syslog_ident_str,
2841                 "postgres",
2842                 NULL, assign_syslog_ident, NULL
2843         },
2844
2845         {
2846                 {"event_source", PGC_POSTMASTER, LOGGING_WHERE,
2847                         gettext_noop("Sets the application name used to identify "
2848                                                  "PostgreSQL messages in the event log."),
2849                         NULL
2850                 },
2851                 &event_source,
2852                 "PostgreSQL",
2853                 NULL, NULL, NULL
2854         },
2855
2856         {
2857                 {"TimeZone", PGC_USERSET, CLIENT_CONN_LOCALE,
2858                         gettext_noop("Sets the time zone for displaying and interpreting time stamps."),
2859                         NULL,
2860                         GUC_REPORT
2861                 },
2862                 &timezone_string,
2863                 "GMT",
2864                 check_timezone, assign_timezone, show_timezone
2865         },
2866         {
2867                 {"timezone_abbreviations", PGC_USERSET, CLIENT_CONN_LOCALE,
2868                         gettext_noop("Selects a file of time zone abbreviations."),
2869                         NULL
2870                 },
2871                 &timezone_abbreviations_string,
2872                 NULL,
2873                 check_timezone_abbreviations, assign_timezone_abbreviations, NULL
2874         },
2875
2876         {
2877                 {"transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
2878                         gettext_noop("Sets the current transaction's isolation level."),
2879                         NULL,
2880                         GUC_NO_RESET_ALL | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE
2881                 },
2882                 &XactIsoLevel_string,
2883                 "default",
2884                 check_XactIsoLevel, assign_XactIsoLevel, show_XactIsoLevel
2885         },
2886
2887         {
2888                 {"unix_socket_group", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2889                         gettext_noop("Sets the owning group of the Unix-domain socket."),
2890                         gettext_noop("The owning user of the socket is always the user "
2891                                                  "that starts the server.")
2892                 },
2893                 &Unix_socket_group,
2894                 "",
2895                 NULL, NULL, NULL
2896         },
2897
2898         {
2899                 {"unix_socket_directories", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2900                         gettext_noop("Sets the directories where Unix-domain sockets will be created."),
2901                         NULL,
2902                         GUC_SUPERUSER_ONLY
2903                 },
2904                 &Unix_socket_directories,
2905 #ifdef HAVE_UNIX_SOCKETS
2906                 DEFAULT_PGSOCKET_DIR,
2907 #else
2908                 "",
2909 #endif
2910                 NULL, NULL, NULL
2911         },
2912
2913         {
2914                 {"listen_addresses", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
2915                         gettext_noop("Sets the host name or IP address(es) to listen to."),
2916                         NULL,
2917                         GUC_LIST_INPUT
2918                 },
2919                 &ListenAddresses,
2920                 "localhost",
2921                 NULL, NULL, NULL
2922         },
2923
2924         {
2925                 {"data_directory", PGC_POSTMASTER, FILE_LOCATIONS,
2926                         gettext_noop("Sets the server's data directory."),
2927                         NULL,
2928                         GUC_SUPERUSER_ONLY
2929                 },
2930                 &data_directory,
2931                 NULL,
2932                 NULL, NULL, NULL
2933         },
2934
2935         {
2936                 {"config_file", PGC_POSTMASTER, FILE_LOCATIONS,
2937                         gettext_noop("Sets the server's main configuration file."),
2938                         NULL,
2939                         GUC_DISALLOW_IN_FILE | GUC_SUPERUSER_ONLY
2940                 },
2941                 &ConfigFileName,
2942                 NULL,
2943                 NULL, NULL, NULL
2944         },
2945
2946         {
2947                 {"hba_file", PGC_POSTMASTER, FILE_LOCATIONS,
2948                         gettext_noop("Sets the server's \"hba\" configuration file."),
2949                         NULL,
2950                         GUC_SUPERUSER_ONLY
2951                 },
2952                 &HbaFileName,
2953                 NULL,
2954                 NULL, NULL, NULL
2955         },
2956
2957         {
2958                 {"ident_file", PGC_POSTMASTER, FILE_LOCATIONS,
2959                         gettext_noop("Sets the server's \"ident\" configuration file."),
2960                         NULL,
2961                         GUC_SUPERUSER_ONLY
2962                 },
2963                 &IdentFileName,
2964                 NULL,
2965                 NULL, NULL, NULL
2966         },
2967
2968         {
2969                 {"external_pid_file", PGC_POSTMASTER, FILE_LOCATIONS,
2970                         gettext_noop("Writes the postmaster PID to the specified file."),
2971                         NULL,
2972                         GUC_SUPERUSER_ONLY
2973                 },
2974                 &external_pid_file,
2975                 NULL,
2976                 check_canonical_path, NULL, NULL
2977         },
2978
2979         {
2980                 {"ssl_cert_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2981                         gettext_noop("Location of the SSL server certificate file."),
2982                         NULL
2983                 },
2984                 &ssl_cert_file,
2985                 "server.crt",
2986                 NULL, NULL, NULL
2987         },
2988
2989         {
2990                 {"ssl_key_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
2991                         gettext_noop("Location of the SSL server private key file."),
2992                         NULL
2993                 },
2994                 &ssl_key_file,
2995                 "server.key",
2996                 NULL, NULL, NULL
2997         },
2998
2999         {
3000                 {"ssl_ca_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3001                         gettext_noop("Location of the SSL certificate authority file."),
3002                         NULL
3003                 },
3004                 &ssl_ca_file,
3005                 "",
3006                 NULL, NULL, NULL
3007         },
3008
3009         {
3010                 {"ssl_crl_file", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3011                         gettext_noop("Location of the SSL certificate revocation list file."),
3012                         NULL
3013                 },
3014                 &ssl_crl_file,
3015                 "",
3016                 NULL, NULL, NULL
3017         },
3018
3019         {
3020                 {"stats_temp_directory", PGC_SIGHUP, STATS_COLLECTOR,
3021                         gettext_noop("Writes temporary statistics files to the specified directory."),
3022                         NULL,
3023                         GUC_SUPERUSER_ONLY
3024                 },
3025                 &pgstat_temp_directory,
3026                 "pg_stat_tmp",
3027                 check_canonical_path, assign_pgstat_temp_directory, NULL
3028         },
3029
3030         {
3031                 {"synchronous_standby_names", PGC_SIGHUP, REPLICATION_MASTER,
3032                         gettext_noop("List of names of potential synchronous standbys."),
3033                         NULL,
3034                         GUC_LIST_INPUT
3035                 },
3036                 &SyncRepStandbyNames,
3037                 "",
3038                 check_synchronous_standby_names, NULL, NULL
3039         },
3040
3041         {
3042                 {"default_text_search_config", PGC_USERSET, CLIENT_CONN_LOCALE,
3043                         gettext_noop("Sets default text search configuration."),
3044                         NULL
3045                 },
3046                 &TSCurrentConfig,
3047                 "pg_catalog.simple",
3048                 check_TSCurrentConfig, assign_TSCurrentConfig, NULL
3049         },
3050
3051         {
3052                 {"ssl_ciphers", PGC_POSTMASTER, CONN_AUTH_SECURITY,
3053                         gettext_noop("Sets the list of allowed SSL ciphers."),
3054                         NULL,
3055                         GUC_SUPERUSER_ONLY
3056                 },
3057                 &SSLCipherSuites,
3058 #ifdef USE_SSL
3059                 "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH",
3060 #else
3061                 "none",
3062 #endif
3063                 NULL, NULL, NULL
3064         },
3065
3066         {
3067                 {"application_name", PGC_USERSET, LOGGING_WHAT,
3068                         gettext_noop("Sets the application name to be reported in statistics and logs."),
3069                         NULL,
3070                         GUC_IS_NAME | GUC_REPORT | GUC_NOT_IN_SAMPLE
3071                 },
3072                 &application_name,
3073                 "",
3074                 check_application_name, assign_application_name, NULL
3075         },
3076
3077         /* End-of-list marker */
3078         {
3079                 {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL
3080         }
3081 };
3082
3083
3084 static struct config_enum ConfigureNamesEnum[] =
3085 {
3086         {
3087                 {"backslash_quote", PGC_USERSET, COMPAT_OPTIONS_PREVIOUS,
3088                         gettext_noop("Sets whether \"\\'\" is allowed in string literals."),
3089                         NULL
3090                 },
3091                 &backslash_quote,
3092                 BACKSLASH_QUOTE_SAFE_ENCODING, backslash_quote_options,
3093                 NULL, NULL, NULL
3094         },
3095
3096         {
3097                 {"bytea_output", PGC_USERSET, CLIENT_CONN_STATEMENT,
3098                         gettext_noop("Sets the output format for bytea."),
3099                         NULL
3100                 },
3101                 &bytea_output,
3102                 BYTEA_OUTPUT_HEX, bytea_output_options,
3103                 NULL, NULL, NULL
3104         },
3105
3106         {
3107                 {"client_min_messages", PGC_USERSET, LOGGING_WHEN,
3108                         gettext_noop("Sets the message levels that are sent to the client."),
3109                         gettext_noop("Each level includes all the levels that follow it. The later"
3110                                                  " the level, the fewer messages are sent.")
3111                 },
3112                 &client_min_messages,
3113                 NOTICE, client_message_level_options,
3114                 NULL, NULL, NULL
3115         },
3116
3117         {
3118                 {"constraint_exclusion", PGC_USERSET, QUERY_TUNING_OTHER,
3119                         gettext_noop("Enables the planner to use constraints to optimize queries."),
3120                         gettext_noop("Table scans will be skipped if their constraints"
3121                                                  " guarantee that no rows match the query.")
3122                 },
3123                 &constraint_exclusion,
3124                 CONSTRAINT_EXCLUSION_PARTITION, constraint_exclusion_options,
3125                 NULL, NULL, NULL
3126         },
3127
3128         {
3129                 {"default_transaction_isolation", PGC_USERSET, CLIENT_CONN_STATEMENT,
3130                         gettext_noop("Sets the transaction isolation level of each new transaction."),
3131                         NULL
3132                 },
3133                 &DefaultXactIsoLevel,
3134                 XACT_READ_COMMITTED, isolation_level_options,
3135                 NULL, NULL, NULL
3136         },
3137
3138         {
3139                 {"IntervalStyle", PGC_USERSET, CLIENT_CONN_LOCALE,
3140                         gettext_noop("Sets the display format for interval values."),
3141                         NULL,
3142                         GUC_REPORT
3143                 },
3144                 &IntervalStyle,
3145                 INTSTYLE_POSTGRES, intervalstyle_options,
3146                 NULL, NULL, NULL
3147         },
3148
3149         {
3150                 {"log_error_verbosity", PGC_SUSET, LOGGING_WHAT,
3151                         gettext_noop("Sets the verbosity of logged messages."),
3152                         NULL
3153                 },
3154                 &Log_error_verbosity,
3155                 PGERROR_DEFAULT, log_error_verbosity_options,
3156                 NULL, NULL, NULL
3157         },
3158
3159         {
3160                 {"log_min_messages", PGC_SUSET, LOGGING_WHEN,
3161                         gettext_noop("Sets the message levels that are logged."),
3162                         gettext_noop("Each level includes all the levels that follow it. The later"
3163                                                  " the level, the fewer messages are sent.")
3164                 },
3165                 &log_min_messages,
3166                 WARNING, server_message_level_options,
3167                 NULL, NULL, NULL
3168         },
3169
3170         {
3171                 {"log_min_error_statement", PGC_SUSET, LOGGING_WHEN,
3172                         gettext_noop("Causes all statements generating error at or above this level to be logged."),
3173                         gettext_noop("Each level includes all the levels that follow it. The later"
3174                                                  " the level, the fewer messages are sent.")
3175                 },
3176                 &log_min_error_statement,
3177                 ERROR, server_message_level_options,
3178                 NULL, NULL, NULL
3179         },
3180
3181         {
3182                 {"log_statement", PGC_SUSET, LOGGING_WHAT,
3183                         gettext_noop("Sets the type of statements logged."),
3184                         NULL
3185                 },
3186                 &log_statement,
3187                 LOGSTMT_NONE, log_statement_options,
3188                 NULL, NULL, NULL
3189         },
3190
3191         {
3192                 {"syslog_facility", PGC_SIGHUP, LOGGING_WHERE,
3193                         gettext_noop("Sets the syslog \"facility\" to be used when syslog enabled."),
3194                         NULL
3195                 },
3196                 &syslog_facility,
3197 #ifdef HAVE_SYSLOG
3198                 LOG_LOCAL0,
3199 #else
3200                 0,
3201 #endif
3202                 syslog_facility_options,
3203                 NULL, assign_syslog_facility, NULL
3204         },
3205
3206         {
3207                 {"session_replication_role", PGC_SUSET, CLIENT_CONN_STATEMENT,
3208                         gettext_noop("Sets the session's behavior for triggers and rewrite rules."),
3209                         NULL
3210                 },
3211                 &SessionReplicationRole,
3212                 SESSION_REPLICATION_ROLE_ORIGIN, session_replication_role_options,
3213                 NULL, assign_session_replication_role, NULL
3214         },
3215
3216         {
3217                 {"synchronous_commit", PGC_USERSET, WAL_SETTINGS,
3218                         gettext_noop("Sets the current transaction's synchronization level."),
3219                         NULL
3220                 },
3221                 &synchronous_commit,
3222                 SYNCHRONOUS_COMMIT_ON, synchronous_commit_options,
3223                 NULL, assign_synchronous_commit, NULL
3224         },
3225
3226         {
3227                 {"trace_recovery_messages", PGC_SIGHUP, DEVELOPER_OPTIONS,
3228                         gettext_noop("Enables logging of recovery-related debugging information."),
3229                         gettext_noop("Each level includes all the levels that follow it. The later"
3230                                                  " the level, the fewer messages are sent.")
3231                 },
3232                 &trace_recovery_messages,
3233
3234                 /*
3235                  * client_message_level_options allows too many values, really, but
3236                  * it's not worth having a separate options array for this.
3237                  */
3238                 LOG, client_message_level_options,
3239                 NULL, NULL, NULL
3240         },
3241
3242         {
3243                 {"track_functions", PGC_SUSET, STATS_COLLECTOR,
3244                         gettext_noop("Collects function-level statistics on database activity."),
3245                         NULL
3246                 },
3247                 &pgstat_track_functions,
3248                 TRACK_FUNC_OFF, track_function_options,
3249                 NULL, NULL, NULL
3250         },
3251
3252         {
3253                 {"wal_level", PGC_POSTMASTER, WAL_SETTINGS,
3254                         gettext_noop("Set the level of information written to the WAL."),
3255                         NULL
3256                 },
3257                 &wal_level,
3258                 WAL_LEVEL_MINIMAL, wal_level_options,
3259                 NULL, NULL, NULL
3260         },
3261
3262         {
3263                 {"wal_sync_method", PGC_SIGHUP, WAL_SETTINGS,
3264                         gettext_noop("Selects the method used for forcing WAL updates to disk."),
3265                         NULL
3266                 },
3267                 &sync_method,
3268                 DEFAULT_SYNC_METHOD, sync_method_options,
3269                 NULL, assign_xlog_sync_method, NULL
3270         },
3271
3272         {
3273                 {"xmlbinary", PGC_USERSET, CLIENT_CONN_STATEMENT,
3274                         gettext_noop("Sets how binary values are to be encoded in XML."),
3275                         NULL
3276                 },
3277                 &xmlbinary,
3278                 XMLBINARY_BASE64, xmlbinary_options,
3279                 NULL, NULL, NULL
3280         },
3281
3282         {
3283                 {"xmloption", PGC_USERSET, CLIENT_CONN_STATEMENT,
3284                         gettext_noop("Sets whether XML data in implicit parsing and serialization "
3285                                                  "operations is to be considered as documents or content fragments."),
3286                         NULL
3287                 },
3288                 &xmloption,
3289                 XMLOPTION_CONTENT, xmloption_options,
3290                 NULL, NULL, NULL
3291         },
3292
3293
3294         /* End-of-list marker */
3295         {
3296                 {NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL
3297         }
3298 };
3299
3300 /******** end of options list ********/
3301
3302
3303 /*
3304  * To allow continued support of obsolete names for GUC variables, we apply
3305  * the following mappings to any unrecognized name.  Note that an old name
3306  * should be mapped to a new one only if the new variable has very similar
3307  * semantics to the old.
3308  */
3309 static const char *const map_old_guc_names[] = {
3310         "sort_mem", "work_mem",
3311         "vacuum_mem", "maintenance_work_mem",
3312         NULL
3313 };
3314
3315
3316 /*
3317  * Actual lookup of variables is done through this single, sorted array.
3318  */
3319 static struct config_generic **guc_variables;
3320
3321 /* Current number of variables contained in the vector */
3322 static int      num_guc_variables;
3323
3324 /* Vector capacity */
3325 static int      size_guc_variables;
3326
3327
3328 static bool guc_dirty;                  /* TRUE if need to do commit/abort work */
3329
3330 static bool reporting_enabled;  /* TRUE to enable GUC_REPORT */
3331
3332 static int      GUCNestLevel = 0;       /* 1 when in main transaction */
3333
3334
3335 static int      guc_var_compare(const void *a, const void *b);
3336 static int      guc_name_compare(const char *namea, const char *nameb);
3337 static void InitializeGUCOptionsFromEnvironment(void);
3338 static void InitializeOneGUCOption(struct config_generic * gconf);
3339 static void push_old_value(struct config_generic * gconf, GucAction action);
3340 static void ReportGUCOption(struct config_generic * record);
3341 static void reapply_stacked_values(struct config_generic * variable,
3342                                            struct config_string * pHolder,
3343                                            GucStack *stack,
3344                                            const char *curvalue,
3345                                            GucContext curscontext, GucSource cursource);
3346 static void ShowGUCConfigOption(const char *name, DestReceiver *dest);
3347 static void ShowAllGUCConfig(DestReceiver *dest);
3348 static char *_ShowOption(struct config_generic * record, bool use_units);
3349 static bool validate_option_array_item(const char *name, const char *value,
3350                                                    bool skipIfNoPermissions);
3351
3352
3353 /*
3354  * Some infrastructure for checking malloc/strdup/realloc calls
3355  */
3356 static void *
3357 guc_malloc(int elevel, size_t size)
3358 {
3359         void       *data;
3360
3361         data = malloc(size);
3362         if (data == NULL)
3363                 ereport(elevel,
3364                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3365                                  errmsg("out of memory")));
3366         return data;
3367 }
3368
3369 static void *
3370 guc_realloc(int elevel, void *old, size_t size)
3371 {
3372         void       *data;
3373
3374         data = realloc(old, size);
3375         if (data == NULL)
3376                 ereport(elevel,
3377                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3378                                  errmsg("out of memory")));
3379         return data;
3380 }
3381
3382 static char *
3383 guc_strdup(int elevel, const char *src)
3384 {
3385         char       *data;
3386
3387         data = strdup(src);
3388         if (data == NULL)
3389                 ereport(elevel,
3390                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3391                                  errmsg("out of memory")));
3392         return data;
3393 }
3394
3395
3396 /*
3397  * Detect whether strval is referenced anywhere in a GUC string item
3398  */
3399 static bool
3400 string_field_used(struct config_string * conf, char *strval)
3401 {
3402         GucStack   *stack;
3403
3404         if (strval == *(conf->variable) ||
3405                 strval == conf->reset_val ||
3406                 strval == conf->boot_val)
3407                 return true;
3408         for (stack = conf->gen.stack; stack; stack = stack->prev)
3409         {
3410                 if (strval == stack->prior.val.stringval ||
3411                         strval == stack->masked.val.stringval)
3412                         return true;
3413         }
3414         return false;
3415 }
3416
3417 /*
3418  * Support for assigning to a field of a string GUC item.  Free the prior
3419  * value if it's not referenced anywhere else in the item (including stacked
3420  * states).
3421  */
3422 static void
3423 set_string_field(struct config_string * conf, char **field, char *newval)
3424 {
3425         char       *oldval = *field;
3426
3427         /* Do the assignment */
3428         *field = newval;
3429
3430         /* Free old value if it's not NULL and isn't referenced anymore */
3431         if (oldval && !string_field_used(conf, oldval))
3432                 free(oldval);
3433 }
3434
3435 /*
3436  * Detect whether an "extra" struct is referenced anywhere in a GUC item
3437  */
3438 static bool
3439 extra_field_used(struct config_generic * gconf, void *extra)
3440 {
3441         GucStack   *stack;
3442
3443         if (extra == gconf->extra)
3444                 return true;
3445         switch (gconf->vartype)
3446         {
3447                 case PGC_BOOL:
3448                         if (extra == ((struct config_bool *) gconf)->reset_extra)
3449                                 return true;
3450                         break;
3451                 case PGC_INT:
3452                         if (extra == ((struct config_int *) gconf)->reset_extra)
3453                                 return true;
3454                         break;
3455                 case PGC_REAL:
3456                         if (extra == ((struct config_real *) gconf)->reset_extra)
3457                                 return true;
3458                         break;
3459                 case PGC_STRING:
3460                         if (extra == ((struct config_string *) gconf)->reset_extra)
3461                                 return true;
3462                         break;
3463                 case PGC_ENUM:
3464                         if (extra == ((struct config_enum *) gconf)->reset_extra)
3465                                 return true;
3466                         break;
3467         }
3468         for (stack = gconf->stack; stack; stack = stack->prev)
3469         {
3470                 if (extra == stack->prior.extra ||
3471                         extra == stack->masked.extra)
3472                         return true;
3473         }
3474
3475         return false;
3476 }
3477
3478 /*
3479  * Support for assigning to an "extra" field of a GUC item.  Free the prior
3480  * value if it's not referenced anywhere else in the item (including stacked
3481  * states).
3482  */
3483 static void
3484 set_extra_field(struct config_generic * gconf, void **field, void *newval)
3485 {
3486         void       *oldval = *field;
3487
3488         /* Do the assignment */
3489         *field = newval;
3490
3491         /* Free old value if it's not NULL and isn't referenced anymore */
3492         if (oldval && !extra_field_used(gconf, oldval))
3493                 free(oldval);
3494 }
3495
3496 /*
3497  * Support for copying a variable's active value into a stack entry.
3498  * The "extra" field associated with the active value is copied, too.
3499  *
3500  * NB: be sure stringval and extra fields of a new stack entry are
3501  * initialized to NULL before this is used, else we'll try to free() them.
3502  */
3503 static void
3504 set_stack_value(struct config_generic * gconf, config_var_value *val)
3505 {
3506         switch (gconf->vartype)
3507         {
3508                 case PGC_BOOL:
3509                         val->val.boolval =
3510                                 *((struct config_bool *) gconf)->variable;
3511                         break;
3512                 case PGC_INT:
3513                         val->val.intval =
3514                                 *((struct config_int *) gconf)->variable;
3515                         break;
3516                 case PGC_REAL:
3517                         val->val.realval =
3518                                 *((struct config_real *) gconf)->variable;
3519                         break;
3520                 case PGC_STRING:
3521                         set_string_field((struct config_string *) gconf,
3522                                                          &(val->val.stringval),
3523                                                          *((struct config_string *) gconf)->variable);
3524                         break;
3525                 case PGC_ENUM:
3526                         val->val.enumval =
3527                                 *((struct config_enum *) gconf)->variable;
3528                         break;
3529         }
3530         set_extra_field(gconf, &(val->extra), gconf->extra);
3531 }
3532
3533 /*
3534  * Support for discarding a no-longer-needed value in a stack entry.
3535  * The "extra" field associated with the stack entry is cleared, too.
3536  */
3537 static void
3538 discard_stack_value(struct config_generic * gconf, config_var_value *val)
3539 {
3540         switch (gconf->vartype)
3541         {
3542                 case PGC_BOOL:
3543                 case PGC_INT:
3544                 case PGC_REAL:
3545                 case PGC_ENUM:
3546                         /* no need to do anything */
3547                         break;
3548                 case PGC_STRING:
3549                         set_string_field((struct config_string *) gconf,
3550                                                          &(val->val.stringval),
3551                                                          NULL);
3552                         break;
3553         }
3554         set_extra_field(gconf, &(val->extra), NULL);
3555 }
3556
3557
3558 /*
3559  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
3560  */
3561 struct config_generic **
3562 get_guc_variables(void)
3563 {
3564         return guc_variables;
3565 }
3566
3567
3568 /*
3569  * Build the sorted array.      This is split out so that it could be
3570  * re-executed after startup (eg, we could allow loadable modules to
3571  * add vars, and then we'd need to re-sort).
3572  */
3573 void
3574 build_guc_variables(void)
3575 {
3576         int                     size_vars;
3577         int                     num_vars = 0;
3578         struct config_generic **guc_vars;
3579         int                     i;
3580
3581         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3582         {
3583                 struct config_bool *conf = &ConfigureNamesBool[i];
3584
3585                 /* Rather than requiring vartype to be filled in by hand, do this: */
3586                 conf->gen.vartype = PGC_BOOL;
3587                 num_vars++;
3588         }
3589
3590         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3591         {
3592                 struct config_int *conf = &ConfigureNamesInt[i];
3593
3594                 conf->gen.vartype = PGC_INT;
3595                 num_vars++;
3596         }
3597
3598         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3599         {
3600                 struct config_real *conf = &ConfigureNamesReal[i];
3601
3602                 conf->gen.vartype = PGC_REAL;
3603                 num_vars++;
3604         }
3605
3606         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3607         {
3608                 struct config_string *conf = &ConfigureNamesString[i];
3609
3610                 conf->gen.vartype = PGC_STRING;
3611                 num_vars++;
3612         }
3613
3614         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3615         {
3616                 struct config_enum *conf = &ConfigureNamesEnum[i];
3617
3618                 conf->gen.vartype = PGC_ENUM;
3619                 num_vars++;
3620         }
3621
3622         /*
3623          * Create table with 20% slack
3624          */
3625         size_vars = num_vars + num_vars / 4;
3626
3627         guc_vars = (struct config_generic **)
3628                 guc_malloc(FATAL, size_vars * sizeof(struct config_generic *));
3629
3630         num_vars = 0;
3631
3632         for (i = 0; ConfigureNamesBool[i].gen.name; i++)
3633                 guc_vars[num_vars++] = &ConfigureNamesBool[i].gen;
3634
3635         for (i = 0; ConfigureNamesInt[i].gen.name; i++)
3636                 guc_vars[num_vars++] = &ConfigureNamesInt[i].gen;
3637
3638         for (i = 0; ConfigureNamesReal[i].gen.name; i++)
3639                 guc_vars[num_vars++] = &ConfigureNamesReal[i].gen;
3640
3641         for (i = 0; ConfigureNamesString[i].gen.name; i++)
3642                 guc_vars[num_vars++] = &ConfigureNamesString[i].gen;
3643
3644         for (i = 0; ConfigureNamesEnum[i].gen.name; i++)
3645                 guc_vars[num_vars++] = &ConfigureNamesEnum[i].gen;
3646
3647         if (guc_variables)
3648                 free(guc_variables);
3649         guc_variables = guc_vars;
3650         num_guc_variables = num_vars;
3651         size_guc_variables = size_vars;
3652         qsort((void *) guc_variables, num_guc_variables,
3653                   sizeof(struct config_generic *), guc_var_compare);
3654 }
3655
3656 /*
3657  * Add a new GUC variable to the list of known variables. The
3658  * list is expanded if needed.
3659  */
3660 static bool
3661 add_guc_variable(struct config_generic * var, int elevel)
3662 {
3663         if (num_guc_variables + 1 >= size_guc_variables)
3664         {
3665                 /*
3666                  * Increase the vector by 25%
3667                  */
3668                 int                     size_vars = size_guc_variables + size_guc_variables / 4;
3669                 struct config_generic **guc_vars;
3670
3671                 if (size_vars == 0)
3672                 {
3673                         size_vars = 100;
3674                         guc_vars = (struct config_generic **)
3675                                 guc_malloc(elevel, size_vars * sizeof(struct config_generic *));
3676                 }
3677                 else
3678                 {
3679                         guc_vars = (struct config_generic **)
3680                                 guc_realloc(elevel, guc_variables, size_vars * sizeof(struct config_generic *));
3681                 }
3682
3683                 if (guc_vars == NULL)
3684                         return false;           /* out of memory */
3685
3686                 guc_variables = guc_vars;
3687                 size_guc_variables = size_vars;
3688         }
3689         guc_variables[num_guc_variables++] = var;
3690         qsort((void *) guc_variables, num_guc_variables,
3691                   sizeof(struct config_generic *), guc_var_compare);
3692         return true;
3693 }
3694
3695 /*
3696  * Create and add a placeholder variable for a custom variable name.
3697  */
3698 static struct config_generic *
3699 add_placeholder_variable(const char *name, int elevel)
3700 {
3701         size_t          sz = sizeof(struct config_string) + sizeof(char *);
3702         struct config_string *var;
3703         struct config_generic *gen;
3704
3705         var = (struct config_string *) guc_malloc(elevel, sz);
3706         if (var == NULL)
3707                 return NULL;
3708         memset(var, 0, sz);
3709         gen = &var->gen;
3710
3711         gen->name = guc_strdup(elevel, name);
3712         if (gen->name == NULL)
3713         {
3714                 free(var);
3715                 return NULL;
3716         }
3717
3718         gen->context = PGC_USERSET;
3719         gen->group = CUSTOM_OPTIONS;
3720         gen->short_desc = "GUC placeholder variable";
3721         gen->flags = GUC_NO_SHOW_ALL | GUC_NOT_IN_SAMPLE | GUC_CUSTOM_PLACEHOLDER;
3722         gen->vartype = PGC_STRING;
3723
3724         /*
3725          * The char* is allocated at the end of the struct since we have no
3726          * 'static' place to point to.  Note that the current value, as well as
3727          * the boot and reset values, start out NULL.
3728          */
3729         var->variable = (char **) (var + 1);
3730
3731         if (!add_guc_variable((struct config_generic *) var, elevel))
3732         {
3733                 free((void *) gen->name);
3734                 free(var);
3735                 return NULL;
3736         }
3737
3738         return gen;
3739 }
3740
3741 /*
3742  * Look up option NAME.  If it exists, return a pointer to its record,
3743  * else return NULL.  If create_placeholders is TRUE, we'll create a
3744  * placeholder record for a valid-looking custom variable name.
3745  */
3746 static struct config_generic *
3747 find_option(const char *name, bool create_placeholders, int elevel)
3748 {
3749         const char **key = &name;
3750         struct config_generic **res;
3751         int                     i;
3752
3753         Assert(name);
3754
3755         /*
3756          * By equating const char ** with struct config_generic *, we are assuming
3757          * the name field is first in config_generic.
3758          */
3759         res = (struct config_generic **) bsearch((void *) &key,
3760                                                                                          (void *) guc_variables,
3761                                                                                          num_guc_variables,
3762                                                                                          sizeof(struct config_generic *),
3763                                                                                          guc_var_compare);
3764         if (res)
3765                 return *res;
3766
3767         /*
3768          * See if the name is an obsolete name for a variable.  We assume that the
3769          * set of supported old names is short enough that a brute-force search is
3770          * the best way.
3771          */
3772         for (i = 0; map_old_guc_names[i] != NULL; i += 2)
3773         {
3774                 if (guc_name_compare(name, map_old_guc_names[i]) == 0)
3775                         return find_option(map_old_guc_names[i + 1], false, elevel);
3776         }
3777
3778         if (create_placeholders)
3779         {
3780                 /*
3781                  * Check if the name is qualified, and if so, add a placeholder.
3782                  */
3783                 if (strchr(name, GUC_QUALIFIER_SEPARATOR) != NULL)
3784                         return add_placeholder_variable(name, elevel);
3785         }
3786
3787         /* Unknown name */
3788         return NULL;
3789 }
3790
3791
3792 /*
3793  * comparator for qsorting and bsearching guc_variables array
3794  */
3795 static int
3796 guc_var_compare(const void *a, const void *b)
3797 {
3798         const struct config_generic *confa = *(struct config_generic * const *) a;
3799         const struct config_generic *confb = *(struct config_generic * const *) b;
3800
3801         return guc_name_compare(confa->name, confb->name);
3802 }
3803
3804 /*
3805  * the bare comparison function for GUC names
3806  */
3807 static int
3808 guc_name_compare(const char *namea, const char *nameb)
3809 {
3810         /*
3811          * The temptation to use strcasecmp() here must be resisted, because the
3812          * array ordering has to remain stable across setlocale() calls. So, build
3813          * our own with a simple ASCII-only downcasing.
3814          */
3815         while (*namea && *nameb)
3816         {
3817                 char            cha = *namea++;
3818                 char            chb = *nameb++;
3819
3820                 if (cha >= 'A' && cha <= 'Z')
3821                         cha += 'a' - 'A';
3822                 if (chb >= 'A' && chb <= 'Z')
3823                         chb += 'a' - 'A';
3824                 if (cha != chb)
3825                         return cha - chb;
3826         }
3827         if (*namea)
3828                 return 1;                               /* a is longer */
3829         if (*nameb)
3830                 return -1;                              /* b is longer */
3831         return 0;
3832 }
3833
3834
3835 /*
3836  * Initialize GUC options during program startup.
3837  *
3838  * Note that we cannot read the config file yet, since we have not yet
3839  * processed command-line switches.
3840  */
3841 void
3842 InitializeGUCOptions(void)
3843 {
3844         int                     i;
3845
3846         /*
3847          * Before log_line_prefix could possibly receive a nonempty setting, make
3848          * sure that timezone processing is minimally alive (see elog.c).
3849          */
3850         pg_timezone_initialize();
3851
3852         /*
3853          * Build sorted array of all GUC variables.
3854          */
3855         build_guc_variables();
3856
3857         /*
3858          * Load all variables with their compiled-in defaults, and initialize
3859          * status fields as needed.
3860          */
3861         for (i = 0; i < num_guc_variables; i++)
3862         {
3863                 InitializeOneGUCOption(guc_variables[i]);
3864         }
3865
3866         guc_dirty = false;
3867
3868         reporting_enabled = false;
3869
3870         /*
3871          * Prevent any attempt to override the transaction modes from
3872          * non-interactive sources.
3873          */
3874         SetConfigOption("transaction_isolation", "default",
3875                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3876         SetConfigOption("transaction_read_only", "no",
3877                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3878         SetConfigOption("transaction_deferrable", "no",
3879                                         PGC_POSTMASTER, PGC_S_OVERRIDE);
3880
3881         /*
3882          * For historical reasons, some GUC parameters can receive defaults from
3883          * environment variables.  Process those settings.
3884          */
3885         InitializeGUCOptionsFromEnvironment();
3886 }
3887
3888 /*
3889  * Assign any GUC values that can come from the server's environment.
3890  *
3891  * This is called from InitializeGUCOptions, and also from ProcessConfigFile
3892  * to deal with the possibility that a setting has been removed from
3893  * postgresql.conf and should now get a value from the environment.
3894  * (The latter is a kludge that should probably go away someday; if so,
3895  * fold this back into InitializeGUCOptions.)
3896  */
3897 static void
3898 InitializeGUCOptionsFromEnvironment(void)
3899 {
3900         char       *env;
3901         long            stack_rlimit;
3902
3903         env = getenv("PGPORT");
3904         if (env != NULL)
3905                 SetConfigOption("port", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3906
3907         env = getenv("PGDATESTYLE");
3908         if (env != NULL)
3909                 SetConfigOption("datestyle", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3910
3911         env = getenv("PGCLIENTENCODING");
3912         if (env != NULL)
3913                 SetConfigOption("client_encoding", env, PGC_POSTMASTER, PGC_S_ENV_VAR);
3914
3915         /*
3916          * rlimit isn't exactly an "environment variable", but it behaves about
3917          * the same.  If we can identify the platform stack depth rlimit, increase
3918          * default stack depth setting up to whatever is safe (but at most 2MB).
3919          */
3920         stack_rlimit = get_stack_depth_rlimit();
3921         if (stack_rlimit > 0)
3922         {
3923                 long            new_limit = (stack_rlimit - STACK_DEPTH_SLOP) / 1024L;
3924
3925                 if (new_limit > 100)
3926                 {
3927                         char            limbuf[16];
3928
3929                         new_limit = Min(new_limit, 2048);
3930                         sprintf(limbuf, "%ld", new_limit);
3931                         SetConfigOption("max_stack_depth", limbuf,
3932                                                         PGC_POSTMASTER, PGC_S_ENV_VAR);
3933                 }
3934         }
3935 }
3936
3937 /*
3938  * Initialize one GUC option variable to its compiled-in default.
3939  *
3940  * Note: the reason for calling check_hooks is not that we think the boot_val
3941  * might fail, but that the hooks might wish to compute an "extra" struct.
3942  */
3943 static void
3944 InitializeOneGUCOption(struct config_generic * gconf)
3945 {
3946         gconf->status = 0;
3947         gconf->source = PGC_S_DEFAULT;
3948         gconf->reset_source = PGC_S_DEFAULT;
3949         gconf->scontext = PGC_INTERNAL;
3950         gconf->reset_scontext = PGC_INTERNAL;
3951         gconf->stack = NULL;
3952         gconf->extra = NULL;
3953         gconf->sourcefile = NULL;
3954         gconf->sourceline = 0;
3955
3956         switch (gconf->vartype)
3957         {
3958                 case PGC_BOOL:
3959                         {
3960                                 struct config_bool *conf = (struct config_bool *) gconf;
3961                                 bool            newval = conf->boot_val;
3962                                 void       *extra = NULL;
3963
3964                                 if (!call_bool_check_hook(conf, &newval, &extra,
3965                                                                                   PGC_S_DEFAULT, LOG))
3966                                         elog(FATAL, "failed to initialize %s to %d",
3967                                                  conf->gen.name, (int) newval);
3968                                 if (conf->assign_hook)
3969                                         (*conf->assign_hook) (newval, extra);
3970                                 *conf->variable = conf->reset_val = newval;
3971                                 conf->gen.extra = conf->reset_extra = extra;
3972                                 break;
3973                         }
3974                 case PGC_INT:
3975                         {
3976                                 struct config_int *conf = (struct config_int *) gconf;
3977                                 int                     newval = conf->boot_val;
3978                                 void       *extra = NULL;
3979
3980                                 Assert(newval >= conf->min);
3981                                 Assert(newval <= conf->max);
3982                                 if (!call_int_check_hook(conf, &newval, &extra,
3983                                                                                  PGC_S_DEFAULT, LOG))
3984                                         elog(FATAL, "failed to initialize %s to %d",
3985                                                  conf->gen.name, newval);
3986                                 if (conf->assign_hook)
3987                                         (*conf->assign_hook) (newval, extra);
3988                                 *conf->variable = conf->reset_val = newval;
3989                                 conf->gen.extra = conf->reset_extra = extra;
3990                                 break;
3991                         }
3992                 case PGC_REAL:
3993                         {
3994                                 struct config_real *conf = (struct config_real *) gconf;
3995                                 double          newval = conf->boot_val;
3996                                 void       *extra = NULL;
3997
3998                                 Assert(newval >= conf->min);
3999                                 Assert(newval <= conf->max);
4000                                 if (!call_real_check_hook(conf, &newval, &extra,
4001                                                                                   PGC_S_DEFAULT, LOG))
4002                                         elog(FATAL, "failed to initialize %s to %g",
4003                                                  conf->gen.name, newval);
4004                                 if (conf->assign_hook)
4005                                         (*conf->assign_hook) (newval, extra);
4006                                 *conf->variable = conf->reset_val = newval;
4007                                 conf->gen.extra = conf->reset_extra = extra;
4008                                 break;
4009                         }
4010                 case PGC_STRING:
4011                         {
4012                                 struct config_string *conf = (struct config_string *) gconf;
4013                                 char       *newval;
4014                                 void       *extra = NULL;
4015
4016                                 /* non-NULL boot_val must always get strdup'd */
4017                                 if (conf->boot_val != NULL)
4018                                         newval = guc_strdup(FATAL, conf->boot_val);
4019                                 else
4020                                         newval = NULL;
4021
4022                                 if (!call_string_check_hook(conf, &newval, &extra,
4023                                                                                         PGC_S_DEFAULT, LOG))
4024                                         elog(FATAL, "failed to initialize %s to \"%s\"",
4025                                                  conf->gen.name, newval ? newval : "");
4026                                 if (conf->assign_hook)
4027                                         (*conf->assign_hook) (newval, extra);
4028                                 *conf->variable = conf->reset_val = newval;
4029                                 conf->gen.extra = conf->reset_extra = extra;
4030                                 break;
4031                         }
4032                 case PGC_ENUM:
4033                         {
4034                                 struct config_enum *conf = (struct config_enum *) gconf;
4035                                 int                     newval = conf->boot_val;
4036                                 void       *extra = NULL;
4037
4038                                 if (!call_enum_check_hook(conf, &newval, &extra,
4039                                                                                   PGC_S_DEFAULT, LOG))
4040                                         elog(FATAL, "failed to initialize %s to %d",
4041                                                  conf->gen.name, newval);
4042                                 if (conf->assign_hook)
4043                                         (*conf->assign_hook) (newval, extra);
4044                                 *conf->variable = conf->reset_val = newval;
4045                                 conf->gen.extra = conf->reset_extra = extra;
4046                                 break;
4047                         }
4048         }
4049 }
4050
4051
4052 /*
4053  * Select the configuration files and data directory to be used, and
4054  * do the initial read of postgresql.conf.
4055  *
4056  * This is called after processing command-line switches.
4057  *              userDoption is the -D switch value if any (NULL if unspecified).
4058  *              progname is just for use in error messages.
4059  *
4060  * Returns true on success; on failure, prints a suitable error message
4061  * to stderr and returns false.
4062  */
4063 bool
4064 SelectConfigFiles(const char *userDoption, const char *progname)
4065 {
4066         char       *configdir;
4067         char       *fname;
4068         struct stat stat_buf;
4069
4070         /* configdir is -D option, or $PGDATA if no -D */
4071         if (userDoption)
4072                 configdir = make_absolute_path(userDoption);
4073         else
4074                 configdir = make_absolute_path(getenv("PGDATA"));
4075
4076         /*
4077          * Find the configuration file: if config_file was specified on the
4078          * command line, use it, else use configdir/postgresql.conf.  In any case
4079          * ensure the result is an absolute path, so that it will be interpreted
4080          * the same way by future backends.
4081          */
4082         if (ConfigFileName)
4083                 fname = make_absolute_path(ConfigFileName);
4084         else if (configdir)
4085         {
4086                 fname = guc_malloc(FATAL,
4087                                                    strlen(configdir) + strlen(CONFIG_FILENAME) + 2);
4088                 sprintf(fname, "%s/%s", configdir, CONFIG_FILENAME);
4089         }
4090         else
4091         {
4092                 write_stderr("%s does not know where to find the server configuration file.\n"
4093                                          "You must specify the --config-file or -D invocation "
4094                                          "option or set the PGDATA environment variable.\n",
4095                                          progname);
4096                 return false;
4097         }
4098
4099         /*
4100          * Set the ConfigFileName GUC variable to its final value, ensuring that
4101          * it can't be overridden later.
4102          */
4103         SetConfigOption("config_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4104         free(fname);
4105
4106         /*
4107          * Now read the config file for the first time.
4108          */
4109         if (stat(ConfigFileName, &stat_buf) != 0)
4110         {
4111                 write_stderr("%s cannot access the server configuration file \"%s\": %s\n",
4112                                          progname, ConfigFileName, strerror(errno));
4113                 free(configdir);
4114                 return false;
4115         }
4116
4117         ProcessConfigFile(PGC_POSTMASTER);
4118
4119         /*
4120          * If the data_directory GUC variable has been set, use that as DataDir;
4121          * otherwise use configdir if set; else punt.
4122          *
4123          * Note: SetDataDir will copy and absolute-ize its argument, so we don't
4124          * have to.
4125          */
4126         if (data_directory)
4127                 SetDataDir(data_directory);
4128         else if (configdir)
4129                 SetDataDir(configdir);
4130         else
4131         {
4132                 write_stderr("%s does not know where to find the database system data.\n"
4133                                          "This can be specified as \"data_directory\" in \"%s\", "
4134                                          "or by the -D invocation option, or by the "
4135                                          "PGDATA environment variable.\n",
4136                                          progname, ConfigFileName);
4137                 return false;
4138         }
4139
4140         /*
4141          * Reflect the final DataDir value back into the data_directory GUC var.
4142          * (If you are wondering why we don't just make them a single variable,
4143          * it's because the EXEC_BACKEND case needs DataDir to be transmitted to
4144          * child backends specially.  XXX is that still true?  Given that we now
4145          * chdir to DataDir, EXEC_BACKEND can read the config file without knowing
4146          * DataDir in advance.)
4147          */
4148         SetConfigOption("data_directory", DataDir, PGC_POSTMASTER, PGC_S_OVERRIDE);
4149
4150         /*
4151          * If timezone_abbreviations wasn't set in the configuration file, install
4152          * the default value.  We do it this way because we can't safely install a
4153          * "real" value until my_exec_path is set, which may not have happened
4154          * when InitializeGUCOptions runs, so the bootstrap default value cannot
4155          * be the real desired default.
4156          */
4157         pg_timezone_abbrev_initialize();
4158
4159         /*
4160          * Figure out where pg_hba.conf is, and make sure the path is absolute.
4161          */
4162         if (HbaFileName)
4163                 fname = make_absolute_path(HbaFileName);
4164         else if (configdir)
4165         {
4166                 fname = guc_malloc(FATAL,
4167                                                    strlen(configdir) + strlen(HBA_FILENAME) + 2);
4168                 sprintf(fname, "%s/%s", configdir, HBA_FILENAME);
4169         }
4170         else
4171         {
4172                 write_stderr("%s does not know where to find the \"hba\" configuration file.\n"
4173                                          "This can be specified as \"hba_file\" in \"%s\", "
4174                                          "or by the -D invocation option, or by the "
4175                                          "PGDATA environment variable.\n",
4176                                          progname, ConfigFileName);
4177                 return false;
4178         }
4179         SetConfigOption("hba_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4180         free(fname);
4181
4182         /*
4183          * Likewise for pg_ident.conf.
4184          */
4185         if (IdentFileName)
4186                 fname = make_absolute_path(IdentFileName);
4187         else if (configdir)
4188         {
4189                 fname = guc_malloc(FATAL,
4190                                                    strlen(configdir) + strlen(IDENT_FILENAME) + 2);
4191                 sprintf(fname, "%s/%s", configdir, IDENT_FILENAME);
4192         }
4193         else
4194         {
4195                 write_stderr("%s does not know where to find the \"ident\" configuration file.\n"
4196                                          "This can be specified as \"ident_file\" in \"%s\", "
4197                                          "or by the -D invocation option, or by the "
4198                                          "PGDATA environment variable.\n",
4199                                          progname, ConfigFileName);
4200                 return false;
4201         }
4202         SetConfigOption("ident_file", fname, PGC_POSTMASTER, PGC_S_OVERRIDE);
4203         free(fname);
4204
4205         free(configdir);
4206
4207         return true;
4208 }
4209
4210
4211 /*
4212  * Reset all options to their saved default values (implements RESET ALL)
4213  */
4214 void
4215 ResetAllOptions(void)
4216 {
4217         int                     i;
4218
4219         for (i = 0; i < num_guc_variables; i++)
4220         {
4221                 struct config_generic *gconf = guc_variables[i];
4222
4223                 /* Don't reset non-SET-able values */
4224                 if (gconf->context != PGC_SUSET &&
4225                         gconf->context != PGC_USERSET)
4226                         continue;
4227                 /* Don't reset if special exclusion from RESET ALL */
4228                 if (gconf->flags & GUC_NO_RESET_ALL)
4229                         continue;
4230                 /* No need to reset if wasn't SET */
4231                 if (gconf->source <= PGC_S_OVERRIDE)
4232                         continue;
4233
4234                 /* Save old value to support transaction abort */
4235                 push_old_value(gconf, GUC_ACTION_SET);
4236
4237                 switch (gconf->vartype)
4238                 {
4239                         case PGC_BOOL:
4240                                 {
4241                                         struct config_bool *conf = (struct config_bool *) gconf;
4242
4243                                         if (conf->assign_hook)
4244                                                 (*conf->assign_hook) (conf->reset_val,
4245                                                                                           conf->reset_extra);
4246                                         *conf->variable = conf->reset_val;
4247                                         set_extra_field(&conf->gen, &conf->gen.extra,
4248                                                                         conf->reset_extra);
4249                                         break;
4250                                 }
4251                         case PGC_INT:
4252                                 {
4253                                         struct config_int *conf = (struct config_int *) gconf;
4254
4255                                         if (conf->assign_hook)
4256                                                 (*conf->assign_hook) (conf->reset_val,
4257                                                                                           conf->reset_extra);
4258                                         *conf->variable = conf->reset_val;
4259                                         set_extra_field(&conf->gen, &conf->gen.extra,
4260                                                                         conf->reset_extra);
4261                                         break;
4262                                 }
4263                         case PGC_REAL:
4264                                 {
4265                                         struct config_real *conf = (struct config_real *) gconf;
4266
4267                                         if (conf->assign_hook)
4268                                                 (*conf->assign_hook) (conf->reset_val,
4269                                                                                           conf->reset_extra);
4270                                         *conf->variable = conf->reset_val;
4271                                         set_extra_field(&conf->gen, &conf->gen.extra,
4272                                                                         conf->reset_extra);
4273                                         break;
4274                                 }
4275                         case PGC_STRING:
4276                                 {
4277                                         struct config_string *conf = (struct config_string *) gconf;
4278
4279                                         if (conf->assign_hook)
4280                                                 (*conf->assign_hook) (conf->reset_val,
4281                                                                                           conf->reset_extra);
4282                                         set_string_field(conf, conf->variable, conf->reset_val);
4283                                         set_extra_field(&conf->gen, &conf->gen.extra,
4284                                                                         conf->reset_extra);
4285                                         break;
4286                                 }
4287                         case PGC_ENUM:
4288                                 {
4289                                         struct config_enum *conf = (struct config_enum *) gconf;
4290
4291                                         if (conf->assign_hook)
4292                                                 (*conf->assign_hook) (conf->reset_val,
4293                                                                                           conf->reset_extra);
4294                                         *conf->variable = conf->reset_val;
4295                                         set_extra_field(&conf->gen, &conf->gen.extra,
4296                                                                         conf->reset_extra);
4297                                         break;
4298                                 }
4299                 }
4300
4301                 gconf->source = gconf->reset_source;
4302                 gconf->scontext = gconf->reset_scontext;
4303
4304                 if (gconf->flags & GUC_REPORT)
4305                         ReportGUCOption(gconf);
4306         }
4307 }
4308
4309
4310 /*
4311  * push_old_value
4312  *              Push previous state during transactional assignment to a GUC variable.
4313  */
4314 static void
4315 push_old_value(struct config_generic * gconf, GucAction action)
4316 {
4317         GucStack   *stack;
4318
4319         /* If we're not inside a nest level, do nothing */
4320         if (GUCNestLevel == 0)
4321                 return;
4322
4323         /* Do we already have a stack entry of the current nest level? */
4324         stack = gconf->stack;
4325         if (stack && stack->nest_level >= GUCNestLevel)
4326         {
4327                 /* Yes, so adjust its state if necessary */
4328                 Assert(stack->nest_level == GUCNestLevel);
4329                 switch (action)
4330                 {
4331                         case GUC_ACTION_SET:
4332                                 /* SET overrides any prior action at same nest level */
4333                                 if (stack->state == GUC_SET_LOCAL)
4334                                 {
4335                                         /* must discard old masked value */
4336                                         discard_stack_value(gconf, &stack->masked);
4337                                 }
4338                                 stack->state = GUC_SET;
4339                                 break;
4340                         case GUC_ACTION_LOCAL:
4341                                 if (stack->state == GUC_SET)
4342                                 {
4343                                         /* SET followed by SET LOCAL, remember SET's value */
4344                                         stack->masked_scontext = gconf->scontext;
4345                                         set_stack_value(gconf, &stack->masked);
4346                                         stack->state = GUC_SET_LOCAL;
4347                                 }
4348                                 /* in all other cases, no change to stack entry */
4349                                 break;
4350                         case GUC_ACTION_SAVE:
4351                                 /* Could only have a prior SAVE of same variable */
4352                                 Assert(stack->state == GUC_SAVE);
4353                                 break;
4354                 }
4355                 Assert(guc_dirty);              /* must be set already */
4356                 return;
4357         }
4358
4359         /*
4360          * Push a new stack entry
4361          *
4362          * We keep all the stack entries in TopTransactionContext for simplicity.
4363          */
4364         stack = (GucStack *) MemoryContextAllocZero(TopTransactionContext,
4365                                                                                                 sizeof(GucStack));
4366
4367         stack->prev = gconf->stack;
4368         stack->nest_level = GUCNestLevel;
4369         switch (action)
4370         {
4371                 case GUC_ACTION_SET:
4372                         stack->state = GUC_SET;
4373                         break;
4374                 case GUC_ACTION_LOCAL:
4375                         stack->state = GUC_LOCAL;
4376                         break;
4377                 case GUC_ACTION_SAVE:
4378                         stack->state = GUC_SAVE;
4379                         break;
4380         }
4381         stack->source = gconf->source;
4382         stack->scontext = gconf->scontext;
4383         set_stack_value(gconf, &stack->prior);
4384
4385         gconf->stack = stack;
4386
4387         /* Ensure we remember to pop at end of xact */
4388         guc_dirty = true;
4389 }
4390
4391
4392 /*
4393  * Do GUC processing at main transaction start.
4394  */
4395 void
4396 AtStart_GUC(void)
4397 {
4398         /*
4399          * The nest level should be 0 between transactions; if it isn't, somebody
4400          * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
4401          * throw a warning but make no other effort to clean up.
4402          */
4403         if (GUCNestLevel != 0)
4404                 elog(WARNING, "GUC nest level = %d at transaction start",
4405                          GUCNestLevel);
4406         GUCNestLevel = 1;
4407 }
4408
4409 /*
4410  * Enter a new nesting level for GUC values.  This is called at subtransaction
4411  * start, and when entering a function that has proconfig settings, and in
4412  * some other places where we want to set GUC variables transiently.
4413  * NOTE we must not risk error here, else subtransaction start will be unhappy.
4414  */
4415 int
4416 NewGUCNestLevel(void)
4417 {
4418         return ++GUCNestLevel;
4419 }
4420
4421 /*
4422  * Do GUC processing at transaction or subtransaction commit or abort, or
4423  * when exiting a function that has proconfig settings, or when undoing a
4424  * transient assignment to some GUC variables.  (The name is thus a bit of
4425  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
4426  * During abort, we discard all GUC settings that were applied at nesting
4427  * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
4428  */
4429 void
4430 AtEOXact_GUC(bool isCommit, int nestLevel)
4431 {
4432         bool            still_dirty;
4433         int                     i;
4434
4435         /*
4436          * Note: it's possible to get here with GUCNestLevel == nestLevel-1 during
4437          * abort, if there is a failure during transaction start before
4438          * AtStart_GUC is called.
4439          */
4440         Assert(nestLevel > 0 &&
4441                    (nestLevel <= GUCNestLevel ||
4442                         (nestLevel == GUCNestLevel + 1 && !isCommit)));
4443
4444         /* Quick exit if nothing's changed in this transaction */
4445         if (!guc_dirty)
4446         {
4447                 GUCNestLevel = nestLevel - 1;
4448                 return;
4449         }
4450
4451         still_dirty = false;
4452         for (i = 0; i < num_guc_variables; i++)
4453         {
4454                 struct config_generic *gconf = guc_variables[i];
4455                 GucStack   *stack;
4456
4457                 /*
4458                  * Process and pop each stack entry within the nest level. To simplify
4459                  * fmgr_security_definer() and other places that use GUC_ACTION_SAVE,
4460                  * we allow failure exit from code that uses a local nest level to be
4461                  * recovered at the surrounding transaction or subtransaction abort;
4462                  * so there could be more than one stack entry to pop.
4463                  */
4464                 while ((stack = gconf->stack) != NULL &&
4465                            stack->nest_level >= nestLevel)
4466                 {
4467                         GucStack   *prev = stack->prev;
4468                         bool            restorePrior = false;
4469                         bool            restoreMasked = false;
4470                         bool            changed;
4471
4472                         /*
4473                          * In this next bit, if we don't set either restorePrior or
4474                          * restoreMasked, we must "discard" any unwanted fields of the
4475                          * stack entries to avoid leaking memory.  If we do set one of
4476                          * those flags, unused fields will be cleaned up after restoring.
4477                          */
4478                         if (!isCommit)          /* if abort, always restore prior value */
4479                                 restorePrior = true;
4480                         else if (stack->state == GUC_SAVE)
4481                                 restorePrior = true;
4482                         else if (stack->nest_level == 1)
4483                         {
4484                                 /* transaction commit */
4485                                 if (stack->state == GUC_SET_LOCAL)
4486                                         restoreMasked = true;
4487                                 else if (stack->state == GUC_SET)
4488                                 {
4489                                         /* we keep the current active value */
4490                                         discard_stack_value(gconf, &stack->prior);
4491                                 }
4492                                 else    /* must be GUC_LOCAL */
4493                                         restorePrior = true;
4494                         }
4495                         else if (prev == NULL ||
4496                                          prev->nest_level < stack->nest_level - 1)
4497                         {
4498                                 /* decrement entry's level and do not pop it */
4499                                 stack->nest_level--;
4500                                 continue;
4501                         }
4502                         else
4503                         {
4504                                 /*
4505                                  * We have to merge this stack entry into prev. See README for
4506                                  * discussion of this bit.
4507                                  */
4508                                 switch (stack->state)
4509                                 {
4510                                         case GUC_SAVE:
4511                                                 Assert(false);  /* can't get here */
4512
4513                                         case GUC_SET:
4514                                                 /* next level always becomes SET */
4515                                                 discard_stack_value(gconf, &stack->prior);
4516                                                 if (prev->state == GUC_SET_LOCAL)
4517                                                         discard_stack_value(gconf, &prev->masked);
4518                                                 prev->state = GUC_SET;
4519                                                 break;
4520
4521                                         case GUC_LOCAL:
4522                                                 if (prev->state == GUC_SET)
4523                                                 {
4524                                                         /* LOCAL migrates down */
4525                                                         prev->masked_scontext = stack->scontext;
4526                                                         prev->masked = stack->prior;
4527                                                         prev->state = GUC_SET_LOCAL;
4528                                                 }
4529                                                 else
4530                                                 {
4531                                                         /* else just forget this stack level */
4532                                                         discard_stack_value(gconf, &stack->prior);
4533                                                 }
4534                                                 break;
4535
4536                                         case GUC_SET_LOCAL:
4537                                                 /* prior state at this level no longer wanted */
4538                                                 discard_stack_value(gconf, &stack->prior);
4539                                                 /* copy down the masked state */
4540                                                 prev->masked_scontext = stack->masked_scontext;
4541                                                 if (prev->state == GUC_SET_LOCAL)
4542                                                         discard_stack_value(gconf, &prev->masked);
4543                                                 prev->masked = stack->masked;
4544                                                 prev->state = GUC_SET_LOCAL;
4545                                                 break;
4546                                 }
4547                         }
4548
4549                         changed = false;
4550
4551                         if (restorePrior || restoreMasked)
4552                         {
4553                                 /* Perform appropriate restoration of the stacked value */
4554                                 config_var_value newvalue;
4555                                 GucSource       newsource;
4556                                 GucContext      newscontext;
4557
4558                                 if (restoreMasked)
4559                                 {
4560                                         newvalue = stack->masked;
4561                                         newsource = PGC_S_SESSION;
4562                                         newscontext = stack->masked_scontext;
4563                                 }
4564                                 else
4565                                 {
4566                                         newvalue = stack->prior;
4567                                         newsource = stack->source;
4568                                         newscontext = stack->scontext;
4569                                 }
4570
4571                                 switch (gconf->vartype)
4572                                 {
4573                                         case PGC_BOOL:
4574                                                 {
4575                                                         struct config_bool *conf = (struct config_bool *) gconf;
4576                                                         bool            newval = newvalue.val.boolval;
4577                                                         void       *newextra = newvalue.extra;
4578
4579                                                         if (*conf->variable != newval ||
4580                                                                 conf->gen.extra != newextra)
4581                                                         {
4582                                                                 if (conf->assign_hook)
4583                                                                         (*conf->assign_hook) (newval, newextra);
4584                                                                 *conf->variable = newval;
4585                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4586                                                                                                 newextra);
4587                                                                 changed = true;
4588                                                         }
4589                                                         break;
4590                                                 }
4591                                         case PGC_INT:
4592                                                 {
4593                                                         struct config_int *conf = (struct config_int *) gconf;
4594                                                         int                     newval = newvalue.val.intval;
4595                                                         void       *newextra = newvalue.extra;
4596
4597                                                         if (*conf->variable != newval ||
4598                                                                 conf->gen.extra != newextra)
4599                                                         {
4600                                                                 if (conf->assign_hook)
4601                                                                         (*conf->assign_hook) (newval, newextra);
4602                                                                 *conf->variable = newval;
4603                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4604                                                                                                 newextra);
4605                                                                 changed = true;
4606                                                         }
4607                                                         break;
4608                                                 }
4609                                         case PGC_REAL:
4610                                                 {
4611                                                         struct config_real *conf = (struct config_real *) gconf;
4612                                                         double          newval = newvalue.val.realval;
4613                                                         void       *newextra = newvalue.extra;
4614
4615                                                         if (*conf->variable != newval ||
4616                                                                 conf->gen.extra != newextra)
4617                                                         {
4618                                                                 if (conf->assign_hook)
4619                                                                         (*conf->assign_hook) (newval, newextra);
4620                                                                 *conf->variable = newval;
4621                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4622                                                                                                 newextra);
4623                                                                 changed = true;
4624                                                         }
4625                                                         break;
4626                                                 }
4627                                         case PGC_STRING:
4628                                                 {
4629                                                         struct config_string *conf = (struct config_string *) gconf;
4630                                                         char       *newval = newvalue.val.stringval;
4631                                                         void       *newextra = newvalue.extra;
4632
4633                                                         if (*conf->variable != newval ||
4634                                                                 conf->gen.extra != newextra)
4635                                                         {
4636                                                                 if (conf->assign_hook)
4637                                                                         (*conf->assign_hook) (newval, newextra);
4638                                                                 set_string_field(conf, conf->variable, newval);
4639                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4640                                                                                                 newextra);
4641                                                                 changed = true;
4642                                                         }
4643
4644                                                         /*
4645                                                          * Release stacked values if not used anymore. We
4646                                                          * could use discard_stack_value() here, but since
4647                                                          * we have type-specific code anyway, might as
4648                                                          * well inline it.
4649                                                          */
4650                                                         set_string_field(conf, &stack->prior.val.stringval, NULL);
4651                                                         set_string_field(conf, &stack->masked.val.stringval, NULL);
4652                                                         break;
4653                                                 }
4654                                         case PGC_ENUM:
4655                                                 {
4656                                                         struct config_enum *conf = (struct config_enum *) gconf;
4657                                                         int                     newval = newvalue.val.enumval;
4658                                                         void       *newextra = newvalue.extra;
4659
4660                                                         if (*conf->variable != newval ||
4661                                                                 conf->gen.extra != newextra)
4662                                                         {
4663                                                                 if (conf->assign_hook)
4664                                                                         (*conf->assign_hook) (newval, newextra);
4665                                                                 *conf->variable = newval;
4666                                                                 set_extra_field(&conf->gen, &conf->gen.extra,
4667                                                                                                 newextra);
4668                                                                 changed = true;
4669                                                         }
4670                                                         break;
4671                                                 }
4672                                 }
4673
4674                                 /*
4675                                  * Release stacked extra values if not used anymore.
4676                                  */
4677                                 set_extra_field(gconf, &(stack->prior.extra), NULL);
4678                                 set_extra_field(gconf, &(stack->masked.extra), NULL);
4679
4680                                 /* And restore source information */
4681                                 gconf->source = newsource;
4682                                 gconf->scontext = newscontext;
4683                         }
4684
4685                         /* Finish popping the state stack */
4686                         gconf->stack = prev;
4687                         pfree(stack);
4688
4689                         /* Report new value if we changed it */
4690                         if (changed && (gconf->flags & GUC_REPORT))
4691                                 ReportGUCOption(gconf);
4692                 }                                               /* end of stack-popping loop */
4693
4694                 if (stack != NULL)
4695                         still_dirty = true;
4696         }
4697
4698         /* If there are no remaining stack entries, we can reset guc_dirty */
4699         guc_dirty = still_dirty;
4700
4701         /* Update nesting level */
4702         GUCNestLevel = nestLevel - 1;
4703 }
4704
4705
4706 /*
4707  * Start up automatic reporting of changes to variables marked GUC_REPORT.
4708  * This is executed at completion of backend startup.
4709  */
4710 void
4711 BeginReportingGUCOptions(void)
4712 {
4713         int                     i;
4714
4715         /*
4716          * Don't do anything unless talking to an interactive frontend of protocol
4717          * 3.0 or later.
4718          */
4719         if (whereToSendOutput != DestRemote ||
4720                 PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
4721                 return;
4722
4723         reporting_enabled = true;
4724
4725         /* Transmit initial values of interesting variables */
4726         for (i = 0; i < num_guc_variables; i++)
4727         {
4728                 struct config_generic *conf = guc_variables[i];
4729
4730                 if (conf->flags & GUC_REPORT)
4731                         ReportGUCOption(conf);
4732         }
4733 }
4734
4735 /*
4736  * ReportGUCOption: if appropriate, transmit option value to frontend
4737  */
4738 static void
4739 ReportGUCOption(struct config_generic * record)
4740 {
4741         if (reporting_enabled && (record->flags & GUC_REPORT))
4742         {
4743                 char       *val = _ShowOption(record, false);
4744                 StringInfoData msgbuf;
4745
4746                 pq_beginmessage(&msgbuf, 'S');
4747                 pq_sendstring(&msgbuf, record->name);
4748                 pq_sendstring(&msgbuf, val);
4749                 pq_endmessage(&msgbuf);
4750
4751                 pfree(val);
4752         }
4753 }
4754
4755 /*
4756  * Try to parse value as an integer.  The accepted formats are the
4757  * usual decimal, octal, or hexadecimal formats, optionally followed by
4758  * a unit name if "flags" indicates a unit is allowed.
4759  *
4760  * If the string parses okay, return true, else false.
4761  * If okay and result is not NULL, return the value in *result.
4762  * If not okay and hintmsg is not NULL, *hintmsg is set to a suitable
4763  *      HINT message, or NULL if no hint provided.
4764  */
4765 bool
4766 parse_int(const char *value, int *result, int flags, const char **hintmsg)
4767 {
4768         int64           val;
4769         char       *endptr;
4770
4771         /* To suppress compiler warnings, always set output params */
4772         if (result)
4773                 *result = 0;
4774         if (hintmsg)
4775                 *hintmsg = NULL;
4776
4777         /* We assume here that int64 is at least as wide as long */
4778         errno = 0;
4779         val = strtol(value, &endptr, 0);
4780
4781         if (endptr == value)
4782                 return false;                   /* no HINT for integer syntax error */
4783
4784         if (errno == ERANGE || val != (int64) ((int32) val))
4785         {
4786                 if (hintmsg)
4787                         *hintmsg = gettext_noop("Value exceeds integer range.");
4788                 return false;
4789         }
4790
4791         /* allow whitespace between integer and unit */
4792         while (isspace((unsigned char) *endptr))
4793                 endptr++;
4794
4795         /* Handle possible unit */
4796         if (*endptr != '\0')
4797         {
4798                 /*
4799                  * Note: the multiple-switch coding technique here is a bit tedious,
4800                  * but seems necessary to avoid intermediate-value overflows.
4801                  */
4802                 if (flags & GUC_UNIT_MEMORY)
4803                 {
4804                         /* Set hint for use if no match or trailing garbage */
4805                         if (hintmsg)
4806                                 *hintmsg = gettext_noop("Valid units for this parameter are \"kB\", \"MB\", and \"GB\".");
4807
4808 #if BLCKSZ < 1024 || BLCKSZ > (1024*1024)
4809 #error BLCKSZ must be between 1KB and 1MB
4810 #endif
4811 #if XLOG_BLCKSZ < 1024 || XLOG_BLCKSZ > (1024*1024)
4812 #error XLOG_BLCKSZ must be between 1KB and 1MB
4813 #endif
4814
4815                         if (strncmp(endptr, "kB", 2) == 0)
4816                         {
4817                                 endptr += 2;
4818                                 switch (flags & GUC_UNIT_MEMORY)
4819                                 {
4820                                         case GUC_UNIT_BLOCKS:
4821                                                 val /= (BLCKSZ / 1024);
4822                                                 break;
4823                                         case GUC_UNIT_XBLOCKS:
4824                                                 val /= (XLOG_BLCKSZ / 1024);
4825                                                 break;
4826                                 }
4827                         }
4828                         else if (strncmp(endptr, "MB", 2) == 0)
4829                         {
4830                                 endptr += 2;
4831                                 switch (flags & GUC_UNIT_MEMORY)
4832                                 {
4833                                         case GUC_UNIT_KB:
4834                                                 val *= KB_PER_MB;
4835                                                 break;
4836                                         case GUC_UNIT_BLOCKS:
4837                                                 val *= KB_PER_MB / (BLCKSZ / 1024);
4838                                                 break;
4839                                         case GUC_UNIT_XBLOCKS:
4840                                                 val *= KB_PER_MB / (XLOG_BLCKSZ / 1024);
4841                                                 break;
4842                                 }
4843                         }
4844                         else if (strncmp(endptr, "GB", 2) == 0)
4845                         {
4846                                 endptr += 2;
4847                                 switch (flags & GUC_UNIT_MEMORY)
4848                                 {
4849                                         case GUC_UNIT_KB:
4850                                                 val *= KB_PER_GB;
4851                                                 break;
4852                                         case GUC_UNIT_BLOCKS:
4853                                                 val *= KB_PER_GB / (BLCKSZ / 1024);
4854                                                 break;
4855                                         case GUC_UNIT_XBLOCKS:
4856                                                 val *= KB_PER_GB / (XLOG_BLCKSZ / 1024);
4857                                                 break;
4858                                 }
4859                         }
4860                 }
4861                 else if (flags & GUC_UNIT_TIME)
4862                 {
4863                         /* Set hint for use if no match or trailing garbage */
4864                         if (hintmsg)
4865                                 *hintmsg = gettext_noop("Valid units for this parameter are \"ms\", \"s\", \"min\", \"h\", and \"d\".");
4866
4867                         if (strncmp(endptr, "ms", 2) == 0)
4868                         {
4869                                 endptr += 2;
4870                                 switch (flags & GUC_UNIT_TIME)
4871                                 {
4872                                         case GUC_UNIT_S:
4873                                                 val /= MS_PER_S;
4874                                                 break;
4875                                         case GUC_UNIT_MIN:
4876                                                 val /= MS_PER_MIN;
4877                                                 break;
4878                                 }
4879                         }
4880                         else if (strncmp(endptr, "s", 1) == 0)
4881                         {
4882                                 endptr += 1;
4883                                 switch (flags & GUC_UNIT_TIME)
4884                                 {
4885                                         case GUC_UNIT_MS:
4886                                                 val *= MS_PER_S;
4887                                                 break;
4888                                         case GUC_UNIT_MIN:
4889                                                 val /= S_PER_MIN;
4890                                                 break;
4891                                 }
4892                         }
4893                         else if (strncmp(endptr, "min", 3) == 0)
4894                         {
4895                                 endptr += 3;
4896                                 switch (flags & GUC_UNIT_TIME)
4897                                 {
4898                                         case GUC_UNIT_MS:
4899                                                 val *= MS_PER_MIN;
4900                                                 break;
4901                                         case GUC_UNIT_S:
4902                                                 val *= S_PER_MIN;
4903                                                 break;
4904                                 }
4905                         }
4906                         else if (strncmp(endptr, "h", 1) == 0)
4907                         {
4908                                 endptr += 1;
4909                                 switch (flags & GUC_UNIT_TIME)
4910                                 {
4911                                         case GUC_UNIT_MS:
4912                                                 val *= MS_PER_H;
4913                                                 break;
4914                                         case GUC_UNIT_S:
4915                                                 val *= S_PER_H;
4916                                                 break;
4917                                         case GUC_UNIT_MIN:
4918                                                 val *= MIN_PER_H;
4919                                                 break;
4920                                 }
4921                         }
4922                         else if (strncmp(endptr, "d", 1) == 0)
4923                         {
4924                                 endptr += 1;
4925                                 switch (flags & GUC_UNIT_TIME)
4926                                 {
4927                                         case GUC_UNIT_MS:
4928                                                 val *= MS_PER_D;
4929                                                 break;
4930                                         case GUC_UNIT_S:
4931                                                 val *= S_PER_D;
4932                                                 break;
4933                                         case GUC_UNIT_MIN:
4934                                                 val *= MIN_PER_D;
4935                                                 break;
4936                                 }
4937                         }
4938                 }
4939
4940                 /* allow whitespace after unit */
4941                 while (isspace((unsigned char) *endptr))
4942                         endptr++;
4943
4944                 if (*endptr != '\0')
4945                         return false;           /* appropriate hint, if any, already set */
4946
4947                 /* Check for overflow due to units conversion */
4948                 if (val != (int64) ((int32) val))
4949                 {
4950                         if (hintmsg)
4951                                 *hintmsg = gettext_noop("Value exceeds integer range.");
4952                         return false;
4953                 }
4954         }
4955
4956         if (result)
4957                 *result = (int) val;
4958         return true;
4959 }
4960
4961
4962
4963 /*
4964  * Try to parse value as a floating point number in the usual format.
4965  * If the string parses okay, return true, else false.
4966  * If okay and result is not NULL, return the value in *result.
4967  */
4968 bool
4969 parse_real(const char *value, double *result)
4970 {
4971         double          val;
4972         char       *endptr;
4973
4974         if (result)
4975                 *result = 0;                    /* suppress compiler warning */
4976
4977         errno = 0;
4978         val = strtod(value, &endptr);
4979         if (endptr == value || errno == ERANGE)
4980                 return false;
4981
4982         /* allow whitespace after number */
4983         while (isspace((unsigned char) *endptr))
4984                 endptr++;
4985         if (*endptr != '\0')
4986                 return false;
4987
4988         if (result)
4989                 *result = val;
4990         return true;
4991 }
4992
4993
4994 /*
4995  * Lookup the name for an enum option with the selected value.
4996  * Should only ever be called with known-valid values, so throws
4997  * an elog(ERROR) if the enum option is not found.
4998  *
4999  * The returned string is a pointer to static data and not
5000  * allocated for modification.
5001  */
5002 const char *
5003 config_enum_lookup_by_value(struct config_enum * record, int val)
5004 {
5005         const struct config_enum_entry *entry;
5006
5007         for (entry = record->options; entry && entry->name; entry++)
5008         {
5009                 if (entry->val == val)
5010                         return entry->name;
5011         }
5012
5013         elog(ERROR, "could not find enum option %d for %s",
5014                  val, record->gen.name);
5015         return NULL;                            /* silence compiler */
5016 }
5017
5018
5019 /*
5020  * Lookup the value for an enum option with the selected name
5021  * (case-insensitive).
5022  * If the enum option is found, sets the retval value and returns
5023  * true. If it's not found, return FALSE and retval is set to 0.
5024  */
5025 bool
5026 config_enum_lookup_by_name(struct config_enum * record, const char *value,
5027                                                    int *retval)
5028 {
5029         const struct config_enum_entry *entry;
5030
5031         for (entry = record->options; entry && entry->name; entry++)
5032         {
5033                 if (pg_strcasecmp(value, entry->name) == 0)
5034                 {
5035                         *retval = entry->val;
5036                         return TRUE;
5037                 }
5038         }
5039
5040         *retval = 0;
5041         return FALSE;
5042 }
5043
5044
5045 /*
5046  * Return a list of all available options for an enum, excluding
5047  * hidden ones, separated by the given separator.
5048  * If prefix is non-NULL, it is added before the first enum value.
5049  * If suffix is non-NULL, it is added to the end of the string.
5050  */
5051 static char *
5052 config_enum_get_options(struct config_enum * record, const char *prefix,
5053                                                 const char *suffix, const char *separator)
5054 {
5055         const struct config_enum_entry *entry;
5056         StringInfoData retstr;
5057         int                     seplen;
5058
5059         initStringInfo(&retstr);
5060         appendStringInfoString(&retstr, prefix);
5061
5062         seplen = strlen(separator);
5063         for (entry = record->options; entry && entry->name; entry++)
5064         {
5065                 if (!entry->hidden)
5066                 {
5067                         appendStringInfoString(&retstr, entry->name);
5068                         appendBinaryStringInfo(&retstr, separator, seplen);
5069                 }
5070         }
5071
5072         /*
5073          * All the entries may have been hidden, leaving the string empty if no
5074          * prefix was given. This indicates a broken GUC setup, since there is no
5075          * use for an enum without any values, so we just check to make sure we
5076          * don't write to invalid memory instead of actually trying to do
5077          * something smart with it.
5078          */
5079         if (retstr.len >= seplen)
5080         {
5081                 /* Replace final separator */
5082                 retstr.data[retstr.len - seplen] = '\0';
5083                 retstr.len -= seplen;
5084         }
5085
5086         appendStringInfoString(&retstr, suffix);
5087
5088         return retstr.data;
5089 }
5090
5091
5092 /*
5093  * Sets option `name' to given value.
5094  *
5095  * The value should be a string, which will be parsed and converted to
5096  * the appropriate data type.  The context and source parameters indicate
5097  * in which context this function is being called, so that it can apply the
5098  * access restrictions properly.
5099  *
5100  * If value is NULL, set the option to its default value (normally the
5101  * reset_val, but if source == PGC_S_DEFAULT we instead use the boot_val).
5102  *
5103  * action indicates whether to set the value globally in the session, locally
5104  * to the current top transaction, or just for the duration of a function call.
5105  *
5106  * If changeVal is false then don't really set the option but do all
5107  * the checks to see if it would work.
5108  *
5109  * elevel should normally be passed as zero, allowing this function to make
5110  * its standard choice of ereport level.  However some callers need to be
5111  * able to override that choice; they should pass the ereport level to use.
5112  *
5113  * Return value:
5114  *      +1: the value is valid and was successfully applied.
5115  *      0:      the name or value is invalid (but see below).
5116  *      -1: the value was not applied because of context, priority, or changeVal.
5117  *
5118  * If there is an error (non-existing option, invalid value) then an
5119  * ereport(ERROR) is thrown *unless* this is called for a source for which
5120  * we don't want an ERROR (currently, those are defaults, the config file,
5121  * and per-database or per-user settings, as well as callers who specify
5122  * a less-than-ERROR elevel).  In those cases we write a suitable error
5123  * message via ereport() and return 0.
5124  *
5125  * See also SetConfigOption for an external interface.
5126  */
5127 int
5128 set_config_option(const char *name, const char *value,
5129                                   GucContext context, GucSource source,
5130                                   GucAction action, bool changeVal, int elevel)
5131 {
5132         struct config_generic *record;
5133         bool            prohibitValueChange = false;
5134         bool            makeDefault;
5135
5136         if (elevel == 0)
5137         {
5138                 if (source == PGC_S_DEFAULT || source == PGC_S_FILE)
5139                 {
5140                         /*
5141                          * To avoid cluttering the log, only the postmaster bleats loudly
5142                          * about problems with the config file.
5143                          */
5144                         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5145                 }
5146                 else if (source == PGC_S_DATABASE || source == PGC_S_USER ||
5147                                  source == PGC_S_DATABASE_USER)
5148                         elevel = WARNING;
5149                 else
5150                         elevel = ERROR;
5151         }
5152
5153         record = find_option(name, true, elevel);
5154         if (record == NULL)
5155         {
5156                 ereport(elevel,
5157                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5158                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5159                 return 0;
5160         }
5161
5162         /*
5163          * Check if the option can be set at this time. See guc.h for the precise
5164          * rules.
5165          */
5166         switch (record->context)
5167         {
5168                 case PGC_INTERNAL:
5169                         if (context != PGC_INTERNAL)
5170                         {
5171                                 ereport(elevel,
5172                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5173                                                  errmsg("parameter \"%s\" cannot be changed",
5174                                                                 name)));
5175                                 return 0;
5176                         }
5177                         break;
5178                 case PGC_POSTMASTER:
5179                         if (context == PGC_SIGHUP)
5180                         {
5181                                 /*
5182                                  * We are re-reading a PGC_POSTMASTER variable from
5183                                  * postgresql.conf.  We can't change the setting, so we should
5184                                  * give a warning if the DBA tries to change it.  However,
5185                                  * because of variant formats, canonicalization by check
5186                                  * hooks, etc, we can't just compare the given string directly
5187                                  * to what's stored.  Set a flag to check below after we have
5188                                  * the final storable value.
5189                                  */
5190                                 prohibitValueChange = true;
5191                         }
5192                         else if (context != PGC_POSTMASTER)
5193                         {
5194                                 ereport(elevel,
5195                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5196                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5197                                                                 name)));
5198                                 return 0;
5199                         }
5200                         break;
5201                 case PGC_SIGHUP:
5202                         if (context != PGC_SIGHUP && context != PGC_POSTMASTER)
5203                         {
5204                                 ereport(elevel,
5205                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5206                                                  errmsg("parameter \"%s\" cannot be changed now",
5207                                                                 name)));
5208                                 return 0;
5209                         }
5210
5211                         /*
5212                          * Hmm, the idea of the SIGHUP context is "ought to be global, but
5213                          * can be changed after postmaster start". But there's nothing
5214                          * that prevents a crafty administrator from sending SIGHUP
5215                          * signals to individual backends only.
5216                          */
5217                         break;
5218                 case PGC_BACKEND:
5219                         if (context == PGC_SIGHUP)
5220                         {
5221                                 /*
5222                                  * If a PGC_BACKEND parameter is changed in the config file,
5223                                  * we want to accept the new value in the postmaster (whence
5224                                  * it will propagate to subsequently-started backends), but
5225                                  * ignore it in existing backends.      This is a tad klugy, but
5226                                  * necessary because we don't re-read the config file during
5227                                  * backend start.
5228                                  */
5229                                 if (IsUnderPostmaster)
5230                                         return -1;
5231                         }
5232                         else if (context != PGC_POSTMASTER && context != PGC_BACKEND &&
5233                                          source != PGC_S_CLIENT)
5234                         {
5235                                 ereport(elevel,
5236                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5237                                                  errmsg("parameter \"%s\" cannot be set after connection start",
5238                                                                 name)));
5239                                 return 0;
5240                         }
5241                         break;
5242                 case PGC_SUSET:
5243                         if (context == PGC_USERSET || context == PGC_BACKEND)
5244                         {
5245                                 ereport(elevel,
5246                                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5247                                                  errmsg("permission denied to set parameter \"%s\"",
5248                                                                 name)));
5249                                 return 0;
5250                         }
5251                         break;
5252                 case PGC_USERSET:
5253                         /* always okay */
5254                         break;
5255         }
5256
5257         /*
5258          * Disallow changing GUC_NOT_WHILE_SEC_REST values if we are inside a
5259          * security restriction context.  We can reject this regardless of the GUC
5260          * context or source, mainly because sources that it might be reasonable
5261          * to override for won't be seen while inside a function.
5262          *
5263          * Note: variables marked GUC_NOT_WHILE_SEC_REST should usually be marked
5264          * GUC_NO_RESET_ALL as well, because ResetAllOptions() doesn't check this.
5265          * An exception might be made if the reset value is assumed to be "safe".
5266          *
5267          * Note: this flag is currently used for "session_authorization" and
5268          * "role".      We need to prohibit changing these inside a local userid
5269          * context because when we exit it, GUC won't be notified, leaving things
5270          * out of sync.  (This could be fixed by forcing a new GUC nesting level,
5271          * but that would change behavior in possibly-undesirable ways.)  Also, we
5272          * prohibit changing these in a security-restricted operation because
5273          * otherwise RESET could be used to regain the session user's privileges.
5274          */
5275         if (record->flags & GUC_NOT_WHILE_SEC_REST)
5276         {
5277                 if (InLocalUserIdChange())
5278                 {
5279                         /*
5280                          * Phrasing of this error message is historical, but it's the most
5281                          * common case.
5282                          */
5283                         ereport(elevel,
5284                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5285                                          errmsg("cannot set parameter \"%s\" within security-definer function",
5286                                                         name)));
5287                         return 0;
5288                 }
5289                 if (InSecurityRestrictedOperation())
5290                 {
5291                         ereport(elevel,
5292                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5293                                          errmsg("cannot set parameter \"%s\" within security-restricted operation",
5294                                                         name)));
5295                         return 0;
5296                 }
5297         }
5298
5299         /*
5300          * Should we set reset/stacked values?  (If so, the behavior is not
5301          * transactional.)      This is done either when we get a default value from
5302          * the database's/user's/client's default settings or when we reset a
5303          * value to its default.
5304          */
5305         makeDefault = changeVal && (source <= PGC_S_OVERRIDE) &&
5306                 ((value != NULL) || source == PGC_S_DEFAULT);
5307
5308         /*
5309          * Ignore attempted set if overridden by previously processed setting.
5310          * However, if changeVal is false then plow ahead anyway since we are
5311          * trying to find out if the value is potentially good, not actually use
5312          * it. Also keep going if makeDefault is true, since we may want to set
5313          * the reset/stacked values even if we can't set the variable itself.
5314          */
5315         if (record->source > source)
5316         {
5317                 if (changeVal && !makeDefault)
5318                 {
5319                         elog(DEBUG3, "\"%s\": setting ignored because previous source is higher priority",
5320                                  name);
5321                         return -1;
5322                 }
5323                 changeVal = false;
5324         }
5325
5326         /*
5327          * Evaluate value and set variable.
5328          */
5329         switch (record->vartype)
5330         {
5331                 case PGC_BOOL:
5332                         {
5333                                 struct config_bool *conf = (struct config_bool *) record;
5334                                 bool            newval;
5335                                 void       *newextra = NULL;
5336
5337                                 if (value)
5338                                 {
5339                                         if (!parse_bool(value, &newval))
5340                                         {
5341                                                 ereport(elevel,
5342                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5343                                                   errmsg("parameter \"%s\" requires a Boolean value",
5344                                                                  name)));
5345                                                 return 0;
5346                                         }
5347                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5348                                                                                           source, elevel))
5349                                                 return 0;
5350                                 }
5351                                 else if (source == PGC_S_DEFAULT)
5352                                 {
5353                                         newval = conf->boot_val;
5354                                         if (!call_bool_check_hook(conf, &newval, &newextra,
5355                                                                                           source, elevel))
5356                                                 return 0;
5357                                 }
5358                                 else
5359                                 {
5360                                         newval = conf->reset_val;
5361                                         newextra = conf->reset_extra;
5362                                         source = conf->gen.reset_source;
5363                                         context = conf->gen.reset_scontext;
5364                                 }
5365
5366                                 if (prohibitValueChange)
5367                                 {
5368                                         if (*conf->variable != newval)
5369                                         {
5370                                                 ereport(elevel,
5371                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5372                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5373                                                                                 name)));
5374                                                 return 0;
5375                                         }
5376                                         return -1;
5377                                 }
5378
5379                                 if (changeVal)
5380                                 {
5381                                         /* Save old value to support transaction abort */
5382                                         if (!makeDefault)
5383                                                 push_old_value(&conf->gen, action);
5384
5385                                         if (conf->assign_hook)
5386                                                 (*conf->assign_hook) (newval, newextra);
5387                                         *conf->variable = newval;
5388                                         set_extra_field(&conf->gen, &conf->gen.extra,
5389                                                                         newextra);
5390                                         conf->gen.source = source;
5391                                         conf->gen.scontext = context;
5392                                 }
5393                                 if (makeDefault)
5394                                 {
5395                                         GucStack   *stack;
5396
5397                                         if (conf->gen.reset_source <= source)
5398                                         {
5399                                                 conf->reset_val = newval;
5400                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5401                                                                                 newextra);
5402                                                 conf->gen.reset_source = source;
5403                                                 conf->gen.reset_scontext = context;
5404                                         }
5405                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5406                                         {
5407                                                 if (stack->source <= source)
5408                                                 {
5409                                                         stack->prior.val.boolval = newval;
5410                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5411                                                                                         newextra);
5412                                                         stack->source = source;
5413                                                         stack->scontext = context;
5414                                                 }
5415                                         }
5416                                 }
5417
5418                                 /* Perhaps we didn't install newextra anywhere */
5419                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5420                                         free(newextra);
5421                                 break;
5422                         }
5423
5424                 case PGC_INT:
5425                         {
5426                                 struct config_int *conf = (struct config_int *) record;
5427                                 int                     newval;
5428                                 void       *newextra = NULL;
5429
5430                                 if (value)
5431                                 {
5432                                         const char *hintmsg;
5433
5434                                         if (!parse_int(value, &newval, conf->gen.flags, &hintmsg))
5435                                         {
5436                                                 ereport(elevel,
5437                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5438                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5439                                                                 name, value),
5440                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5441                                                 return 0;
5442                                         }
5443                                         if (newval < conf->min || newval > conf->max)
5444                                         {
5445                                                 ereport(elevel,
5446                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5447                                                                  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
5448                                                                                 newval, name, conf->min, conf->max)));
5449                                                 return 0;
5450                                         }
5451                                         if (!call_int_check_hook(conf, &newval, &newextra,
5452                                                                                          source, elevel))
5453                                                 return 0;
5454                                 }
5455                                 else if (source == PGC_S_DEFAULT)
5456                                 {
5457                                         newval = conf->boot_val;
5458                                         if (!call_int_check_hook(conf, &newval, &newextra,
5459                                                                                          source, elevel))
5460                                                 return 0;
5461                                 }
5462                                 else
5463                                 {
5464                                         newval = conf->reset_val;
5465                                         newextra = conf->reset_extra;
5466                                         source = conf->gen.reset_source;
5467                                         context = conf->gen.reset_scontext;
5468                                 }
5469
5470                                 if (prohibitValueChange)
5471                                 {
5472                                         if (*conf->variable != newval)
5473                                         {
5474                                                 ereport(elevel,
5475                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5476                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5477                                                                                 name)));
5478                                                 return 0;
5479                                         }
5480                                         return -1;
5481                                 }
5482
5483                                 if (changeVal)
5484                                 {
5485                                         /* Save old value to support transaction abort */
5486                                         if (!makeDefault)
5487                                                 push_old_value(&conf->gen, action);
5488
5489                                         if (conf->assign_hook)
5490                                                 (*conf->assign_hook) (newval, newextra);
5491                                         *conf->variable = newval;
5492                                         set_extra_field(&conf->gen, &conf->gen.extra,
5493                                                                         newextra);
5494                                         conf->gen.source = source;
5495                                         conf->gen.scontext = context;
5496                                 }
5497                                 if (makeDefault)
5498                                 {
5499                                         GucStack   *stack;
5500
5501                                         if (conf->gen.reset_source <= source)
5502                                         {
5503                                                 conf->reset_val = newval;
5504                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5505                                                                                 newextra);
5506                                                 conf->gen.reset_source = source;
5507                                                 conf->gen.reset_scontext = context;
5508                                         }
5509                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5510                                         {
5511                                                 if (stack->source <= source)
5512                                                 {
5513                                                         stack->prior.val.intval = newval;
5514                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5515                                                                                         newextra);
5516                                                         stack->source = source;
5517                                                         stack->scontext = context;
5518                                                 }
5519                                         }
5520                                 }
5521
5522                                 /* Perhaps we didn't install newextra anywhere */
5523                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5524                                         free(newextra);
5525                                 break;
5526                         }
5527
5528                 case PGC_REAL:
5529                         {
5530                                 struct config_real *conf = (struct config_real *) record;
5531                                 double          newval;
5532                                 void       *newextra = NULL;
5533
5534                                 if (value)
5535                                 {
5536                                         if (!parse_real(value, &newval))
5537                                         {
5538                                                 ereport(elevel,
5539                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5540                                                   errmsg("parameter \"%s\" requires a numeric value",
5541                                                                  name)));
5542                                                 return 0;
5543                                         }
5544                                         if (newval < conf->min || newval > conf->max)
5545                                         {
5546                                                 ereport(elevel,
5547                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5548                                                                  errmsg("%g is outside the valid range for parameter \"%s\" (%g .. %g)",
5549                                                                                 newval, name, conf->min, conf->max)));
5550                                                 return 0;
5551                                         }
5552                                         if (!call_real_check_hook(conf, &newval, &newextra,
5553                                                                                           source, elevel))
5554                                                 return 0;
5555                                 }
5556                                 else if (source == PGC_S_DEFAULT)
5557                                 {
5558                                         newval = conf->boot_val;
5559                                         if (!call_real_check_hook(conf, &newval, &newextra,
5560                                                                                           source, elevel))
5561                                                 return 0;
5562                                 }
5563                                 else
5564                                 {
5565                                         newval = conf->reset_val;
5566                                         newextra = conf->reset_extra;
5567                                         source = conf->gen.reset_source;
5568                                         context = conf->gen.reset_scontext;
5569                                 }
5570
5571                                 if (prohibitValueChange)
5572                                 {
5573                                         if (*conf->variable != newval)
5574                                         {
5575                                                 ereport(elevel,
5576                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5577                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5578                                                                                 name)));
5579                                                 return 0;
5580                                         }
5581                                         return -1;
5582                                 }
5583
5584                                 if (changeVal)
5585                                 {
5586                                         /* Save old value to support transaction abort */
5587                                         if (!makeDefault)
5588                                                 push_old_value(&conf->gen, action);
5589
5590                                         if (conf->assign_hook)
5591                                                 (*conf->assign_hook) (newval, newextra);
5592                                         *conf->variable = newval;
5593                                         set_extra_field(&conf->gen, &conf->gen.extra,
5594                                                                         newextra);
5595                                         conf->gen.source = source;
5596                                         conf->gen.scontext = context;
5597                                 }
5598                                 if (makeDefault)
5599                                 {
5600                                         GucStack   *stack;
5601
5602                                         if (conf->gen.reset_source <= source)
5603                                         {
5604                                                 conf->reset_val = newval;
5605                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5606                                                                                 newextra);
5607                                                 conf->gen.reset_source = source;
5608                                                 conf->gen.reset_scontext = context;
5609                                         }
5610                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5611                                         {
5612                                                 if (stack->source <= source)
5613                                                 {
5614                                                         stack->prior.val.realval = newval;
5615                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5616                                                                                         newextra);
5617                                                         stack->source = source;
5618                                                         stack->scontext = context;
5619                                                 }
5620                                         }
5621                                 }
5622
5623                                 /* Perhaps we didn't install newextra anywhere */
5624                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5625                                         free(newextra);
5626                                 break;
5627                         }
5628
5629                 case PGC_STRING:
5630                         {
5631                                 struct config_string *conf = (struct config_string *) record;
5632                                 char       *newval;
5633                                 void       *newextra = NULL;
5634
5635                                 if (value)
5636                                 {
5637                                         /*
5638                                          * The value passed by the caller could be transient, so
5639                                          * we always strdup it.
5640                                          */
5641                                         newval = guc_strdup(elevel, value);
5642                                         if (newval == NULL)
5643                                                 return 0;
5644
5645                                         /*
5646                                          * The only built-in "parsing" check we have is to apply
5647                                          * truncation if GUC_IS_NAME.
5648                                          */
5649                                         if (conf->gen.flags & GUC_IS_NAME)
5650                                                 truncate_identifier(newval, strlen(newval), true);
5651
5652                                         if (!call_string_check_hook(conf, &newval, &newextra,
5653                                                                                                 source, elevel))
5654                                         {
5655                                                 free(newval);
5656                                                 return 0;
5657                                         }
5658                                 }
5659                                 else if (source == PGC_S_DEFAULT)
5660                                 {
5661                                         /* non-NULL boot_val must always get strdup'd */
5662                                         if (conf->boot_val != NULL)
5663                                         {
5664                                                 newval = guc_strdup(elevel, conf->boot_val);
5665                                                 if (newval == NULL)
5666                                                         return 0;
5667                                         }
5668                                         else
5669                                                 newval = NULL;
5670
5671                                         if (!call_string_check_hook(conf, &newval, &newextra,
5672                                                                                                 source, elevel))
5673                                         {
5674                                                 free(newval);
5675                                                 return 0;
5676                                         }
5677                                 }
5678                                 else
5679                                 {
5680                                         /*
5681                                          * strdup not needed, since reset_val is already under
5682                                          * guc.c's control
5683                                          */
5684                                         newval = conf->reset_val;
5685                                         newextra = conf->reset_extra;
5686                                         source = conf->gen.reset_source;
5687                                         context = conf->gen.reset_scontext;
5688                                 }
5689
5690                                 if (prohibitValueChange)
5691                                 {
5692                                         /* newval shouldn't be NULL, so we're a bit sloppy here */
5693                                         if (*conf->variable == NULL || newval == NULL ||
5694                                                 strcmp(*conf->variable, newval) != 0)
5695                                         {
5696                                                 ereport(elevel,
5697                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5698                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5699                                                                                 name)));
5700                                                 return 0;
5701                                         }
5702                                         return -1;
5703                                 }
5704
5705                                 if (changeVal)
5706                                 {
5707                                         /* Save old value to support transaction abort */
5708                                         if (!makeDefault)
5709                                                 push_old_value(&conf->gen, action);
5710
5711                                         if (conf->assign_hook)
5712                                                 (*conf->assign_hook) (newval, newextra);
5713                                         set_string_field(conf, conf->variable, newval);
5714                                         set_extra_field(&conf->gen, &conf->gen.extra,
5715                                                                         newextra);
5716                                         conf->gen.source = source;
5717                                         conf->gen.scontext = context;
5718                                 }
5719
5720                                 if (makeDefault)
5721                                 {
5722                                         GucStack   *stack;
5723
5724                                         if (conf->gen.reset_source <= source)
5725                                         {
5726                                                 set_string_field(conf, &conf->reset_val, newval);
5727                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5728                                                                                 newextra);
5729                                                 conf->gen.reset_source = source;
5730                                                 conf->gen.reset_scontext = context;
5731                                         }
5732                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5733                                         {
5734                                                 if (stack->source <= source)
5735                                                 {
5736                                                         set_string_field(conf, &stack->prior.val.stringval,
5737                                                                                          newval);
5738                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5739                                                                                         newextra);
5740                                                         stack->source = source;
5741                                                         stack->scontext = context;
5742                                                 }
5743                                         }
5744                                 }
5745
5746                                 /* Perhaps we didn't install newval anywhere */
5747                                 if (newval && !string_field_used(conf, newval))
5748                                         free(newval);
5749                                 /* Perhaps we didn't install newextra anywhere */
5750                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5751                                         free(newextra);
5752                                 break;
5753                         }
5754
5755                 case PGC_ENUM:
5756                         {
5757                                 struct config_enum *conf = (struct config_enum *) record;
5758                                 int                     newval;
5759                                 void       *newextra = NULL;
5760
5761                                 if (value)
5762                                 {
5763                                         if (!config_enum_lookup_by_name(conf, value, &newval))
5764                                         {
5765                                                 char       *hintmsg;
5766
5767                                                 hintmsg = config_enum_get_options(conf,
5768                                                                                                                 "Available values: ",
5769                                                                                                                   ".", ", ");
5770
5771                                                 ereport(elevel,
5772                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5773                                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
5774                                                                 name, value),
5775                                                                  hintmsg ? errhint("%s", _(hintmsg)) : 0));
5776
5777                                                 if (hintmsg)
5778                                                         pfree(hintmsg);
5779                                                 return 0;
5780                                         }
5781                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5782                                                                                           source, elevel))
5783                                                 return 0;
5784                                 }
5785                                 else if (source == PGC_S_DEFAULT)
5786                                 {
5787                                         newval = conf->boot_val;
5788                                         if (!call_enum_check_hook(conf, &newval, &newextra,
5789                                                                                           source, elevel))
5790                                                 return 0;
5791                                 }
5792                                 else
5793                                 {
5794                                         newval = conf->reset_val;
5795                                         newextra = conf->reset_extra;
5796                                         source = conf->gen.reset_source;
5797                                         context = conf->gen.reset_scontext;
5798                                 }
5799
5800                                 if (prohibitValueChange)
5801                                 {
5802                                         if (*conf->variable != newval)
5803                                         {
5804                                                 ereport(elevel,
5805                                                                 (errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
5806                                                                  errmsg("parameter \"%s\" cannot be changed without restarting the server",
5807                                                                                 name)));
5808                                                 return 0;
5809                                         }
5810                                         return -1;
5811                                 }
5812
5813                                 if (changeVal)
5814                                 {
5815                                         /* Save old value to support transaction abort */
5816                                         if (!makeDefault)
5817                                                 push_old_value(&conf->gen, action);
5818
5819                                         if (conf->assign_hook)
5820                                                 (*conf->assign_hook) (newval, newextra);
5821                                         *conf->variable = newval;
5822                                         set_extra_field(&conf->gen, &conf->gen.extra,
5823                                                                         newextra);
5824                                         conf->gen.source = source;
5825                                         conf->gen.scontext = context;
5826                                 }
5827                                 if (makeDefault)
5828                                 {
5829                                         GucStack   *stack;
5830
5831                                         if (conf->gen.reset_source <= source)
5832                                         {
5833                                                 conf->reset_val = newval;
5834                                                 set_extra_field(&conf->gen, &conf->reset_extra,
5835                                                                                 newextra);
5836                                                 conf->gen.reset_source = source;
5837                                                 conf->gen.reset_scontext = context;
5838                                         }
5839                                         for (stack = conf->gen.stack; stack; stack = stack->prev)
5840                                         {
5841                                                 if (stack->source <= source)
5842                                                 {
5843                                                         stack->prior.val.enumval = newval;
5844                                                         set_extra_field(&conf->gen, &stack->prior.extra,
5845                                                                                         newextra);
5846                                                         stack->source = source;
5847                                                         stack->scontext = context;
5848                                                 }
5849                                         }
5850                                 }
5851
5852                                 /* Perhaps we didn't install newextra anywhere */
5853                                 if (newextra && !extra_field_used(&conf->gen, newextra))
5854                                         free(newextra);
5855                                 break;
5856                         }
5857         }
5858
5859         if (changeVal && (record->flags & GUC_REPORT))
5860                 ReportGUCOption(record);
5861
5862         return changeVal ? 1 : -1;
5863 }
5864
5865
5866 /*
5867  * Set the fields for source file and line number the setting came from.
5868  */
5869 static void
5870 set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
5871 {
5872         struct config_generic *record;
5873         int                     elevel;
5874
5875         /*
5876          * To avoid cluttering the log, only the postmaster bleats loudly about
5877          * problems with the config file.
5878          */
5879         elevel = IsUnderPostmaster ? DEBUG3 : LOG;
5880
5881         record = find_option(name, true, elevel);
5882         /* should not happen */
5883         if (record == NULL)
5884                 elog(ERROR, "unrecognized configuration parameter \"%s\"", name);
5885
5886         sourcefile = guc_strdup(elevel, sourcefile);
5887         if (record->sourcefile)
5888                 free(record->sourcefile);
5889         record->sourcefile = sourcefile;
5890         record->sourceline = sourceline;
5891 }
5892
5893 /*
5894  * Set a config option to the given value.
5895  *
5896  * See also set_config_option; this is just the wrapper to be called from
5897  * outside GUC.  (This function should be used when possible, because its API
5898  * is more stable than set_config_option's.)
5899  *
5900  * Note: there is no support here for setting source file/line, as it
5901  * is currently not needed.
5902  */
5903 void
5904 SetConfigOption(const char *name, const char *value,
5905                                 GucContext context, GucSource source)
5906 {
5907         (void) set_config_option(name, value, context, source,
5908                                                          GUC_ACTION_SET, true, 0);
5909 }
5910
5911
5912
5913 /*
5914  * Fetch the current value of the option `name', as a string.
5915  *
5916  * If the option doesn't exist, return NULL if missing_ok is true (NOTE that
5917  * this cannot be distinguished from a string variable with a NULL value!),
5918  * otherwise throw an ereport and don't return.
5919  *
5920  * If restrict_superuser is true, we also enforce that only superusers can
5921  * see GUC_SUPERUSER_ONLY variables.  This should only be passed as true
5922  * in user-driven calls.
5923  *
5924  * The string is *not* allocated for modification and is really only
5925  * valid until the next call to configuration related functions.
5926  */
5927 const char *
5928 GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
5929 {
5930         struct config_generic *record;
5931         static char buffer[256];
5932
5933         record = find_option(name, false, ERROR);
5934         if (record == NULL)
5935         {
5936                 if (missing_ok)
5937                         return NULL;
5938                 ereport(ERROR,
5939                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5940                                  errmsg("unrecognized configuration parameter \"%s\"",
5941                                                 name)));
5942         }
5943         if (restrict_superuser &&
5944                 (record->flags & GUC_SUPERUSER_ONLY) &&
5945                 !superuser())
5946                 ereport(ERROR,
5947                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5948                                  errmsg("must be superuser to examine \"%s\"", name)));
5949
5950         switch (record->vartype)
5951         {
5952                 case PGC_BOOL:
5953                         return *((struct config_bool *) record)->variable ? "on" : "off";
5954
5955                 case PGC_INT:
5956                         snprintf(buffer, sizeof(buffer), "%d",
5957                                          *((struct config_int *) record)->variable);
5958                         return buffer;
5959
5960                 case PGC_REAL:
5961                         snprintf(buffer, sizeof(buffer), "%g",
5962                                          *((struct config_real *) record)->variable);
5963                         return buffer;
5964
5965                 case PGC_STRING:
5966                         return *((struct config_string *) record)->variable;
5967
5968                 case PGC_ENUM:
5969                         return config_enum_lookup_by_value((struct config_enum *) record,
5970                                                                  *((struct config_enum *) record)->variable);
5971         }
5972         return NULL;
5973 }
5974
5975 /*
5976  * Get the RESET value associated with the given option.
5977  *
5978  * Note: this is not re-entrant, due to use of static result buffer;
5979  * not to mention that a string variable could have its reset_val changed.
5980  * Beware of assuming the result value is good for very long.
5981  */
5982 const char *
5983 GetConfigOptionResetString(const char *name)
5984 {
5985         struct config_generic *record;
5986         static char buffer[256];
5987
5988         record = find_option(name, false, ERROR);
5989         if (record == NULL)
5990                 ereport(ERROR,
5991                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
5992                            errmsg("unrecognized configuration parameter \"%s\"", name)));
5993         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
5994                 ereport(ERROR,
5995                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
5996                                  errmsg("must be superuser to examine \"%s\"", name)));
5997
5998         switch (record->vartype)
5999         {
6000                 case PGC_BOOL:
6001                         return ((struct config_bool *) record)->reset_val ? "on" : "off";
6002
6003                 case PGC_INT:
6004                         snprintf(buffer, sizeof(buffer), "%d",
6005                                          ((struct config_int *) record)->reset_val);
6006                         return buffer;
6007
6008                 case PGC_REAL:
6009                         snprintf(buffer, sizeof(buffer), "%g",
6010                                          ((struct config_real *) record)->reset_val);
6011                         return buffer;
6012
6013                 case PGC_STRING:
6014                         return ((struct config_string *) record)->reset_val;
6015
6016                 case PGC_ENUM:
6017                         return config_enum_lookup_by_value((struct config_enum *) record,
6018                                                                  ((struct config_enum *) record)->reset_val);
6019         }
6020         return NULL;
6021 }
6022
6023
6024 /*
6025  * flatten_set_variable_args
6026  *              Given a parsenode List as emitted by the grammar for SET,
6027  *              convert to the flat string representation used by GUC.
6028  *
6029  * We need to be told the name of the variable the args are for, because
6030  * the flattening rules vary (ugh).
6031  *
6032  * The result is NULL if args is NIL (ie, SET ... TO DEFAULT), otherwise
6033  * a palloc'd string.
6034  */
6035 static char *
6036 flatten_set_variable_args(const char *name, List *args)
6037 {
6038         struct config_generic *record;
6039         int                     flags;
6040         StringInfoData buf;
6041         ListCell   *l;
6042
6043         /* Fast path if just DEFAULT */
6044         if (args == NIL)
6045                 return NULL;
6046
6047         /*
6048          * Get flags for the variable; if it's not known, use default flags.
6049          * (Caller might throw error later, but not our business to do so here.)
6050          */
6051         record = find_option(name, false, WARNING);
6052         if (record)
6053                 flags = record->flags;
6054         else
6055                 flags = 0;
6056
6057         /* Complain if list input and non-list variable */
6058         if ((flags & GUC_LIST_INPUT) == 0 &&
6059                 list_length(args) != 1)
6060                 ereport(ERROR,
6061                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
6062                                  errmsg("SET %s takes only one argument", name)));
6063
6064         initStringInfo(&buf);
6065
6066         /*
6067          * Each list member may be a plain A_Const node, or an A_Const within a
6068          * TypeCast; the latter case is supported only for ConstInterval arguments
6069          * (for SET TIME ZONE).
6070          */
6071         foreach(l, args)
6072         {
6073                 Node       *arg = (Node *) lfirst(l);
6074                 char       *val;
6075                 TypeName   *typeName = NULL;
6076                 A_Const    *con;
6077
6078                 if (l != list_head(args))
6079                         appendStringInfo(&buf, ", ");
6080
6081                 if (IsA(arg, TypeCast))
6082                 {
6083                         TypeCast   *tc = (TypeCast *) arg;
6084
6085                         arg = tc->arg;
6086                         typeName = tc->typeName;
6087                 }
6088
6089                 if (!IsA(arg, A_Const))
6090                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(arg));
6091                 con = (A_Const *) arg;
6092
6093                 switch (nodeTag(&con->val))
6094                 {
6095                         case T_Integer:
6096                                 appendStringInfo(&buf, "%ld", intVal(&con->val));
6097                                 break;
6098                         case T_Float:
6099                                 /* represented as a string, so just copy it */
6100                                 appendStringInfoString(&buf, strVal(&con->val));
6101                                 break;
6102                         case T_String:
6103                                 val = strVal(&con->val);
6104                                 if (typeName != NULL)
6105                                 {
6106                                         /*
6107                                          * Must be a ConstInterval argument for TIME ZONE. Coerce
6108                                          * to interval and back to normalize the value and account
6109                                          * for any typmod.
6110                                          */
6111                                         Oid                     typoid;
6112                                         int32           typmod;
6113                                         Datum           interval;
6114                                         char       *intervalout;
6115
6116                                         typenameTypeIdAndMod(NULL, typeName, &typoid, &typmod);
6117                                         Assert(typoid == INTERVALOID);
6118
6119                                         interval =
6120                                                 DirectFunctionCall3(interval_in,
6121                                                                                         CStringGetDatum(val),
6122                                                                                         ObjectIdGetDatum(InvalidOid),
6123                                                                                         Int32GetDatum(typmod));
6124
6125                                         intervalout =
6126                                                 DatumGetCString(DirectFunctionCall1(interval_out,
6127                                                                                                                         interval));
6128                                         appendStringInfo(&buf, "INTERVAL '%s'", intervalout);
6129                                 }
6130                                 else
6131                                 {
6132                                         /*
6133                                          * Plain string literal or identifier.  For quote mode,
6134                                          * quote it if it's not a vanilla identifier.
6135                                          */
6136                                         if (flags & GUC_LIST_QUOTE)
6137                                                 appendStringInfoString(&buf, quote_identifier(val));
6138                                         else
6139                                                 appendStringInfoString(&buf, val);
6140                                 }
6141                                 break;
6142                         default:
6143                                 elog(ERROR, "unrecognized node type: %d",
6144                                          (int) nodeTag(&con->val));
6145                                 break;
6146                 }
6147         }
6148
6149         return buf.data;
6150 }
6151
6152
6153 /*
6154  * SET command
6155  */
6156 void
6157 ExecSetVariableStmt(VariableSetStmt *stmt)
6158 {
6159         GucAction       action = stmt->is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET;
6160
6161         switch (stmt->kind)
6162         {
6163                 case VAR_SET_VALUE:
6164                 case VAR_SET_CURRENT:
6165                         (void) set_config_option(stmt->name,
6166                                                                          ExtractSetVariableArgs(stmt),
6167                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6168                                                                          PGC_S_SESSION,
6169                                                                          action,
6170                                                                          true,
6171                                                                          0);
6172                         break;
6173                 case VAR_SET_MULTI:
6174
6175                         /*
6176                          * Special-case SQL syntaxes.  The TRANSACTION and SESSION
6177                          * CHARACTERISTICS cases effectively set more than one variable
6178                          * per statement.  TRANSACTION SNAPSHOT only takes one argument,
6179                          * but we put it here anyway since it's a special case and not
6180                          * related to any GUC variable.
6181                          */
6182                         if (strcmp(stmt->name, "TRANSACTION") == 0)
6183                         {
6184                                 ListCell   *head;
6185
6186                                 foreach(head, stmt->args)
6187                                 {
6188                                         DefElem    *item = (DefElem *) lfirst(head);
6189
6190                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6191                                                 SetPGVariable("transaction_isolation",
6192                                                                           list_make1(item->arg), stmt->is_local);
6193                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6194                                                 SetPGVariable("transaction_read_only",
6195                                                                           list_make1(item->arg), stmt->is_local);
6196                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6197                                                 SetPGVariable("transaction_deferrable",
6198                                                                           list_make1(item->arg), stmt->is_local);
6199                                         else
6200                                                 elog(ERROR, "unexpected SET TRANSACTION element: %s",
6201                                                          item->defname);
6202                                 }
6203                         }
6204                         else if (strcmp(stmt->name, "SESSION CHARACTERISTICS") == 0)
6205                         {
6206                                 ListCell   *head;
6207
6208                                 foreach(head, stmt->args)
6209                                 {
6210                                         DefElem    *item = (DefElem *) lfirst(head);
6211
6212                                         if (strcmp(item->defname, "transaction_isolation") == 0)
6213                                                 SetPGVariable("default_transaction_isolation",
6214                                                                           list_make1(item->arg), stmt->is_local);
6215                                         else if (strcmp(item->defname, "transaction_read_only") == 0)
6216                                                 SetPGVariable("default_transaction_read_only",
6217                                                                           list_make1(item->arg), stmt->is_local);
6218                                         else if (strcmp(item->defname, "transaction_deferrable") == 0)
6219                                                 SetPGVariable("default_transaction_deferrable",
6220                                                                           list_make1(item->arg), stmt->is_local);
6221                                         else
6222                                                 elog(ERROR, "unexpected SET SESSION element: %s",
6223                                                          item->defname);
6224                                 }
6225                         }
6226                         else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
6227                         {
6228                                 A_Const    *con = (A_Const *) linitial(stmt->args);
6229
6230                                 if (stmt->is_local)
6231                                         ereport(ERROR,
6232                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6233                                                          errmsg("SET LOCAL TRANSACTION SNAPSHOT is not implemented")));
6234                                 Assert(IsA(con, A_Const));
6235                                 Assert(nodeTag(&con->val) == T_String);
6236                                 ImportSnapshot(strVal(&con->val));
6237                         }
6238                         else
6239                                 elog(ERROR, "unexpected SET MULTI element: %s",
6240                                          stmt->name);
6241                         break;
6242                 case VAR_SET_DEFAULT:
6243                 case VAR_RESET:
6244                         (void) set_config_option(stmt->name,
6245                                                                          NULL,
6246                                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6247                                                                          PGC_S_SESSION,
6248                                                                          action,
6249                                                                          true,
6250                                                                          0);
6251                         break;
6252                 case VAR_RESET_ALL:
6253                         ResetAllOptions();
6254                         break;
6255         }
6256 }
6257
6258 /*
6259  * Get the value to assign for a VariableSetStmt, or NULL if it's RESET.
6260  * The result is palloc'd.
6261  *
6262  * This is exported for use by actions such as ALTER ROLE SET.
6263  */
6264 char *
6265 ExtractSetVariableArgs(VariableSetStmt *stmt)
6266 {
6267         switch (stmt->kind)
6268         {
6269                 case VAR_SET_VALUE:
6270                         return flatten_set_variable_args(stmt->name, stmt->args);
6271                 case VAR_SET_CURRENT:
6272                         return GetConfigOptionByName(stmt->name, NULL);
6273                 default:
6274                         return NULL;
6275         }
6276 }
6277
6278 /*
6279  * SetPGVariable - SET command exported as an easily-C-callable function.
6280  *
6281  * This provides access to SET TO value, as well as SET TO DEFAULT (expressed
6282  * by passing args == NIL), but not SET FROM CURRENT functionality.
6283  */
6284 void
6285 SetPGVariable(const char *name, List *args, bool is_local)
6286 {
6287         char       *argstring = flatten_set_variable_args(name, args);
6288
6289         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6290         (void) set_config_option(name,
6291                                                          argstring,
6292                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6293                                                          PGC_S_SESSION,
6294                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6295                                                          true,
6296                                                          0);
6297 }
6298
6299 /*
6300  * SET command wrapped as a SQL callable function.
6301  */
6302 Datum
6303 set_config_by_name(PG_FUNCTION_ARGS)
6304 {
6305         char       *name;
6306         char       *value;
6307         char       *new_value;
6308         bool            is_local;
6309
6310         if (PG_ARGISNULL(0))
6311                 ereport(ERROR,
6312                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6313                                  errmsg("SET requires parameter name")));
6314
6315         /* Get the GUC variable name */
6316         name = TextDatumGetCString(PG_GETARG_DATUM(0));
6317
6318         /* Get the desired value or set to NULL for a reset request */
6319         if (PG_ARGISNULL(1))
6320                 value = NULL;
6321         else
6322                 value = TextDatumGetCString(PG_GETARG_DATUM(1));
6323
6324         /*
6325          * Get the desired state of is_local. Default to false if provided value
6326          * is NULL
6327          */
6328         if (PG_ARGISNULL(2))
6329                 is_local = false;
6330         else
6331                 is_local = PG_GETARG_BOOL(2);
6332
6333         /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
6334         (void) set_config_option(name,
6335                                                          value,
6336                                                          (superuser() ? PGC_SUSET : PGC_USERSET),
6337                                                          PGC_S_SESSION,
6338                                                          is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
6339                                                          true,
6340                                                          0);
6341
6342         /* get the new current value */
6343         new_value = GetConfigOptionByName(name, NULL);
6344
6345         /* Convert return string to text */
6346         PG_RETURN_TEXT_P(cstring_to_text(new_value));
6347 }
6348
6349
6350 /*
6351  * Common code for DefineCustomXXXVariable subroutines: allocate the
6352  * new variable's config struct and fill in generic fields.
6353  */
6354 static struct config_generic *
6355 init_custom_variable(const char *name,
6356                                          const char *short_desc,
6357                                          const char *long_desc,
6358                                          GucContext context,
6359                                          int flags,
6360                                          enum config_type type,
6361                                          size_t sz)
6362 {
6363         struct config_generic *gen;
6364
6365         /*
6366          * Only allow custom PGC_POSTMASTER variables to be created during shared
6367          * library preload; any later than that, we can't ensure that the value
6368          * doesn't change after startup.  This is a fatal elog if it happens; just
6369          * erroring out isn't safe because we don't know what the calling loadable
6370          * module might already have hooked into.
6371          */
6372         if (context == PGC_POSTMASTER &&
6373                 !process_shared_preload_libraries_in_progress)
6374                 elog(FATAL, "cannot create PGC_POSTMASTER variables after startup");
6375
6376         gen = (struct config_generic *) guc_malloc(ERROR, sz);
6377         memset(gen, 0, sz);
6378
6379         gen->name = guc_strdup(ERROR, name);
6380         gen->context = context;
6381         gen->group = CUSTOM_OPTIONS;
6382         gen->short_desc = short_desc;
6383         gen->long_desc = long_desc;
6384         gen->flags = flags;
6385         gen->vartype = type;
6386
6387         return gen;
6388 }
6389
6390 /*
6391  * Common code for DefineCustomXXXVariable subroutines: insert the new
6392  * variable into the GUC variable array, replacing any placeholder.
6393  */
6394 static void
6395 define_custom_variable(struct config_generic * variable)
6396 {
6397         const char *name = variable->name;
6398         const char **nameAddr = &name;
6399         struct config_string *pHolder;
6400         struct config_generic **res;
6401
6402         /*
6403          * See if there's a placeholder by the same name.
6404          */
6405         res = (struct config_generic **) bsearch((void *) &nameAddr,
6406                                                                                          (void *) guc_variables,
6407                                                                                          num_guc_variables,
6408                                                                                          sizeof(struct config_generic *),
6409                                                                                          guc_var_compare);
6410         if (res == NULL)
6411         {
6412                 /*
6413                  * No placeholder to replace, so we can just add it ... but first,
6414                  * make sure it's initialized to its default value.
6415                  */
6416                 InitializeOneGUCOption(variable);
6417                 add_guc_variable(variable, ERROR);
6418                 return;
6419         }
6420
6421         /*
6422          * This better be a placeholder
6423          */
6424         if (((*res)->flags & GUC_CUSTOM_PLACEHOLDER) == 0)
6425                 ereport(ERROR,
6426                                 (errcode(ERRCODE_INTERNAL_ERROR),
6427                                  errmsg("attempt to redefine parameter \"%s\"", name)));
6428
6429         Assert((*res)->vartype == PGC_STRING);
6430         pHolder = (struct config_string *) (*res);
6431
6432         /*
6433          * First, set the variable to its default value.  We must do this even
6434          * though we intend to immediately apply a new value, since it's possible
6435          * that the new value is invalid.
6436          */
6437         InitializeOneGUCOption(variable);
6438
6439         /*
6440          * Replace the placeholder. We aren't changing the name, so no re-sorting
6441          * is necessary
6442          */
6443         *res = variable;
6444
6445         /*
6446          * Assign the string value(s) stored in the placeholder to the real
6447          * variable.  Essentially, we need to duplicate all the active and stacked
6448          * values, but with appropriate validation and datatype adjustment.
6449          *
6450          * If an assignment fails, we report a WARNING and keep going.  We don't
6451          * want to throw ERROR for bad values, because it'd bollix the add-on
6452          * module that's presumably halfway through getting loaded.  In such cases
6453          * the default or previous state will become active instead.
6454          */
6455
6456         /* First, apply the reset value if any */
6457         if (pHolder->reset_val)
6458                 (void) set_config_option(name, pHolder->reset_val,
6459                                                                  pHolder->gen.reset_scontext,
6460                                                                  pHolder->gen.reset_source,
6461                                                                  GUC_ACTION_SET, true, WARNING);
6462         /* That should not have resulted in stacking anything */
6463         Assert(variable->stack == NULL);
6464
6465         /* Now, apply current and stacked values, in the order they were stacked */
6466         reapply_stacked_values(variable, pHolder, pHolder->gen.stack,
6467                                                    *(pHolder->variable),
6468                                                    pHolder->gen.scontext, pHolder->gen.source);
6469
6470         /* Also copy over any saved source-location information */
6471         if (pHolder->gen.sourcefile)
6472                 set_config_sourcefile(name, pHolder->gen.sourcefile,
6473                                                           pHolder->gen.sourceline);
6474
6475         /*
6476          * Free up as much as we conveniently can of the placeholder structure.
6477          * (This neglects any stack items, so it's possible for some memory to be
6478          * leaked.      Since this can only happen once per session per variable, it
6479          * doesn't seem worth spending much code on.)
6480          */
6481         set_string_field(pHolder, pHolder->variable, NULL);
6482         set_string_field(pHolder, &pHolder->reset_val, NULL);
6483
6484         free(pHolder);
6485 }
6486
6487 /*
6488  * Recursive subroutine for define_custom_variable: reapply non-reset values
6489  *
6490  * We recurse so that the values are applied in the same order as originally.
6491  * At each recursion level, apply the upper-level value (passed in) in the
6492  * fashion implied by the stack entry.
6493  */
6494 static void
6495 reapply_stacked_values(struct config_generic * variable,
6496                                            struct config_string * pHolder,
6497                                            GucStack *stack,
6498                                            const char *curvalue,
6499                                            GucContext curscontext, GucSource cursource)
6500 {
6501         const char *name = variable->name;
6502         GucStack   *oldvarstack = variable->stack;
6503
6504         if (stack != NULL)
6505         {
6506                 /* First, recurse, so that stack items are processed bottom to top */
6507                 reapply_stacked_values(variable, pHolder, stack->prev,
6508                                                            stack->prior.val.stringval,
6509                                                            stack->scontext, stack->source);
6510
6511                 /* See how to apply the passed-in value */
6512                 switch (stack->state)
6513                 {
6514                         case GUC_SAVE:
6515                                 (void) set_config_option(name, curvalue,
6516                                                                                  curscontext, cursource,
6517                                                                                  GUC_ACTION_SAVE, true, WARNING);
6518                                 break;
6519
6520                         case GUC_SET:
6521                                 (void) set_config_option(name, curvalue,
6522                                                                                  curscontext, cursource,
6523                                                                                  GUC_ACTION_SET, true, WARNING);
6524                                 break;
6525
6526                         case GUC_LOCAL:
6527                                 (void) set_config_option(name, curvalue,
6528                                                                                  curscontext, cursource,
6529                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6530                                 break;
6531
6532                         case GUC_SET_LOCAL:
6533                                 /* first, apply the masked value as SET */
6534                                 (void) set_config_option(name, stack->masked.val.stringval,
6535                                                                            stack->masked_scontext, PGC_S_SESSION,
6536                                                                                  GUC_ACTION_SET, true, WARNING);
6537                                 /* then apply the current value as LOCAL */
6538                                 (void) set_config_option(name, curvalue,
6539                                                                                  curscontext, cursource,
6540                                                                                  GUC_ACTION_LOCAL, true, WARNING);
6541                                 break;
6542                 }
6543
6544                 /* If we successfully made a stack entry, adjust its nest level */
6545                 if (variable->stack != oldvarstack)
6546                         variable->stack->nest_level = stack->nest_level;
6547         }
6548         else
6549         {
6550                 /*
6551                  * We are at the end of the stack.      If the active/previous value is
6552                  * different from the reset value, it must represent a previously
6553                  * committed session value.  Apply it, and then drop the stack entry
6554                  * that set_config_option will have created under the impression that
6555                  * this is to be just a transactional assignment.  (We leak the stack
6556                  * entry.)
6557                  */
6558                 if (curvalue != pHolder->reset_val ||
6559                         curscontext != pHolder->gen.reset_scontext ||
6560                         cursource != pHolder->gen.reset_source)
6561                 {
6562                         (void) set_config_option(name, curvalue,
6563                                                                          curscontext, cursource,
6564                                                                          GUC_ACTION_SET, true, WARNING);
6565                         variable->stack = NULL;
6566                 }
6567         }
6568 }
6569
6570 void
6571 DefineCustomBoolVariable(const char *name,
6572                                                  const char *short_desc,
6573                                                  const char *long_desc,
6574                                                  bool *valueAddr,
6575                                                  bool bootValue,
6576                                                  GucContext context,
6577                                                  int flags,
6578                                                  GucBoolCheckHook check_hook,
6579                                                  GucBoolAssignHook assign_hook,
6580                                                  GucShowHook show_hook)
6581 {
6582         struct config_bool *var;
6583
6584         var = (struct config_bool *)
6585                 init_custom_variable(name, short_desc, long_desc, context, flags,
6586                                                          PGC_BOOL, sizeof(struct config_bool));
6587         var->variable = valueAddr;
6588         var->boot_val = bootValue;
6589         var->reset_val = bootValue;
6590         var->check_hook = check_hook;
6591         var->assign_hook = assign_hook;
6592         var->show_hook = show_hook;
6593         define_custom_variable(&var->gen);
6594 }
6595
6596 void
6597 DefineCustomIntVariable(const char *name,
6598                                                 const char *short_desc,
6599                                                 const char *long_desc,
6600                                                 int *valueAddr,
6601                                                 int bootValue,
6602                                                 int minValue,
6603                                                 int maxValue,
6604                                                 GucContext context,
6605                                                 int flags,
6606                                                 GucIntCheckHook check_hook,
6607                                                 GucIntAssignHook assign_hook,
6608                                                 GucShowHook show_hook)
6609 {
6610         struct config_int *var;
6611
6612         var = (struct config_int *)
6613                 init_custom_variable(name, short_desc, long_desc, context, flags,
6614                                                          PGC_INT, sizeof(struct config_int));
6615         var->variable = valueAddr;
6616         var->boot_val = bootValue;
6617         var->reset_val = bootValue;
6618         var->min = minValue;
6619         var->max = maxValue;
6620         var->check_hook = check_hook;
6621         var->assign_hook = assign_hook;
6622         var->show_hook = show_hook;
6623         define_custom_variable(&var->gen);
6624 }
6625
6626 void
6627 DefineCustomRealVariable(const char *name,
6628                                                  const char *short_desc,
6629                                                  const char *long_desc,
6630                                                  double *valueAddr,
6631                                                  double bootValue,
6632                                                  double minValue,
6633                                                  double maxValue,
6634                                                  GucContext context,
6635                                                  int flags,
6636                                                  GucRealCheckHook check_hook,
6637                                                  GucRealAssignHook assign_hook,
6638                                                  GucShowHook show_hook)
6639 {
6640         struct config_real *var;
6641
6642         var = (struct config_real *)
6643                 init_custom_variable(name, short_desc, long_desc, context, flags,
6644                                                          PGC_REAL, sizeof(struct config_real));
6645         var->variable = valueAddr;
6646         var->boot_val = bootValue;
6647         var->reset_val = bootValue;
6648         var->min = minValue;
6649         var->max = maxValue;
6650         var->check_hook = check_hook;
6651         var->assign_hook = assign_hook;
6652         var->show_hook = show_hook;
6653         define_custom_variable(&var->gen);
6654 }
6655
6656 void
6657 DefineCustomStringVariable(const char *name,
6658                                                    const char *short_desc,
6659                                                    const char *long_desc,
6660                                                    char **valueAddr,
6661                                                    const char *bootValue,
6662                                                    GucContext context,
6663                                                    int flags,
6664                                                    GucStringCheckHook check_hook,
6665                                                    GucStringAssignHook assign_hook,
6666                                                    GucShowHook show_hook)
6667 {
6668         struct config_string *var;
6669
6670         var = (struct config_string *)
6671                 init_custom_variable(name, short_desc, long_desc, context, flags,
6672                                                          PGC_STRING, sizeof(struct config_string));
6673         var->variable = valueAddr;
6674         var->boot_val = bootValue;
6675         var->check_hook = check_hook;
6676         var->assign_hook = assign_hook;
6677         var->show_hook = show_hook;
6678         define_custom_variable(&var->gen);
6679 }
6680
6681 void
6682 DefineCustomEnumVariable(const char *name,
6683                                                  const char *short_desc,
6684                                                  const char *long_desc,
6685                                                  int *valueAddr,
6686                                                  int bootValue,
6687                                                  const struct config_enum_entry * options,
6688                                                  GucContext context,
6689                                                  int flags,
6690                                                  GucEnumCheckHook check_hook,
6691                                                  GucEnumAssignHook assign_hook,
6692                                                  GucShowHook show_hook)
6693 {
6694         struct config_enum *var;
6695
6696         var = (struct config_enum *)
6697                 init_custom_variable(name, short_desc, long_desc, context, flags,
6698                                                          PGC_ENUM, sizeof(struct config_enum));
6699         var->variable = valueAddr;
6700         var->boot_val = bootValue;
6701         var->reset_val = bootValue;
6702         var->options = options;
6703         var->check_hook = check_hook;
6704         var->assign_hook = assign_hook;
6705         var->show_hook = show_hook;
6706         define_custom_variable(&var->gen);
6707 }
6708
6709 void
6710 EmitWarningsOnPlaceholders(const char *className)
6711 {
6712         int                     classLen = strlen(className);
6713         int                     i;
6714
6715         for (i = 0; i < num_guc_variables; i++)
6716         {
6717                 struct config_generic *var = guc_variables[i];
6718
6719                 if ((var->flags & GUC_CUSTOM_PLACEHOLDER) != 0 &&
6720                         strncmp(className, var->name, classLen) == 0 &&
6721                         var->name[classLen] == GUC_QUALIFIER_SEPARATOR)
6722                 {
6723                         ereport(WARNING,
6724                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
6725                                          errmsg("unrecognized configuration parameter \"%s\"",
6726                                                         var->name)));
6727                 }
6728         }
6729 }
6730
6731
6732 /*
6733  * SHOW command
6734  */
6735 void
6736 GetPGVariable(const char *name, DestReceiver *dest)
6737 {
6738         if (guc_name_compare(name, "all") == 0)
6739                 ShowAllGUCConfig(dest);
6740         else
6741                 ShowGUCConfigOption(name, dest);
6742 }
6743
6744 TupleDesc
6745 GetPGVariableResultDesc(const char *name)
6746 {
6747         TupleDesc       tupdesc;
6748
6749         if (guc_name_compare(name, "all") == 0)
6750         {
6751                 /* need a tuple descriptor representing three TEXT columns */
6752                 tupdesc = CreateTemplateTupleDesc(3, false);
6753                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6754                                                    TEXTOID, -1, 0);
6755                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6756                                                    TEXTOID, -1, 0);
6757                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6758                                                    TEXTOID, -1, 0);
6759         }
6760         else
6761         {
6762                 const char *varname;
6763
6764                 /* Get the canonical spelling of name */
6765                 (void) GetConfigOptionByName(name, &varname);
6766
6767                 /* need a tuple descriptor representing a single TEXT column */
6768                 tupdesc = CreateTemplateTupleDesc(1, false);
6769                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6770                                                    TEXTOID, -1, 0);
6771         }
6772         return tupdesc;
6773 }
6774
6775
6776 /*
6777  * SHOW command
6778  */
6779 static void
6780 ShowGUCConfigOption(const char *name, DestReceiver *dest)
6781 {
6782         TupOutputState *tstate;
6783         TupleDesc       tupdesc;
6784         const char *varname;
6785         char       *value;
6786
6787         /* Get the value and canonical spelling of name */
6788         value = GetConfigOptionByName(name, &varname);
6789
6790         /* need a tuple descriptor representing a single TEXT column */
6791         tupdesc = CreateTemplateTupleDesc(1, false);
6792         TupleDescInitEntry(tupdesc, (AttrNumber) 1, varname,
6793                                            TEXTOID, -1, 0);
6794
6795         /* prepare for projection of tuples */
6796         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6797
6798         /* Send it */
6799         do_text_output_oneline(tstate, value);
6800
6801         end_tup_output(tstate);
6802 }
6803
6804 /*
6805  * SHOW ALL command
6806  */
6807 static void
6808 ShowAllGUCConfig(DestReceiver *dest)
6809 {
6810         bool            am_superuser = superuser();
6811         int                     i;
6812         TupOutputState *tstate;
6813         TupleDesc       tupdesc;
6814         Datum           values[3];
6815         bool            isnull[3] = {false, false, false};
6816
6817         /* need a tuple descriptor representing three TEXT columns */
6818         tupdesc = CreateTemplateTupleDesc(3, false);
6819         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
6820                                            TEXTOID, -1, 0);
6821         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
6822                                            TEXTOID, -1, 0);
6823         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
6824                                            TEXTOID, -1, 0);
6825
6826         /* prepare for projection of tuples */
6827         tstate = begin_tup_output_tupdesc(dest, tupdesc);
6828
6829         for (i = 0; i < num_guc_variables; i++)
6830         {
6831                 struct config_generic *conf = guc_variables[i];
6832                 char       *setting;
6833
6834                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6835                         ((conf->flags & GUC_SUPERUSER_ONLY) && !am_superuser))
6836                         continue;
6837
6838                 /* assign to the values array */
6839                 values[0] = PointerGetDatum(cstring_to_text(conf->name));
6840
6841                 setting = _ShowOption(conf, true);
6842                 if (setting)
6843                 {
6844                         values[1] = PointerGetDatum(cstring_to_text(setting));
6845                         isnull[1] = false;
6846                 }
6847                 else
6848                 {
6849                         values[1] = PointerGetDatum(NULL);
6850                         isnull[1] = true;
6851                 }
6852
6853                 values[2] = PointerGetDatum(cstring_to_text(conf->short_desc));
6854
6855                 /* send it to dest */
6856                 do_tup_output(tstate, values, isnull);
6857
6858                 /* clean up */
6859                 pfree(DatumGetPointer(values[0]));
6860                 if (setting)
6861                 {
6862                         pfree(setting);
6863                         pfree(DatumGetPointer(values[1]));
6864                 }
6865                 pfree(DatumGetPointer(values[2]));
6866         }
6867
6868         end_tup_output(tstate);
6869 }
6870
6871 /*
6872  * Return GUC variable value by name; optionally return canonical
6873  * form of name.  Return value is palloc'd.
6874  */
6875 char *
6876 GetConfigOptionByName(const char *name, const char **varname)
6877 {
6878         struct config_generic *record;
6879
6880         record = find_option(name, false, ERROR);
6881         if (record == NULL)
6882                 ereport(ERROR,
6883                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
6884                            errmsg("unrecognized configuration parameter \"%s\"", name)));
6885         if ((record->flags & GUC_SUPERUSER_ONLY) && !superuser())
6886                 ereport(ERROR,
6887                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
6888                                  errmsg("must be superuser to examine \"%s\"", name)));
6889
6890         if (varname)
6891                 *varname = record->name;
6892
6893         return _ShowOption(record, true);
6894 }
6895
6896 /*
6897  * Return GUC variable value by variable number; optionally return canonical
6898  * form of name.  Return value is palloc'd.
6899  */
6900 void
6901 GetConfigOptionByNum(int varnum, const char **values, bool *noshow)
6902 {
6903         char            buffer[256];
6904         struct config_generic *conf;
6905
6906         /* check requested variable number valid */
6907         Assert((varnum >= 0) && (varnum < num_guc_variables));
6908
6909         conf = guc_variables[varnum];
6910
6911         if (noshow)
6912         {
6913                 if ((conf->flags & GUC_NO_SHOW_ALL) ||
6914                         ((conf->flags & GUC_SUPERUSER_ONLY) && !superuser()))
6915                         *noshow = true;
6916                 else
6917                         *noshow = false;
6918         }
6919
6920         /* first get the generic attributes */
6921
6922         /* name */
6923         values[0] = conf->name;
6924
6925         /* setting : use _ShowOption in order to avoid duplicating the logic */
6926         values[1] = _ShowOption(conf, false);
6927
6928         /* unit */
6929         if (conf->vartype == PGC_INT)
6930         {
6931                 static char buf[8];
6932
6933                 switch (conf->flags & (GUC_UNIT_MEMORY | GUC_UNIT_TIME))
6934                 {
6935                         case GUC_UNIT_KB:
6936                                 values[2] = "kB";
6937                                 break;
6938                         case GUC_UNIT_BLOCKS:
6939                                 snprintf(buf, sizeof(buf), "%dkB", BLCKSZ / 1024);
6940                                 values[2] = buf;
6941                                 break;
6942                         case GUC_UNIT_XBLOCKS:
6943                                 snprintf(buf, sizeof(buf), "%dkB", XLOG_BLCKSZ / 1024);
6944                                 values[2] = buf;
6945                                 break;
6946                         case GUC_UNIT_MS:
6947                                 values[2] = "ms";
6948                                 break;
6949                         case GUC_UNIT_S:
6950                                 values[2] = "s";
6951                                 break;
6952                         case GUC_UNIT_MIN:
6953                                 values[2] = "min";
6954                                 break;
6955                         default:
6956                                 values[2] = "";
6957                                 break;
6958                 }
6959         }
6960         else
6961                 values[2] = NULL;
6962
6963         /* group */
6964         values[3] = config_group_names[conf->group];
6965
6966         /* short_desc */
6967         values[4] = conf->short_desc;
6968
6969         /* extra_desc */
6970         values[5] = conf->long_desc;
6971
6972         /* context */
6973         values[6] = GucContext_Names[conf->context];
6974
6975         /* vartype */
6976         values[7] = config_type_names[conf->vartype];
6977
6978         /* source */
6979         values[8] = GucSource_Names[conf->source];
6980
6981         /* now get the type specifc attributes */
6982         switch (conf->vartype)
6983         {
6984                 case PGC_BOOL:
6985                         {
6986                                 struct config_bool *lconf = (struct config_bool *) conf;
6987
6988                                 /* min_val */
6989                                 values[9] = NULL;
6990
6991                                 /* max_val */
6992                                 values[10] = NULL;
6993
6994                                 /* enumvals */
6995                                 values[11] = NULL;
6996
6997                                 /* boot_val */
6998                                 values[12] = pstrdup(lconf->boot_val ? "on" : "off");
6999
7000                                 /* reset_val */
7001                                 values[13] = pstrdup(lconf->reset_val ? "on" : "off");
7002                         }
7003                         break;
7004
7005                 case PGC_INT:
7006                         {
7007                                 struct config_int *lconf = (struct config_int *) conf;
7008
7009                                 /* min_val */
7010                                 snprintf(buffer, sizeof(buffer), "%d", lconf->min);
7011                                 values[9] = pstrdup(buffer);
7012
7013                                 /* max_val */
7014                                 snprintf(buffer, sizeof(buffer), "%d", lconf->max);
7015                                 values[10] = pstrdup(buffer);
7016
7017                                 /* enumvals */
7018                                 values[11] = NULL;
7019
7020                                 /* boot_val */
7021                                 snprintf(buffer, sizeof(buffer), "%d", lconf->boot_val);
7022                                 values[12] = pstrdup(buffer);
7023
7024                                 /* reset_val */
7025                                 snprintf(buffer, sizeof(buffer), "%d", lconf->reset_val);
7026                                 values[13] = pstrdup(buffer);
7027                         }
7028                         break;
7029
7030                 case PGC_REAL:
7031                         {
7032                                 struct config_real *lconf = (struct config_real *) conf;
7033
7034                                 /* min_val */
7035                                 snprintf(buffer, sizeof(buffer), "%g", lconf->min);
7036                                 values[9] = pstrdup(buffer);
7037
7038                                 /* max_val */
7039                                 snprintf(buffer, sizeof(buffer), "%g", lconf->max);
7040                                 values[10] = pstrdup(buffer);
7041
7042                                 /* enumvals */
7043                                 values[11] = NULL;
7044
7045                                 /* boot_val */
7046                                 snprintf(buffer, sizeof(buffer), "%g", lconf->boot_val);
7047                                 values[12] = pstrdup(buffer);
7048
7049                                 /* reset_val */
7050                                 snprintf(buffer, sizeof(buffer), "%g", lconf->reset_val);
7051                                 values[13] = pstrdup(buffer);
7052                         }
7053                         break;
7054
7055                 case PGC_STRING:
7056                         {
7057                                 struct config_string *lconf = (struct config_string *) conf;
7058
7059                                 /* min_val */
7060                                 values[9] = NULL;
7061
7062                                 /* max_val */
7063                                 values[10] = NULL;
7064
7065                                 /* enumvals */
7066                                 values[11] = NULL;
7067
7068                                 /* boot_val */
7069                                 if (lconf->boot_val == NULL)
7070                                         values[12] = NULL;
7071                                 else
7072                                         values[12] = pstrdup(lconf->boot_val);
7073
7074                                 /* reset_val */
7075                                 if (lconf->reset_val == NULL)
7076                                         values[13] = NULL;
7077                                 else
7078                                         values[13] = pstrdup(lconf->reset_val);
7079                         }
7080                         break;
7081
7082                 case PGC_ENUM:
7083                         {
7084                                 struct config_enum *lconf = (struct config_enum *) conf;
7085
7086                                 /* min_val */
7087                                 values[9] = NULL;
7088
7089                                 /* max_val */
7090                                 values[10] = NULL;
7091
7092                                 /* enumvals */
7093
7094                                 /*
7095                                  * NOTE! enumvals with double quotes in them are not
7096                                  * supported!
7097                                  */
7098                                 values[11] = config_enum_get_options((struct config_enum *) conf,
7099                                                                                                          "{\"", "\"}", "\",\"");
7100
7101                                 /* boot_val */
7102                                 values[12] = pstrdup(config_enum_lookup_by_value(lconf,
7103                                                                                                                    lconf->boot_val));
7104
7105                                 /* reset_val */
7106                                 values[13] = pstrdup(config_enum_lookup_by_value(lconf,
7107                                                                                                                   lconf->reset_val));
7108                         }
7109                         break;
7110
7111                 default:
7112                         {
7113                                 /*
7114                                  * should never get here, but in case we do, set 'em to NULL
7115                                  */
7116
7117                                 /* min_val */
7118                                 values[9] = NULL;
7119
7120                                 /* max_val */
7121                                 values[10] = NULL;
7122
7123                                 /* enumvals */
7124                                 values[11] = NULL;
7125
7126                                 /* boot_val */
7127                                 values[12] = NULL;
7128
7129                                 /* reset_val */
7130                                 values[13] = NULL;
7131                         }
7132                         break;
7133         }
7134
7135         /*
7136          * If the setting came from a config file, set the source location. For
7137          * security reasons, we don't show source file/line number for
7138          * non-superusers.
7139          */
7140         if (conf->source == PGC_S_FILE && superuser())
7141         {
7142                 values[14] = conf->sourcefile;
7143                 snprintf(buffer, sizeof(buffer), "%d", conf->sourceline);
7144                 values[15] = pstrdup(buffer);
7145         }
7146         else
7147         {
7148                 values[14] = NULL;
7149                 values[15] = NULL;
7150         }
7151 }
7152
7153 /*
7154  * Return the total number of GUC variables
7155  */
7156 int
7157 GetNumConfigOptions(void)
7158 {
7159         return num_guc_variables;
7160 }
7161
7162 /*
7163  * show_config_by_name - equiv to SHOW X command but implemented as
7164  * a function.
7165  */
7166 Datum
7167 show_config_by_name(PG_FUNCTION_ARGS)
7168 {
7169         char       *varname;
7170         char       *varval;
7171
7172         /* Get the GUC variable name */
7173         varname = TextDatumGetCString(PG_GETARG_DATUM(0));
7174
7175         /* Get the value */
7176         varval = GetConfigOptionByName(varname, NULL);
7177
7178         /* Convert to text */
7179         PG_RETURN_TEXT_P(cstring_to_text(varval));
7180 }
7181
7182 /*
7183  * show_all_settings - equiv to SHOW ALL command but implemented as
7184  * a Table Function.
7185  */
7186 #define NUM_PG_SETTINGS_ATTS    16
7187
7188 Datum
7189 show_all_settings(PG_FUNCTION_ARGS)
7190 {
7191         FuncCallContext *funcctx;
7192         TupleDesc       tupdesc;
7193         int                     call_cntr;
7194         int                     max_calls;
7195         AttInMetadata *attinmeta;
7196         MemoryContext oldcontext;
7197
7198         /* stuff done only on the first call of the function */
7199         if (SRF_IS_FIRSTCALL())
7200         {
7201                 /* create a function context for cross-call persistence */
7202                 funcctx = SRF_FIRSTCALL_INIT();
7203
7204                 /*
7205                  * switch to memory context appropriate for multiple function calls
7206                  */
7207                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
7208
7209                 /*
7210                  * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
7211                  * of the appropriate types
7212                  */
7213                 tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
7214                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
7215                                                    TEXTOID, -1, 0);
7216                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
7217                                                    TEXTOID, -1, 0);
7218                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
7219                                                    TEXTOID, -1, 0);
7220                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
7221                                                    TEXTOID, -1, 0);
7222                 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
7223                                                    TEXTOID, -1, 0);
7224                 TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
7225                                                    TEXTOID, -1, 0);
7226                 TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
7227                                                    TEXTOID, -1, 0);
7228                 TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
7229                                                    TEXTOID, -1, 0);
7230                 TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
7231                                                    TEXTOID, -1, 0);
7232                 TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
7233                                                    TEXTOID, -1, 0);
7234                 TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
7235                                                    TEXTOID, -1, 0);
7236                 TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
7237                                                    TEXTARRAYOID, -1, 0);
7238                 TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
7239                                                    TEXTOID, -1, 0);
7240                 TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
7241                                                    TEXTOID, -1, 0);
7242                 TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
7243                                                    TEXTOID, -1, 0);
7244                 TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
7245                                                    INT4OID, -1, 0);
7246
7247                 /*
7248                  * Generate attribute metadata needed later to produce tuples from raw
7249                  * C strings
7250                  */
7251                 attinmeta = TupleDescGetAttInMetadata(tupdesc);
7252                 funcctx->attinmeta = attinmeta;
7253
7254                 /* total number of tuples to be returned */
7255                 funcctx->max_calls = GetNumConfigOptions();
7256
7257                 MemoryContextSwitchTo(oldcontext);
7258         }
7259
7260         /* stuff done on every call of the function */
7261         funcctx = SRF_PERCALL_SETUP();
7262
7263         call_cntr = funcctx->call_cntr;
7264         max_calls = funcctx->max_calls;
7265         attinmeta = funcctx->attinmeta;
7266
7267         if (call_cntr < max_calls)      /* do when there is more left to send */
7268         {
7269                 char       *values[NUM_PG_SETTINGS_ATTS];
7270                 bool            noshow;
7271                 HeapTuple       tuple;
7272                 Datum           result;
7273
7274                 /*
7275                  * Get the next visible GUC variable name and value
7276                  */
7277                 do
7278                 {
7279                         GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
7280                         if (noshow)
7281                         {
7282                                 /* bump the counter and get the next config setting */
7283                                 call_cntr = ++funcctx->call_cntr;
7284
7285                                 /* make sure we haven't gone too far now */
7286                                 if (call_cntr >= max_calls)
7287                                         SRF_RETURN_DONE(funcctx);
7288                         }
7289                 } while (noshow);
7290
7291                 /* build a tuple */
7292                 tuple = BuildTupleFromCStrings(attinmeta, values);
7293
7294                 /* make the tuple into a datum */
7295                 result = HeapTupleGetDatum(tuple);
7296
7297                 SRF_RETURN_NEXT(funcctx, result);
7298         }
7299         else
7300         {
7301                 /* do when there is no more left */
7302                 SRF_RETURN_DONE(funcctx);
7303         }
7304 }
7305
7306 static char *
7307 _ShowOption(struct config_generic * record, bool use_units)
7308 {
7309         char            buffer[256];
7310         const char *val;
7311
7312         switch (record->vartype)
7313         {
7314                 case PGC_BOOL:
7315                         {
7316                                 struct config_bool *conf = (struct config_bool *) record;
7317
7318                                 if (conf->show_hook)
7319                                         val = (*conf->show_hook) ();
7320                                 else
7321                                         val = *conf->variable ? "on" : "off";
7322                         }
7323                         break;
7324
7325                 case PGC_INT:
7326                         {
7327                                 struct config_int *conf = (struct config_int *) record;
7328
7329                                 if (conf->show_hook)
7330                                         val = (*conf->show_hook) ();
7331                                 else
7332                                 {
7333                                         /*
7334                                          * Use int64 arithmetic to avoid overflows in units
7335                                          * conversion.
7336                                          */
7337                                         int64           result = *conf->variable;
7338                                         const char *unit;
7339
7340                                         if (use_units && result > 0 &&
7341                                                 (record->flags & GUC_UNIT_MEMORY))
7342                                         {
7343                                                 switch (record->flags & GUC_UNIT_MEMORY)
7344                                                 {
7345                                                         case GUC_UNIT_BLOCKS:
7346                                                                 result *= BLCKSZ / 1024;
7347                                                                 break;
7348                                                         case GUC_UNIT_XBLOCKS:
7349                                                                 result *= XLOG_BLCKSZ / 1024;
7350                                                                 break;
7351                                                 }
7352
7353                                                 if (result % KB_PER_GB == 0)
7354                                                 {
7355                                                         result /= KB_PER_GB;
7356                                                         unit = "GB";
7357                                                 }
7358                                                 else if (result % KB_PER_MB == 0)
7359                                                 {
7360                                                         result /= KB_PER_MB;
7361                                                         unit = "MB";
7362                                                 }
7363                                                 else
7364                                                 {
7365                                                         unit = "kB";
7366                                                 }
7367                                         }
7368                                         else if (use_units && result > 0 &&
7369                                                          (record->flags & GUC_UNIT_TIME))
7370                                         {
7371                                                 switch (record->flags & GUC_UNIT_TIME)
7372                                                 {
7373                                                         case GUC_UNIT_S:
7374                                                                 result *= MS_PER_S;
7375                                                                 break;
7376                                                         case GUC_UNIT_MIN:
7377                                                                 result *= MS_PER_MIN;
7378                                                                 break;
7379                                                 }
7380
7381                                                 if (result % MS_PER_D == 0)
7382                                                 {
7383                                                         result /= MS_PER_D;
7384                                                         unit = "d";
7385                                                 }
7386                                                 else if (result % MS_PER_H == 0)
7387                                                 {
7388                                                         result /= MS_PER_H;
7389                                                         unit = "h";
7390                                                 }
7391                                                 else if (result % MS_PER_MIN == 0)
7392                                                 {
7393                                                         result /= MS_PER_MIN;
7394                                                         unit = "min";
7395                                                 }
7396                                                 else if (result % MS_PER_S == 0)
7397                                                 {
7398                                                         result /= MS_PER_S;
7399                                                         unit = "s";
7400                                                 }
7401                                                 else
7402                                                 {
7403                                                         unit = "ms";
7404                                                 }
7405                                         }
7406                                         else
7407                                                 unit = "";
7408
7409                                         snprintf(buffer, sizeof(buffer), INT64_FORMAT "%s",
7410                                                          result, unit);
7411                                         val = buffer;
7412                                 }
7413                         }
7414                         break;
7415
7416                 case PGC_REAL:
7417                         {
7418                                 struct config_real *conf = (struct config_real *) record;
7419
7420                                 if (conf->show_hook)
7421                                         val = (*conf->show_hook) ();
7422                                 else
7423                                 {
7424                                         snprintf(buffer, sizeof(buffer), "%g",
7425                                                          *conf->variable);
7426                                         val = buffer;
7427                                 }
7428                         }
7429                         break;
7430
7431                 case PGC_STRING:
7432                         {
7433                                 struct config_string *conf = (struct config_string *) record;
7434
7435                                 if (conf->show_hook)
7436                                         val = (*conf->show_hook) ();
7437                                 else if (*conf->variable && **conf->variable)
7438                                         val = *conf->variable;
7439                                 else
7440                                         val = "";
7441                         }
7442                         break;
7443
7444                 case PGC_ENUM:
7445                         {
7446                                 struct config_enum *conf = (struct config_enum *) record;
7447
7448                                 if (conf->show_hook)
7449                                         val = (*conf->show_hook) ();
7450                                 else
7451                                         val = config_enum_lookup_by_value(conf, *conf->variable);
7452                         }
7453                         break;
7454
7455                 default:
7456                         /* just to keep compiler quiet */
7457                         val = "???";
7458                         break;
7459         }
7460
7461         return pstrdup(val);
7462 }
7463
7464
7465 #ifdef EXEC_BACKEND
7466
7467 /*
7468  *      These routines dump out all non-default GUC options into a binary
7469  *      file that is read by all exec'ed backends.  The format is:
7470  *
7471  *              variable name, string, null terminated
7472  *              variable value, string, null terminated
7473  *              variable sourcefile, string, null terminated (empty if none)
7474  *              variable sourceline, integer
7475  *              variable source, integer
7476  *              variable scontext, integer
7477  */
7478 static void
7479 write_one_nondefault_variable(FILE *fp, struct config_generic * gconf)
7480 {
7481         if (gconf->source == PGC_S_DEFAULT)
7482                 return;
7483
7484         fprintf(fp, "%s", gconf->name);
7485         fputc(0, fp);
7486
7487         switch (gconf->vartype)
7488         {
7489                 case PGC_BOOL:
7490                         {
7491                                 struct config_bool *conf = (struct config_bool *) gconf;
7492
7493                                 if (*conf->variable)
7494                                         fprintf(fp, "true");
7495                                 else
7496                                         fprintf(fp, "false");
7497                         }
7498                         break;
7499
7500                 case PGC_INT:
7501                         {
7502                                 struct config_int *conf = (struct config_int *) gconf;
7503
7504                                 fprintf(fp, "%d", *conf->variable);
7505                         }
7506                         break;
7507
7508                 case PGC_REAL:
7509                         {
7510                                 struct config_real *conf = (struct config_real *) gconf;
7511
7512                                 fprintf(fp, "%.17g", *conf->variable);
7513                         }
7514                         break;
7515
7516                 case PGC_STRING:
7517                         {
7518                                 struct config_string *conf = (struct config_string *) gconf;
7519
7520                                 fprintf(fp, "%s", *conf->variable);
7521                         }
7522                         break;
7523
7524                 case PGC_ENUM:
7525                         {
7526                                 struct config_enum *conf = (struct config_enum *) gconf;
7527
7528                                 fprintf(fp, "%s",
7529                                                 config_enum_lookup_by_value(conf, *conf->variable));
7530                         }
7531                         break;
7532         }
7533
7534         fputc(0, fp);
7535
7536         if (gconf->sourcefile)
7537                 fprintf(fp, "%s", gconf->sourcefile);
7538         fputc(0, fp);
7539
7540         fwrite(&gconf->sourceline, 1, sizeof(gconf->sourceline), fp);
7541         fwrite(&gconf->source, 1, sizeof(gconf->source), fp);
7542         fwrite(&gconf->scontext, 1, sizeof(gconf->scontext), fp);
7543 }
7544
7545 void
7546 write_nondefault_variables(GucContext context)
7547 {
7548         int                     elevel;
7549         FILE       *fp;
7550         int                     i;
7551
7552         Assert(context == PGC_POSTMASTER || context == PGC_SIGHUP);
7553
7554         elevel = (context == PGC_SIGHUP) ? LOG : ERROR;
7555
7556         /*
7557          * Open file
7558          */
7559         fp = AllocateFile(CONFIG_EXEC_PARAMS_NEW, "w");
7560         if (!fp)
7561         {
7562                 ereport(elevel,
7563                                 (errcode_for_file_access(),
7564                                  errmsg("could not write to file \"%s\": %m",
7565                                                 CONFIG_EXEC_PARAMS_NEW)));
7566                 return;
7567         }
7568
7569         for (i = 0; i < num_guc_variables; i++)
7570         {
7571                 write_one_nondefault_variable(fp, guc_variables[i]);
7572         }
7573
7574         if (FreeFile(fp))
7575         {
7576                 ereport(elevel,
7577                                 (errcode_for_file_access(),
7578                                  errmsg("could not write to file \"%s\": %m",
7579                                                 CONFIG_EXEC_PARAMS_NEW)));
7580                 return;
7581         }
7582
7583         /*
7584          * Put new file in place.  This could delay on Win32, but we don't hold
7585          * any exclusive locks.
7586          */
7587         rename(CONFIG_EXEC_PARAMS_NEW, CONFIG_EXEC_PARAMS);
7588 }
7589
7590
7591 /*
7592  *      Read string, including null byte from file
7593  *
7594  *      Return NULL on EOF and nothing read
7595  */
7596 static char *
7597 read_string_with_null(FILE *fp)
7598 {
7599         int                     i = 0,
7600                                 ch,
7601                                 maxlen = 256;
7602         char       *str = NULL;
7603
7604         do
7605         {
7606                 if ((ch = fgetc(fp)) == EOF)
7607                 {
7608                         if (i == 0)
7609                                 return NULL;
7610                         else
7611                                 elog(FATAL, "invalid format of exec config params file");
7612                 }
7613                 if (i == 0)
7614                         str = guc_malloc(FATAL, maxlen);
7615                 else if (i == maxlen)
7616                         str = guc_realloc(FATAL, str, maxlen *= 2);
7617                 str[i++] = ch;
7618         } while (ch != 0);
7619
7620         return str;
7621 }
7622
7623
7624 /*
7625  *      This routine loads a previous postmaster dump of its non-default
7626  *      settings.
7627  */
7628 void
7629 read_nondefault_variables(void)
7630 {
7631         FILE       *fp;
7632         char       *varname,
7633                            *varvalue,
7634                            *varsourcefile;
7635         int                     varsourceline;
7636         GucSource       varsource;
7637         GucContext      varscontext;
7638
7639         /*
7640          * Open file
7641          */
7642         fp = AllocateFile(CONFIG_EXEC_PARAMS, "r");
7643         if (!fp)
7644         {
7645                 /* File not found is fine */
7646                 if (errno != ENOENT)
7647                         ereport(FATAL,
7648                                         (errcode_for_file_access(),
7649                                          errmsg("could not read from file \"%s\": %m",
7650                                                         CONFIG_EXEC_PARAMS)));
7651                 return;
7652         }
7653
7654         for (;;)
7655         {
7656                 struct config_generic *record;
7657
7658                 if ((varname = read_string_with_null(fp)) == NULL)
7659                         break;
7660
7661                 if ((record = find_option(varname, true, FATAL)) == NULL)
7662                         elog(FATAL, "failed to locate variable \"%s\" in exec config params file", varname);
7663
7664                 if ((varvalue = read_string_with_null(fp)) == NULL)
7665                         elog(FATAL, "invalid format of exec config params file");
7666                 if ((varsourcefile = read_string_with_null(fp)) == NULL)
7667                         elog(FATAL, "invalid format of exec config params file");
7668                 if (fread(&varsourceline, 1, sizeof(varsourceline), fp) != sizeof(varsourceline))
7669                         elog(FATAL, "invalid format of exec config params file");
7670                 if (fread(&varsource, 1, sizeof(varsource), fp) != sizeof(varsource))
7671                         elog(FATAL, "invalid format of exec config params file");
7672                 if (fread(&varscontext, 1, sizeof(varscontext), fp) != sizeof(varscontext))
7673                         elog(FATAL, "invalid format of exec config params file");
7674
7675                 (void) set_config_option(varname, varvalue,
7676                                                                  varscontext, varsource,
7677                                                                  GUC_ACTION_SET, true, 0);
7678                 if (varsourcefile[0])
7679                         set_config_sourcefile(varname, varsourcefile, varsourceline);
7680
7681                 free(varname);
7682                 free(varvalue);
7683                 free(varsourcefile);
7684         }
7685
7686         FreeFile(fp);
7687 }
7688 #endif   /* EXEC_BACKEND */
7689
7690
7691 /*
7692  * A little "long argument" simulation, although not quite GNU
7693  * compliant. Takes a string of the form "some-option=some value" and
7694  * returns name = "some_option" and value = "some value" in malloc'ed
7695  * storage. Note that '-' is converted to '_' in the option name. If
7696  * there is no '=' in the input string then value will be NULL.
7697  */
7698 void
7699 ParseLongOption(const char *string, char **name, char **value)
7700 {
7701         size_t          equal_pos;
7702         char       *cp;
7703
7704         AssertArg(string);
7705         AssertArg(name);
7706         AssertArg(value);
7707
7708         equal_pos = strcspn(string, "=");
7709
7710         if (string[equal_pos] == '=')
7711         {
7712                 *name = guc_malloc(FATAL, equal_pos + 1);
7713                 strlcpy(*name, string, equal_pos + 1);
7714
7715                 *value = guc_strdup(FATAL, &string[equal_pos + 1]);
7716         }
7717         else
7718         {
7719                 /* no equal sign in string */
7720                 *name = guc_strdup(FATAL, string);
7721                 *value = NULL;
7722         }
7723
7724         for (cp = *name; *cp; cp++)
7725                 if (*cp == '-')
7726                         *cp = '_';
7727 }
7728
7729
7730 /*
7731  * Handle options fetched from pg_db_role_setting.setconfig,
7732  * pg_proc.proconfig, etc.      Caller must specify proper context/source/action.
7733  *
7734  * The array parameter must be an array of TEXT (it must not be NULL).
7735  */
7736 void
7737 ProcessGUCArray(ArrayType *array,
7738                                 GucContext context, GucSource source, GucAction action)
7739 {
7740         int                     i;
7741
7742         Assert(array != NULL);
7743         Assert(ARR_ELEMTYPE(array) == TEXTOID);
7744         Assert(ARR_NDIM(array) == 1);
7745         Assert(ARR_LBOUND(array)[0] == 1);
7746
7747         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7748         {
7749                 Datum           d;
7750                 bool            isnull;
7751                 char       *s;
7752                 char       *name;
7753                 char       *value;
7754
7755                 d = array_ref(array, 1, &i,
7756                                           -1 /* varlenarray */ ,
7757                                           -1 /* TEXT's typlen */ ,
7758                                           false /* TEXT's typbyval */ ,
7759                                           'i' /* TEXT's typalign */ ,
7760                                           &isnull);
7761
7762                 if (isnull)
7763                         continue;
7764
7765                 s = TextDatumGetCString(d);
7766
7767                 ParseLongOption(s, &name, &value);
7768                 if (!value)
7769                 {
7770                         ereport(WARNING,
7771                                         (errcode(ERRCODE_SYNTAX_ERROR),
7772                                          errmsg("could not parse setting for parameter \"%s\"",
7773                                                         name)));
7774                         free(name);
7775                         continue;
7776                 }
7777
7778                 (void) set_config_option(name, value,
7779                                                                  context, source,
7780                                                                  action, true, 0);
7781
7782                 free(name);
7783                 if (value)
7784                         free(value);
7785                 pfree(s);
7786         }
7787 }
7788
7789
7790 /*
7791  * Add an entry to an option array.  The array parameter may be NULL
7792  * to indicate the current table entry is NULL.
7793  */
7794 ArrayType *
7795 GUCArrayAdd(ArrayType *array, const char *name, const char *value)
7796 {
7797         struct config_generic *record;
7798         Datum           datum;
7799         char       *newval;
7800         ArrayType  *a;
7801
7802         Assert(name);
7803         Assert(value);
7804
7805         /* test if the option is valid and we're allowed to set it */
7806         (void) validate_option_array_item(name, value, false);
7807
7808         /* normalize name (converts obsolete GUC names to modern spellings) */
7809         record = find_option(name, false, WARNING);
7810         if (record)
7811                 name = record->name;
7812
7813         /* build new item for array */
7814         newval = palloc(strlen(name) + 1 + strlen(value) + 1);
7815         sprintf(newval, "%s=%s", name, value);
7816         datum = CStringGetTextDatum(newval);
7817
7818         if (array)
7819         {
7820                 int                     index;
7821                 bool            isnull;
7822                 int                     i;
7823
7824                 Assert(ARR_ELEMTYPE(array) == TEXTOID);
7825                 Assert(ARR_NDIM(array) == 1);
7826                 Assert(ARR_LBOUND(array)[0] == 1);
7827
7828                 index = ARR_DIMS(array)[0] + 1; /* add after end */
7829
7830                 for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7831                 {
7832                         Datum           d;
7833                         char       *current;
7834
7835                         d = array_ref(array, 1, &i,
7836                                                   -1 /* varlenarray */ ,
7837                                                   -1 /* TEXT's typlen */ ,
7838                                                   false /* TEXT's typbyval */ ,
7839                                                   'i' /* TEXT's typalign */ ,
7840                                                   &isnull);
7841                         if (isnull)
7842                                 continue;
7843                         current = TextDatumGetCString(d);
7844
7845                         /* check for match up through and including '=' */
7846                         if (strncmp(current, newval, strlen(name) + 1) == 0)
7847                         {
7848                                 index = i;
7849                                 break;
7850                         }
7851                 }
7852
7853                 a = array_set(array, 1, &index,
7854                                           datum,
7855                                           false,
7856                                           -1 /* varlena array */ ,
7857                                           -1 /* TEXT's typlen */ ,
7858                                           false /* TEXT's typbyval */ ,
7859                                           'i' /* TEXT's typalign */ );
7860         }
7861         else
7862                 a = construct_array(&datum, 1,
7863                                                         TEXTOID,
7864                                                         -1, false, 'i');
7865
7866         return a;
7867 }
7868
7869
7870 /*
7871  * Delete an entry from an option array.  The array parameter may be NULL
7872  * to indicate the current table entry is NULL.  Also, if the return value
7873  * is NULL then a null should be stored.
7874  */
7875 ArrayType *
7876 GUCArrayDelete(ArrayType *array, const char *name)
7877 {
7878         struct config_generic *record;
7879         ArrayType  *newarray;
7880         int                     i;
7881         int                     index;
7882
7883         Assert(name);
7884
7885         /* test if the option is valid and we're allowed to set it */
7886         (void) validate_option_array_item(name, NULL, false);
7887
7888         /* normalize name (converts obsolete GUC names to modern spellings) */
7889         record = find_option(name, false, WARNING);
7890         if (record)
7891                 name = record->name;
7892
7893         /* if array is currently null, then surely nothing to delete */
7894         if (!array)
7895                 return NULL;
7896
7897         newarray = NULL;
7898         index = 1;
7899
7900         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7901         {
7902                 Datum           d;
7903                 char       *val;
7904                 bool            isnull;
7905
7906                 d = array_ref(array, 1, &i,
7907                                           -1 /* varlenarray */ ,
7908                                           -1 /* TEXT's typlen */ ,
7909                                           false /* TEXT's typbyval */ ,
7910                                           'i' /* TEXT's typalign */ ,
7911                                           &isnull);
7912                 if (isnull)
7913                         continue;
7914                 val = TextDatumGetCString(d);
7915
7916                 /* ignore entry if it's what we want to delete */
7917                 if (strncmp(val, name, strlen(name)) == 0
7918                         && val[strlen(name)] == '=')
7919                         continue;
7920
7921                 /* else add it to the output array */
7922                 if (newarray)
7923                         newarray = array_set(newarray, 1, &index,
7924                                                                  d,
7925                                                                  false,
7926                                                                  -1 /* varlenarray */ ,
7927                                                                  -1 /* TEXT's typlen */ ,
7928                                                                  false /* TEXT's typbyval */ ,
7929                                                                  'i' /* TEXT's typalign */ );
7930                 else
7931                         newarray = construct_array(&d, 1,
7932                                                                            TEXTOID,
7933                                                                            -1, false, 'i');
7934
7935                 index++;
7936         }
7937
7938         return newarray;
7939 }
7940
7941
7942 /*
7943  * Given a GUC array, delete all settings from it that our permission
7944  * level allows: if superuser, delete them all; if regular user, only
7945  * those that are PGC_USERSET
7946  */
7947 ArrayType *
7948 GUCArrayReset(ArrayType *array)
7949 {
7950         ArrayType  *newarray;
7951         int                     i;
7952         int                     index;
7953
7954         /* if array is currently null, nothing to do */
7955         if (!array)
7956                 return NULL;
7957
7958         /* if we're superuser, we can delete everything, so just do it */
7959         if (superuser())
7960                 return NULL;
7961
7962         newarray = NULL;
7963         index = 1;
7964
7965         for (i = 1; i <= ARR_DIMS(array)[0]; i++)
7966         {
7967                 Datum           d;
7968                 char       *val;
7969                 char       *eqsgn;
7970                 bool            isnull;
7971
7972                 d = array_ref(array, 1, &i,
7973                                           -1 /* varlenarray */ ,
7974                                           -1 /* TEXT's typlen */ ,
7975                                           false /* TEXT's typbyval */ ,
7976                                           'i' /* TEXT's typalign */ ,
7977                                           &isnull);
7978                 if (isnull)
7979                         continue;
7980                 val = TextDatumGetCString(d);
7981
7982                 eqsgn = strchr(val, '=');
7983                 *eqsgn = '\0';
7984
7985                 /* skip if we have permission to delete it */
7986                 if (validate_option_array_item(val, NULL, true))
7987                         continue;
7988
7989                 /* else add it to the output array */
7990                 if (newarray)
7991                         newarray = array_set(newarray, 1, &index,
7992                                                                  d,
7993                                                                  false,
7994                                                                  -1 /* varlenarray */ ,
7995                                                                  -1 /* TEXT's typlen */ ,
7996                                                                  false /* TEXT's typbyval */ ,
7997                                                                  'i' /* TEXT's typalign */ );
7998                 else
7999                         newarray = construct_array(&d, 1,
8000                                                                            TEXTOID,
8001                                                                            -1, false, 'i');
8002
8003                 index++;
8004                 pfree(val);
8005         }
8006
8007         return newarray;
8008 }
8009
8010 /*
8011  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
8012  *
8013  * name is the option name.  value is the proposed value for the Add case,
8014  * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
8015  * not an error to have no permissions to set the option.
8016  *
8017  * Returns TRUE if OK, FALSE if skipIfNoPermissions is true and user does not
8018  * have permission to change this option (all other error cases result in an
8019  * error being thrown).
8020  */
8021 static bool
8022 validate_option_array_item(const char *name, const char *value,
8023                                                    bool skipIfNoPermissions)
8024
8025 {
8026         struct config_generic *gconf;
8027
8028         /*
8029          * There are three cases to consider:
8030          *
8031          * name is a known GUC variable.  Check the value normally, check
8032          * permissions normally (ie, allow if variable is USERSET, or if it's
8033          * SUSET and user is superuser).
8034          *
8035          * name is not known, but exists or can be created as a placeholder (i.e.,
8036          * it has a prefixed name).  We allow this case if you're a superuser,
8037          * otherwise not.  Superusers are assumed to know what they're doing. We
8038          * can't allow it for other users, because when the placeholder is
8039          * resolved it might turn out to be a SUSET variable;
8040          * define_custom_variable assumes we checked that.
8041          *
8042          * name is not known and can't be created as a placeholder.  Throw error,
8043          * unless skipIfNoPermissions is true, in which case return FALSE.
8044          */
8045         gconf = find_option(name, true, WARNING);
8046         if (!gconf)
8047         {
8048                 /* not known, failed to make a placeholder */
8049                 if (skipIfNoPermissions)
8050                         return false;
8051                 ereport(ERROR,
8052                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
8053                                  errmsg("unrecognized configuration parameter \"%s\"",
8054                                                 name)));
8055         }
8056
8057         if (gconf->flags & GUC_CUSTOM_PLACEHOLDER)
8058         {
8059                 /*
8060                  * We cannot do any meaningful check on the value, so only permissions
8061                  * are useful to check.
8062                  */
8063                 if (superuser())
8064                         return true;
8065                 if (skipIfNoPermissions)
8066                         return false;
8067                 ereport(ERROR,
8068                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
8069                                  errmsg("permission denied to set parameter \"%s\"", name)));
8070         }
8071
8072         /* manual permissions check so we can avoid an error being thrown */
8073         if (gconf->context == PGC_USERSET)
8074                  /* ok */ ;
8075         else if (gconf->context == PGC_SUSET && superuser())
8076                  /* ok */ ;
8077         else if (skipIfNoPermissions)
8078                 return false;
8079         /* if a permissions error should be thrown, let set_config_option do it */
8080
8081         /* test for permissions and valid option value */
8082         (void) set_config_option(name, value,
8083                                                          superuser() ? PGC_SUSET : PGC_USERSET,
8084                                                          PGC_S_TEST, GUC_ACTION_SET, false, 0);
8085
8086         return true;
8087 }
8088
8089
8090 /*
8091  * Called by check_hooks that want to override the normal
8092  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
8093  *
8094  * Note that GUC_check_errmsg() etc are just macros that result in a direct
8095  * assignment to the associated variables.      That is ugly, but forced by the
8096  * limitations of C's macro mechanisms.
8097  */
8098 void
8099 GUC_check_errcode(int sqlerrcode)
8100 {
8101         GUC_check_errcode_value = sqlerrcode;
8102 }
8103
8104
8105 /*
8106  * Convenience functions to manage calling a variable's check_hook.
8107  * These mostly take care of the protocol for letting check hooks supply
8108  * portions of the error report on failure.
8109  */
8110
8111 static bool
8112 call_bool_check_hook(struct config_bool * conf, bool *newval, void **extra,
8113                                          GucSource source, int elevel)
8114 {
8115         /* Quick success if no hook */
8116         if (!conf->check_hook)
8117                 return true;
8118
8119         /* Reset variables that might be set by hook */
8120         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8121         GUC_check_errmsg_string = NULL;
8122         GUC_check_errdetail_string = NULL;
8123         GUC_check_errhint_string = NULL;
8124
8125         if (!(*conf->check_hook) (newval, extra, source))
8126         {
8127                 ereport(elevel,
8128                                 (errcode(GUC_check_errcode_value),
8129                                  GUC_check_errmsg_string ?
8130                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8131                                  errmsg("invalid value for parameter \"%s\": %d",
8132                                                 conf->gen.name, (int) *newval),
8133                                  GUC_check_errdetail_string ?
8134                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8135                                  GUC_check_errhint_string ?
8136                                  errhint("%s", GUC_check_errhint_string) : 0));
8137                 /* Flush any strings created in ErrorContext */
8138                 FlushErrorState();
8139                 return false;
8140         }
8141
8142         return true;
8143 }
8144
8145 static bool
8146 call_int_check_hook(struct config_int * conf, int *newval, void **extra,
8147                                         GucSource source, int elevel)
8148 {
8149         /* Quick success if no hook */
8150         if (!conf->check_hook)
8151                 return true;
8152
8153         /* Reset variables that might be set by hook */
8154         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8155         GUC_check_errmsg_string = NULL;
8156         GUC_check_errdetail_string = NULL;
8157         GUC_check_errhint_string = NULL;
8158
8159         if (!(*conf->check_hook) (newval, extra, source))
8160         {
8161                 ereport(elevel,
8162                                 (errcode(GUC_check_errcode_value),
8163                                  GUC_check_errmsg_string ?
8164                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8165                                  errmsg("invalid value for parameter \"%s\": %d",
8166                                                 conf->gen.name, *newval),
8167                                  GUC_check_errdetail_string ?
8168                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8169                                  GUC_check_errhint_string ?
8170                                  errhint("%s", GUC_check_errhint_string) : 0));
8171                 /* Flush any strings created in ErrorContext */
8172                 FlushErrorState();
8173                 return false;
8174         }
8175
8176         return true;
8177 }
8178
8179 static bool
8180 call_real_check_hook(struct config_real * conf, double *newval, void **extra,
8181                                          GucSource source, int elevel)
8182 {
8183         /* Quick success if no hook */
8184         if (!conf->check_hook)
8185                 return true;
8186
8187         /* Reset variables that might be set by hook */
8188         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8189         GUC_check_errmsg_string = NULL;
8190         GUC_check_errdetail_string = NULL;
8191         GUC_check_errhint_string = NULL;
8192
8193         if (!(*conf->check_hook) (newval, extra, source))
8194         {
8195                 ereport(elevel,
8196                                 (errcode(GUC_check_errcode_value),
8197                                  GUC_check_errmsg_string ?
8198                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8199                                  errmsg("invalid value for parameter \"%s\": %g",
8200                                                 conf->gen.name, *newval),
8201                                  GUC_check_errdetail_string ?
8202                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8203                                  GUC_check_errhint_string ?
8204                                  errhint("%s", GUC_check_errhint_string) : 0));
8205                 /* Flush any strings created in ErrorContext */
8206                 FlushErrorState();
8207                 return false;
8208         }
8209
8210         return true;
8211 }
8212
8213 static bool
8214 call_string_check_hook(struct config_string * conf, char **newval, void **extra,
8215                                            GucSource source, int elevel)
8216 {
8217         /* Quick success if no hook */
8218         if (!conf->check_hook)
8219                 return true;
8220
8221         /* Reset variables that might be set by hook */
8222         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8223         GUC_check_errmsg_string = NULL;
8224         GUC_check_errdetail_string = NULL;
8225         GUC_check_errhint_string = NULL;
8226
8227         if (!(*conf->check_hook) (newval, extra, source))
8228         {
8229                 ereport(elevel,
8230                                 (errcode(GUC_check_errcode_value),
8231                                  GUC_check_errmsg_string ?
8232                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8233                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8234                                                 conf->gen.name, *newval ? *newval : ""),
8235                                  GUC_check_errdetail_string ?
8236                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8237                                  GUC_check_errhint_string ?
8238                                  errhint("%s", GUC_check_errhint_string) : 0));
8239                 /* Flush any strings created in ErrorContext */
8240                 FlushErrorState();
8241                 return false;
8242         }
8243
8244         return true;
8245 }
8246
8247 static bool
8248 call_enum_check_hook(struct config_enum * conf, int *newval, void **extra,
8249                                          GucSource source, int elevel)
8250 {
8251         /* Quick success if no hook */
8252         if (!conf->check_hook)
8253                 return true;
8254
8255         /* Reset variables that might be set by hook */
8256         GUC_check_errcode_value = ERRCODE_INVALID_PARAMETER_VALUE;
8257         GUC_check_errmsg_string = NULL;
8258         GUC_check_errdetail_string = NULL;
8259         GUC_check_errhint_string = NULL;
8260
8261         if (!(*conf->check_hook) (newval, extra, source))
8262         {
8263                 ereport(elevel,
8264                                 (errcode(GUC_check_errcode_value),
8265                                  GUC_check_errmsg_string ?
8266                                  errmsg_internal("%s", GUC_check_errmsg_string) :
8267                                  errmsg("invalid value for parameter \"%s\": \"%s\"",
8268                                                 conf->gen.name,
8269                                                 config_enum_lookup_by_value(conf, *newval)),
8270                                  GUC_check_errdetail_string ?
8271                                  errdetail_internal("%s", GUC_check_errdetail_string) : 0,
8272                                  GUC_check_errhint_string ?
8273                                  errhint("%s", GUC_check_errhint_string) : 0));
8274                 /* Flush any strings created in ErrorContext */
8275                 FlushErrorState();
8276                 return false;
8277         }
8278
8279         return true;
8280 }
8281
8282
8283 /*
8284  * check_hook, assign_hook and show_hook subroutines
8285  */
8286
8287 static bool
8288 check_log_destination(char **newval, void **extra, GucSource source)
8289 {
8290         char       *rawstring;
8291         List       *elemlist;
8292         ListCell   *l;
8293         int                     newlogdest = 0;
8294         int                *myextra;
8295
8296         /* Need a modifiable copy of string */
8297         rawstring = pstrdup(*newval);
8298
8299         /* Parse string into list of identifiers */
8300         if (!SplitIdentifierString(rawstring, ',', &elemlist))
8301         {
8302                 /* syntax error in list */
8303                 GUC_check_errdetail("List syntax is invalid.");
8304                 pfree(rawstring);
8305                 list_free(elemlist);
8306                 return false;
8307         }
8308
8309         foreach(l, elemlist)
8310         {
8311                 char       *tok = (char *) lfirst(l);
8312
8313                 if (pg_strcasecmp(tok, "stderr") == 0)
8314                         newlogdest |= LOG_DESTINATION_STDERR;
8315                 else if (pg_strcasecmp(tok, "csvlog") == 0)
8316                         newlogdest |= LOG_DESTINATION_CSVLOG;
8317 #ifdef HAVE_SYSLOG
8318                 else if (pg_strcasecmp(tok, "syslog") == 0)
8319                         newlogdest |= LOG_DESTINATION_SYSLOG;
8320 #endif
8321 #ifdef WIN32
8322                 else if (pg_strcasecmp(tok, "eventlog") == 0)
8323                         newlogdest |= LOG_DESTINATION_EVENTLOG;
8324 #endif
8325                 else
8326                 {
8327                         GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
8328                         pfree(rawstring);
8329                         list_free(elemlist);
8330                         return false;
8331                 }
8332         }
8333
8334         pfree(rawstring);
8335         list_free(elemlist);
8336
8337         myextra = (int *) guc_malloc(ERROR, sizeof(int));
8338         *myextra = newlogdest;
8339         *extra = (void *) myextra;
8340
8341         return true;
8342 }
8343
8344 static void
8345 assign_log_destination(const char *newval, void *extra)
8346 {
8347         Log_destination = *((int *) extra);
8348 }
8349
8350 static void
8351 assign_syslog_facility(int newval, void *extra)
8352 {
8353 #ifdef HAVE_SYSLOG
8354         set_syslog_parameters(syslog_ident_str ? syslog_ident_str : "postgres",
8355                                                   newval);
8356 #endif
8357         /* Without syslog support, just ignore it */
8358 }
8359
8360 static void
8361 assign_syslog_ident(const char *newval, void *extra)
8362 {
8363 #ifdef HAVE_SYSLOG
8364         set_syslog_parameters(newval, syslog_facility);
8365 #endif
8366         /* Without syslog support, it will always be set to "none", so ignore */
8367 }
8368
8369
8370 static void
8371 assign_session_replication_role(int newval, void *extra)
8372 {
8373         /*
8374          * Must flush the plan cache when changing replication role; but don't
8375          * flush unnecessarily.
8376          */
8377         if (SessionReplicationRole != newval)
8378                 ResetPlanCache();
8379 }
8380
8381 static bool
8382 check_temp_buffers(int *newval, void **extra, GucSource source)
8383 {
8384         /*
8385          * Once local buffers have been initialized, it's too late to change this.
8386          */
8387         if (NLocBuffer && NLocBuffer != *newval)
8388         {
8389                 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
8390                 return false;
8391         }
8392         return true;
8393 }
8394
8395 static bool
8396 check_phony_autocommit(bool *newval, void **extra, GucSource source)
8397 {
8398         if (!*newval)
8399         {
8400                 GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
8401                 GUC_check_errmsg("SET AUTOCOMMIT TO OFF is no longer supported");
8402                 return false;
8403         }
8404         return true;
8405 }
8406
8407 static bool
8408 check_debug_assertions(bool *newval, void **extra, GucSource source)
8409 {
8410 #ifndef USE_ASSERT_CHECKING
8411         if (*newval)
8412         {
8413                 GUC_check_errmsg("assertion checking is not supported by this build");
8414                 return false;
8415         }
8416 #endif
8417         return true;
8418 }
8419
8420 static bool
8421 check_bonjour(bool *newval, void **extra, GucSource source)
8422 {
8423 #ifndef USE_BONJOUR
8424         if (*newval)
8425         {
8426                 GUC_check_errmsg("Bonjour is not supported by this build");
8427                 return false;
8428         }
8429 #endif
8430         return true;
8431 }
8432
8433 static bool
8434 check_ssl(bool *newval, void **extra, GucSource source)
8435 {
8436 #ifndef USE_SSL
8437         if (*newval)
8438         {
8439                 GUC_check_errmsg("SSL is not supported by this build");
8440                 return false;
8441         }
8442 #endif
8443         return true;
8444 }
8445
8446 static bool
8447 check_stage_log_stats(bool *newval, void **extra, GucSource source)
8448 {
8449         if (*newval && log_statement_stats)
8450         {
8451                 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
8452                 return false;
8453         }
8454         return true;
8455 }
8456
8457 static bool
8458 check_log_stats(bool *newval, void **extra, GucSource source)
8459 {
8460         if (*newval &&
8461                 (log_parser_stats || log_planner_stats || log_executor_stats))
8462         {
8463                 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
8464                                                         "\"log_parser_stats\", \"log_planner_stats\", "
8465                                                         "or \"log_executor_stats\" is true.");
8466                 return false;
8467         }
8468         return true;
8469 }
8470
8471 static bool
8472 check_canonical_path(char **newval, void **extra, GucSource source)
8473 {
8474         /*
8475          * Since canonicalize_path never enlarges the string, we can just modify
8476          * newval in-place.  But watch out for NULL, which is the default value
8477          * for external_pid_file.
8478          */
8479         if (*newval)
8480                 canonicalize_path(*newval);
8481         return true;
8482 }
8483
8484 static bool
8485 check_timezone_abbreviations(char **newval, void **extra, GucSource source)
8486 {
8487         /*
8488          * The boot_val given above for timezone_abbreviations is NULL. When we
8489          * see this we just do nothing.  If this value isn't overridden from the
8490          * config file then pg_timezone_abbrev_initialize() will eventually
8491          * replace it with "Default".  This hack has two purposes: to avoid
8492          * wasting cycles loading values that might soon be overridden from the
8493          * config file, and to avoid trying to read the timezone abbrev files
8494          * during InitializeGUCOptions().  The latter doesn't work in an
8495          * EXEC_BACKEND subprocess because my_exec_path hasn't been set yet and so
8496          * we can't locate PGSHAREDIR.
8497          */
8498         if (*newval == NULL)
8499         {
8500                 Assert(source == PGC_S_DEFAULT);
8501                 return true;
8502         }
8503
8504         /* OK, load the file and produce a malloc'd TimeZoneAbbrevTable */
8505         *extra = load_tzoffsets(*newval);
8506
8507         /* tzparser.c returns NULL on failure, reporting via GUC_check_errmsg */
8508         if (!*extra)
8509                 return false;
8510
8511         return true;
8512 }
8513
8514 static void
8515 assign_timezone_abbreviations(const char *newval, void *extra)
8516 {
8517         /* Do nothing for the boot_val default of NULL */
8518         if (!extra)
8519                 return;
8520
8521         InstallTimeZoneAbbrevs((TimeZoneAbbrevTable *) extra);
8522 }
8523
8524 /*
8525  * pg_timezone_abbrev_initialize --- set default value if not done already
8526  *
8527  * This is called after initial loading of postgresql.conf.  If no
8528  * timezone_abbreviations setting was found therein, select default.
8529  * If a non-default value is already installed, nothing will happen.
8530  *
8531  * This can also be called from ProcessConfigFile to establish the default
8532  * value after a postgresql.conf entry for it is removed.
8533  */
8534 static void
8535 pg_timezone_abbrev_initialize(void)
8536 {
8537         SetConfigOption("timezone_abbreviations", "Default",
8538                                         PGC_POSTMASTER, PGC_S_DYNAMIC_DEFAULT);
8539 }
8540
8541 static const char *
8542 show_archive_command(void)
8543 {
8544         if (XLogArchivingActive())
8545                 return XLogArchiveCommand;
8546         else
8547                 return "(disabled)";
8548 }
8549
8550 static void
8551 assign_tcp_keepalives_idle(int newval, void *extra)
8552 {
8553         /*
8554          * The kernel API provides no way to test a value without setting it; and
8555          * once we set it we might fail to unset it.  So there seems little point
8556          * in fully implementing the check-then-assign GUC API for these
8557          * variables.  Instead we just do the assignment on demand.  pqcomm.c
8558          * reports any problems via elog(LOG).
8559          *
8560          * This approach means that the GUC value might have little to do with the
8561          * actual kernel value, so we use a show_hook that retrieves the kernel
8562          * value rather than trusting GUC's copy.
8563          */
8564         (void) pq_setkeepalivesidle(newval, MyProcPort);
8565 }
8566
8567 static const char *
8568 show_tcp_keepalives_idle(void)
8569 {
8570         /* See comments in assign_tcp_keepalives_idle */
8571         static char nbuf[16];
8572
8573         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
8574         return nbuf;
8575 }
8576
8577 static void
8578 assign_tcp_keepalives_interval(int newval, void *extra)
8579 {
8580         /* See comments in assign_tcp_keepalives_idle */
8581         (void) pq_setkeepalivesinterval(newval, MyProcPort);
8582 }
8583
8584 static const char *
8585 show_tcp_keepalives_interval(void)
8586 {
8587         /* See comments in assign_tcp_keepalives_idle */
8588         static char nbuf[16];
8589
8590         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
8591         return nbuf;
8592 }
8593
8594 static void
8595 assign_tcp_keepalives_count(int newval, void *extra)
8596 {
8597         /* See comments in assign_tcp_keepalives_idle */
8598         (void) pq_setkeepalivescount(newval, MyProcPort);
8599 }
8600
8601 static const char *
8602 show_tcp_keepalives_count(void)
8603 {
8604         /* See comments in assign_tcp_keepalives_idle */
8605         static char nbuf[16];
8606
8607         snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
8608         return nbuf;
8609 }
8610
8611 static bool
8612 check_maxconnections(int *newval, void **extra, GucSource source)
8613 {
8614         if (*newval + autovacuum_max_workers + 1 > MAX_BACKENDS)
8615                 return false;
8616         return true;
8617 }
8618
8619 static void
8620 assign_maxconnections(int newval, void *extra)
8621 {
8622         MaxBackends = newval + autovacuum_max_workers + 1;
8623 }
8624
8625 static bool
8626 check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
8627 {
8628         if (MaxConnections + *newval + 1 > MAX_BACKENDS)
8629                 return false;
8630         return true;
8631 }
8632
8633 static void
8634 assign_autovacuum_max_workers(int newval, void *extra)
8635 {
8636         MaxBackends = MaxConnections + newval + 1;
8637 }
8638
8639 static bool
8640 check_effective_io_concurrency(int *newval, void **extra, GucSource source)
8641 {
8642 #ifdef USE_PREFETCH
8643         double          new_prefetch_pages = 0.0;
8644         int                     i;
8645
8646         /*----------
8647          * The user-visible GUC parameter is the number of drives (spindles),
8648          * which we need to translate to a number-of-pages-to-prefetch target.
8649          * The target value is stashed in *extra and then assigned to the actual
8650          * variable by assign_effective_io_concurrency.
8651          *
8652          * The expected number of prefetch pages needed to keep N drives busy is:
8653          *
8654          * drives |   I/O requests
8655          * -------+----------------
8656          *              1 |   1
8657          *              2 |   2/1 + 2/2 = 3
8658          *              3 |   3/1 + 3/2 + 3/3 = 5 1/2
8659          *              4 |   4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
8660          *              n |   n * H(n)
8661          *
8662          * This is called the "coupon collector problem" and H(n) is called the
8663          * harmonic series.  This could be approximated by n * ln(n), but for
8664          * reasonable numbers of drives we might as well just compute the series.
8665          *
8666          * Alternatively we could set the target to the number of pages necessary
8667          * so that the expected number of active spindles is some arbitrary
8668          * percentage of the total.  This sounds the same but is actually slightly
8669          * different.  The result ends up being ln(1-P)/ln((n-1)/n) where P is
8670          * that desired fraction.
8671          *
8672          * Experimental results show that both of these formulas aren't aggressive
8673          * enough, but we don't really have any better proposals.
8674          *
8675          * Note that if *newval = 0 (disabled), we must set target = 0.
8676          *----------
8677          */
8678
8679         for (i = 1; i <= *newval; i++)
8680                 new_prefetch_pages += (double) *newval / (double) i;
8681
8682         /* This range check shouldn't fail, but let's be paranoid */
8683         if (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX)
8684         {
8685                 int                *myextra = (int *) guc_malloc(ERROR, sizeof(int));
8686
8687                 *myextra = (int) rint(new_prefetch_pages);
8688                 *extra = (void *) myextra;
8689
8690                 return true;
8691         }
8692         else
8693                 return false;
8694 #else
8695         return true;
8696 #endif   /* USE_PREFETCH */
8697 }
8698
8699 static void
8700 assign_effective_io_concurrency(int newval, void *extra)
8701 {
8702 #ifdef USE_PREFETCH
8703         target_prefetch_pages = *((int *) extra);
8704 #endif   /* USE_PREFETCH */
8705 }
8706
8707 static void
8708 assign_pgstat_temp_directory(const char *newval, void *extra)
8709 {
8710         /* check_canonical_path already canonicalized newval for us */
8711         char       *tname;
8712         char       *fname;
8713
8714         tname = guc_malloc(ERROR, strlen(newval) + 12);         /* /pgstat.tmp */
8715         sprintf(tname, "%s/pgstat.tmp", newval);
8716         fname = guc_malloc(ERROR, strlen(newval) + 13);         /* /pgstat.stat */
8717         sprintf(fname, "%s/pgstat.stat", newval);
8718
8719         if (pgstat_stat_tmpname)
8720                 free(pgstat_stat_tmpname);
8721         pgstat_stat_tmpname = tname;
8722         if (pgstat_stat_filename)
8723                 free(pgstat_stat_filename);
8724         pgstat_stat_filename = fname;
8725 }
8726
8727 static bool
8728 check_application_name(char **newval, void **extra, GucSource source)
8729 {
8730         /* Only allow clean ASCII chars in the application name */
8731         char       *p;
8732
8733         for (p = *newval; *p; p++)
8734         {
8735                 if (*p < 32 || *p > 126)
8736                         *p = '?';
8737         }
8738
8739         return true;
8740 }
8741
8742 static void
8743 assign_application_name(const char *newval, void *extra)
8744 {
8745         /* Update the pg_stat_activity view */
8746         pgstat_report_appname(newval);
8747 }
8748
8749 static const char *
8750 show_unix_socket_permissions(void)
8751 {
8752         static char buf[8];
8753
8754         snprintf(buf, sizeof(buf), "%04o", Unix_socket_permissions);
8755         return buf;
8756 }
8757
8758 static const char *
8759 show_log_file_mode(void)
8760 {
8761         static char buf[8];
8762
8763         snprintf(buf, sizeof(buf), "%04o", Log_file_mode);
8764         return buf;
8765 }
8766
8767 #include "guc-file.c"