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