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