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