PostgreSQL Source Code git master
Loading...
Searching...
No Matches
option.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * option.c
4 * FDW and GUC option handling for postgres_fdw
5 *
6 * Portions Copyright (c) 2012-2026, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/postgres_fdw/option.c
10 *
11 *-------------------------------------------------------------------------
12 */
13#include "postgres.h"
14
15#include "access/reloptions.h"
19#include "commands/defrem.h"
20#include "commands/extension.h"
21#include "libpq/libpq-be.h"
22#include "postgres_fdw.h"
23#include "utils/guc.h"
24#include "utils/memutils.h"
25#include "utils/varlena.h"
26
27/*
28 * Describes the valid options for objects that this wrapper uses.
29 */
30typedef struct PgFdwOption
31{
32 const char *keyword;
33 Oid optcontext; /* OID of catalog in which option may appear */
34 bool is_libpq_opt; /* true if it's used in libpq */
36
37/*
38 * Valid options for postgres_fdw.
39 * Allocated and filled in InitPgFdwOptions.
40 */
42
43/*
44 * GUC parameters
45 */
47
48/*
49 * Helper functions
50 */
51static void InitPgFdwOptions(void);
52static bool is_valid_option(const char *keyword, Oid context);
53static bool is_libpq_option(const char *keyword);
54
55#include "miscadmin.h"
56
57/*
58 * Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
59 * USER MAPPING or FOREIGN TABLE that uses postgres_fdw.
60 *
61 * Raise an ERROR if the option or its value is considered invalid.
62 */
64
67{
70 ListCell *cell;
71
72 /* Build our options lists if we didn't yet. */
74
75 /*
76 * Check that only options supported by postgres_fdw, and allowed for the
77 * current object type, are given.
78 */
79 foreach(cell, options_list)
80 {
81 DefElem *def = (DefElem *) lfirst(cell);
82
84 {
85 /*
86 * Unknown option specified, complain about it. Provide a hint
87 * with a valid option that looks similar, if there is one.
88 */
89 PgFdwOption *opt;
90 const char *closest_match;
92 bool has_valid_options = false;
93
95 for (opt = postgres_fdw_options; opt->keyword; opt++)
96 {
97 if (catalog == opt->optcontext)
98 {
99 has_valid_options = true;
101 }
102 }
103
107 errmsg("invalid option \"%s\"", def->defname),
109 errhint("Perhaps you meant the option \"%s\".",
110 closest_match) : 0 :
111 errhint("There are no valid options in this context.")));
112 }
113
114 /*
115 * Validate option value, when we can do so without any context.
116 */
117 if (strcmp(def->defname, "use_remote_estimate") == 0 ||
118 strcmp(def->defname, "updatable") == 0 ||
119 strcmp(def->defname, "truncatable") == 0 ||
120 strcmp(def->defname, "async_capable") == 0 ||
121 strcmp(def->defname, "parallel_commit") == 0 ||
122 strcmp(def->defname, "parallel_abort") == 0 ||
123 strcmp(def->defname, "keep_connections") == 0 ||
124 strcmp(def->defname, "restore_stats") == 0)
125 {
126 /* these accept only boolean values */
127 (void) defGetBoolean(def);
128 }
129 else if (strcmp(def->defname, "fdw_startup_cost") == 0 ||
130 strcmp(def->defname, "fdw_tuple_cost") == 0)
131 {
132 /*
133 * These must have a floating point value greater than or equal to
134 * zero.
135 */
136 char *value;
137 double real_val;
138 bool is_parsed;
139
140 value = defGetString(def);
141 is_parsed = parse_real(value, &real_val, 0, NULL);
142
143 if (!is_parsed)
146 errmsg("invalid value for floating point option \"%s\": %s",
147 def->defname, value)));
148
149 if (real_val < 0)
152 errmsg("\"%s\" must be a floating point value greater than or equal to zero",
153 def->defname)));
154 }
155 else if (strcmp(def->defname, "extensions") == 0)
156 {
157 /* check list syntax, warn about uninstalled extensions */
159 }
160 else if (strcmp(def->defname, "fetch_size") == 0 ||
161 strcmp(def->defname, "batch_size") == 0)
162 {
163 char *value;
164 int int_val;
165 bool is_parsed;
166
167 value = defGetString(def);
168 is_parsed = parse_int(value, &int_val, 0, NULL);
169
170 if (!is_parsed)
173 errmsg("invalid value for integer option \"%s\": %s",
174 def->defname, value)));
175
176 if (int_val <= 0)
179 errmsg("\"%s\" must be an integer value greater than zero",
180 def->defname)));
181 }
182 else if (strcmp(def->defname, "password_required") == 0)
183 {
184 bool pw_required = defGetBoolean(def);
185
186 /*
187 * Only the superuser may set this option on a user mapping, or
188 * alter a user mapping on which this option is set. We allow a
189 * user to clear this option if it's set - in fact, we don't have
190 * a choice since we can't see the old mapping when validating an
191 * alter.
192 */
193 if (!superuser() && !pw_required)
196 errmsg("password_required=false is superuser-only"),
197 errhint("User mappings with the password_required option set to false may only be created or modified by the superuser.")));
198 }
199 else if (strcmp(def->defname, "sslcert") == 0 ||
200 strcmp(def->defname, "sslkey") == 0)
201 {
202 /* similarly for sslcert / sslkey on user mapping */
206 errmsg("sslcert and sslkey are superuser-only"),
207 errhint("User mappings with the sslcert or sslkey options set may only be created or modified by the superuser.")));
208 }
209 else if (strcmp(def->defname, "analyze_sampling") == 0)
210 {
211 char *value;
212
213 value = defGetString(def);
214
215 /* we recognize off/auto/random/system/bernoulli */
216 if (strcmp(value, "off") != 0 &&
217 strcmp(value, "auto") != 0 &&
218 strcmp(value, "random") != 0 &&
219 strcmp(value, "system") != 0 &&
220 strcmp(value, "bernoulli") != 0)
223 errmsg("invalid value for string option \"%s\": %s",
224 def->defname, value)));
225 }
226 }
227
229}
230
231/*
232 * Initialize option lists.
233 */
234static void
236{
237 int num_libpq_opts;
240 PgFdwOption *popt;
241
242 /* non-libpq FDW-specific FDW options */
243 static const PgFdwOption non_libpq_options[] = {
244 {"schema_name", ForeignTableRelationId, false},
245 {"table_name", ForeignTableRelationId, false},
246 {"column_name", AttributeRelationId, false},
247 /* use_remote_estimate is available on both server and table */
248 {"use_remote_estimate", ForeignServerRelationId, false},
249 {"use_remote_estimate", ForeignTableRelationId, false},
250 /* cost factors */
251 {"fdw_startup_cost", ForeignServerRelationId, false},
252 {"fdw_tuple_cost", ForeignServerRelationId, false},
253 /* shippable extensions */
254 {"extensions", ForeignServerRelationId, false},
255 /* updatable is available on both server and table */
256 {"updatable", ForeignServerRelationId, false},
257 {"updatable", ForeignTableRelationId, false},
258 /* truncatable is available on both server and table */
259 {"truncatable", ForeignServerRelationId, false},
260 {"truncatable", ForeignTableRelationId, false},
261 /* fetch_size is available on both server and table */
262 {"fetch_size", ForeignServerRelationId, false},
263 {"fetch_size", ForeignTableRelationId, false},
264 /* batch_size is available on both server and table */
265 {"batch_size", ForeignServerRelationId, false},
266 {"batch_size", ForeignTableRelationId, false},
267 /* async_capable is available on both server and table */
268 {"async_capable", ForeignServerRelationId, false},
269 {"async_capable", ForeignTableRelationId, false},
270 {"parallel_commit", ForeignServerRelationId, false},
271 {"parallel_abort", ForeignServerRelationId, false},
272 {"keep_connections", ForeignServerRelationId, false},
273 {"password_required", UserMappingRelationId, false},
274
275 /* sampling is available on both server and table */
276 {"analyze_sampling", ForeignServerRelationId, false},
277 {"analyze_sampling", ForeignTableRelationId, false},
278 /* restore_stats is available on both server and table */
279 {"restore_stats", ForeignServerRelationId, false},
280 {"restore_stats", ForeignTableRelationId, false},
281
282 {"use_scram_passthrough", ForeignServerRelationId, false},
283 {"use_scram_passthrough", UserMappingRelationId, false},
284
285 /*
286 * sslcert and sslkey are in fact libpq options, but we repeat them
287 * here to allow them to appear in both foreign server context (when
288 * we generate libpq options) and user mapping context (from here).
289 */
290 {"sslcert", UserMappingRelationId, true},
291 {"sslkey", UserMappingRelationId, true},
292
293 /*
294 * gssdelegation is also a libpq option but should be allowed in a
295 * user mapping context too
296 */
297 {"gssdelegation", UserMappingRelationId, true},
298
299 {NULL, InvalidOid, false}
300 };
301
302 /* Prevent redundant initialization. */
304 return;
305
306 /*
307 * Get list of valid libpq options.
308 *
309 * To avoid unnecessary work, we get the list once and use it throughout
310 * the lifetime of this backend process. Hence, we'll allocate it in
311 * TopMemoryContext.
312 */
314 if (!libpq_options) /* assume reason for failure is OOM */
317 errmsg("out of memory"),
318 errdetail("Could not get libpq's default connection options.")));
319
320 /* Count how many libpq options are available. */
321 num_libpq_opts = 0;
322 for (lopt = libpq_options; lopt->keyword; lopt++)
324
325 /*
326 * Construct an array which consists of all valid options for
327 * postgres_fdw, by appending FDW-specific options to libpq options.
328 */
331 sizeof(PgFdwOption) * num_libpq_opts +
332 sizeof(non_libpq_options));
333
335 for (lopt = libpq_options; lopt->keyword; lopt++)
336 {
337 /* Hide debug options, as well as settings we override internally. */
338 if (strchr(lopt->dispchar, 'D') ||
339 strcmp(lopt->keyword, "fallback_application_name") == 0 ||
340 strcmp(lopt->keyword, "client_encoding") == 0)
341 continue;
342
343 /*
344 * Disallow OAuth options for now, since the builtin flow communicates
345 * on stderr by default and can't cache tokens yet.
346 */
347 if (strncmp(lopt->keyword, "oauth_", strlen("oauth_")) == 0)
348 continue;
349
351 lopt->keyword);
352
353 /*
354 * "user" and any secret options are allowed only on user mappings.
355 * Everything else is a server option.
356 */
357 if (strcmp(lopt->keyword, "user") == 0 || strchr(lopt->dispchar, '*'))
359 else
361 popt->is_libpq_opt = true;
362
363 popt++;
364 }
365
366 /* Done with libpq's output structure. */
368
369 /* Append FDW-specific options and dummy terminator. */
371}
372
373/*
374 * Check whether the given option is one of the valid postgres_fdw options.
375 * context is the Oid of the catalog holding the object the option is for.
376 */
377static bool
378is_valid_option(const char *keyword, Oid context)
379{
380 PgFdwOption *opt;
381
382 Assert(postgres_fdw_options); /* must be initialized already */
383
384 for (opt = postgres_fdw_options; opt->keyword; opt++)
385 {
386 if (context == opt->optcontext && strcmp(opt->keyword, keyword) == 0)
387 return true;
388 }
389
390 return false;
391}
392
393/*
394 * Check whether the given option is one of the valid libpq options.
395 */
396static bool
397is_libpq_option(const char *keyword)
398{
399 PgFdwOption *opt;
400
401 Assert(postgres_fdw_options); /* must be initialized already */
402
403 for (opt = postgres_fdw_options; opt->keyword; opt++)
404 {
405 if (opt->is_libpq_opt && strcmp(opt->keyword, keyword) == 0)
406 return true;
407 }
408
409 return false;
410}
411
412/*
413 * Generate key-value arrays which include only libpq options from the
414 * given list (which can contain any kind of options). Caller must have
415 * allocated large-enough arrays. Returns number of options found.
416 */
417int
419 const char **values)
420{
421 ListCell *lc;
422 int i;
423
424 /* Build our options lists if we didn't yet. */
426
427 i = 0;
428 foreach(lc, defelems)
429 {
430 DefElem *d = (DefElem *) lfirst(lc);
431
432 if (is_libpq_option(d->defname))
433 {
434 keywords[i] = d->defname;
435 values[i] = defGetString(d);
436 i++;
437 }
438 }
439 return i;
440}
441
442/*
443 * Parse a comma-separated string and return a List of the OIDs of the
444 * extensions named in the string. If any names in the list cannot be
445 * found, report a warning if warnOnMissing is true, else just silently
446 * ignore them.
447 */
448List *
450{
452 List *extlist;
453 ListCell *lc;
454
455 /* SplitIdentifierString scribbles on its input, so pstrdup first */
457 {
458 /* syntax error in name list */
461 errmsg("parameter \"%s\" must be a list of extension names",
462 "extensions")));
463 }
464
465 foreach(lc, extlist)
466 {
467 const char *extension_name = (const char *) lfirst(lc);
469
471 {
473 }
474 else if (warnOnMissing)
475 {
478 errmsg("extension \"%s\" is not installed",
480 }
481 }
482
484 return extensionOids;
485}
486
487/*
488 * Replace escape sequences beginning with % character in the given
489 * application_name with status information, and return it.
490 *
491 * This function always returns a palloc'd string, so the caller is
492 * responsible for pfreeing it.
493 */
494char *
495process_pgfdw_appname(const char *appname)
496{
497 const char *p;
499
501
502 for (p = appname; *p != '\0'; p++)
503 {
504 if (*p != '%')
505 {
506 /* literal char, just copy */
508 continue;
509 }
510
511 /* must be a '%', so skip to the next char */
512 p++;
513 if (*p == '\0')
514 break; /* format error - ignore it */
515 else if (*p == '%')
516 {
517 /* string contains %% */
519 continue;
520 }
521
522 /* process the option */
523 switch (*p)
524 {
525 case 'a':
527 break;
528 case 'c':
530 break;
531 case 'C':
533 break;
534 case 'd':
535 if (MyProcPort)
536 {
537 const char *dbname = MyProcPort->database_name;
538
539 if (dbname)
541 else
542 appendStringInfoString(&buf, "[unknown]");
543 }
544 break;
545 case 'p':
547 break;
548 case 'u':
549 if (MyProcPort)
550 {
551 const char *username = MyProcPort->user_name;
552
553 if (username)
555 else
556 appendStringInfoString(&buf, "[unknown]");
557 }
558 break;
559 default:
560 /* format error - ignore it */
561 break;
562 }
563 }
564
565 return buf.data;
566}
567
568/*
569 * Module load callback
570 */
571void
573{
574 /*
575 * Unlike application_name GUC, don't set GUC_IS_NAME flag nor check_hook
576 * to allow postgres_fdw.application_name to be any string more than
577 * NAMEDATALEN characters and to include non-ASCII characters. Instead,
578 * remote server truncates application_name of remote connection to less
579 * than NAMEDATALEN and replaces any non-ASCII characters in it with a '?'
580 * character.
581 */
582 DefineCustomStringVariable("postgres_fdw.application_name",
583 "Sets the application name to be used on the remote server.",
584 NULL,
586 NULL,
588 0,
589 NULL,
590 NULL,
591 NULL);
592
593 MarkGUCPrefixReserved("postgres_fdw");
594}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define Assert(condition)
Definition c.h:943
#define OidIsValid(objectId)
Definition c.h:858
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void _PG_init(void)
Definition option.c:572
static bool is_valid_option(const char *keyword, Oid context)
Definition option.c:378
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition option.c:418
static bool is_libpq_option(const char *keyword)
Definition option.c:397
Datum postgres_fdw_validator(PG_FUNCTION_ARGS)
Definition option.c:66
List * ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
Definition option.c:449
static PgFdwOption * postgres_fdw_options
Definition option.c:41
char * pgfdw_application_name
Definition option.c:46
char * process_pgfdw_appname(const char *appname)
Definition option.c:495
static void InitPgFdwOptions(void)
Definition option.c:235
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition extension.c:229
void PQconninfoFree(PQconninfoOption *connOptions)
PQconninfoOption * PQconndefaults(void)
#define PG_RETURN_VOID()
Definition fmgr.h:350
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_GETARG_DATUM(n)
Definition fmgr.h:268
#define PG_FUNCTION_INFO_V1(funcname)
Definition fmgr.h:417
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
int MyProcPid
Definition globals.c:49
struct Port * MyProcPort
Definition globals.c:53
pg_time_t MyStartTime
Definition globals.c:50
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition guc.c:2775
void DefineCustomStringVariable(const char *name, const char *short_desc, const char *long_desc, char **valueAddr, const char *bootValue, GucContext context, int flags, GucStringCheckHook check_hook, GucStringAssignHook assign_hook, GucShowHook show_hook)
Definition guc.c:5129
bool parse_real(const char *value, double *result, int flags, const char **hintmsg)
Definition guc.c:2865
void MarkGUCPrefixReserved(const char *className)
Definition guc.c:5186
@ PGC_USERSET
Definition guc.h:79
char * cluster_name
Definition guc_tables.c:582
char * application_name
Definition guc_tables.c:589
struct parser_state match_state[5]
static struct @177 value
static char * username
Definition initdb.c:153
int i
Definition isn.c:77
static const JsonPathKeyword keywords[]
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free(List *list)
Definition list.c:1546
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition mcxt.c:1768
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
char * pstrdup(const char *in)
Definition mcxt.c:1781
MemoryContext TopMemoryContext
Definition mcxt.c:166
static char * errmsg
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
static char buf[DEFAULT_XLOG_SEG_SIZE]
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
static int fb(int x)
List * untransformRelOptions(Datum options)
char * dbname
Definition streamutil.c:49
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
char * defname
Definition parsenodes.h:860
Definition pg_list.h:54
Oid optcontext
Definition option.c:33
const char * keyword
Definition option.c:32
bool is_libpq_opt
Definition option.c:34
char * user_name
Definition libpq-be.h:151
char * database_name
Definition libpq-be.h:150
bool superuser(void)
Definition superuser.c:47
const char * getClosestMatch(ClosestMatchState *state)
Definition varlena.c:5386
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2867
void initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
Definition varlena.c:5331
void updateClosestMatch(ClosestMatchState *state, const char *candidate)
Definition varlena.c:5351