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