OSDN Git Service

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