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