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