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