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