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