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