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