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