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