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