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