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