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