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