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