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