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