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