PostgreSQL Source Code  git master
foreigncmds.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * foreigncmds.c
4  * foreign-data wrapper/server creation/manipulation commands
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  *
8  *
9  * IDENTIFICATION
10  * src/backend/commands/foreigncmds.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15 
16 #include "access/htup_details.h"
17 #include "access/reloptions.h"
18 #include "access/table.h"
19 #include "access/xact.h"
20 #include "catalog/catalog.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/objectaccess.h"
27 #include "catalog/pg_proc.h"
28 #include "catalog/pg_type.h"
30 #include "commands/defrem.h"
31 #include "foreign/fdwapi.h"
32 #include "foreign/foreign.h"
33 #include "miscadmin.h"
34 #include "parser/parse_func.h"
35 #include "tcop/utility.h"
36 #include "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/lsyscache.h"
39 #include "utils/rel.h"
40 #include "utils/syscache.h"
41 
42 
43 typedef struct
44 {
45  char *tablename;
46  char *cmd;
48 
49 /* Internal functions */
50 static void import_error_callback(void *arg);
51 
52 
53 /*
54  * Convert a DefElem list to the text array format that is used in
55  * pg_foreign_data_wrapper, pg_foreign_server, pg_user_mapping, and
56  * pg_foreign_table.
57  *
58  * Returns the array in the form of a Datum, or PointerGetDatum(NULL)
59  * if the list is empty.
60  *
61  * Note: The array is usually stored to database without further
62  * processing, hence any validation should be done before this
63  * conversion.
64  */
65 static Datum
67 {
68  ArrayBuildState *astate = NULL;
69  ListCell *cell;
70 
71  foreach(cell, options)
72  {
73  DefElem *def = lfirst(cell);
74  const char *value;
75  Size len;
76  text *t;
77 
78  value = defGetString(def);
79  len = VARHDRSZ + strlen(def->defname) + 1 + strlen(value);
80  t = palloc(len + 1);
81  SET_VARSIZE(t, len);
82  sprintf(VARDATA(t), "%s=%s", def->defname, value);
83 
84  astate = accumArrayResult(astate, PointerGetDatum(t),
85  false, TEXTOID,
87  }
88 
89  if (astate)
90  return makeArrayResult(astate, CurrentMemoryContext);
91 
92  return PointerGetDatum(NULL);
93 }
94 
95 
96 /*
97  * Transform a list of DefElem into text array format. This is substantially
98  * the same thing as optionListToArray(), except we recognize SET/ADD/DROP
99  * actions for modifying an existing list of options, which is passed in
100  * Datum form as oldOptions. Also, if fdwvalidator isn't InvalidOid
101  * it specifies a validator function to call on the result.
102  *
103  * Returns the array in the form of a Datum, or PointerGetDatum(NULL)
104  * if the list is empty.
105  *
106  * This is used by CREATE/ALTER of FOREIGN DATA WRAPPER/SERVER/USER MAPPING/
107  * FOREIGN TABLE.
108  */
109 Datum
111  Datum oldOptions,
112  List *options,
113  Oid fdwvalidator)
114 {
115  List *resultOptions = untransformRelOptions(oldOptions);
116  ListCell *optcell;
117  Datum result;
118 
119  foreach(optcell, options)
120  {
121  DefElem *od = lfirst(optcell);
122  ListCell *cell;
123 
124  /*
125  * Find the element in resultOptions. We need this for validation in
126  * all cases.
127  */
128  foreach(cell, resultOptions)
129  {
130  DefElem *def = lfirst(cell);
131 
132  if (strcmp(def->defname, od->defname) == 0)
133  break;
134  }
135 
136  /*
137  * It is possible to perform multiple SET/DROP actions on the same
138  * option. The standard permits this, as long as the options to be
139  * added are unique. Note that an unspecified action is taken to be
140  * ADD.
141  */
142  switch (od->defaction)
143  {
144  case DEFELEM_DROP:
145  if (!cell)
146  ereport(ERROR,
147  (errcode(ERRCODE_UNDEFINED_OBJECT),
148  errmsg("option \"%s\" not found",
149  od->defname)));
150  resultOptions = list_delete_cell(resultOptions, cell);
151  break;
152 
153  case DEFELEM_SET:
154  if (!cell)
155  ereport(ERROR,
156  (errcode(ERRCODE_UNDEFINED_OBJECT),
157  errmsg("option \"%s\" not found",
158  od->defname)));
159  lfirst(cell) = od;
160  break;
161 
162  case DEFELEM_ADD:
163  case DEFELEM_UNSPEC:
164  if (cell)
165  ereport(ERROR,
167  errmsg("option \"%s\" provided more than once",
168  od->defname)));
169  resultOptions = lappend(resultOptions, od);
170  break;
171 
172  default:
173  elog(ERROR, "unrecognized action %d on option \"%s\"",
174  (int) od->defaction, od->defname);
175  break;
176  }
177  }
178 
179  result = optionListToArray(resultOptions);
180 
181  if (OidIsValid(fdwvalidator))
182  {
183  Datum valarg = result;
184 
185  /*
186  * Pass a null options list as an empty array, so that validators
187  * don't have to be declared non-strict to handle the case.
188  */
189  if (DatumGetPointer(valarg) == NULL)
190  valarg = PointerGetDatum(construct_empty_array(TEXTOID));
191  OidFunctionCall2(fdwvalidator, valarg, ObjectIdGetDatum(catalogId));
192  }
193 
194  return result;
195 }
196 
197 
198 /*
199  * Internal workhorse for changing a data wrapper's owner.
200  *
201  * Allow this only for superusers; also the new owner must be a
202  * superuser.
203  */
204 static void
206 {
208  Datum repl_val[Natts_pg_foreign_data_wrapper];
209  bool repl_null[Natts_pg_foreign_data_wrapper];
210  bool repl_repl[Natts_pg_foreign_data_wrapper];
211  Acl *newAcl;
212  Datum aclDatum;
213  bool isNull;
214 
216 
217  /* Must be a superuser to change a FDW owner */
218  if (!superuser())
219  ereport(ERROR,
220  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
221  errmsg("permission denied to change owner of foreign-data wrapper \"%s\"",
222  NameStr(form->fdwname)),
223  errhint("Must be superuser to change owner of a foreign-data wrapper.")));
224 
225  /* New owner must also be a superuser */
226  if (!superuser_arg(newOwnerId))
227  ereport(ERROR,
228  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
229  errmsg("permission denied to change owner of foreign-data wrapper \"%s\"",
230  NameStr(form->fdwname)),
231  errhint("The owner of a foreign-data wrapper must be a superuser.")));
232 
233  if (form->fdwowner != newOwnerId)
234  {
235  memset(repl_null, false, sizeof(repl_null));
236  memset(repl_repl, false, sizeof(repl_repl));
237 
238  repl_repl[Anum_pg_foreign_data_wrapper_fdwowner - 1] = true;
239  repl_val[Anum_pg_foreign_data_wrapper_fdwowner - 1] = ObjectIdGetDatum(newOwnerId);
240 
241  aclDatum = heap_getattr(tup,
242  Anum_pg_foreign_data_wrapper_fdwacl,
243  RelationGetDescr(rel),
244  &isNull);
245  /* Null ACLs do not require changes */
246  if (!isNull)
247  {
248  newAcl = aclnewowner(DatumGetAclP(aclDatum),
249  form->fdwowner, newOwnerId);
250  repl_repl[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
251  repl_val[Anum_pg_foreign_data_wrapper_fdwacl - 1] = PointerGetDatum(newAcl);
252  }
253 
254  tup = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val, repl_null,
255  repl_repl);
256 
257  CatalogTupleUpdate(rel, &tup->t_self, tup);
258 
259  /* Update owner dependency reference */
260  changeDependencyOnOwner(ForeignDataWrapperRelationId,
261  form->oid,
262  newOwnerId);
263  }
264 
265  InvokeObjectPostAlterHook(ForeignDataWrapperRelationId,
266  form->oid, 0);
267 }
268 
269 /*
270  * Change foreign-data wrapper owner -- by name
271  *
272  * Note restrictions in the "_internal" function, above.
273  */
275 AlterForeignDataWrapperOwner(const char *name, Oid newOwnerId)
276 {
277  Oid fdwId;
278  HeapTuple tup;
279  Relation rel;
280  ObjectAddress address;
282 
283 
284  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
285 
287 
288  if (!HeapTupleIsValid(tup))
289  ereport(ERROR,
290  (errcode(ERRCODE_UNDEFINED_OBJECT),
291  errmsg("foreign-data wrapper \"%s\" does not exist", name)));
292 
294  fdwId = form->oid;
295 
296  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
297 
298  ObjectAddressSet(address, ForeignDataWrapperRelationId, fdwId);
299 
300  heap_freetuple(tup);
301 
303 
304  return address;
305 }
306 
307 /*
308  * Change foreign-data wrapper owner -- by OID
309  *
310  * Note restrictions in the "_internal" function, above.
311  */
312 void
314 {
315  HeapTuple tup;
316  Relation rel;
317 
318  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
319 
321 
322  if (!HeapTupleIsValid(tup))
323  ereport(ERROR,
324  (errcode(ERRCODE_UNDEFINED_OBJECT),
325  errmsg("foreign-data wrapper with OID %u does not exist", fwdId)));
326 
327  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
328 
329  heap_freetuple(tup);
330 
332 }
333 
334 /*
335  * Internal workhorse for changing a foreign server's owner
336  */
337 static void
339 {
341  Datum repl_val[Natts_pg_foreign_server];
342  bool repl_null[Natts_pg_foreign_server];
343  bool repl_repl[Natts_pg_foreign_server];
344  Acl *newAcl;
345  Datum aclDatum;
346  bool isNull;
347 
348  form = (Form_pg_foreign_server) GETSTRUCT(tup);
349 
350  if (form->srvowner != newOwnerId)
351  {
352  /* Superusers can always do it */
353  if (!superuser())
354  {
355  Oid srvId;
356  AclResult aclresult;
357 
358  srvId = form->oid;
359 
360  /* Must be owner */
363  NameStr(form->srvname));
364 
365  /* Must be able to become new owner */
366  check_is_member_of_role(GetUserId(), newOwnerId);
367 
368  /* New owner must have USAGE privilege on foreign-data wrapper */
369  aclresult = pg_foreign_data_wrapper_aclcheck(form->srvfdw, newOwnerId, ACL_USAGE);
370  if (aclresult != ACLCHECK_OK)
371  {
372  ForeignDataWrapper *fdw = GetForeignDataWrapper(form->srvfdw);
373 
374  aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);
375  }
376  }
377 
378  memset(repl_null, false, sizeof(repl_null));
379  memset(repl_repl, false, sizeof(repl_repl));
380 
381  repl_repl[Anum_pg_foreign_server_srvowner - 1] = true;
382  repl_val[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(newOwnerId);
383 
384  aclDatum = heap_getattr(tup,
385  Anum_pg_foreign_server_srvacl,
386  RelationGetDescr(rel),
387  &isNull);
388  /* Null ACLs do not require changes */
389  if (!isNull)
390  {
391  newAcl = aclnewowner(DatumGetAclP(aclDatum),
392  form->srvowner, newOwnerId);
393  repl_repl[Anum_pg_foreign_server_srvacl - 1] = true;
394  repl_val[Anum_pg_foreign_server_srvacl - 1] = PointerGetDatum(newAcl);
395  }
396 
397  tup = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val, repl_null,
398  repl_repl);
399 
400  CatalogTupleUpdate(rel, &tup->t_self, tup);
401 
402  /* Update owner dependency reference */
403  changeDependencyOnOwner(ForeignServerRelationId, form->oid,
404  newOwnerId);
405  }
406 
407  InvokeObjectPostAlterHook(ForeignServerRelationId,
408  form->oid, 0);
409 }
410 
411 /*
412  * Change foreign server owner -- by name
413  */
415 AlterForeignServerOwner(const char *name, Oid newOwnerId)
416 {
417  Oid servOid;
418  HeapTuple tup;
419  Relation rel;
420  ObjectAddress address;
422 
423  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
424 
426 
427  if (!HeapTupleIsValid(tup))
428  ereport(ERROR,
429  (errcode(ERRCODE_UNDEFINED_OBJECT),
430  errmsg("server \"%s\" does not exist", name)));
431 
432  form = (Form_pg_foreign_server) GETSTRUCT(tup);
433  servOid = form->oid;
434 
435  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
436 
437  ObjectAddressSet(address, ForeignServerRelationId, servOid);
438 
439  heap_freetuple(tup);
440 
442 
443  return address;
444 }
445 
446 /*
447  * Change foreign server owner -- by OID
448  */
449 void
451 {
452  HeapTuple tup;
453  Relation rel;
454 
455  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
456 
458 
459  if (!HeapTupleIsValid(tup))
460  ereport(ERROR,
461  (errcode(ERRCODE_UNDEFINED_OBJECT),
462  errmsg("foreign server with OID %u does not exist", srvId)));
463 
464  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
465 
466  heap_freetuple(tup);
467 
469 }
470 
471 /*
472  * Convert a handler function name passed from the parser to an Oid.
473  */
474 static Oid
476 {
477  Oid handlerOid;
478 
479  if (handler == NULL || handler->arg == NULL)
480  return InvalidOid;
481 
482  /* handlers have no arguments */
483  handlerOid = LookupFuncName((List *) handler->arg, 0, NULL, false);
484 
485  /* check that handler has correct return type */
486  if (get_func_rettype(handlerOid) != FDW_HANDLEROID)
487  ereport(ERROR,
488  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
489  errmsg("function %s must return type %s",
490  NameListToString((List *) handler->arg), "fdw_handler")));
491 
492  return handlerOid;
493 }
494 
495 /*
496  * Convert a validator function name passed from the parser to an Oid.
497  */
498 static Oid
500 {
501  Oid funcargtypes[2];
502 
503  if (validator == NULL || validator->arg == NULL)
504  return InvalidOid;
505 
506  /* validators take text[], oid */
507  funcargtypes[0] = TEXTARRAYOID;
508  funcargtypes[1] = OIDOID;
509 
510  return LookupFuncName((List *) validator->arg, 2, funcargtypes, false);
511  /* validator's return value is ignored, so we don't check the type */
512 }
513 
514 /*
515  * Process function options of CREATE/ALTER FDW
516  */
517 static void
518 parse_func_options(ParseState *pstate, List *func_options,
519  bool *handler_given, Oid *fdwhandler,
520  bool *validator_given, Oid *fdwvalidator)
521 {
522  ListCell *cell;
523 
524  *handler_given = false;
525  *validator_given = false;
526  /* return InvalidOid if not given */
527  *fdwhandler = InvalidOid;
528  *fdwvalidator = InvalidOid;
529 
530  foreach(cell, func_options)
531  {
532  DefElem *def = (DefElem *) lfirst(cell);
533 
534  if (strcmp(def->defname, "handler") == 0)
535  {
536  if (*handler_given)
537  errorConflictingDefElem(def, pstate);
538  *handler_given = true;
539  *fdwhandler = lookup_fdw_handler_func(def);
540  }
541  else if (strcmp(def->defname, "validator") == 0)
542  {
543  if (*validator_given)
544  errorConflictingDefElem(def, pstate);
545  *validator_given = true;
546  *fdwvalidator = lookup_fdw_validator_func(def);
547  }
548  else
549  elog(ERROR, "option \"%s\" not recognized",
550  def->defname);
551  }
552 }
553 
554 /*
555  * Create a foreign-data wrapper
556  */
559 {
560  Relation rel;
561  Datum values[Natts_pg_foreign_data_wrapper];
562  bool nulls[Natts_pg_foreign_data_wrapper];
563  HeapTuple tuple;
564  Oid fdwId;
565  bool handler_given;
566  bool validator_given;
567  Oid fdwhandler;
568  Oid fdwvalidator;
569  Datum fdwoptions;
570  Oid ownerId;
571  ObjectAddress myself;
572  ObjectAddress referenced;
573 
574  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
575 
576  /* Must be super user */
577  if (!superuser())
578  ereport(ERROR,
579  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
580  errmsg("permission denied to create foreign-data wrapper \"%s\"",
581  stmt->fdwname),
582  errhint("Must be superuser to create a foreign-data wrapper.")));
583 
584  /* For now the owner cannot be specified on create. Use effective user ID. */
585  ownerId = GetUserId();
586 
587  /*
588  * Check that there is no other foreign-data wrapper by this name.
589  */
590  if (GetForeignDataWrapperByName(stmt->fdwname, true) != NULL)
591  ereport(ERROR,
593  errmsg("foreign-data wrapper \"%s\" already exists",
594  stmt->fdwname)));
595 
596  /*
597  * Insert tuple into pg_foreign_data_wrapper.
598  */
599  memset(values, 0, sizeof(values));
600  memset(nulls, false, sizeof(nulls));
601 
602  fdwId = GetNewOidWithIndex(rel, ForeignDataWrapperOidIndexId,
603  Anum_pg_foreign_data_wrapper_oid);
604  values[Anum_pg_foreign_data_wrapper_oid - 1] = ObjectIdGetDatum(fdwId);
605  values[Anum_pg_foreign_data_wrapper_fdwname - 1] =
607  values[Anum_pg_foreign_data_wrapper_fdwowner - 1] = ObjectIdGetDatum(ownerId);
608 
609  /* Lookup handler and validator functions, if given */
610  parse_func_options(pstate, stmt->func_options,
611  &handler_given, &fdwhandler,
612  &validator_given, &fdwvalidator);
613 
614  values[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
615  values[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
616 
617  nulls[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
618 
619  fdwoptions = transformGenericOptions(ForeignDataWrapperRelationId,
620  PointerGetDatum(NULL),
621  stmt->options,
622  fdwvalidator);
623 
624  if (PointerIsValid(DatumGetPointer(fdwoptions)))
625  values[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = fdwoptions;
626  else
627  nulls[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
628 
629  tuple = heap_form_tuple(rel->rd_att, values, nulls);
630 
631  CatalogTupleInsert(rel, tuple);
632 
633  heap_freetuple(tuple);
634 
635  /* record dependencies */
636  myself.classId = ForeignDataWrapperRelationId;
637  myself.objectId = fdwId;
638  myself.objectSubId = 0;
639 
640  if (OidIsValid(fdwhandler))
641  {
642  referenced.classId = ProcedureRelationId;
643  referenced.objectId = fdwhandler;
644  referenced.objectSubId = 0;
645  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
646  }
647 
648  if (OidIsValid(fdwvalidator))
649  {
650  referenced.classId = ProcedureRelationId;
651  referenced.objectId = fdwvalidator;
652  referenced.objectSubId = 0;
653  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
654  }
655 
656  recordDependencyOnOwner(ForeignDataWrapperRelationId, fdwId, ownerId);
657 
658  /* dependency on extension */
659  recordDependencyOnCurrentExtension(&myself, false);
660 
661  /* Post creation hook for new foreign data wrapper */
662  InvokeObjectPostCreateHook(ForeignDataWrapperRelationId, fdwId, 0);
663 
665 
666  return myself;
667 }
668 
669 
670 /*
671  * Alter foreign-data wrapper
672  */
675 {
676  Relation rel;
677  HeapTuple tp;
679  Datum repl_val[Natts_pg_foreign_data_wrapper];
680  bool repl_null[Natts_pg_foreign_data_wrapper];
681  bool repl_repl[Natts_pg_foreign_data_wrapper];
682  Oid fdwId;
683  bool isnull;
684  Datum datum;
685  bool handler_given;
686  bool validator_given;
687  Oid fdwhandler;
688  Oid fdwvalidator;
689  ObjectAddress myself;
690 
691  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
692 
693  /* Must be super user */
694  if (!superuser())
695  ereport(ERROR,
696  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
697  errmsg("permission denied to alter foreign-data wrapper \"%s\"",
698  stmt->fdwname),
699  errhint("Must be superuser to alter a foreign-data wrapper.")));
700 
702  CStringGetDatum(stmt->fdwname));
703 
704  if (!HeapTupleIsValid(tp))
705  ereport(ERROR,
706  (errcode(ERRCODE_UNDEFINED_OBJECT),
707  errmsg("foreign-data wrapper \"%s\" does not exist", stmt->fdwname)));
708 
709  fdwForm = (Form_pg_foreign_data_wrapper) GETSTRUCT(tp);
710  fdwId = fdwForm->oid;
711 
712  memset(repl_val, 0, sizeof(repl_val));
713  memset(repl_null, false, sizeof(repl_null));
714  memset(repl_repl, false, sizeof(repl_repl));
715 
716  parse_func_options(pstate, stmt->func_options,
717  &handler_given, &fdwhandler,
718  &validator_given, &fdwvalidator);
719 
720  if (handler_given)
721  {
722  repl_val[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
723  repl_repl[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = true;
724 
725  /*
726  * It could be that the behavior of accessing foreign table changes
727  * with the new handler. Warn about this.
728  */
730  (errmsg("changing the foreign-data wrapper handler can change behavior of existing foreign tables")));
731  }
732 
733  if (validator_given)
734  {
735  repl_val[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
736  repl_repl[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = true;
737 
738  /*
739  * It could be that existing options for the FDW or dependent SERVER,
740  * USER MAPPING or FOREIGN TABLE objects are no longer valid according
741  * to the new validator. Warn about this.
742  */
743  if (OidIsValid(fdwvalidator))
745  (errmsg("changing the foreign-data wrapper validator can cause "
746  "the options for dependent objects to become invalid")));
747  }
748  else
749  {
750  /*
751  * Validator is not changed, but we need it for validating options.
752  */
753  fdwvalidator = fdwForm->fdwvalidator;
754  }
755 
756  /*
757  * If options specified, validate and update.
758  */
759  if (stmt->options)
760  {
761  /* Extract the current options */
763  tp,
764  Anum_pg_foreign_data_wrapper_fdwoptions,
765  &isnull);
766  if (isnull)
767  datum = PointerGetDatum(NULL);
768 
769  /* Transform the options */
770  datum = transformGenericOptions(ForeignDataWrapperRelationId,
771  datum,
772  stmt->options,
773  fdwvalidator);
774 
775  if (PointerIsValid(DatumGetPointer(datum)))
776  repl_val[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = datum;
777  else
778  repl_null[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
779 
780  repl_repl[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
781  }
782 
783  /* Everything looks good - update the tuple */
784  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
785  repl_val, repl_null, repl_repl);
786 
787  CatalogTupleUpdate(rel, &tp->t_self, tp);
788 
789  heap_freetuple(tp);
790 
791  ObjectAddressSet(myself, ForeignDataWrapperRelationId, fdwId);
792 
793  /* Update function dependencies if we changed them */
794  if (handler_given || validator_given)
795  {
796  ObjectAddress referenced;
797 
798  /*
799  * Flush all existing dependency records of this FDW on functions; we
800  * assume there can be none other than the ones we are fixing.
801  */
802  deleteDependencyRecordsForClass(ForeignDataWrapperRelationId,
803  fdwId,
804  ProcedureRelationId,
806 
807  /* And build new ones. */
808 
809  if (OidIsValid(fdwhandler))
810  {
811  referenced.classId = ProcedureRelationId;
812  referenced.objectId = fdwhandler;
813  referenced.objectSubId = 0;
814  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
815  }
816 
817  if (OidIsValid(fdwvalidator))
818  {
819  referenced.classId = ProcedureRelationId;
820  referenced.objectId = fdwvalidator;
821  referenced.objectSubId = 0;
822  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
823  }
824  }
825 
826  InvokeObjectPostAlterHook(ForeignDataWrapperRelationId, fdwId, 0);
827 
829 
830  return myself;
831 }
832 
833 
834 /*
835  * Create a foreign server
836  */
839 {
840  Relation rel;
841  Datum srvoptions;
842  Datum values[Natts_pg_foreign_server];
843  bool nulls[Natts_pg_foreign_server];
844  HeapTuple tuple;
845  Oid srvId;
846  Oid ownerId;
847  AclResult aclresult;
848  ObjectAddress myself;
849  ObjectAddress referenced;
850  ForeignDataWrapper *fdw;
851 
852  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
853 
854  /* For now the owner cannot be specified on create. Use effective user ID. */
855  ownerId = GetUserId();
856 
857  /*
858  * Check that there is no other foreign server by this name. Do nothing if
859  * IF NOT EXISTS was enforced.
860  */
861  if (GetForeignServerByName(stmt->servername, true) != NULL)
862  {
863  if (stmt->if_not_exists)
864  {
865  ereport(NOTICE,
867  errmsg("server \"%s\" already exists, skipping",
868  stmt->servername)));
870  return InvalidObjectAddress;
871  }
872  else
873  ereport(ERROR,
875  errmsg("server \"%s\" already exists",
876  stmt->servername)));
877  }
878 
879  /*
880  * Check that the FDW exists and that we have USAGE on it. Also get the
881  * actual FDW for option validation etc.
882  */
883  fdw = GetForeignDataWrapperByName(stmt->fdwname, false);
884 
885  aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE);
886  if (aclresult != ACLCHECK_OK)
887  aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);
888 
889  /*
890  * Insert tuple into pg_foreign_server.
891  */
892  memset(values, 0, sizeof(values));
893  memset(nulls, false, sizeof(nulls));
894 
895  srvId = GetNewOidWithIndex(rel, ForeignServerOidIndexId,
896  Anum_pg_foreign_server_oid);
897  values[Anum_pg_foreign_server_oid - 1] = ObjectIdGetDatum(srvId);
898  values[Anum_pg_foreign_server_srvname - 1] =
900  values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);
901  values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid);
902 
903  /* Add server type if supplied */
904  if (stmt->servertype)
905  values[Anum_pg_foreign_server_srvtype - 1] =
907  else
908  nulls[Anum_pg_foreign_server_srvtype - 1] = true;
909 
910  /* Add server version if supplied */
911  if (stmt->version)
912  values[Anum_pg_foreign_server_srvversion - 1] =
914  else
915  nulls[Anum_pg_foreign_server_srvversion - 1] = true;
916 
917  /* Start with a blank acl */
918  nulls[Anum_pg_foreign_server_srvacl - 1] = true;
919 
920  /* Add server options */
921  srvoptions = transformGenericOptions(ForeignServerRelationId,
922  PointerGetDatum(NULL),
923  stmt->options,
924  fdw->fdwvalidator);
925 
926  if (PointerIsValid(DatumGetPointer(srvoptions)))
927  values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;
928  else
929  nulls[Anum_pg_foreign_server_srvoptions - 1] = true;
930 
931  tuple = heap_form_tuple(rel->rd_att, values, nulls);
932 
933  CatalogTupleInsert(rel, tuple);
934 
935  heap_freetuple(tuple);
936 
937  /* record dependencies */
938  myself.classId = ForeignServerRelationId;
939  myself.objectId = srvId;
940  myself.objectSubId = 0;
941 
942  referenced.classId = ForeignDataWrapperRelationId;
943  referenced.objectId = fdw->fdwid;
944  referenced.objectSubId = 0;
945  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
946 
947  recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId);
948 
949  /* dependency on extension */
950  recordDependencyOnCurrentExtension(&myself, false);
951 
952  /* Post creation hook for new foreign server */
953  InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0);
954 
956 
957  return myself;
958 }
959 
960 
961 /*
962  * Alter foreign server
963  */
966 {
967  Relation rel;
968  HeapTuple tp;
969  Datum repl_val[Natts_pg_foreign_server];
970  bool repl_null[Natts_pg_foreign_server];
971  bool repl_repl[Natts_pg_foreign_server];
972  Oid srvId;
973  Form_pg_foreign_server srvForm;
974  ObjectAddress address;
975 
976  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
977 
979  CStringGetDatum(stmt->servername));
980 
981  if (!HeapTupleIsValid(tp))
982  ereport(ERROR,
983  (errcode(ERRCODE_UNDEFINED_OBJECT),
984  errmsg("server \"%s\" does not exist", stmt->servername)));
985 
986  srvForm = (Form_pg_foreign_server) GETSTRUCT(tp);
987  srvId = srvForm->oid;
988 
989  /*
990  * Only owner or a superuser can ALTER a SERVER.
991  */
994  stmt->servername);
995 
996  memset(repl_val, 0, sizeof(repl_val));
997  memset(repl_null, false, sizeof(repl_null));
998  memset(repl_repl, false, sizeof(repl_repl));
999 
1000  if (stmt->has_version)
1001  {
1002  /*
1003  * Change the server VERSION string.
1004  */
1005  if (stmt->version)
1006  repl_val[Anum_pg_foreign_server_srvversion - 1] =
1008  else
1009  repl_null[Anum_pg_foreign_server_srvversion - 1] = true;
1010 
1011  repl_repl[Anum_pg_foreign_server_srvversion - 1] = true;
1012  }
1013 
1014  if (stmt->options)
1015  {
1016  ForeignDataWrapper *fdw = GetForeignDataWrapper(srvForm->srvfdw);
1017  Datum datum;
1018  bool isnull;
1019 
1020  /* Extract the current srvoptions */
1022  tp,
1023  Anum_pg_foreign_server_srvoptions,
1024  &isnull);
1025  if (isnull)
1026  datum = PointerGetDatum(NULL);
1027 
1028  /* Prepare the options array */
1029  datum = transformGenericOptions(ForeignServerRelationId,
1030  datum,
1031  stmt->options,
1032  fdw->fdwvalidator);
1033 
1034  if (PointerIsValid(DatumGetPointer(datum)))
1035  repl_val[Anum_pg_foreign_server_srvoptions - 1] = datum;
1036  else
1037  repl_null[Anum_pg_foreign_server_srvoptions - 1] = true;
1038 
1039  repl_repl[Anum_pg_foreign_server_srvoptions - 1] = true;
1040  }
1041 
1042  /* Everything looks good - update the tuple */
1043  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1044  repl_val, repl_null, repl_repl);
1045 
1046  CatalogTupleUpdate(rel, &tp->t_self, tp);
1047 
1048  InvokeObjectPostAlterHook(ForeignServerRelationId, srvId, 0);
1049 
1050  ObjectAddressSet(address, ForeignServerRelationId, srvId);
1051 
1052  heap_freetuple(tp);
1053 
1055 
1056  return address;
1057 }
1058 
1059 
1060 /*
1061  * Common routine to check permission for user-mapping-related DDL
1062  * commands. We allow server owners to operate on any mapping, and
1063  * users to operate on their own mapping.
1064  */
1065 static void
1066 user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
1067 {
1068  Oid curuserid = GetUserId();
1069 
1070  if (!pg_foreign_server_ownercheck(serverid, curuserid))
1071  {
1072  if (umuserid == curuserid)
1073  {
1074  AclResult aclresult;
1075 
1076  aclresult = pg_foreign_server_aclcheck(serverid, curuserid, ACL_USAGE);
1077  if (aclresult != ACLCHECK_OK)
1078  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, servername);
1079  }
1080  else
1082  servername);
1083  }
1084 }
1085 
1086 
1087 /*
1088  * Create user mapping
1089  */
1092 {
1093  Relation rel;
1094  Datum useoptions;
1095  Datum values[Natts_pg_user_mapping];
1096  bool nulls[Natts_pg_user_mapping];
1097  HeapTuple tuple;
1098  Oid useId;
1099  Oid umId;
1100  ObjectAddress myself;
1101  ObjectAddress referenced;
1102  ForeignServer *srv;
1103  ForeignDataWrapper *fdw;
1104  RoleSpec *role = (RoleSpec *) stmt->user;
1105 
1106  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1107 
1108  if (role->roletype == ROLESPEC_PUBLIC)
1109  useId = ACL_ID_PUBLIC;
1110  else
1111  useId = get_rolespec_oid(stmt->user, false);
1112 
1113  /* Check that the server exists. */
1114  srv = GetForeignServerByName(stmt->servername, false);
1115 
1116  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1117 
1118  /*
1119  * Check that the user mapping is unique within server.
1120  */
1121  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1122  ObjectIdGetDatum(useId),
1123  ObjectIdGetDatum(srv->serverid));
1124 
1125  if (OidIsValid(umId))
1126  {
1127  if (stmt->if_not_exists)
1128  {
1129  ereport(NOTICE,
1131  errmsg("user mapping for \"%s\" already exists for server \"%s\", skipping",
1132  MappingUserName(useId),
1133  stmt->servername)));
1134 
1136  return InvalidObjectAddress;
1137  }
1138  else
1139  ereport(ERROR,
1141  errmsg("user mapping for \"%s\" already exists for server \"%s\"",
1142  MappingUserName(useId),
1143  stmt->servername)));
1144  }
1145 
1146  fdw = GetForeignDataWrapper(srv->fdwid);
1147 
1148  /*
1149  * Insert tuple into pg_user_mapping.
1150  */
1151  memset(values, 0, sizeof(values));
1152  memset(nulls, false, sizeof(nulls));
1153 
1154  umId = GetNewOidWithIndex(rel, UserMappingOidIndexId,
1155  Anum_pg_user_mapping_oid);
1156  values[Anum_pg_user_mapping_oid - 1] = ObjectIdGetDatum(umId);
1157  values[Anum_pg_user_mapping_umuser - 1] = ObjectIdGetDatum(useId);
1158  values[Anum_pg_user_mapping_umserver - 1] = ObjectIdGetDatum(srv->serverid);
1159 
1160  /* Add user options */
1161  useoptions = transformGenericOptions(UserMappingRelationId,
1162  PointerGetDatum(NULL),
1163  stmt->options,
1164  fdw->fdwvalidator);
1165 
1166  if (PointerIsValid(DatumGetPointer(useoptions)))
1167  values[Anum_pg_user_mapping_umoptions - 1] = useoptions;
1168  else
1169  nulls[Anum_pg_user_mapping_umoptions - 1] = true;
1170 
1171  tuple = heap_form_tuple(rel->rd_att, values, nulls);
1172 
1173  CatalogTupleInsert(rel, tuple);
1174 
1175  heap_freetuple(tuple);
1176 
1177  /* Add dependency on the server */
1178  myself.classId = UserMappingRelationId;
1179  myself.objectId = umId;
1180  myself.objectSubId = 0;
1181 
1182  referenced.classId = ForeignServerRelationId;
1183  referenced.objectId = srv->serverid;
1184  referenced.objectSubId = 0;
1185  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1186 
1187  if (OidIsValid(useId))
1188  {
1189  /* Record the mapped user dependency */
1190  recordDependencyOnOwner(UserMappingRelationId, umId, useId);
1191  }
1192 
1193  /*
1194  * Perhaps someday there should be a recordDependencyOnCurrentExtension
1195  * call here; but since roles aren't members of extensions, it seems like
1196  * user mappings shouldn't be either. Note that the grammar and pg_dump
1197  * would need to be extended too if we change this.
1198  */
1199 
1200  /* Post creation hook for new user mapping */
1201  InvokeObjectPostCreateHook(UserMappingRelationId, umId, 0);
1202 
1204 
1205  return myself;
1206 }
1207 
1208 
1209 /*
1210  * Alter user mapping
1211  */
1214 {
1215  Relation rel;
1216  HeapTuple tp;
1217  Datum repl_val[Natts_pg_user_mapping];
1218  bool repl_null[Natts_pg_user_mapping];
1219  bool repl_repl[Natts_pg_user_mapping];
1220  Oid useId;
1221  Oid umId;
1222  ForeignServer *srv;
1223  ObjectAddress address;
1224  RoleSpec *role = (RoleSpec *) stmt->user;
1225 
1226  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1227 
1228  if (role->roletype == ROLESPEC_PUBLIC)
1229  useId = ACL_ID_PUBLIC;
1230  else
1231  useId = get_rolespec_oid(stmt->user, false);
1232 
1233  srv = GetForeignServerByName(stmt->servername, false);
1234 
1235  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1236  ObjectIdGetDatum(useId),
1237  ObjectIdGetDatum(srv->serverid));
1238  if (!OidIsValid(umId))
1239  ereport(ERROR,
1240  (errcode(ERRCODE_UNDEFINED_OBJECT),
1241  errmsg("user mapping for \"%s\" does not exist for server \"%s\"",
1242  MappingUserName(useId), stmt->servername)));
1243 
1244  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1245 
1247 
1248  if (!HeapTupleIsValid(tp))
1249  elog(ERROR, "cache lookup failed for user mapping %u", umId);
1250 
1251  memset(repl_val, 0, sizeof(repl_val));
1252  memset(repl_null, false, sizeof(repl_null));
1253  memset(repl_repl, false, sizeof(repl_repl));
1254 
1255  if (stmt->options)
1256  {
1257  ForeignDataWrapper *fdw;
1258  Datum datum;
1259  bool isnull;
1260 
1261  /*
1262  * Process the options.
1263  */
1264 
1265  fdw = GetForeignDataWrapper(srv->fdwid);
1266 
1267  datum = SysCacheGetAttr(USERMAPPINGUSERSERVER,
1268  tp,
1269  Anum_pg_user_mapping_umoptions,
1270  &isnull);
1271  if (isnull)
1272  datum = PointerGetDatum(NULL);
1273 
1274  /* Prepare the options array */
1275  datum = transformGenericOptions(UserMappingRelationId,
1276  datum,
1277  stmt->options,
1278  fdw->fdwvalidator);
1279 
1280  if (PointerIsValid(DatumGetPointer(datum)))
1281  repl_val[Anum_pg_user_mapping_umoptions - 1] = datum;
1282  else
1283  repl_null[Anum_pg_user_mapping_umoptions - 1] = true;
1284 
1285  repl_repl[Anum_pg_user_mapping_umoptions - 1] = true;
1286  }
1287 
1288  /* Everything looks good - update the tuple */
1289  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1290  repl_val, repl_null, repl_repl);
1291 
1292  CatalogTupleUpdate(rel, &tp->t_self, tp);
1293 
1294  InvokeObjectPostAlterHook(UserMappingRelationId,
1295  umId, 0);
1296 
1297  ObjectAddressSet(address, UserMappingRelationId, umId);
1298 
1299  heap_freetuple(tp);
1300 
1302 
1303  return address;
1304 }
1305 
1306 
1307 /*
1308  * Drop user mapping
1309  */
1310 Oid
1312 {
1313  ObjectAddress object;
1314  Oid useId;
1315  Oid umId;
1316  ForeignServer *srv;
1317  RoleSpec *role = (RoleSpec *) stmt->user;
1318 
1319  if (role->roletype == ROLESPEC_PUBLIC)
1320  useId = ACL_ID_PUBLIC;
1321  else
1322  {
1323  useId = get_rolespec_oid(stmt->user, stmt->missing_ok);
1324  if (!OidIsValid(useId))
1325  {
1326  /*
1327  * IF EXISTS specified, role not found and not public. Notice this
1328  * and leave.
1329  */
1330  elog(NOTICE, "role \"%s\" does not exist, skipping",
1331  role->rolename);
1332  return InvalidOid;
1333  }
1334  }
1335 
1336  srv = GetForeignServerByName(stmt->servername, true);
1337 
1338  if (!srv)
1339  {
1340  if (!stmt->missing_ok)
1341  ereport(ERROR,
1342  (errcode(ERRCODE_UNDEFINED_OBJECT),
1343  errmsg("server \"%s\" does not exist",
1344  stmt->servername)));
1345  /* IF EXISTS, just note it */
1346  ereport(NOTICE,
1347  (errmsg("server \"%s\" does not exist, skipping",
1348  stmt->servername)));
1349  return InvalidOid;
1350  }
1351 
1352  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1353  ObjectIdGetDatum(useId),
1354  ObjectIdGetDatum(srv->serverid));
1355 
1356  if (!OidIsValid(umId))
1357  {
1358  if (!stmt->missing_ok)
1359  ereport(ERROR,
1360  (errcode(ERRCODE_UNDEFINED_OBJECT),
1361  errmsg("user mapping for \"%s\" does not exist for server \"%s\"",
1362  MappingUserName(useId), stmt->servername)));
1363 
1364  /* IF EXISTS specified, just note it */
1365  ereport(NOTICE,
1366  (errmsg("user mapping for \"%s\" does not exist for server \"%s\", skipping",
1367  MappingUserName(useId), stmt->servername)));
1368  return InvalidOid;
1369  }
1370 
1371  user_mapping_ddl_aclcheck(useId, srv->serverid, srv->servername);
1372 
1373  /*
1374  * Do the deletion
1375  */
1376  object.classId = UserMappingRelationId;
1377  object.objectId = umId;
1378  object.objectSubId = 0;
1379 
1380  performDeletion(&object, DROP_CASCADE, 0);
1381 
1382  return umId;
1383 }
1384 
1385 
1386 /*
1387  * Create a foreign table
1388  * call after DefineRelation().
1389  */
1390 void
1392 {
1393  Relation ftrel;
1394  Datum ftoptions;
1395  Datum values[Natts_pg_foreign_table];
1396  bool nulls[Natts_pg_foreign_table];
1397  HeapTuple tuple;
1398  AclResult aclresult;
1399  ObjectAddress myself;
1400  ObjectAddress referenced;
1401  Oid ownerId;
1402  ForeignDataWrapper *fdw;
1403  ForeignServer *server;
1404 
1405  /*
1406  * Advance command counter to ensure the pg_attribute tuple is visible;
1407  * the tuple might be updated to add constraints in previous step.
1408  */
1410 
1411  ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
1412 
1413  /*
1414  * For now the owner cannot be specified on create. Use effective user ID.
1415  */
1416  ownerId = GetUserId();
1417 
1418  /*
1419  * Check that the foreign server exists and that we have USAGE on it. Also
1420  * get the actual FDW for option validation etc.
1421  */
1422  server = GetForeignServerByName(stmt->servername, false);
1423  aclresult = pg_foreign_server_aclcheck(server->serverid, ownerId, ACL_USAGE);
1424  if (aclresult != ACLCHECK_OK)
1425  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
1426 
1427  fdw = GetForeignDataWrapper(server->fdwid);
1428 
1429  /*
1430  * Insert tuple into pg_foreign_table.
1431  */
1432  memset(values, 0, sizeof(values));
1433  memset(nulls, false, sizeof(nulls));
1434 
1435  values[Anum_pg_foreign_table_ftrelid - 1] = ObjectIdGetDatum(relid);
1436  values[Anum_pg_foreign_table_ftserver - 1] = ObjectIdGetDatum(server->serverid);
1437  /* Add table generic options */
1438  ftoptions = transformGenericOptions(ForeignTableRelationId,
1439  PointerGetDatum(NULL),
1440  stmt->options,
1441  fdw->fdwvalidator);
1442 
1443  if (PointerIsValid(DatumGetPointer(ftoptions)))
1444  values[Anum_pg_foreign_table_ftoptions - 1] = ftoptions;
1445  else
1446  nulls[Anum_pg_foreign_table_ftoptions - 1] = true;
1447 
1448  tuple = heap_form_tuple(ftrel->rd_att, values, nulls);
1449 
1450  CatalogTupleInsert(ftrel, tuple);
1451 
1452  heap_freetuple(tuple);
1453 
1454  /* Add pg_class dependency on the server */
1455  myself.classId = RelationRelationId;
1456  myself.objectId = relid;
1457  myself.objectSubId = 0;
1458 
1459  referenced.classId = ForeignServerRelationId;
1460  referenced.objectId = server->serverid;
1461  referenced.objectSubId = 0;
1462  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1463 
1464  table_close(ftrel, RowExclusiveLock);
1465 }
1466 
1467 /*
1468  * Import a foreign schema
1469  */
1470 void
1472 {
1473  ForeignServer *server;
1474  ForeignDataWrapper *fdw;
1475  FdwRoutine *fdw_routine;
1476  AclResult aclresult;
1477  List *cmd_list;
1478  ListCell *lc;
1479 
1480  /* Check that the foreign server exists and that we have USAGE on it */
1481  server = GetForeignServerByName(stmt->server_name, false);
1482  aclresult = pg_foreign_server_aclcheck(server->serverid, GetUserId(), ACL_USAGE);
1483  if (aclresult != ACLCHECK_OK)
1484  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
1485 
1486  /* Check that the schema exists and we have CREATE permissions on it */
1487  (void) LookupCreationNamespace(stmt->local_schema);
1488 
1489  /* Get the FDW and check it supports IMPORT */
1490  fdw = GetForeignDataWrapper(server->fdwid);
1491  if (!OidIsValid(fdw->fdwhandler))
1492  ereport(ERROR,
1493  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1494  errmsg("foreign-data wrapper \"%s\" has no handler",
1495  fdw->fdwname)));
1496  fdw_routine = GetFdwRoutine(fdw->fdwhandler);
1497  if (fdw_routine->ImportForeignSchema == NULL)
1498  ereport(ERROR,
1499  (errcode(ERRCODE_FDW_NO_SCHEMAS),
1500  errmsg("foreign-data wrapper \"%s\" does not support IMPORT FOREIGN SCHEMA",
1501  fdw->fdwname)));
1502 
1503  /* Call FDW to get a list of commands */
1504  cmd_list = fdw_routine->ImportForeignSchema(stmt, server->serverid);
1505 
1506  /* Parse and execute each command */
1507  foreach(lc, cmd_list)
1508  {
1509  char *cmd = (char *) lfirst(lc);
1510  import_error_callback_arg callback_arg;
1511  ErrorContextCallback sqlerrcontext;
1512  List *raw_parsetree_list;
1513  ListCell *lc2;
1514 
1515  /*
1516  * Setup error traceback support for ereport(). This is so that any
1517  * error in the generated SQL will be displayed nicely.
1518  */
1519  callback_arg.tablename = NULL; /* not known yet */
1520  callback_arg.cmd = cmd;
1521  sqlerrcontext.callback = import_error_callback;
1522  sqlerrcontext.arg = (void *) &callback_arg;
1523  sqlerrcontext.previous = error_context_stack;
1524  error_context_stack = &sqlerrcontext;
1525 
1526  /*
1527  * Parse the SQL string into a list of raw parse trees.
1528  */
1529  raw_parsetree_list = pg_parse_query(cmd);
1530 
1531  /*
1532  * Process each parse tree (we allow the FDW to put more than one
1533  * command per string, though this isn't really advised).
1534  */
1535  foreach(lc2, raw_parsetree_list)
1536  {
1537  RawStmt *rs = lfirst_node(RawStmt, lc2);
1539  PlannedStmt *pstmt;
1540 
1541  /*
1542  * Because we only allow CreateForeignTableStmt, we can skip parse
1543  * analysis, rewrite, and planning steps here.
1544  */
1545  if (!IsA(cstmt, CreateForeignTableStmt))
1546  elog(ERROR,
1547  "foreign-data wrapper \"%s\" returned incorrect statement type %d",
1548  fdw->fdwname, (int) nodeTag(cstmt));
1549 
1550  /* Ignore commands for tables excluded by filter options */
1551  if (!IsImportableForeignTable(cstmt->base.relation->relname, stmt))
1552  continue;
1553 
1554  /* Enable reporting of current table's name on error */
1555  callback_arg.tablename = cstmt->base.relation->relname;
1556 
1557  /* Ensure creation schema is the one given in IMPORT statement */
1558  cstmt->base.relation->schemaname = pstrdup(stmt->local_schema);
1559 
1560  /* No planning needed, just make a wrapper PlannedStmt */
1561  pstmt = makeNode(PlannedStmt);
1562  pstmt->commandType = CMD_UTILITY;
1563  pstmt->canSetTag = false;
1564  pstmt->utilityStmt = (Node *) cstmt;
1565  pstmt->stmt_location = rs->stmt_location;
1566  pstmt->stmt_len = rs->stmt_len;
1567 
1568  /* Execute statement */
1569  ProcessUtility(pstmt, cmd, false,
1570  PROCESS_UTILITY_SUBCOMMAND, NULL, NULL,
1571  None_Receiver, NULL);
1572 
1573  /* Be sure to advance the command counter between subcommands */
1575 
1576  callback_arg.tablename = NULL;
1577  }
1578 
1579  error_context_stack = sqlerrcontext.previous;
1580  }
1581 }
1582 
1583 /*
1584  * error context callback to let us supply the failing SQL statement's text
1585  */
1586 static void
1588 {
1589  import_error_callback_arg *callback_arg = (import_error_callback_arg *) arg;
1590  int syntaxerrposition;
1591 
1592  /* If it's a syntax error, convert to internal syntax error report */
1593  syntaxerrposition = geterrposition();
1594  if (syntaxerrposition > 0)
1595  {
1596  errposition(0);
1597  internalerrposition(syntaxerrposition);
1598  internalerrquery(callback_arg->cmd);
1599  }
1600 
1601  if (callback_arg->tablename)
1602  errcontext("importing foreign table \"%s\"",
1603  callback_arg->tablename);
1604 }
RangeVar * relation
Definition: parsenodes.h:2170
ObjectAddress AlterForeignServer(AlterForeignServerStmt *stmt)
Definition: foreigncmds.c:965
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
void CreateForeignTable(CreateForeignTableStmt *stmt, Oid relid)
Definition: foreigncmds.c:1391
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
ObjectAddress CreateForeignDataWrapper(ParseState *pstate, CreateFdwStmt *stmt)
Definition: foreigncmds.c:558
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define VARDATA(PTR)
Definition: postgres.h:315
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
void AlterForeignDataWrapperOwner_oid(Oid fwdId, Oid newOwnerId)
Definition: foreigncmds.c:313
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
char * fdwname
Definition: foreign.h:28
#define DatumGetAclP(X)
Definition: acl.h:120
#define PointerGetDatum(X)
Definition: postgres.h:600
Oid LookupCreationNamespace(const char *nspname)
Definition: namespace.c:2981
#define VARHDRSZ
Definition: c.h:627
char * pstrdup(const char *in)
Definition: mcxt.c:1299
AclResult pg_foreign_data_wrapper_aclcheck(Oid fdw_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4781
bool pg_foreign_server_ownercheck(Oid srv_oid, Oid roleid)
Definition: aclchk.c:5182
void AlterForeignServerOwner_oid(Oid srvId, Oid newOwnerId)
Definition: foreigncmds.c:450
DefElemAction defaction
Definition: parsenodes.h:748
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1066
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:163
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3439
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
DestReceiver * None_Receiver
Definition: dest.c:96
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
#define OidIsValid(objectId)
Definition: c.h:710
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1626
char * schemaname
Definition: primnodes.h:67
ErrorContextCallback * error_context_stack
Definition: elog.c:93
static Oid lookup_fdw_validator_func(DefElem *validator)
Definition: foreigncmds.c:499
FdwRoutine * GetFdwRoutine(Oid fdwhandler)
Definition: foreign.c:319
char * relname
Definition: primnodes.h:68
#define sprintf
Definition: port.h:218
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:311
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
List * options
Definition: parsenodes.h:2378
static Oid lookup_fdw_handler_func(DefElem *handler)
Definition: foreigncmds.c:475
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:503
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
char * defGetString(DefElem *def)
Definition: define.c:49
List * pg_parse_query(const char *query_string)
Definition: postgres.c:594
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2145
ItemPointerData t_self
Definition: htup.h:65
ObjectAddress AlterForeignDataWrapperOwner(const char *name, Oid newOwnerId)
Definition: foreigncmds.c:275
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Oid RemoveUserMapping(DropUserMappingStmt *stmt)
Definition: foreigncmds.c:1311
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4794
ObjectAddress CreateUserMapping(CreateUserMappingStmt *stmt)
Definition: foreigncmds.c:1091
bool IsImportableForeignTable(const char *tablename, ImportForeignSchemaStmt *stmt)
Definition: foreign.c:467
Node * stmt
Definition: parsenodes.h:1560
#define RowExclusiveLock
Definition: lockdefs.h:38
char * fdwname
Definition: parsenodes.h:2376
#define CStringGetDatum(X)
Definition: postgres.h:622
int geterrposition(void)
Definition: elog.c:1417
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:313
char * fdwname
Definition: parsenodes.h:2384
#define ACL_USAGE
Definition: parsenodes.h:90
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
ImportForeignSchema_function ImportForeignSchema
Definition: fdwapi.h:260
ObjectAddress AlterUserMapping(AlterUserMappingStmt *stmt)
Definition: foreigncmds.c:1213
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4893
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5151
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
Node * arg
Definition: parsenodes.h:747
List * lappend(List *list, void *datum)
Definition: list.c:336
ObjectAddress AlterForeignDataWrapper(ParseState *pstate, AlterFdwStmt *stmt)
Definition: foreigncmds.c:674
List * func_options
Definition: parsenodes.h:2385
#define WARNING
Definition: elog.h:40
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:761
ObjectAddress CreateForeignServer(CreateForeignServerStmt *stmt)
Definition: foreigncmds.c:838
char * NameListToString(List *names)
Definition: namespace.c:3147
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void CommandCounterIncrement(void)
Definition: xact.c:1021
RoleSpecType roletype
Definition: parsenodes.h:339
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5128
int stmt_len
Definition: parsenodes.h:1562
int stmt_location
Definition: parsenodes.h:1561
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1325
TupleDesc rd_att
Definition: rel.h:110
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:286
List * list_delete_cell(List *list, ListCell *cell)
Definition: list.c:782
FormData_pg_foreign_server * Form_pg_foreign_server
#define InvalidOid
Definition: postgres_ext.h:36
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
int internalerrquery(const char *query)
Definition: elog.c:1321
#define NOTICE
Definition: elog.h:37
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:169
ObjectAddress AlterForeignServerOwner(const char *name, Oid newOwnerId)
Definition: foreigncmds.c:415
FormData_pg_foreign_data_wrapper * Form_pg_foreign_data_wrapper
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:94
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:184
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:195
static void parse_func_options(ParseState *pstate, List *func_options, bool *handler_given, Oid *fdwhandler, bool *validator_given, Oid *fdwvalidator)
Definition: foreigncmds.c:518
size_t Size
Definition: c.h:540
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:338
char * rolename
Definition: parsenodes.h:340
const char * name
Definition: encode.c:515
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:593
List * options
Definition: parsenodes.h:2386
static Datum values[MAXATTR]
Definition: bootstrap.c:166
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5087
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define OidFunctionCall2(functionId, arg1, arg2)
Definition: fmgr.h:666
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:1062
void ImportForeignSchema(ImportForeignSchemaStmt *stmt)
Definition: foreigncmds.c:1471
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * servername
Definition: foreign.h:39
#define elog(elevel,...)
Definition: elog.h:232
#define errcontext
Definition: elog.h:204
#define NameStr(name)
Definition: c.h:681
#define CStringGetTextDatum(s)
Definition: builtins.h:82
#define ACL_ID_PUBLIC
Definition: acl.h:46
void * arg
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:205
Definition: c.h:621
char * defname
Definition: parsenodes.h:746
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:342
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
#define PointerIsValid(pointer)
Definition: c.h:698
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1037
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
Oid serverid
Definition: foreign.h:36
#define MappingUserName(userid)
Definition: foreign.h:20
int errposition(int cursorpos)
Definition: elog.c:1285
List * func_options
Definition: parsenodes.h:2377
static Datum optionListToArray(List *options)
Definition: foreigncmds.c:66
static void import_error_callback(void *arg)
Definition: foreigncmds.c:1587
int internalerrposition(int cursorpos)
Definition: elog.c:1301