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