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