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