OSDN Git Service

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