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