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