PostgreSQL Source Code  git master
defrem.h File Reference
#include "catalog/objectaddress.h"
#include "nodes/parsenodes.h"
#include "utils/array.h"
Include dependency graph for defrem.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void RemoveObjects (DropStmt *stmt)
 
ObjectAddress DefineIndex (Oid relationId, IndexStmt *stmt, Oid indexRelationId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
 
Oid ReindexIndex (RangeVar *indexRelation, int options)
 
Oid ReindexTable (RangeVar *relation, int options)
 
void ReindexMultipleTables (const char *objectName, ReindexObjectType objectKind, int options)
 
char * makeObjectName (const char *name1, const char *name2, const char *label)
 
char * ChooseRelationName (const char *name1, const char *name2, const char *label, Oid namespaceid)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
Oid ResolveOpClass (List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
 
ObjectAddress CreateFunction (ParseState *pstate, CreateFunctionStmt *stmt)
 
void RemoveFunctionById (Oid funcOid)
 
void SetFunctionReturnType (Oid funcOid, Oid newRetType)
 
void SetFunctionArgType (Oid funcOid, int argIndex, Oid newArgType)
 
ObjectAddress AlterFunction (ParseState *pstate, AlterFunctionStmt *stmt)
 
ObjectAddress CreateCast (CreateCastStmt *stmt)
 
void DropCastById (Oid castOid)
 
ObjectAddress CreateTransform (CreateTransformStmt *stmt)
 
void DropTransformById (Oid transformOid)
 
void IsThereFunctionInNamespace (const char *proname, int pronargs, oidvector *proargtypes, Oid nspOid)
 
void ExecuteDoStmt (DoStmt *stmt)
 
Oid get_cast_oid (Oid sourcetypeid, Oid targettypeid, bool missing_ok)
 
Oid get_transform_oid (Oid type_id, Oid lang_id, bool missing_ok)
 
void interpret_function_parameter_list (ParseState *pstate, List *parameters, Oid languageOid, bool is_aggregate, oidvector **parameterTypes, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
 
ObjectAddress DefineOperator (List *names, List *parameters)
 
void RemoveOperatorById (Oid operOid)
 
ObjectAddress AlterOperator (AlterOperatorStmt *stmt)
 
ObjectAddress CreateStatistics (CreateStatsStmt *stmt)
 
void RemoveStatisticsById (Oid statsOid)
 
void UpdateStatisticsForTypeChange (Oid statsOid, Oid relationOid, int attnum, Oid oldColumnType, Oid newColumnType)
 
ObjectAddress DefineAggregate (ParseState *pstate, List *name, List *args, bool oldstyle, List *parameters)
 
ObjectAddress DefineOpClass (CreateOpClassStmt *stmt)
 
ObjectAddress DefineOpFamily (CreateOpFamilyStmt *stmt)
 
Oid AlterOpFamily (AlterOpFamilyStmt *stmt)
 
void RemoveOpClassById (Oid opclassOid)
 
void RemoveOpFamilyById (Oid opfamilyOid)
 
void RemoveAmOpEntryById (Oid entryOid)
 
void RemoveAmProcEntryById (Oid entryOid)
 
void IsThereOpClassInNamespace (const char *opcname, Oid opcmethod, Oid opcnamespace)
 
void IsThereOpFamilyInNamespace (const char *opfname, Oid opfmethod, Oid opfnamespace)
 
Oid get_opclass_oid (Oid amID, List *opclassname, bool missing_ok)
 
Oid get_opfamily_oid (Oid amID, List *opfamilyname, bool missing_ok)
 
ObjectAddress DefineTSParser (List *names, List *parameters)
 
void RemoveTSParserById (Oid prsId)
 
ObjectAddress DefineTSDictionary (List *names, List *parameters)
 
void RemoveTSDictionaryById (Oid dictId)
 
ObjectAddress AlterTSDictionary (AlterTSDictionaryStmt *stmt)
 
ObjectAddress DefineTSTemplate (List *names, List *parameters)
 
void RemoveTSTemplateById (Oid tmplId)
 
ObjectAddress DefineTSConfiguration (List *names, List *parameters, ObjectAddress *copied)
 
void RemoveTSConfigurationById (Oid cfgId)
 
ObjectAddress AlterTSConfiguration (AlterTSConfigurationStmt *stmt)
 
textserialize_deflist (List *deflist)
 
Listdeserialize_deflist (Datum txt)
 
ObjectAddress AlterForeignServerOwner (const char *name, Oid newOwnerId)
 
void AlterForeignServerOwner_oid (Oid, Oid newOwnerId)
 
ObjectAddress AlterForeignDataWrapperOwner (const char *name, Oid newOwnerId)
 
void AlterForeignDataWrapperOwner_oid (Oid fwdId, Oid newOwnerId)
 
ObjectAddress CreateForeignDataWrapper (CreateFdwStmt *stmt)
 
ObjectAddress AlterForeignDataWrapper (AlterFdwStmt *stmt)
 
void RemoveForeignDataWrapperById (Oid fdwId)
 
ObjectAddress CreateForeignServer (CreateForeignServerStmt *stmt)
 
ObjectAddress AlterForeignServer (AlterForeignServerStmt *stmt)
 
void RemoveForeignServerById (Oid srvId)
 
ObjectAddress CreateUserMapping (CreateUserMappingStmt *stmt)
 
ObjectAddress AlterUserMapping (AlterUserMappingStmt *stmt)
 
Oid RemoveUserMapping (DropUserMappingStmt *stmt)
 
void RemoveUserMappingById (Oid umId)
 
void CreateForeignTable (CreateForeignTableStmt *stmt, Oid relid)
 
void ImportForeignSchema (ImportForeignSchemaStmt *stmt)
 
Datum transformGenericOptions (Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
 
ObjectAddress CreateAccessMethod (CreateAmStmt *stmt)
 
void RemoveAccessMethodById (Oid amOid)
 
Oid get_index_am_oid (const char *amname, bool missing_ok)
 
Oid get_am_oid (const char *amname, bool missing_ok)
 
char * get_am_name (Oid amOid)
 
char * defGetString (DefElem *def)
 
double defGetNumeric (DefElem *def)
 
bool defGetBoolean (DefElem *def)
 
int32 defGetInt32 (DefElem *def)
 
int64 defGetInt64 (DefElem *def)
 
ListdefGetQualifiedName (DefElem *def)
 
TypeNamedefGetTypeName (DefElem *def)
 
int defGetTypeLength (DefElem *def)
 
ListdefGetStringList (DefElem *def)
 

Function Documentation

◆ AlterForeignDataWrapper()

ObjectAddress AlterForeignDataWrapper ( AlterFdwStmt stmt)

Definition at line 673 of file foreigncmds.c.

References Anum_pg_foreign_data_wrapper_fdwhandler, Anum_pg_foreign_data_wrapper_fdwoptions, Anum_pg_foreign_data_wrapper_fdwvalidator, CatalogTupleUpdate(), ObjectAddress::classId, CStringGetDatum, DatumGetPointer, deleteDependencyRecordsForClass(), DEPENDENCY_NORMAL, ereport, errcode(), errhint(), errmsg(), ERROR, AlterFdwStmt::fdwname, FOREIGNDATAWRAPPERNAME, FOREIGNDATAWRAPPEROID, ForeignDataWrapperRelationId, AlterFdwStmt::func_options, GETSTRUCT, heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, Natts_pg_foreign_data_wrapper, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, AlterFdwStmt::options, parse_func_options(), PointerGetDatum, PointerIsValid, ProcedureRelationId, recordDependencyOn(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, superuser(), SysCacheGetAttr(), HeapTupleData::t_self, transformGenericOptions(), and WARNING.

Referenced by ProcessUtilitySlow().

674 {
675  Relation rel;
676  HeapTuple tp;
679  bool repl_null[Natts_pg_foreign_data_wrapper];
680  bool repl_repl[Natts_pg_foreign_data_wrapper];
681  Oid fdwId;
682  bool isnull;
683  Datum datum;
684  bool handler_given;
685  bool validator_given;
686  Oid fdwhandler;
687  Oid fdwvalidator;
688  ObjectAddress myself;
689 
691 
692  /* Must be super user */
693  if (!superuser())
694  ereport(ERROR,
695  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
696  errmsg("permission denied to alter foreign-data wrapper \"%s\"",
697  stmt->fdwname),
698  errhint("Must be superuser to alter a foreign-data wrapper.")));
699 
701  CStringGetDatum(stmt->fdwname));
702 
703  if (!HeapTupleIsValid(tp))
704  ereport(ERROR,
705  (errcode(ERRCODE_UNDEFINED_OBJECT),
706  errmsg("foreign-data wrapper \"%s\" does not exist", stmt->fdwname)));
707 
708  fdwForm = (Form_pg_foreign_data_wrapper) GETSTRUCT(tp);
709  fdwId = HeapTupleGetOid(tp);
710 
711  memset(repl_val, 0, sizeof(repl_val));
712  memset(repl_null, false, sizeof(repl_null));
713  memset(repl_repl, false, sizeof(repl_repl));
714 
716  &handler_given, &fdwhandler,
717  &validator_given, &fdwvalidator);
718 
719  if (handler_given)
720  {
721  repl_val[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
722  repl_repl[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = true;
723 
724  /*
725  * It could be that the behavior of accessing foreign table changes
726  * with the new handler. Warn about this.
727  */
729  (errmsg("changing the foreign-data wrapper handler can change behavior of existing foreign tables")));
730  }
731 
732  if (validator_given)
733  {
734  repl_val[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
735  repl_repl[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = true;
736 
737  /*
738  * It could be that existing options for the FDW or dependent SERVER,
739  * USER MAPPING or FOREIGN TABLE objects are no longer valid according
740  * to the new validator. Warn about this.
741  */
742  if (OidIsValid(fdwvalidator))
744  (errmsg("changing the foreign-data wrapper validator can cause "
745  "the options for dependent objects to become invalid")));
746  }
747  else
748  {
749  /*
750  * Validator is not changed, but we need it for validating options.
751  */
752  fdwvalidator = fdwForm->fdwvalidator;
753  }
754 
755  /*
756  * If options specified, validate and update.
757  */
758  if (stmt->options)
759  {
760  /* Extract the current options */
762  tp,
764  &isnull);
765  if (isnull)
766  datum = PointerGetDatum(NULL);
767 
768  /* Transform the options */
770  datum,
771  stmt->options,
772  fdwvalidator);
773 
774  if (PointerIsValid(DatumGetPointer(datum)))
775  repl_val[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = datum;
776  else
777  repl_null[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
778 
779  repl_repl[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
780  }
781 
782  /* Everything looks good - update the tuple */
783  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
784  repl_val, repl_null, repl_repl);
785 
786  CatalogTupleUpdate(rel, &tp->t_self, tp);
787 
788  heap_freetuple(tp);
789 
791 
792  /* Update function dependencies if we changed them */
793  if (handler_given || validator_given)
794  {
795  ObjectAddress referenced;
796 
797  /*
798  * Flush all existing dependency records of this FDW on functions; we
799  * assume there can be none other than the ones we are fixing.
800  */
802  fdwId,
805 
806  /* And build new ones. */
807 
808  if (OidIsValid(fdwhandler))
809  {
810  referenced.classId = ProcedureRelationId;
811  referenced.objectId = fdwhandler;
812  referenced.objectSubId = 0;
813  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
814  }
815 
816  if (OidIsValid(fdwvalidator))
817  {
818  referenced.classId = ProcedureRelationId;
819  referenced.objectId = fdwvalidator;
820  referenced.objectSubId = 0;
821  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
822  }
823  }
824 
826 
828 
829  return myself;
830 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
static void parse_func_options(List *func_options, bool *handler_given, Oid *fdwhandler, bool *validator_given, Oid *fdwvalidator)
Definition: foreigncmds.c:516
#define RelationGetDescr(relation)
Definition: rel.h:437
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define ProcedureRelationId
Definition: pg_proc.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define Anum_pg_foreign_data_wrapper_fdwhandler
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
char * fdwname
Definition: parsenodes.h:2217
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
List * func_options
Definition: parsenodes.h:2218
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:241
#define Anum_pg_foreign_data_wrapper_fdwvalidator
#define Natts_pg_foreign_data_wrapper
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_foreign_data_wrapper * Form_pg_foreign_data_wrapper
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ForeignDataWrapperRelationId
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:555
List * options
Definition: parsenodes.h:2219
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define PointerIsValid(pointer)
Definition: c.h:564
#define Anum_pg_foreign_data_wrapper_fdwoptions

◆ AlterForeignDataWrapperOwner()

ObjectAddress AlterForeignDataWrapperOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 277 of file foreigncmds.c.

References AlterForeignDataWrapperOwner_internal(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, FOREIGNDATAWRAPPERNAME, ForeignDataWrapperRelationId, heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, ObjectAddressSet, RowExclusiveLock, and SearchSysCacheCopy1.

Referenced by ExecAlterOwnerStmt().

278 {
279  Oid fdwId;
280  HeapTuple tup;
281  Relation rel;
282  ObjectAddress address;
283 
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 
293  fdwId = HeapTupleGetOid(tup);
294 
295  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
296 
298 
299  heap_freetuple(tup);
300 
302 
303  return address;
304 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define ForeignDataWrapperRelationId
const char * name
Definition: encode.c:521
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:207
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ AlterForeignDataWrapperOwner_oid()

void AlterForeignDataWrapperOwner_oid ( Oid  fwdId,
Oid  newOwnerId 
)

Definition at line 312 of file foreigncmds.c.

References AlterForeignDataWrapperOwner_internal(), ereport, errcode(), errmsg(), ERROR, FOREIGNDATAWRAPPEROID, ForeignDataWrapperRelationId, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, ObjectIdGetDatum, RowExclusiveLock, and SearchSysCacheCopy1.

Referenced by shdepReassignOwned().

313 {
314  HeapTuple tup;
315  Relation rel;
316 
318 
320 
321  if (!HeapTupleIsValid(tup))
322  ereport(ERROR,
323  (errcode(ERRCODE_UNDEFINED_OBJECT),
324  errmsg("foreign-data wrapper with OID %u does not exist", fwdId)));
325 
326  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
327 
328  heap_freetuple(tup);
329 
331 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define ForeignDataWrapperRelationId
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:207

◆ AlterForeignServer()

ObjectAddress AlterForeignServer ( AlterForeignServerStmt stmt)

Definition at line 985 of file foreigncmds.c.

References ACL_KIND_FOREIGN_SERVER, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_foreign_server_srvoptions, Anum_pg_foreign_server_srvversion, CatalogTupleUpdate(), CStringGetDatum, CStringGetTextDatum, DatumGetPointer, ereport, errcode(), errmsg(), ERROR, ForeignDataWrapper::fdwvalidator, FOREIGNSERVERNAME, FOREIGNSERVEROID, ForeignServerRelationId, GetForeignDataWrapper(), GETSTRUCT, GetUserId(), AlterForeignServerStmt::has_version, heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, Natts_pg_foreign_server, ObjectAddressSet, AlterForeignServerStmt::options, pg_foreign_server_ownercheck(), PointerGetDatum, PointerIsValid, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, AlterForeignServerStmt::servername, SysCacheGetAttr(), HeapTupleData::t_self, transformGenericOptions(), and AlterForeignServerStmt::version.

Referenced by ProcessUtilitySlow().

986 {
987  Relation rel;
988  HeapTuple tp;
989  Datum repl_val[Natts_pg_foreign_server];
990  bool repl_null[Natts_pg_foreign_server];
991  bool repl_repl[Natts_pg_foreign_server];
992  Oid srvId;
993  Form_pg_foreign_server srvForm;
994  ObjectAddress address;
995 
997 
999  CStringGetDatum(stmt->servername));
1000 
1001  if (!HeapTupleIsValid(tp))
1002  ereport(ERROR,
1003  (errcode(ERRCODE_UNDEFINED_OBJECT),
1004  errmsg("server \"%s\" does not exist", stmt->servername)));
1005 
1006  srvId = HeapTupleGetOid(tp);
1007  srvForm = (Form_pg_foreign_server) GETSTRUCT(tp);
1008 
1009  /*
1010  * Only owner or a superuser can ALTER a SERVER.
1011  */
1012  if (!pg_foreign_server_ownercheck(srvId, GetUserId()))
1014  stmt->servername);
1015 
1016  memset(repl_val, 0, sizeof(repl_val));
1017  memset(repl_null, false, sizeof(repl_null));
1018  memset(repl_repl, false, sizeof(repl_repl));
1019 
1020  if (stmt->has_version)
1021  {
1022  /*
1023  * Change the server VERSION string.
1024  */
1025  if (stmt->version)
1026  repl_val[Anum_pg_foreign_server_srvversion - 1] =
1028  else
1029  repl_null[Anum_pg_foreign_server_srvversion - 1] = true;
1030 
1031  repl_repl[Anum_pg_foreign_server_srvversion - 1] = true;
1032  }
1033 
1034  if (stmt->options)
1035  {
1036  ForeignDataWrapper *fdw = GetForeignDataWrapper(srvForm->srvfdw);
1037  Datum datum;
1038  bool isnull;
1039 
1040  /* Extract the current srvoptions */
1042  tp,
1044  &isnull);
1045  if (isnull)
1046  datum = PointerGetDatum(NULL);
1047 
1048  /* Prepare the options array */
1050  datum,
1051  stmt->options,
1052  fdw->fdwvalidator);
1053 
1054  if (PointerIsValid(DatumGetPointer(datum)))
1055  repl_val[Anum_pg_foreign_server_srvoptions - 1] = datum;
1056  else
1057  repl_null[Anum_pg_foreign_server_srvoptions - 1] = true;
1058 
1059  repl_repl[Anum_pg_foreign_server_srvoptions - 1] = true;
1060  }
1061 
1062  /* Everything looks good - update the tuple */
1063  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1064  repl_val, repl_null, repl_repl);
1065 
1066  CatalogTupleUpdate(rel, &tp->t_self, tp);
1067 
1069 
1070  ObjectAddressSet(address, ForeignServerRelationId, srvId);
1071 
1072  heap_freetuple(tp);
1073 
1075 
1076  return address;
1077 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define Anum_pg_foreign_server_srvversion
#define PointerGetDatum(X)
Definition: postgres.h:562
bool pg_foreign_server_ownercheck(Oid srv_oid, Oid roleid)
Definition: aclchk.c:4910
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define Natts_pg_foreign_server
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
FormData_pg_foreign_server * Form_pg_foreign_server
#define ForeignServerRelationId
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:555
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
#define Anum_pg_foreign_server_srvoptions
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define PointerIsValid(pointer)
Definition: c.h:564

◆ AlterForeignServerOwner()

ObjectAddress AlterForeignServerOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 414 of file foreigncmds.c.

References AlterForeignServerOwner_internal(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, FOREIGNSERVERNAME, ForeignServerRelationId, heap_close, heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, ObjectAddressSet, RowExclusiveLock, and SearchSysCacheCopy1.

Referenced by ExecAlterOwnerStmt().

415 {
416  Oid servOid;
417  HeapTuple tup;
418  Relation rel;
419  ObjectAddress address;
420 
422 
424 
425  if (!HeapTupleIsValid(tup))
426  ereport(ERROR,
427  (errcode(ERRCODE_UNDEFINED_OBJECT),
428  errmsg("server \"%s\" does not exist", name)));
429 
430  servOid = HeapTupleGetOid(tup);
431 
432  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
433 
434  ObjectAddressSet(address, ForeignServerRelationId, servOid);
435 
436  heap_freetuple(tup);
437 
439 
440  return address;
441 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define ForeignServerRelationId
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:337
const char * name
Definition: encode.c:521
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ AlterForeignServerOwner_oid()

void AlterForeignServerOwner_oid ( Oid  ,
Oid  newOwnerId 
)

Definition at line 447 of file foreigncmds.c.

References AlterForeignServerOwner_internal(), ereport, errcode(), errmsg(), ERROR, FOREIGNSERVEROID, ForeignServerRelationId, heap_close, heap_freetuple(), heap_open(), HeapTupleIsValid, ObjectIdGetDatum, RowExclusiveLock, and SearchSysCacheCopy1.

Referenced by shdepReassignOwned().

448 {
449  HeapTuple tup;
450  Relation rel;
451 
453 
455 
456  if (!HeapTupleIsValid(tup))
457  ereport(ERROR,
458  (errcode(ERRCODE_UNDEFINED_OBJECT),
459  errmsg("foreign server with OID %u does not exist", srvId)));
460 
461  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
462 
463  heap_freetuple(tup);
464 
466 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define ForeignServerRelationId
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:337
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ AlterFunction()

ObjectAddress AlterFunction ( ParseState pstate,
AlterFunctionStmt stmt 
)

Definition at line 1166 of file functioncmds.c.

References ACL_KIND_PROC, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterFunctionStmt::actions, Anum_pg_proc_proconfig, DefElem::arg, CatalogTupleUpdate(), compute_common_attribute(), DatumGetArrayTypeP, defGetNumeric(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, AlterFunctionStmt::func, GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, interpret_func_parallel(), interpret_func_volatility(), intVal, InvokeObjectPostAlterHook, lfirst, LookupFuncWithArgs(), NameListToString(), Natts_pg_proc, NIL, NoLock, ObjectAddressSet, ObjectIdGetDatum, ObjectWithArgs::objname, pg_proc_ownercheck(), PointerGetDatum, ProcedureRelationId, PROCOID, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, superuser(), SysCacheGetAttr(), HeapTupleData::t_self, and update_proconfig_value().

Referenced by ProcessUtilitySlow().

1167 {
1168  HeapTuple tup;
1169  Oid funcOid;
1170  Form_pg_proc procForm;
1171  Relation rel;
1172  ListCell *l;
1173  DefElem *volatility_item = NULL;
1174  DefElem *strict_item = NULL;
1175  DefElem *security_def_item = NULL;
1176  DefElem *leakproof_item = NULL;
1177  List *set_items = NIL;
1178  DefElem *cost_item = NULL;
1179  DefElem *rows_item = NULL;
1180  DefElem *parallel_item = NULL;
1181  ObjectAddress address;
1182 
1184 
1185  funcOid = LookupFuncWithArgs(stmt->func, false);
1186 
1187  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1188  if (!HeapTupleIsValid(tup)) /* should not happen */
1189  elog(ERROR, "cache lookup failed for function %u", funcOid);
1190 
1191  procForm = (Form_pg_proc) GETSTRUCT(tup);
1192 
1193  /* Permission check: must own function */
1194  if (!pg_proc_ownercheck(funcOid, GetUserId()))
1196  NameListToString(stmt->func->objname));
1197 
1198  if (procForm->proisagg)
1199  ereport(ERROR,
1200  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1201  errmsg("\"%s\" is an aggregate function",
1202  NameListToString(stmt->func->objname))));
1203 
1204  /* Examine requested actions. */
1205  foreach(l, stmt->actions)
1206  {
1207  DefElem *defel = (DefElem *) lfirst(l);
1208 
1209  if (compute_common_attribute(pstate,
1210  defel,
1211  &volatility_item,
1212  &strict_item,
1213  &security_def_item,
1214  &leakproof_item,
1215  &set_items,
1216  &cost_item,
1217  &rows_item,
1218  &parallel_item) == false)
1219  elog(ERROR, "option \"%s\" not recognized", defel->defname);
1220  }
1221 
1222  if (volatility_item)
1223  procForm->provolatile = interpret_func_volatility(volatility_item);
1224  if (strict_item)
1225  procForm->proisstrict = intVal(strict_item->arg);
1226  if (security_def_item)
1227  procForm->prosecdef = intVal(security_def_item->arg);
1228  if (leakproof_item)
1229  {
1230  procForm->proleakproof = intVal(leakproof_item->arg);
1231  if (procForm->proleakproof && !superuser())
1232  ereport(ERROR,
1233  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1234  errmsg("only superuser can define a leakproof function")));
1235  }
1236  if (cost_item)
1237  {
1238  procForm->procost = defGetNumeric(cost_item);
1239  if (procForm->procost <= 0)
1240  ereport(ERROR,
1241  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1242  errmsg("COST must be positive")));
1243  }
1244  if (rows_item)
1245  {
1246  procForm->prorows = defGetNumeric(rows_item);
1247  if (procForm->prorows <= 0)
1248  ereport(ERROR,
1249  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1250  errmsg("ROWS must be positive")));
1251  if (!procForm->proretset)
1252  ereport(ERROR,
1253  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1254  errmsg("ROWS is not applicable when function does not return a set")));
1255  }
1256  if (set_items)
1257  {
1258  Datum datum;
1259  bool isnull;
1260  ArrayType *a;
1261  Datum repl_val[Natts_pg_proc];
1262  bool repl_null[Natts_pg_proc];
1263  bool repl_repl[Natts_pg_proc];
1264 
1265  /* extract existing proconfig setting */
1266  datum = SysCacheGetAttr(PROCOID, tup, Anum_pg_proc_proconfig, &isnull);
1267  a = isnull ? NULL : DatumGetArrayTypeP(datum);
1268 
1269  /* update according to each SET or RESET item, left to right */
1270  a = update_proconfig_value(a, set_items);
1271 
1272  /* update the tuple */
1273  memset(repl_repl, false, sizeof(repl_repl));
1274  repl_repl[Anum_pg_proc_proconfig - 1] = true;
1275 
1276  if (a == NULL)
1277  {
1278  repl_val[Anum_pg_proc_proconfig - 1] = (Datum) 0;
1279  repl_null[Anum_pg_proc_proconfig - 1] = true;
1280  }
1281  else
1282  {
1283  repl_val[Anum_pg_proc_proconfig - 1] = PointerGetDatum(a);
1284  repl_null[Anum_pg_proc_proconfig - 1] = false;
1285  }
1286 
1287  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1288  repl_val, repl_null, repl_repl);
1289  }
1290  if (parallel_item)
1291  procForm->proparallel = interpret_func_parallel(parallel_item);
1292 
1293  /* Do the update */
1294  CatalogTupleUpdate(rel, &tup->t_self, tup);
1295 
1297 
1298  ObjectAddressSet(address, ProcedureRelationId, funcOid);
1299 
1300  heap_close(rel, NoLock);
1301  heap_freetuple(tup);
1302 
1303  return address;
1304 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
#define PointerGetDatum(X)
Definition: postgres.h:562
#define ProcedureRelationId
Definition: pg_proc.h:33
double defGetNumeric(DefElem *def)
Definition: define.c:85
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
#define Natts_pg_proc
Definition: pg_proc.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Oid LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
Definition: parse_func.c:1991
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:532
Node * arg
Definition: parsenodes.h:720
char * NameListToString(List *names)
Definition: namespace.c:3063
uintptr_t Datum
Definition: postgres.h:372
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:575
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
ObjectWithArgs * func
Definition: parsenodes.h:2778
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define lfirst(lc)
Definition: pg_list.h:106
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:719
#define elog
Definition: elog.h:219
static bool compute_common_attribute(ParseState *pstate, DefElem *defel, DefElem **volatility_item, DefElem **strict_item, DefElem **security_item, DefElem **leakproof_item, List **set_items, DefElem **cost_item, DefElem **rows_item, DefElem **parallel_item)
Definition: functioncmds.c:453
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
Definition: pg_list.h:45
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4624
static char interpret_func_parallel(DefElem *defel)
Definition: functioncmds.c:550
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ AlterOperator()

ObjectAddress AlterOperator ( AlterOperatorStmt stmt)

Definition at line 385 of file operatorcmds.c.

References ACL_KIND_OPER, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_operator_oprjoin, Anum_pg_operator_oprrest, DefElem::arg, BOOLOID, CatalogTupleUpdate(), defGetQualifiedName(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), heap_close, heap_modify_tuple(), heap_open(), i, InvalidOid, InvokeObjectPostAlterHook, lfirst, LookupOperWithArgs(), makeOperatorDependencies(), NameStr, Natts_pg_operator, NIL, NoLock, ObjectIdGetDatum, OidIsValid, OperatorRelationId, AlterOperatorStmt::opername, OPEROID, AlterOperatorStmt::options, pg_oper_ownercheck(), pg_strcasecmp(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, ValidateJoinEstimator(), ValidateRestrictionEstimator(), and values.

Referenced by ProcessUtilitySlow().

386 {
387  ObjectAddress address;
388  Oid oprId;
389  Relation catalog;
390  HeapTuple tup;
391  Form_pg_operator oprForm;
392  int i;
393  ListCell *pl;
395  bool nulls[Natts_pg_operator];
396  bool replaces[Natts_pg_operator];
397  List *restrictionName = NIL; /* optional restrict. sel. procedure */
398  bool updateRestriction = false;
399  Oid restrictionOid;
400  List *joinName = NIL; /* optional join sel. procedure */
401  bool updateJoin = false;
402  Oid joinOid;
403 
404  /* Look up the operator */
405  oprId = LookupOperWithArgs(stmt->opername, false);
408  if (tup == NULL)
409  elog(ERROR, "cache lookup failed for operator %u", oprId);
410  oprForm = (Form_pg_operator) GETSTRUCT(tup);
411 
412  /* Process options */
413  foreach(pl, stmt->options)
414  {
415  DefElem *defel = (DefElem *) lfirst(pl);
416  List *param;
417 
418  if (defel->arg == NULL)
419  param = NIL; /* NONE, removes the function */
420  else
421  param = defGetQualifiedName(defel);
422 
423  if (pg_strcasecmp(defel->defname, "restrict") == 0)
424  {
425  restrictionName = param;
426  updateRestriction = true;
427  }
428  else if (pg_strcasecmp(defel->defname, "join") == 0)
429  {
430  joinName = param;
431  updateJoin = true;
432  }
433 
434  /*
435  * The rest of the options that CREATE accepts cannot be changed.
436  * Check for them so that we can give a meaningful error message.
437  */
438  else if (pg_strcasecmp(defel->defname, "leftarg") == 0 ||
439  pg_strcasecmp(defel->defname, "rightarg") == 0 ||
440  pg_strcasecmp(defel->defname, "procedure") == 0 ||
441  pg_strcasecmp(defel->defname, "commutator") == 0 ||
442  pg_strcasecmp(defel->defname, "negator") == 0 ||
443  pg_strcasecmp(defel->defname, "hashes") == 0 ||
444  pg_strcasecmp(defel->defname, "merges") == 0)
445  {
446  ereport(ERROR,
447  (errcode(ERRCODE_SYNTAX_ERROR),
448  errmsg("operator attribute \"%s\" cannot be changed",
449  defel->defname)));
450  }
451  else
452  ereport(ERROR,
453  (errcode(ERRCODE_SYNTAX_ERROR),
454  errmsg("operator attribute \"%s\" not recognized",
455  defel->defname)));
456  }
457 
458  /* Check permissions. Must be owner. */
459  if (!pg_oper_ownercheck(oprId, GetUserId()))
461  NameStr(oprForm->oprname));
462 
463  /*
464  * Look up restriction and join estimators if specified
465  */
466  if (restrictionName)
467  restrictionOid = ValidateRestrictionEstimator(restrictionName);
468  else
469  restrictionOid = InvalidOid;
470  if (joinName)
471  joinOid = ValidateJoinEstimator(joinName);
472  else
473  joinOid = InvalidOid;
474 
475  /* Perform additional checks, like OperatorCreate does */
476  if (!(OidIsValid(oprForm->oprleft) && OidIsValid(oprForm->oprright)))
477  {
478  /* If it's not a binary op, these things mustn't be set: */
479  if (OidIsValid(joinOid))
480  ereport(ERROR,
481  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
482  errmsg("only binary operators can have join selectivity")));
483  }
484 
485  if (oprForm->oprresult != BOOLOID)
486  {
487  if (OidIsValid(restrictionOid))
488  ereport(ERROR,
489  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
490  errmsg("only boolean operators can have restriction selectivity")));
491  if (OidIsValid(joinOid))
492  ereport(ERROR,
493  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
494  errmsg("only boolean operators can have join selectivity")));
495  }
496 
497  /* Update the tuple */
498  for (i = 0; i < Natts_pg_operator; ++i)
499  {
500  values[i] = (Datum) 0;
501  replaces[i] = false;
502  nulls[i] = false;
503  }
504  if (updateRestriction)
505  {
506  replaces[Anum_pg_operator_oprrest - 1] = true;
507  values[Anum_pg_operator_oprrest - 1] = restrictionOid;
508  }
509  if (updateJoin)
510  {
511  replaces[Anum_pg_operator_oprjoin - 1] = true;
512  values[Anum_pg_operator_oprjoin - 1] = joinOid;
513  }
514 
515  tup = heap_modify_tuple(tup, RelationGetDescr(catalog),
516  values, nulls, replaces);
517 
518  CatalogTupleUpdate(catalog, &tup->t_self, tup);
519 
520  address = makeOperatorDependencies(tup, true);
521 
523 
524  heap_close(catalog, NoLock);
525 
526  return address;
527 }
Oid LookupOperWithArgs(ObjectWithArgs *oper, bool noError)
Definition: parse_oper.c:140
#define NIL
Definition: pg_list.h:69
#define OperatorRelationId
Definition: pg_operator.h:32
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
ObjectAddress makeOperatorDependencies(HeapTuple tuple, bool isUpdate)
Definition: pg_operator.c:764
static Oid ValidateJoinEstimator(List *joinName)
Definition: operatorcmds.c:296
bool pg_oper_ownercheck(Oid oper_oid, Oid roleid)
Definition: aclchk.c:4598
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define Anum_pg_operator_oprjoin
Definition: pg_operator.h:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
static Oid ValidateRestrictionEstimator(List *restrictionName)
Definition: operatorcmds.c:261
Node * arg
Definition: parsenodes.h:720
#define Anum_pg_operator_oprrest
Definition: pg_operator.h:77
ObjectWithArgs * opername
Definition: parsenodes.h:2868
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
List * defGetQualifiedName(DefElem *def)
Definition: define.c:223
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define BOOLOID
Definition: pg_type.h:288
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:57
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define Natts_pg_operator
Definition: pg_operator.h:64
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:547
char * defname
Definition: parsenodes.h:719
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
Definition: pg_list.h:45

◆ AlterOpFamily()

Oid AlterOpFamily ( AlterOpFamilyStmt stmt)

Definition at line 764 of file opclasscmds.c.

References AlterOpFamilyAdd(), AlterOpFamilyDrop(), AMNAME, AlterOpFamilyStmt::amname, IndexAmRoutine::amstrategies, IndexAmRoutine::amsupport, CStringGetDatum, ereport, errcode(), errmsg(), ERROR, get_opfamily_oid(), GetIndexAmRoutineByAmId(), HeapTupleGetOid, HeapTupleIsValid, AlterOpFamilyStmt::isDrop, AlterOpFamilyStmt::items, AlterOpFamilyStmt::opfamilyname, ReleaseSysCache(), SearchSysCache1(), and superuser().

Referenced by ProcessUtilitySlow().

765 {
766  Oid amoid, /* our AM's oid */
767  opfamilyoid; /* oid of opfamily */
768  int maxOpNumber, /* amstrategies value */
769  maxProcNumber; /* amsupport value */
770  HeapTuple tup;
771  IndexAmRoutine *amroutine;
772 
773  /* Get necessary info about access method */
775  if (!HeapTupleIsValid(tup))
776  ereport(ERROR,
777  (errcode(ERRCODE_UNDEFINED_OBJECT),
778  errmsg("access method \"%s\" does not exist",
779  stmt->amname)));
780 
781  amoid = HeapTupleGetOid(tup);
782  amroutine = GetIndexAmRoutineByAmId(amoid, false);
783  ReleaseSysCache(tup);
784 
785  maxOpNumber = amroutine->amstrategies;
786  /* if amstrategies is zero, just enforce that op numbers fit in int16 */
787  if (maxOpNumber <= 0)
788  maxOpNumber = SHRT_MAX;
789  maxProcNumber = amroutine->amsupport;
790 
791  /* XXX Should we make any privilege check against the AM? */
792 
793  /* Look up the opfamily */
794  opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
795 
796  /*
797  * Currently, we require superuser privileges to alter an opfamily.
798  *
799  * XXX re-enable NOT_USED code sections below if you remove this test.
800  */
801  if (!superuser())
802  ereport(ERROR,
803  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
804  errmsg("must be superuser to alter an operator family")));
805 
806  /*
807  * ADD and DROP cases need separate code from here on down.
808  */
809  if (stmt->isDrop)
810  AlterOpFamilyDrop(stmt, amoid, opfamilyoid,
811  maxOpNumber, maxProcNumber, stmt->items);
812  else
813  AlterOpFamilyAdd(stmt, amoid, opfamilyoid,
814  maxOpNumber, maxProcNumber, stmt->items);
815 
816  return opfamilyoid;
817 }
uint16 amsupport
Definition: amapi.h:169
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
unsigned int Oid
Definition: postgres_ext.h:31
static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, List *items)
Definition: opclasscmds.c:948
#define ERROR
Definition: elog.h:43
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
static void AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, List *items)
Definition: opclasscmds.c:823
Oid get_opfamily_oid(Oid amID, List *opfamilyname, bool missing_ok)
Definition: opclasscmds.c:142
uint16 amstrategies
Definition: amapi.h:167
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700

◆ AlterTSConfiguration()

ObjectAddress AlterTSConfiguration ( AlterTSConfigurationStmt stmt)

Definition at line 1173 of file tsearchcmds.c.

References ACL_KIND_TSCONFIGURATION, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterTSConfigurationStmt::cfgname, AlterTSConfigurationStmt::dicts, DropConfigurationMapping(), ereport, errcode(), errmsg(), ERROR, GetTSConfigTuple(), GetUserId(), heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, makeConfigurationDependencies(), MakeConfigurationMapping(), NameListToString(), ObjectAddressSet, pg_ts_config_ownercheck(), ReleaseSysCache(), RowExclusiveLock, AlterTSConfigurationStmt::tokentype, TSConfigMapRelationId, and TSConfigRelationId.

Referenced by ProcessUtilitySlow().

1174 {
1175  HeapTuple tup;
1176  Oid cfgId;
1177  Relation relMap;
1178  ObjectAddress address;
1179 
1180  /* Find the configuration */
1181  tup = GetTSConfigTuple(stmt->cfgname);
1182  if (!HeapTupleIsValid(tup))
1183  ereport(ERROR,
1184  (errcode(ERRCODE_UNDEFINED_OBJECT),
1185  errmsg("text search configuration \"%s\" does not exist",
1186  NameListToString(stmt->cfgname))));
1187 
1188  cfgId = HeapTupleGetOid(tup);
1189 
1190  /* must be owner */
1193  NameListToString(stmt->cfgname));
1194 
1196 
1197  /* Add or drop mappings */
1198  if (stmt->dicts)
1199  MakeConfigurationMapping(stmt, tup, relMap);
1200  else if (stmt->tokentype)
1201  DropConfigurationMapping(stmt, tup, relMap);
1202 
1203  /* Update dependencies */
1204  makeConfigurationDependencies(tup, true, relMap);
1205 
1207  HeapTupleGetOid(tup), 0);
1208 
1209  ObjectAddressSet(address, TSConfigRelationId, cfgId);
1210 
1211  heap_close(relMap, RowExclusiveLock);
1212 
1213  ReleaseSysCache(tup);
1214 
1215  return address;
1216 }
Oid GetUserId(void)
Definition: miscinit.c:284
bool pg_ts_config_ownercheck(Oid cfg_oid, Oid roleid)
Definition: aclchk.c:4856
static ObjectAddress makeConfigurationDependencies(HeapTuple tuple, bool removeOld, Relation mapRel)
Definition: tsearchcmds.c:873
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
static void DropConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1439
#define TSConfigRelationId
Definition: pg_ts_config.h:31
#define TSConfigMapRelationId
#define ERROR
Definition: elog.h:43
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
static HeapTuple GetTSConfigTuple(List *names)
Definition: tsearchcmds.c:848
char * NameListToString(List *names)
Definition: namespace.c:3063
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
static void MakeConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1278

◆ AlterTSDictionary()

ObjectAddress AlterTSDictionary ( AlterTSDictionaryStmt stmt)

Definition at line 525 of file tsearchcmds.c.

References ACL_KIND_TSDICTIONARY, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_ts_dict_dictinitoption, DefElem::arg, CatalogTupleUpdate(), DefElem::defname, deserialize_deflist(), AlterTSDictionaryStmt::dictname, elog, ERROR, get_ts_dict_oid(), GETSTRUCT, GetUserId(), heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, InvokeObjectPostAlterHook, lappend(), lfirst, list_delete_cell(), list_head(), lnext, NameListToString(), Natts_pg_ts_dict, next, NIL, ObjectAddressSet, ObjectIdGetDatum, AlterTSDictionaryStmt::options, pg_strcasecmp(), pg_ts_dict_ownercheck(), PointerGetDatum, RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), serialize_deflist(), SysCacheGetAttr(), HeapTupleData::t_self, TSDictionaryRelationId, TSDICTOID, and verify_dictoptions().

Referenced by ProcessUtilitySlow().

526 {
527  HeapTuple tup,
528  newtup;
529  Relation rel;
530  Oid dictId;
531  ListCell *pl;
532  List *dictoptions;
533  Datum opt;
534  bool isnull;
535  Datum repl_val[Natts_pg_ts_dict];
536  bool repl_null[Natts_pg_ts_dict];
537  bool repl_repl[Natts_pg_ts_dict];
538  ObjectAddress address;
539 
540  dictId = get_ts_dict_oid(stmt->dictname, false);
541 
543 
545 
546  if (!HeapTupleIsValid(tup))
547  elog(ERROR, "cache lookup failed for text search dictionary %u",
548  dictId);
549 
550  /* must be owner */
551  if (!pg_ts_dict_ownercheck(dictId, GetUserId()))
553  NameListToString(stmt->dictname));
554 
555  /* deserialize the existing set of options */
556  opt = SysCacheGetAttr(TSDICTOID, tup,
558  &isnull);
559  if (isnull)
560  dictoptions = NIL;
561  else
562  dictoptions = deserialize_deflist(opt);
563 
564  /*
565  * Modify the options list as per specified changes
566  */
567  foreach(pl, stmt->options)
568  {
569  DefElem *defel = (DefElem *) lfirst(pl);
570  ListCell *cell;
571  ListCell *prev;
572  ListCell *next;
573 
574  /*
575  * Remove any matches ...
576  */
577  prev = NULL;
578  for (cell = list_head(dictoptions); cell; cell = next)
579  {
580  DefElem *oldel = (DefElem *) lfirst(cell);
581 
582  next = lnext(cell);
583  if (pg_strcasecmp(oldel->defname, defel->defname) == 0)
584  dictoptions = list_delete_cell(dictoptions, cell, prev);
585  else
586  prev = cell;
587  }
588 
589  /*
590  * and add new value if it's got one
591  */
592  if (defel->arg)
593  dictoptions = lappend(dictoptions, defel);
594  }
595 
596  /*
597  * Validate
598  */
599  verify_dictoptions(((Form_pg_ts_dict) GETSTRUCT(tup))->dicttemplate,
600  dictoptions);
601 
602  /*
603  * Looks good, update
604  */
605  memset(repl_val, 0, sizeof(repl_val));
606  memset(repl_null, false, sizeof(repl_null));
607  memset(repl_repl, false, sizeof(repl_repl));
608 
609  if (dictoptions)
610  repl_val[Anum_pg_ts_dict_dictinitoption - 1] =
611  PointerGetDatum(serialize_deflist(dictoptions));
612  else
613  repl_null[Anum_pg_ts_dict_dictinitoption - 1] = true;
614  repl_repl[Anum_pg_ts_dict_dictinitoption - 1] = true;
615 
616  newtup = heap_modify_tuple(tup, RelationGetDescr(rel),
617  repl_val, repl_null, repl_repl);
618 
619  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
620 
622 
623  ObjectAddressSet(address, TSDictionaryRelationId, dictId);
624 
625  /*
626  * NOTE: because we only support altering the options, not the template,
627  * there is no need to update dependencies. This might have to change if
628  * the options ever reference inside-the-database objects.
629  */
630 
631  heap_freetuple(newtup);
632  ReleaseSysCache(tup);
633 
635 
636  return address;
637 }
#define NIL
Definition: pg_list.h:69
#define Natts_pg_ts_dict
Definition: pg_ts_dict.h:51
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
static int32 next
Definition: blutils.c:210
bool pg_ts_dict_ownercheck(Oid dict_oid, Oid roleid)
Definition: aclchk.c:4829
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
#define PointerGetDatum(X)
Definition: postgres.h:562
List * deserialize_deflist(Datum txt)
Definition: tsearchcmds.c:1562
#define heap_close(r, l)
Definition: heapam.h:97
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
Oid get_ts_dict_oid(List *names, bool missing_ok)
Definition: namespace.c:2386
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define TSDictionaryRelationId
Definition: pg_ts_dict.h:31
ItemPointerData t_self
Definition: htup.h:65
FormData_pg_ts_dict * Form_pg_ts_dict
Definition: pg_ts_dict.h:45
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
Node * arg
Definition: parsenodes.h:720
List * lappend(List *list, void *datum)
Definition: list.c:128
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
char * NameListToString(List *names)
Definition: namespace.c:3063
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
text * serialize_deflist(List *deflist)
Definition: tsearchcmds.c:1517
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define lfirst(lc)
Definition: pg_list.h:106
static void verify_dictoptions(Oid tmplId, List *dictoptions)
Definition: tsearchcmds.c:354
#define Anum_pg_ts_dict_dictinitoption
Definition: pg_ts_dict.h:56
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
char * defname
Definition: parsenodes.h:719
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
Definition: pg_list.h:45

◆ AlterUserMapping()

ObjectAddress AlterUserMapping ( AlterUserMappingStmt stmt)

Definition at line 1250 of file foreigncmds.c.

References ACL_ID_PUBLIC, Anum_pg_user_mapping_umoptions, CatalogTupleUpdate(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, ForeignServer::fdwid, ForeignDataWrapper::fdwvalidator, get_rolespec_oid(), GetForeignDataWrapper(), GetForeignServerByName(), GetSysCacheOid2, heap_close, heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, MappingUserName, Natts_pg_user_mapping, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, AlterUserMappingStmt::options, PointerGetDatum, PointerIsValid, RelationGetDescr, ROLESPEC_PUBLIC, RoleSpec::roletype, RowExclusiveLock, SearchSysCacheCopy1, ForeignServer::serverid, AlterUserMappingStmt::servername, SysCacheGetAttr(), HeapTupleData::t_self, transformGenericOptions(), AlterUserMappingStmt::user, user_mapping_ddl_aclcheck(), USERMAPPINGOID, and UserMappingRelationId.

Referenced by ProcessUtilitySlow().

1251 {
1252  Relation rel;
1253  HeapTuple tp;
1254  Datum repl_val[Natts_pg_user_mapping];
1255  bool repl_null[Natts_pg_user_mapping];
1256  bool repl_repl[Natts_pg_user_mapping];
1257  Oid useId;
1258  Oid umId;
1259  ForeignServer *srv;
1260  ObjectAddress address;
1261  RoleSpec *role = (RoleSpec *) stmt->user;
1262 
1264 
1265  if (role->roletype == ROLESPEC_PUBLIC)
1266  useId = ACL_ID_PUBLIC;
1267  else
1268  useId = get_rolespec_oid(stmt->user, false);
1269 
1270  srv = GetForeignServerByName(stmt->servername, false);
1271 
1272  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER,
1273  ObjectIdGetDatum(useId),
1274  ObjectIdGetDatum(srv->serverid));
1275  if (!OidIsValid(umId))
1276  ereport(ERROR,
1277  (errcode(ERRCODE_UNDEFINED_OBJECT),
1278  errmsg("user mapping for \"%s\" does not exist for the server",
1279  MappingUserName(useId))));
1280 
1281  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1282 
1284 
1285  if (!HeapTupleIsValid(tp))
1286  elog(ERROR, "cache lookup failed for user mapping %u", umId);
1287 
1288  memset(repl_val, 0, sizeof(repl_val));
1289  memset(repl_null, false, sizeof(repl_null));
1290  memset(repl_repl, false, sizeof(repl_repl));
1291 
1292  if (stmt->options)
1293  {
1294  ForeignDataWrapper *fdw;
1295  Datum datum;
1296  bool isnull;
1297 
1298  /*
1299  * Process the options.
1300  */
1301 
1302  fdw = GetForeignDataWrapper(srv->fdwid);
1303 
1304  datum = SysCacheGetAttr(USERMAPPINGUSERSERVER,
1305  tp,
1307  &isnull);
1308  if (isnull)
1309  datum = PointerGetDatum(NULL);
1310 
1311  /* Prepare the options array */
1313  datum,
1314  stmt->options,
1315  fdw->fdwvalidator);
1316 
1317  if (PointerIsValid(DatumGetPointer(datum)))
1318  repl_val[Anum_pg_user_mapping_umoptions - 1] = datum;
1319  else
1320  repl_null[Anum_pg_user_mapping_umoptions - 1] = true;
1321 
1322  repl_repl[Anum_pg_user_mapping_umoptions - 1] = true;
1323  }
1324 
1325  /* Everything looks good - update the tuple */
1326  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1327  repl_val, repl_null, repl_repl);
1328 
1329  CatalogTupleUpdate(rel, &tp->t_self, tp);
1330 
1331  ObjectAddressSet(address, UserMappingRelationId, umId);
1332 
1333  heap_freetuple(tp);
1334 
1336 
1337  return address;
1338 }
#define RelationGetDescr(relation)
Definition: rel.h:437
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1110
#define heap_close(r, l)
Definition: heapam.h:97
#define Natts_pg_user_mapping
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define GetSysCacheOid2(cacheId, key1, key2)
Definition: syscache.h:193
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define Anum_pg_user_mapping_umoptions
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:148
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
RoleSpecType roletype
Definition: parsenodes.h:327
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5146
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:555
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define UserMappingRelationId
#define ACL_ID_PUBLIC
Definition: acl.h:47
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define PointerIsValid(pointer)
Definition: c.h:564
Oid serverid
Definition: foreign.h:47
#define MappingUserName(userid)
Definition: foreign.h:20

◆ CheckIndexCompatible()

bool CheckIndexCompatible ( Oid  oldId,
const char *  accessMethodName,
List attributeList,
List exclusionOpNames 
)

Definition at line 117 of file indexcmds.c.

References AccessShareLock, IndexAmRoutine::amcanorder, AMNAME, Anum_pg_index_indclass, Anum_pg_index_indcollation, Anum_pg_index_indexprs, Anum_pg_index_indpred, Assert, ComputeIndexAttrs(), CurrentMemoryContext, DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_opclass_input_type(), GetIndexAmRoutine(), GETSTRUCT, heap_attisnull(), HeapTupleGetOid, HeapTupleIsValid, i, IndexInfo::ii_AmCache, IndexInfo::ii_Context, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_PredicateState, index_close(), INDEX_MAX_KEYS, index_open(), IndexGetRelation(), IndexIsValid, INDEXRELID, IsPolymorphicType, list_length(), makeNode, NIL, NoLock, ObjectIdGetDatum, op_input_types(), palloc(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, and oidvector::values.

Referenced by TryReuseIndex().

121 {
122  bool isconstraint;
123  Oid *typeObjectId;
124  Oid *collationObjectId;
125  Oid *classObjectId;
126  Oid accessMethodId;
127  Oid relationId;
128  HeapTuple tuple;
129  Form_pg_index indexForm;
130  Form_pg_am accessMethodForm;
131  IndexAmRoutine *amRoutine;
132  bool amcanorder;
133  int16 *coloptions;
134  IndexInfo *indexInfo;
135  int numberOfAttributes;
136  int old_natts;
137  bool isnull;
138  bool ret = true;
139  oidvector *old_indclass;
140  oidvector *old_indcollation;
141  Relation irel;
142  int i;
143  Datum d;
144 
145  /* Caller should already have the relation locked in some way. */
146  relationId = IndexGetRelation(oldId, false);
147 
148  /*
149  * We can pretend isconstraint = false unconditionally. It only serves to
150  * decide the text of an error message that should never happen for us.
151  */
152  isconstraint = false;
153 
154  numberOfAttributes = list_length(attributeList);
155  Assert(numberOfAttributes > 0);
156  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
157 
158  /* look up the access method */
159  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
160  if (!HeapTupleIsValid(tuple))
161  ereport(ERROR,
162  (errcode(ERRCODE_UNDEFINED_OBJECT),
163  errmsg("access method \"%s\" does not exist",
164  accessMethodName)));
165  accessMethodId = HeapTupleGetOid(tuple);
166  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
167  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
168  ReleaseSysCache(tuple);
169 
170  amcanorder = amRoutine->amcanorder;
171 
172  /*
173  * Compute the operator classes, collations, and exclusion operators for
174  * the new index, so we can test whether it's compatible with the existing
175  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
176  * DefineIndex would have called this function with the same arguments
177  * later on, and it would have failed then anyway.
178  */
179  indexInfo = makeNode(IndexInfo);
180  indexInfo->ii_Expressions = NIL;
181  indexInfo->ii_ExpressionsState = NIL;
182  indexInfo->ii_PredicateState = NULL;
183  indexInfo->ii_ExclusionOps = NULL;
184  indexInfo->ii_ExclusionProcs = NULL;
185  indexInfo->ii_ExclusionStrats = NULL;
186  indexInfo->ii_AmCache = NULL;
187  indexInfo->ii_Context = CurrentMemoryContext;
188  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
189  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
190  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
191  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
192  ComputeIndexAttrs(indexInfo,
193  typeObjectId, collationObjectId, classObjectId,
194  coloptions, attributeList,
195  exclusionOpNames, relationId,
196  accessMethodName, accessMethodId,
197  amcanorder, isconstraint);
198 
199 
200  /* Get the soon-obsolete pg_index tuple. */
202  if (!HeapTupleIsValid(tuple))
203  elog(ERROR, "cache lookup failed for index %u", oldId);
204  indexForm = (Form_pg_index) GETSTRUCT(tuple);
205 
206  /*
207  * We don't assess expressions or predicates; assume incompatibility.
208  * Also, if the index is invalid for any reason, treat it as incompatible.
209  */
210  if (!(heap_attisnull(tuple, Anum_pg_index_indpred) &&
212  IndexIsValid(indexForm)))
213  {
214  ReleaseSysCache(tuple);
215  return false;
216  }
217 
218  /* Any change in operator class or collation breaks compatibility. */
219  old_natts = indexForm->indnatts;
220  Assert(old_natts == numberOfAttributes);
221 
223  Assert(!isnull);
224  old_indcollation = (oidvector *) DatumGetPointer(d);
225 
226  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
227  Assert(!isnull);
228  old_indclass = (oidvector *) DatumGetPointer(d);
229 
230  ret = (memcmp(old_indclass->values, classObjectId,
231  old_natts * sizeof(Oid)) == 0 &&
232  memcmp(old_indcollation->values, collationObjectId,
233  old_natts * sizeof(Oid)) == 0);
234 
235  ReleaseSysCache(tuple);
236 
237  if (!ret)
238  return false;
239 
240  /* For polymorphic opcintype, column type changes break compatibility. */
241  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
242  for (i = 0; i < old_natts; i++)
243  {
244  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
245  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
246  {
247  ret = false;
248  break;
249  }
250  }
251 
252  /* Any change in exclusion operator selections breaks compatibility. */
253  if (ret && indexInfo->ii_ExclusionOps != NULL)
254  {
255  Oid *old_operators,
256  *old_procs;
257  uint16 *old_strats;
258 
259  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
260  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
261  old_natts * sizeof(Oid)) == 0;
262 
263  /* Require an exact input type match for polymorphic operators. */
264  if (ret)
265  {
266  for (i = 0; i < old_natts && ret; i++)
267  {
268  Oid left,
269  right;
270 
271  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
272  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
273  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
274  {
275  ret = false;
276  break;
277  }
278  }
279  }
280  }
281 
282  index_close(irel, NoLock);
283  return ret;
284 }
signed short int16
Definition: c.h:283
#define NIL
Definition: pg_list.h:69
Definition: c.h:526
MemoryContext ii_Context
Definition: execnodes.h:151
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3284
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5069
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
#define PointerGetDatum(X)
Definition: postgres.h:562
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
ExprState * ii_PredicateState
Definition: execnodes.h:139
#define Anum_pg_index_indclass
Definition: pg_index.h:89
#define AccessShareLock
Definition: lockdefs.h:36
Oid * ii_ExclusionProcs
Definition: execnodes.h:141
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
List * ii_ExpressionsState
Definition: execnodes.h:137
unsigned short uint16
Definition: c.h:295
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:534
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:296
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1167
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
void * ii_AmCache
Definition: execnodes.h:150
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:558
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
List * ii_Expressions
Definition: execnodes.h:136
#define Assert(condition)
Definition: c.h:670
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:89
bool amcanorder
Definition: amapi.h:171
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
#define DatumGetPointer(X)
Definition: postgres.h:555
#define Anum_pg_index_indcollation
Definition: pg_index.h:88
Oid * ii_ExclusionOps
Definition: execnodes.h:140
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:1023
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
uint16 * ii_ExclusionStrats
Definition: execnodes.h:142
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1069

◆ ChooseRelationName()

char* ChooseRelationName ( const char *  name1,
const char *  name2,
const char *  label,
Oid  namespaceid 
)

Definition at line 1595 of file indexcmds.c.

References get_relname_relid(), makeObjectName(), NAMEDATALEN, OidIsValid, pfree(), snprintf(), and StrNCpy.

Referenced by ChooseIndexName(), and generateSerialExtraStmts().

1597 {
1598  int pass = 0;
1599  char *relname = NULL;
1600  char modlabel[NAMEDATALEN];
1601 
1602  /* try the unmodified label first */
1603  StrNCpy(modlabel, label, sizeof(modlabel));
1604 
1605  for (;;)
1606  {
1607  relname = makeObjectName(name1, name2, modlabel);
1608 
1609  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1610  break;
1611 
1612  /* found a conflict, so try a new name component */
1613  pfree(relname);
1614  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1615  }
1616 
1617  return relname;
1618 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define OidIsValid(objectId)
Definition: c.h:576
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:1515
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:949
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1683
static char * label
Definition: pg_basebackup.c:82
#define StrNCpy(dst, src, len)
Definition: c.h:826

◆ CreateAccessMethod()

ObjectAddress CreateAccessMethod ( CreateAmStmt stmt)

Definition at line 41 of file amcmds.c.

References AccessMethodRelationId, AMNAME, CreateAmStmt::amname, CreateAmStmt::amtype, Anum_pg_am_amhandler, Anum_pg_am_amname, Anum_pg_am_amtype, CatalogTupleInsert(), CharGetDatum, ObjectAddress::classId, CStringGetDatum, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, GetSysCacheOid1, CreateAmStmt::handler_name, heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), lookup_index_am_handler_func(), namein(), Natts_pg_am, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, ProcedureRelationId, recordDependencyOn(), recordDependencyOnCurrentExtension(), RelationGetDescr, RowExclusiveLock, superuser(), and values.

Referenced by ProcessUtilitySlow().

42 {
43  Relation rel;
44  ObjectAddress myself;
45  ObjectAddress referenced;
46  Oid amoid;
47  Oid amhandler;
48  bool nulls[Natts_pg_am];
50  HeapTuple tup;
51 
53 
54  /* Must be super user */
55  if (!superuser())
56  ereport(ERROR,
57  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
58  errmsg("permission denied to create access method \"%s\"",
59  stmt->amname),
60  errhint("Must be superuser to create an access method.")));
61 
62  /* Check if name is used */
64  if (OidIsValid(amoid))
65  {
66  ereport(ERROR,
68  errmsg("access method \"%s\" already exists",
69  stmt->amname)));
70  }
71 
72  /*
73  * Get the handler function oid, verifying the AM type while at it.
74  */
75  amhandler = lookup_index_am_handler_func(stmt->handler_name, stmt->amtype);
76 
77  /*
78  * Insert tuple into pg_am.
79  */
80  memset(values, 0, sizeof(values));
81  memset(nulls, false, sizeof(nulls));
82 
83  values[Anum_pg_am_amname - 1] =
85  values[Anum_pg_am_amhandler - 1] = ObjectIdGetDatum(amhandler);
86  values[Anum_pg_am_amtype - 1] = CharGetDatum(stmt->amtype);
87 
88  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
89 
90  amoid = CatalogTupleInsert(rel, tup);
91  heap_freetuple(tup);
92 
94  myself.objectId = amoid;
95  myself.objectSubId = 0;
96 
97  /* Record dependency on handler function */
98  referenced.classId = ProcedureRelationId;
99  referenced.objectId = amhandler;
100  referenced.objectSubId = 0;
101 
102  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
103 
104  recordDependencyOnCurrentExtension(&myself, false);
105 
107 
108  return myself;
109 }
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
int errhint(const char *fmt,...)
Definition: elog.c:987
#define RelationGetDescr(relation)
Definition: rel.h:437
#define ProcedureRelationId
Definition: pg_proc.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
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:695
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define GetSysCacheOid1(cacheId, key1)
Definition: syscache.h:191
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
char * amname
Definition: parsenodes.h:2349
#define AccessMethodRelationId
Definition: pg_am.h:32
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
static Oid lookup_index_am_handler_func(List *handler_name, char amtype)
Definition: amcmds.c:242
#define ereport(elevel, rest)
Definition: elog.h:122
#define Anum_pg_am_amtype
Definition: pg_am.h:55
uintptr_t Datum
Definition: postgres.h:372
List * handler_name
Definition: parsenodes.h:2350
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define Anum_pg_am_amhandler
Definition: pg_am.h:54
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
#define Natts_pg_am
Definition: pg_am.h:52
#define CharGetDatum(X)
Definition: postgres.h:422
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define Anum_pg_am_amname
Definition: pg_am.h:53
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30

◆ CreateCast()

ObjectAddress CreateCast ( CreateCastStmt stmt)

Definition at line 1398 of file functioncmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, Anum_pg_cast_castcontext, Anum_pg_cast_castfunc, Anum_pg_cast_castmethod, Anum_pg_cast_castsource, Anum_pg_cast_casttarget, BOOLOID, CastRelationId, CASTSOURCETARGET, CatalogTupleInsert(), CharGetDatum, ObjectAddress::classId, COERCION_ASSIGNMENT, COERCION_CODE_ASSIGNMENT, COERCION_CODE_EXPLICIT, COERCION_CODE_IMPLICIT, COERCION_EXPLICIT, COERCION_IMPLICIT, COERCION_METHOD_BINARY, COERCION_METHOD_FUNCTION, COERCION_METHOD_INOUT, CreateCastStmt::context, DEPENDENCY_NORMAL, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), CreateCastStmt::func, get_element_type(), get_typlenbyvalalign(), get_typtype(), GETSTRUCT, GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), HeapTupleIsValid, CreateCastStmt::inout, INT4OID, InvalidOid, InvokeObjectPostCreateHook, IsBinaryCoercible(), LookupFuncWithArgs(), MemSet, Natts_pg_cast, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, pg_type_aclcheck(), pg_type_ownercheck(), ProcedureRelationId, PROCOID, PROVOLATILE_VOLATILE, recordDependencyOn(), recordDependencyOnCurrentExtension(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), SearchSysCache2(), CreateCastStmt::sourcetype, superuser(), CreateCastStmt::targettype, TypeNameToString(), typenameTypeId(), TypeRelationId, TYPTYPE_COMPOSITE, TYPTYPE_DOMAIN, TYPTYPE_ENUM, TYPTYPE_PSEUDO, values, and WARNING.

Referenced by ProcessUtilitySlow().

1399 {
1400  Oid sourcetypeid;
1401  Oid targettypeid;
1402  char sourcetyptype;
1403  char targettyptype;
1404  Oid funcid;
1405  Oid castid;
1406  int nargs;
1407  char castcontext;
1408  char castmethod;
1409  Relation relation;
1410  HeapTuple tuple;
1412  bool nulls[Natts_pg_cast];
1413  ObjectAddress myself,
1414  referenced;
1415  AclResult aclresult;
1416 
1417  sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1418  targettypeid = typenameTypeId(NULL, stmt->targettype);
1419  sourcetyptype = get_typtype(sourcetypeid);
1420  targettyptype = get_typtype(targettypeid);
1421 
1422  /* No pseudo-types allowed */
1423  if (sourcetyptype == TYPTYPE_PSEUDO)
1424  ereport(ERROR,
1425  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1426  errmsg("source data type %s is a pseudo-type",
1427  TypeNameToString(stmt->sourcetype))));
1428 
1429  if (targettyptype == TYPTYPE_PSEUDO)
1430  ereport(ERROR,
1431  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1432  errmsg("target data type %s is a pseudo-type",
1433  TypeNameToString(stmt->targettype))));
1434 
1435  /* Permission check */
1436  if (!pg_type_ownercheck(sourcetypeid, GetUserId())
1437  && !pg_type_ownercheck(targettypeid, GetUserId()))
1438  ereport(ERROR,
1439  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1440  errmsg("must be owner of type %s or type %s",
1441  format_type_be(sourcetypeid),
1442  format_type_be(targettypeid))));
1443 
1444  aclresult = pg_type_aclcheck(sourcetypeid, GetUserId(), ACL_USAGE);
1445  if (aclresult != ACLCHECK_OK)
1446  aclcheck_error_type(aclresult, sourcetypeid);
1447 
1448  aclresult = pg_type_aclcheck(targettypeid, GetUserId(), ACL_USAGE);
1449  if (aclresult != ACLCHECK_OK)
1450  aclcheck_error_type(aclresult, targettypeid);
1451 
1452  /* Domains are allowed for historical reasons, but we warn */
1453  if (sourcetyptype == TYPTYPE_DOMAIN)
1454  ereport(WARNING,
1455  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1456  errmsg("cast will be ignored because the source data type is a domain")));
1457 
1458  else if (targettyptype == TYPTYPE_DOMAIN)
1459  ereport(WARNING,
1460  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1461  errmsg("cast will be ignored because the target data type is a domain")));
1462 
1463  /* Determine the cast method */
1464  if (stmt->func != NULL)
1465  castmethod = COERCION_METHOD_FUNCTION;
1466  else if (stmt->inout)
1467  castmethod = COERCION_METHOD_INOUT;
1468  else
1469  castmethod = COERCION_METHOD_BINARY;
1470 
1471  if (castmethod == COERCION_METHOD_FUNCTION)
1472  {
1473  Form_pg_proc procstruct;
1474 
1475  funcid = LookupFuncWithArgs(stmt->func, false);
1476 
1477  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1478  if (!HeapTupleIsValid(tuple))
1479  elog(ERROR, "cache lookup failed for function %u", funcid);
1480 
1481  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1482  nargs = procstruct->pronargs;
1483  if (nargs < 1 || nargs > 3)
1484  ereport(ERROR,
1485  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1486  errmsg("cast function must take one to three arguments")));
1487  if (!IsBinaryCoercible(sourcetypeid, procstruct->proargtypes.values[0]))
1488  ereport(ERROR,
1489  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1490  errmsg("argument of cast function must match or be binary-coercible from source data type")));
1491  if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1492  ereport(ERROR,
1493  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1494  errmsg("second argument of cast function must be type %s",
1495  "integer")));
1496  if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1497  ereport(ERROR,
1498  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1499  errmsg("third argument of cast function must be type %s",
1500  "boolean")));
1501  if (!IsBinaryCoercible(procstruct->prorettype, targettypeid))
1502  ereport(ERROR,
1503  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1504  errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1505 
1506  /*
1507  * Restricting the volatility of a cast function may or may not be a
1508  * good idea in the abstract, but it definitely breaks many old
1509  * user-defined types. Disable this check --- tgl 2/1/03
1510  */
1511 #ifdef NOT_USED
1512  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1513  ereport(ERROR,
1514  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1515  errmsg("cast function must not be volatile")));
1516 #endif
1517  if (procstruct->proisagg)
1518  ereport(ERROR,
1519  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1520  errmsg("cast function must not be an aggregate function")));
1521  if (procstruct->proiswindow)
1522  ereport(ERROR,
1523  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1524  errmsg("cast function must not be a window function")));
1525  if (procstruct->proretset)
1526  ereport(ERROR,
1527  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1528  errmsg("cast function must not return a set")));
1529 
1530  ReleaseSysCache(tuple);
1531  }
1532  else
1533  {
1534  funcid = InvalidOid;
1535  nargs = 0;
1536  }
1537 
1538  if (castmethod == COERCION_METHOD_BINARY)
1539  {
1540  int16 typ1len;
1541  int16 typ2len;
1542  bool typ1byval;
1543  bool typ2byval;
1544  char typ1align;
1545  char typ2align;
1546 
1547  /*
1548  * Must be superuser to create binary-compatible casts, since
1549  * erroneous casts can easily crash the backend.
1550  */
1551  if (!superuser())
1552  ereport(ERROR,
1553  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1554  errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1555 
1556  /*
1557  * Also, insist that the types match as to size, alignment, and
1558  * pass-by-value attributes; this provides at least a crude check that
1559  * they have similar representations. A pair of types that fail this
1560  * test should certainly not be equated.
1561  */
1562  get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1563  get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1564  if (typ1len != typ2len ||
1565  typ1byval != typ2byval ||
1566  typ1align != typ2align)
1567  ereport(ERROR,
1568  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1569  errmsg("source and target data types are not physically compatible")));
1570 
1571  /*
1572  * We know that composite, enum and array types are never binary-
1573  * compatible with each other. They all have OIDs embedded in them.
1574  *
1575  * Theoretically you could build a user-defined base type that is
1576  * binary-compatible with a composite, enum, or array type. But we
1577  * disallow that too, as in practice such a cast is surely a mistake.
1578  * You can always work around that by writing a cast function.
1579  */
1580  if (sourcetyptype == TYPTYPE_COMPOSITE ||
1581  targettyptype == TYPTYPE_COMPOSITE)
1582  ereport(ERROR,
1583  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1584  errmsg("composite data types are not binary-compatible")));
1585 
1586  if (sourcetyptype == TYPTYPE_ENUM ||
1587  targettyptype == TYPTYPE_ENUM)
1588  ereport(ERROR,
1589  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1590  errmsg("enum data types are not binary-compatible")));
1591 
1592  if (OidIsValid(get_element_type(sourcetypeid)) ||
1593  OidIsValid(get_element_type(targettypeid)))
1594  ereport(ERROR,
1595  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1596  errmsg("array data types are not binary-compatible")));
1597 
1598  /*
1599  * We also disallow creating binary-compatibility casts involving
1600  * domains. Casting from a domain to its base type is already
1601  * allowed, and casting the other way ought to go through domain
1602  * coercion to permit constraint checking. Again, if you're intent on
1603  * having your own semantics for that, create a no-op cast function.
1604  *
1605  * NOTE: if we were to relax this, the above checks for composites
1606  * etc. would have to be modified to look through domains to their
1607  * base types.
1608  */
1609  if (sourcetyptype == TYPTYPE_DOMAIN ||
1610  targettyptype == TYPTYPE_DOMAIN)
1611  ereport(ERROR,
1612  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1613  errmsg("domain data types must not be marked binary-compatible")));
1614  }
1615 
1616  /*
1617  * Allow source and target types to be same only for length coercion
1618  * functions. We assume a multi-arg function does length coercion.
1619  */
1620  if (sourcetypeid == targettypeid && nargs < 2)
1621  ereport(ERROR,
1622  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1623  errmsg("source data type and target data type are the same")));
1624 
1625  /* convert CoercionContext enum to char value for castcontext */
1626  switch (stmt->context)
1627  {
1628  case COERCION_IMPLICIT:
1629  castcontext = COERCION_CODE_IMPLICIT;
1630  break;
1631  case COERCION_ASSIGNMENT:
1632  castcontext = COERCION_CODE_ASSIGNMENT;
1633  break;
1634  case COERCION_EXPLICIT:
1635  castcontext = COERCION_CODE_EXPLICIT;
1636  break;
1637  default:
1638  elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1639  castcontext = 0; /* keep compiler quiet */
1640  break;
1641  }
1642 
1644 
1645  /*
1646  * Check for duplicate. This is just to give a friendly error message,
1647  * the unique index would catch it anyway (so no need to sweat about race
1648  * conditions).
1649  */
1651  ObjectIdGetDatum(sourcetypeid),
1652  ObjectIdGetDatum(targettypeid));
1653  if (HeapTupleIsValid(tuple))
1654  ereport(ERROR,
1656  errmsg("cast from type %s to type %s already exists",
1657  format_type_be(sourcetypeid),
1658  format_type_be(targettypeid))));
1659 
1660  /* ready to go */
1661  values[Anum_pg_cast_castsource - 1] = ObjectIdGetDatum(sourcetypeid);
1662  values[Anum_pg_cast_casttarget - 1] = ObjectIdGetDatum(targettypeid);
1663  values[Anum_pg_cast_castfunc - 1] = ObjectIdGetDatum(funcid);
1664  values[Anum_pg_cast_castcontext - 1] = CharGetDatum(castcontext);
1665  values[Anum_pg_cast_castmethod - 1] = CharGetDatum(castmethod);
1666 
1667  MemSet(nulls, false, sizeof(nulls));
1668 
1669  tuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1670 
1671  castid = CatalogTupleInsert(relation, tuple);
1672 
1673  /* make dependency entries */
1674  myself.classId = CastRelationId;
1675  myself.objectId = castid;
1676  myself.objectSubId = 0;
1677 
1678  /* dependency on source type */
1679  referenced.classId = TypeRelationId;
1680  referenced.objectId = sourcetypeid;
1681  referenced.objectSubId = 0;
1682  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1683 
1684  /* dependency on target type */
1685  referenced.classId = TypeRelationId;
1686  referenced.objectId = targettypeid;
1687  referenced.objectSubId = 0;
1688  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1689 
1690  /* dependency on function */
1691  if (OidIsValid(funcid))
1692  {
1693  referenced.classId = ProcedureRelationId;
1694  referenced.objectId = funcid;
1695  referenced.objectSubId = 0;
1696  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1697  }
1698 
1699  /* dependency on extension */
1700  recordDependencyOnCurrentExtension(&myself, false);
1701 
1702  /* Post creation hook for new cast */
1704 
1705  heap_freetuple(tuple);
1706 
1707  heap_close(relation, RowExclusiveLock);
1708 
1709  return myself;
1710 }
signed short int16
Definition: c.h:283
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
TypeName * sourcetype
Definition: parsenodes.h:3279
#define Anum_pg_cast_castfunc
Definition: pg_cast.h:80
#define Anum_pg_cast_casttarget
Definition: pg_cast.h:79
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2498
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2021
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:459
#define ProcedureRelationId
Definition: pg_proc.h:33
#define INT4OID
Definition: pg_type.h:316
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
char get_typtype(Oid typid)
Definition: lsyscache.c:2379
#define MemSet(start, val, len)
Definition: c.h:853
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
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:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
bool pg_type_ownercheck(Oid type_oid, Oid roleid)
Definition: aclchk.c:4572
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:576
#define Anum_pg_cast_castmethod
Definition: pg_cast.h:82
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3457
#define Natts_pg_cast
Definition: pg_cast.h:77
#define Anum_pg_cast_castsource
Definition: pg_cast.h:78
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
CoercionContext context
Definition: parsenodes.h:3282
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ACL_USAGE
Definition: parsenodes.h:80
#define ereport(elevel, rest)
Definition: elog.h:122
Oid LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
Definition: parse_func.c:1991
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5539
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
ObjectWithArgs * func
Definition: parsenodes.h:3281
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
#define CastRelationId
Definition: pg_cast.h:31
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1123
#define BOOLOID
Definition: pg_type.h:288
#define CharGetDatum(X)
Definition: postgres.h:422
#define TYPTYPE_PSEUDO
Definition: pg_type.h:724
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int errmsg(const char *fmt,...)
Definition: elog.c:797
TypeName * targettype
Definition: parsenodes.h:3280
#define TYPTYPE_ENUM
Definition: pg_type.h:723
#define Anum_pg_cast_castcontext
Definition: pg_cast.h:81
#define elog
Definition: elog.h:219
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4534
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ CreateForeignDataWrapper()

ObjectAddress CreateForeignDataWrapper ( CreateFdwStmt stmt)

Definition at line 560 of file foreigncmds.c.

References Anum_pg_foreign_data_wrapper_fdwacl, Anum_pg_foreign_data_wrapper_fdwhandler, Anum_pg_foreign_data_wrapper_fdwname, Anum_pg_foreign_data_wrapper_fdwoptions, Anum_pg_foreign_data_wrapper_fdwowner, Anum_pg_foreign_data_wrapper_fdwvalidator, CatalogTupleInsert(), ObjectAddress::classId, CStringGetDatum, DatumGetPointer, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, CreateFdwStmt::fdwname, ForeignDataWrapperRelationId, CreateFdwStmt::func_options, GetForeignDataWrapperByName(), GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), InvokeObjectPostCreateHook, namein(), Natts_pg_foreign_data_wrapper, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, CreateFdwStmt::options, parse_func_options(), PointerGetDatum, PointerIsValid, ProcedureRelationId, RelationData::rd_att, recordDependencyOn(), recordDependencyOnCurrentExtension(), recordDependencyOnOwner(), RowExclusiveLock, superuser(), transformGenericOptions(), and values.

Referenced by ProcessUtilitySlow().

561 {
562  Relation rel;
564  bool nulls[Natts_pg_foreign_data_wrapper];
565  HeapTuple tuple;
566  Oid fdwId;
567  bool handler_given;
568  bool validator_given;
569  Oid fdwhandler;
570  Oid fdwvalidator;
571  Datum fdwoptions;
572  Oid ownerId;
573  ObjectAddress myself;
574  ObjectAddress referenced;
575 
577 
578  /* Must be super user */
579  if (!superuser())
580  ereport(ERROR,
581  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
582  errmsg("permission denied to create foreign-data wrapper \"%s\"",
583  stmt->fdwname),
584  errhint("Must be superuser to create a foreign-data wrapper.")));
585 
586  /* For now the owner cannot be specified on create. Use effective user ID. */
587  ownerId = GetUserId();
588 
589  /*
590  * Check that there is no other foreign-data wrapper by this name.
591  */
592  if (GetForeignDataWrapperByName(stmt->fdwname, true) != NULL)
593  ereport(ERROR,
595  errmsg("foreign-data wrapper \"%s\" already exists",
596  stmt->fdwname)));
597 
598  /*
599  * Insert tuple into pg_foreign_data_wrapper.
600  */
601  memset(values, 0, sizeof(values));
602  memset(nulls, false, sizeof(nulls));
603 
607 
608  /* Lookup handler and validator functions, if given */
610  &handler_given, &fdwhandler,
611  &validator_given, &fdwvalidator);
612 
615 
616  nulls[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
617 
619  PointerGetDatum(NULL),
620  stmt->options,
621  fdwvalidator);
622 
623  if (PointerIsValid(DatumGetPointer(fdwoptions)))
624  values[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = fdwoptions;
625  else
626  nulls[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
627 
628  tuple = heap_form_tuple(rel->rd_att, values, nulls);
629 
630  fdwId = CatalogTupleInsert(rel, tuple);
631 
632  heap_freetuple(tuple);
633 
634  /* record dependencies */
636  myself.objectId = fdwId;
637  myself.objectSubId = 0;
638 
639  if (OidIsValid(fdwhandler))
640  {
641  referenced.classId = ProcedureRelationId;
642  referenced.objectId = fdwhandler;
643  referenced.objectSubId = 0;
644  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
645  }
646 
647  if (OidIsValid(fdwvalidator))
648  {
649  referenced.classId = ProcedureRelationId;
650  referenced.objectId = fdwvalidator;
651  referenced.objectSubId = 0;
652  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
653  }
654 
656 
657  /* dependency on extension */
658  recordDependencyOnCurrentExtension(&myself, false);
659 
660  /* Post creation hook for new foreign data wrapper */
662 
664 
665  return myself;
666 }
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
int errhint(const char *fmt,...)
Definition: elog.c:987
static void parse_func_options(List *func_options, bool *handler_given, Oid *fdwhandler, bool *validator_given, Oid *fdwvalidator)
Definition: foreigncmds.c:516
#define Anum_pg_foreign_data_wrapper_fdwowner
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
Oid GetUserId(void)
Definition: miscinit.c:284
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define ProcedureRelationId
Definition: pg_proc.h:33
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define Anum_pg_foreign_data_wrapper_fdwhandler
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:695
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define Anum_pg_foreign_data_wrapper_fdwacl
List * options
Definition: parsenodes.h:2211
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define RowExclusiveLock
Definition: lockdefs.h:38
char * fdwname
Definition: parsenodes.h:2209
#define CStringGetDatum(X)
Definition: postgres.h:584
#define Anum_pg_foreign_data_wrapper_fdwname
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_foreign_data_wrapper_fdwvalidator
#define Natts_pg_foreign_data_wrapper
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:78
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
#define ForeignDataWrapperRelationId
#define DatumGetPointer(X)
Definition: postgres.h:555
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
#define PointerIsValid(pointer)
Definition: c.h:564
#define Anum_pg_foreign_data_wrapper_fdwoptions
List * func_options
Definition: parsenodes.h:2210

◆ CreateForeignServer()

ObjectAddress CreateForeignServer ( CreateForeignServerStmt stmt)

Definition at line 861 of file foreigncmds.c.

References ACL_KIND_FDW, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, Anum_pg_foreign_server_srvacl, Anum_pg_foreign_server_srvfdw, Anum_pg_foreign_server_srvname, Anum_pg_foreign_server_srvoptions, Anum_pg_foreign_server_srvowner, Anum_pg_foreign_server_srvtype, Anum_pg_foreign_server_srvversion, CatalogTupleInsert(), ObjectAddress::classId, CStringGetDatum, CStringGetTextDatum, DatumGetPointer, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, ForeignDataWrapper::fdwid, ForeignDataWrapper::fdwname, CreateForeignServerStmt::fdwname, ForeignDataWrapper::fdwvalidator, ForeignDataWrapperRelationId, ForeignServerRelationId, GetForeignDataWrapperByName(), GetForeignServerByName(), GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), CreateForeignServerStmt::if_not_exists, InvalidObjectAddress, InvokeObjectPostCreateHook, namein(), Natts_pg_foreign_server, NOTICE, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, CreateForeignServerStmt::options, pg_foreign_data_wrapper_aclcheck(), PointerGetDatum, PointerIsValid, RelationData::rd_att, recordDependencyOn(), recordDependencyOnCurrentExtension(), recordDependencyOnOwner(), RowExclusiveLock, CreateForeignServerStmt::servername, CreateForeignServerStmt::servertype, transformGenericOptions(), values, and CreateForeignServerStmt::version.

Referenced by ProcessUtilitySlow().

862 {
863  Relation rel;
864  Datum srvoptions;
866  bool nulls[Natts_pg_foreign_server];
867  HeapTuple tuple;
868  Oid srvId;
869  Oid ownerId;
870  AclResult aclresult;
871  ObjectAddress myself;
872  ObjectAddress referenced;
873  ForeignDataWrapper *fdw;
874 
876 
877  /* For now the owner cannot be specified on create. Use effective user ID. */
878  ownerId = GetUserId();
879 
880  /*
881  * Check that there is no other foreign server by this name. Do nothing if
882  * IF NOT EXISTS was enforced.
883  */
884  if (GetForeignServerByName(stmt->servername, true) != NULL)
885  {
886  if (stmt->if_not_exists)
887  {
888  ereport(NOTICE,
890  errmsg("server \"%s\" already exists, skipping",
891  stmt->servername)));
893  return InvalidObjectAddress;
894  }
895  else
896  ereport(ERROR,
898  errmsg("server \"%s\" already exists",
899  stmt->servername)));
900  }
901 
902  /*
903  * Check that the FDW exists and that we have USAGE on it. Also get the
904  * actual FDW for option validation etc.
905  */
906  fdw = GetForeignDataWrapperByName(stmt->fdwname, false);
907 
908  aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE);
909  if (aclresult != ACLCHECK_OK)
910  aclcheck_error(aclresult, ACL_KIND_FDW, fdw->fdwname);
911 
912  /*
913  * Insert tuple into pg_foreign_server.
914  */
915  memset(values, 0, sizeof(values));
916  memset(nulls, false, sizeof(nulls));
917 
918  values[Anum_pg_foreign_server_srvname - 1] =
920  values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);
922 
923  /* Add server type if supplied */
924  if (stmt->servertype)
925  values[Anum_pg_foreign_server_srvtype - 1] =
927  else
928  nulls[Anum_pg_foreign_server_srvtype - 1] = true;
929 
930  /* Add server version if supplied */
931  if (stmt->version)
934  else
935  nulls[Anum_pg_foreign_server_srvversion - 1] = true;
936 
937  /* Start with a blank acl */
938  nulls[Anum_pg_foreign_server_srvacl - 1] = true;
939 
940  /* Add server options */
942  PointerGetDatum(NULL),
943  stmt->options,
944  fdw->fdwvalidator);
945 
946  if (PointerIsValid(DatumGetPointer(srvoptions)))
947  values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;
948  else
949  nulls[Anum_pg_foreign_server_srvoptions - 1] = true;
950 
951  tuple = heap_form_tuple(rel->rd_att, values, nulls);
952 
953  srvId = CatalogTupleInsert(rel, tuple);
954 
955  heap_freetuple(tuple);
956 
957  /* record dependencies */
959  myself.objectId = srvId;
960  myself.objectSubId = 0;
961 
963  referenced.objectId = fdw->fdwid;
964  referenced.objectSubId = 0;
965  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
966 
968 
969  /* dependency on extension */
970  recordDependencyOnCurrentExtension(&myself, false);
971 
972  /* Post creation hook for new foreign server */
974 
976 
977  return myself;
978 }
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
Oid GetUserId(void)
Definition: miscinit.c:284
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define Anum_pg_foreign_server_srvversion
char * fdwname
Definition: foreign.h:39
#define PointerGetDatum(X)
Definition: postgres.h:562
AclResult pg_foreign_data_wrapper_aclcheck(Oid fdw_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4509
int errcode(int sqlerrcode)
Definition: elog.c:575
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:695
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define Anum_pg_foreign_server_srvname
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ACL_USAGE
Definition: parsenodes.h:80
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:148
#define ereport(elevel, rest)
Definition: elog.h:122
#define Anum_pg_foreign_server_srvacl
#define Natts_pg_foreign_server
#define Anum_pg_foreign_server_srvowner
#define Anum_pg_foreign_server_srvfdw
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define NOTICE
Definition: elog.h:37
#define ForeignServerRelationId
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:78
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
#define ForeignDataWrapperRelationId
#define Anum_pg_foreign_server_srvtype
#define DatumGetPointer(X)
Definition: postgres.h:555
static Datum values[MAXATTR]
Definition: bootstrap.c:164
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
#define Anum_pg_foreign_server_srvoptions
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
#define PointerIsValid(pointer)
Definition: c.h:564

◆ CreateForeignTable()

void CreateForeignTable ( CreateForeignTableStmt stmt,
Oid  relid 
)

Definition at line 1446 of file foreigncmds.c.

References ACL_KIND_FOREIGN_SERVER, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, Anum_pg_foreign_table_ftoptions, Anum_pg_foreign_table_ftrelid, Anum_pg_foreign_table_ftserver, CatalogTupleInsert(), ObjectAddress::classId, CommandCounterIncrement(), DatumGetPointer, DEPENDENCY_NORMAL, ForeignServer::fdwid, ForeignDataWrapper::fdwvalidator, ForeignServerRelationId, ForeignTableRelationId, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), Natts_pg_foreign_table, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, CreateForeignTableStmt::options, pg_foreign_server_aclcheck(), PointerGetDatum, PointerIsValid, RelationData::rd_att, recordDependencyOn(), RelationRelationId, RowExclusiveLock, ForeignServer::serverid, ForeignServer::servername, CreateForeignTableStmt::servername, transformGenericOptions(), and values.

Referenced by ProcessUtilitySlow().

1447 {
1448  Relation ftrel;
1449  Datum ftoptions;
1451  bool nulls[Natts_pg_foreign_table];
1452  HeapTuple tuple;
1453  AclResult aclresult;
1454  ObjectAddress myself;
1455  ObjectAddress referenced;
1456  Oid ownerId;
1457  ForeignDataWrapper *fdw;
1458  ForeignServer *server;
1459 
1460  /*
1461  * Advance command counter to ensure the pg_attribute tuple is visible;
1462  * the tuple might be updated to add constraints in previous step.
1463  */
1465 
1467 
1468  /*
1469  * For now the owner cannot be specified on create. Use effective user ID.
1470  */
1471  ownerId = GetUserId();
1472 
1473  /*
1474  * Check that the foreign server exists and that we have USAGE on it. Also
1475  * get the actual FDW for option validation etc.
1476  */
1477  server = GetForeignServerByName(stmt->servername, false);
1478  aclresult = pg_foreign_server_aclcheck(server->serverid, ownerId, ACL_USAGE);
1479  if (aclresult != ACLCHECK_OK)
1480  aclcheck_error(aclresult, ACL_KIND_FOREIGN_SERVER, server->servername);
1481 
1482  fdw = GetForeignDataWrapper(server->fdwid);
1483 
1484  /*
1485  * Insert tuple into pg_foreign_table.
1486  */
1487  memset(values, 0, sizeof(values));
1488  memset(nulls, false, sizeof(nulls));
1489 
1490  values[Anum_pg_foreign_table_ftrelid - 1] = ObjectIdGetDatum(relid);
1492  /* Add table generic options */
1494  PointerGetDatum(NULL),
1495  stmt->options,
1496  fdw->fdwvalidator);
1497 
1498  if (PointerIsValid(DatumGetPointer(ftoptions)))
1499  values[Anum_pg_foreign_table_ftoptions - 1] = ftoptions;
1500  else
1501  nulls[Anum_pg_foreign_table_ftoptions - 1] = true;
1502 
1503  tuple = heap_form_tuple(ftrel->rd_att, values, nulls);
1504 
1505  CatalogTupleInsert(ftrel, tuple);
1506 
1507  heap_freetuple(tuple);
1508 
1509  /* Add pg_class dependency on the server */
1510  myself.classId = RelationRelationId;
1511  myself.objectId = relid;
1512  myself.objectSubId = 0;
1513 
1514  referenced.classId = ForeignServerRelationId;
1515  referenced.objectId = server->serverid;
1516  referenced.objectSubId = 0;
1517  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1518 
1519  heap_close(ftrel, RowExclusiveLock);
1520 }
Oid GetUserId(void)
Definition: miscinit.c:284
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
#define Natts_pg_foreign_table
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:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define Anum_pg_foreign_table_ftserver
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4522
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ACL_USAGE
Definition: parsenodes.h:80
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:148
#define Anum_pg_foreign_table_ftrelid
#define Anum_pg_foreign_table_ftoptions
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:915
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define ForeignServerRelationId
#define DatumGetPointer(X)
Definition: postgres.h:555
static Datum values[MAXATTR]
Definition: bootstrap.c:164
char * servername
Definition: foreign.h:50
#define ForeignTableRelationId
#define PointerIsValid(pointer)
Definition: c.h:564
Oid serverid
Definition: foreign.h:47

◆ CreateFunction()

ObjectAddress CreateFunction ( ParseState pstate,
CreateFunctionStmt stmt 
)

Definition at line 861 of file functioncmds.c.

References ACL_CREATE, ACL_KIND_LANGUAGE, ACL_KIND_NAMESPACE, ACL_USAGE, aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_OK, castNode, ClanguageId, compute_attributes_sql_style(), compute_attributes_with_style(), compute_return_type(), construct_array(), ereport, errcode(), errhint(), errmsg(), ERROR, format_type_be(), CreateFunctionStmt::funcname, get_base_element_type(), get_namespace_name(), get_transform_oid(), GETSTRUCT, GetUserId(), HeapTupleGetOid, HeapTupleIsValid, i, INTERNALlanguageId, interpret_AS_clause(), interpret_function_parameter_list(), LANGNAME, lappend_oid(), lfirst_node, lfirst_oid, list_length(), NameStr, NIL, ObjectIdGetDatum, OidIsValid, OIDOID, CreateFunctionStmt::options, palloc(), CreateFunctionStmt::parameters, pg_language_aclcheck(), pg_namespace_aclcheck(), PLTemplateExists(), PointerGetDatum, ProcedureCreate(), PROPARALLEL_UNSAFE, PROVOLATILE_VOLATILE, QualifiedNameGetCreationNamespace(), ReleaseSysCache(), CreateFunctionStmt::replace, CreateFunctionStmt::returnType, SearchSysCache1(), superuser(), typenameTypeId(), VOIDOID, and CreateFunctionStmt::withClause.

Referenced by ProcessUtilitySlow().

862 {
863  char *probin_str;
864  char *prosrc_str;
865  Oid prorettype;
866  bool returnsSet;
867  char *language;
868  Oid languageOid;
869  Oid languageValidator;
870  Node *transformDefElem = NULL;
871  char *funcname;
872  Oid namespaceId;
873  AclResult aclresult;
874  oidvector *parameterTypes;
875  ArrayType *allParameterTypes;
876  ArrayType *parameterModes;
877  ArrayType *parameterNames;
878  List *parameterDefaults;
879  Oid variadicArgType;
880  List *trftypes_list = NIL;
881  ArrayType *trftypes;
882  Oid requiredResultType;
883  bool isWindowFunc,
884  isStrict,
885  security,
886  isLeakProof;
887  char volatility;
888  ArrayType *proconfig;
889  float4 procost;
890  float4 prorows;
891  HeapTuple languageTuple;
892  Form_pg_language languageStruct;
893  List *as_clause;
894  char parallel;
895 
896  /* Convert list of names to a name and namespace */
897  namespaceId = QualifiedNameGetCreationNamespace(stmt->funcname,
898  &funcname);
899 
900  /* Check we have creation rights in target namespace */
901  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
902  if (aclresult != ACLCHECK_OK)
904  get_namespace_name(namespaceId));
905 
906  /* default attributes */
907  isWindowFunc = false;
908  isStrict = false;
909  security = false;
910  isLeakProof = false;
911  volatility = PROVOLATILE_VOLATILE;
912  proconfig = NULL;
913  procost = -1; /* indicates not set */
914  prorows = -1; /* indicates not set */
915  parallel = PROPARALLEL_UNSAFE;
916 
917  /* override attributes from explicit list */
919  stmt->options,
920  &as_clause, &language, &transformDefElem,
921  &isWindowFunc, &volatility,
922  &isStrict, &security, &isLeakProof,
923  &proconfig, &procost, &prorows, &parallel);
924 
925  /* Look up the language and validate permissions */
926  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
927  if (!HeapTupleIsValid(languageTuple))
928  ereport(ERROR,
929  (errcode(ERRCODE_UNDEFINED_OBJECT),
930  errmsg("language \"%s\" does not exist", language),
931  (PLTemplateExists(language) ?
932  errhint("Use CREATE LANGUAGE to load the language into the database.") : 0)));
933 
934  languageOid = HeapTupleGetOid(languageTuple);
935  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
936 
937  if (languageStruct->lanpltrusted)
938  {
939  /* if trusted language, need USAGE privilege */
940  AclResult aclresult;
941 
942  aclresult = pg_language_aclcheck(languageOid, GetUserId(), ACL_USAGE);
943  if (aclresult != ACLCHECK_OK)
945  NameStr(languageStruct->lanname));
946  }
947  else
948  {
949  /* if untrusted language, must be superuser */
950  if (!superuser())
952  NameStr(languageStruct->lanname));
953  }
954 
955  languageValidator = languageStruct->lanvalidator;
956 
957  ReleaseSysCache(languageTuple);
958 
959  /*
960  * Only superuser is allowed to create leakproof functions because
961  * leakproof functions can see tuples which have not yet been filtered out
962  * by security barrier views or row level security policies.
963  */
964  if (isLeakProof && !superuser())
965  ereport(ERROR,
966  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
967  errmsg("only superuser can define a leakproof function")));
968 
969  if (transformDefElem)
970  {
971  ListCell *lc;
972 
973  foreach(lc, castNode(List, transformDefElem))
974  {
975  Oid typeid = typenameTypeId(NULL,
976  lfirst_node(TypeName, lc));
977  Oid elt = get_base_element_type(typeid);
978 
979  typeid = elt ? elt : typeid;
980 
981  get_transform_oid(typeid, languageOid, false);
982  trftypes_list = lappend_oid(trftypes_list, typeid);
983  }
984  }
985 
986  /*
987  * Convert remaining parameters of CREATE to form wanted by
988  * ProcedureCreate.
989  */
991  stmt->parameters,
992  languageOid,
993  false, /* not an aggregate */
994  &parameterTypes,
995  &allParameterTypes,
996  &parameterModes,
997  &parameterNames,
998  &parameterDefaults,
999  &variadicArgType,
1000  &requiredResultType);
1001 
1002  if (stmt->returnType)
1003  {
1004  /* explicit RETURNS clause */
1005  compute_return_type(stmt->returnType, languageOid,
1006  &prorettype, &returnsSet);
1007  if (OidIsValid(requiredResultType) && prorettype != requiredResultType)
1008  ereport(ERROR,
1009  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1010  errmsg("function result type must be %s because of OUT parameters",
1011  format_type_be(requiredResultType))));
1012  }
1013  else if (OidIsValid(requiredResultType))
1014  {
1015  /* default RETURNS clause from OUT parameters */
1016  prorettype = requiredResultType;
1017  returnsSet = false;
1018  }
1019  else
1020  {
1021  ereport(ERROR,
1022  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1023  errmsg("function result type must be specified")));
1024  /* Alternative possibility: default to RETURNS VOID */
1025  prorettype = VOIDOID;
1026  returnsSet = false;
1027  }
1028 
1029  if (list_length(trftypes_list) > 0)
1030  {
1031  ListCell *lc;
1032  Datum *arr;
1033  int i;
1034 
1035  arr = palloc(list_length(trftypes_list) * sizeof(Datum));
1036  i = 0;
1037  foreach(lc, trftypes_list)
1038  arr[i++] = ObjectIdGetDatum(lfirst_oid(lc));
1039  trftypes = construct_array(arr, list_length(trftypes_list),
1040  OIDOID, sizeof(Oid), true, 'i');
1041  }
1042  else
1043  {
1044  /* store SQL NULL instead of empty array */
1045  trftypes = NULL;
1046  }
1047 
1048  compute_attributes_with_style(pstate, stmt->withClause, &isStrict, &volatility);
1049 
1050  interpret_AS_clause(languageOid, language, funcname, as_clause,
1051  &prosrc_str, &probin_str);
1052 
1053  /*
1054  * Set default values for COST and ROWS depending on other parameters;
1055  * reject ROWS if it's not returnsSet. NB: pg_dump knows these default
1056  * values, keep it in sync if you change them.
1057  */
1058  if (procost < 0)
1059  {
1060  /* SQL and PL-language functions are assumed more expensive */
1061  if (languageOid == INTERNALlanguageId ||
1062  languageOid == ClanguageId)
1063  procost = 1;
1064  else
1065  procost = 100;
1066  }
1067  if (prorows < 0)
1068  {
1069  if (returnsSet)
1070  prorows = 1000;
1071  else
1072  prorows = 0; /* dummy value if not returnsSet */
1073  }
1074  else if (!returnsSet)
1075  ereport(ERROR,
1076  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1077  errmsg("ROWS is not applicable when function does not return a set")));
1078 
1079  /*
1080  * And now that we have all the parameters, and know we're permitted to do
1081  * so, go ahead and create the function.
1082  */
1083  return ProcedureCreate(funcname,
1084  namespaceId,
1085  stmt->replace,
1086  returnsSet,
1087  prorettype,
1088  GetUserId(),
1089  languageOid,
1090  languageValidator,
1091  prosrc_str, /* converted to text later */
1092  probin_str, /* converted to text later */
1093  false, /* not an aggregate */
1094  isWindowFunc,
1095  security,
1096  isLeakProof,
1097  isStrict,
1098  volatility,
1099  parallel,
1100  parameterTypes,
1101  PointerGetDatum(allParameterTypes),
1102  PointerGetDatum(parameterModes),
1103  PointerGetDatum(parameterNames),
1104  parameterDefaults,
1105  PointerGetDatum(trftypes),
1106  PointerGetDatum(proconfig),
1107  procost,
1108  prorows);
1109 }
#define NIL
Definition: pg_list.h:69
Definition: c.h:526
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
static void compute_attributes_sql_style(ParseState *pstate, List *options, List **as, char **language, Node **transform, bool *windowfunc_p, char *volatility_p, bool *strict_p, bool *security_definer, bool *leakproof_p, ArrayType **proconfig, float4 *procost, float4 *prorows, char *parallel_p)
Definition: functioncmds.c:605
#define INTERNALlanguageId
Definition: pg_language.h:74
Oid GetUserId(void)
Definition: miscinit.c:284
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
#define OIDOID
Definition: pg_type.h:328
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2956
#define PointerGetDatum(X)
Definition: postgres.h:562
static void compute_return_type(TypeName *returnType, Oid languageOid, Oid *prorettype_p, bool *returnsSet_p)
Definition: functioncmds.c:83
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3279
Definition: nodes.h:510
#define ClanguageId
Definition: pg_language.h:77
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
static void interpret_AS_clause(Oid languageOid, const char *languageName, char *funcname, List *as, char **prosrc_str_p, char **probin_str_p)
Definition: functioncmds.c:801
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4484
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4458
void interpret_function_parameter_list(ParseState *pstate, List *parameters, Oid languageOid, bool is_aggregate, oidvector **parameterTypes, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:179
Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
#define VOIDOID
Definition: pg_type.h:690
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3047
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define ACL_USAGE
Definition: parsenodes.h:80
#define ereport(elevel, rest)
Definition: elog.h:122
#define PROPARALLEL_UNSAFE
Definition: pg_proc.h:5548
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5539
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
float float4
Definition: c.h:428
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
bool PLTemplateExists(const char *languageName)
Definition: proclang.c:519
ObjectAddress ProcedureCreate(const char *procedureName, Oid procNamespace, bool replace, bool returnsSet, Oid returnType, Oid proowner, Oid languageObjectId, Oid languageValidator, const char *prosrc, const char *probin, bool isAgg, bool isWindowFunc, bool security_definer, bool isLeakProof, bool isStrict, char volatility, char parallel, oidvector *parameterTypes, Datum allParameterTypes, Datum parameterModes, Datum parameterNames, List *parameterDefaults, Datum trftypes, Datum proconfig, float4 procost, float4 prorows)
Definition: pg_proc.c:67
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
TypeName * returnType
Definition: parsenodes.h:2751
static int list_length(const List *l)
Definition: pg_list.h:89
static void compute_attributes_with_style(ParseState *pstate, List *parameters, bool *isStrict_p, char *volatility_p)
Definition: functioncmds.c:765
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2571
FormData_pg_language * Form_pg_language
Definition: pg_language.h:51
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:547
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ CreateStatistics()

ObjectAddress CreateStatistics ( CreateStatsStmt stmt)

Definition at line 49 of file statscmds.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_statistic_ext_stxdependencies, Anum_pg_statistic_ext_stxkeys, Anum_pg_statistic_ext_stxkind, Anum_pg_statistic_ext_stxname, Anum_pg_statistic_ext_stxnamespace, Anum_pg_statistic_ext_stxndistinct, Anum_pg_statistic_ext_stxowner, Anum_pg_statistic_ext_stxrelid, Assert, buildint2vector(), CacheInvalidateRelcache(), CatalogTupleInsert(), CharGetDatum, CHAROID, compare_int16(), construct_array(), CreateStatsStmt::defnames, DEPENDENCY_AUTO, DEPENDENCY_NORMAL, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, CreateStatsStmt::exprs, ColumnRef::fields, format_type_be(), GETSTRUCT, GetUserId(), heap_form_tuple(), heap_freetuple(), heap_open(), HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, InvalidObjectAddress, InvalidOid, IsA, lengthof, lfirst, linitial, list_length(), lookup_type_cache(), TypeCacheEntry::lt_opr, NameGetDatum, NamespaceRelationId, namestrcpy(), Natts_pg_statistic_ext, NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectIdGetDatum, pg_class_ownercheck(), PointerGetDatum, qsort, QualifiedNameGetCreationNamespace(), RelationData::rd_att, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnOwner(), relation_close(), relation_openrv(), RelationGetRelationName, RelationGetRelid, RelationRelationId, CreateStatsStmt::relations, ReleaseSysCache(), RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RowExclusiveLock, SearchSysCacheAttName(), SearchSysCacheExists2, ShareUpdateExclusiveLock, CreateStatsStmt::stat_types, STATEXTNAMENSP, StatisticExtRelationId, STATS_EXT_DEPENDENCIES, STATS_EXT_NDISTINCT, STATS_MAX_DIMENSIONS, strVal, generate_unaccent_rules::type, TYPECACHE_LT_OPR, types, and values.

Referenced by ProcessUtilitySlow().

50 {
51  int16 attnums[STATS_MAX_DIMENSIONS];
52  int numcols = 0;
53  char *namestr;
54  NameData stxname;
55  Oid statoid;
56  Oid namespaceId;
57  Oid stxowner = GetUserId();
58  HeapTuple htup;
60  bool nulls[Natts_pg_statistic_ext];
61  int2vector *stxkeys;
62  Relation statrel;
63  Relation rel = NULL;
64  Oid relid;
65  ObjectAddress parentobject,
66  myself;
67  Datum types[2]; /* one for each possible type of statistic */
68  int ntypes;
69  ArrayType *stxkind;
70  bool build_ndistinct;
71  bool build_dependencies;
72  bool requested_type = false;
73  int i;
74  ListCell *cell;
75 
76  Assert(IsA(stmt, CreateStatsStmt));
77 
78  /* resolve the pieces of the name (namespace etc.) */
79  namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames, &namestr);
80  namestrcpy(&stxname, namestr);
81 
82  /*
83  * Deal with the possibility that the statistics object already exists.
84  */
86  NameGetDatum(&stxname),
87  ObjectIdGetDatum(namespaceId)))
88  {
89  if (stmt->if_not_exists)
90  {
93  errmsg("statistics object \"%s\" already exists, skipping",
94  namestr)));
95  return InvalidObjectAddress;
96  }
97 
98  ereport(ERROR,
100  errmsg("statistics object \"%s\" already exists", namestr)));
101  }
102 
103  /*
104  * Examine the FROM clause. Currently, we only allow it to be a single
105  * simple table, but later we'll probably allow multiple tables and JOIN
106  * syntax. The grammar is already prepared for that, so we have to check
107  * here that what we got is what we can support.
108  */
109  if (list_length(stmt->relations) != 1)
110  ereport(ERROR,
111  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
112  errmsg("only a single relation is allowed in CREATE STATISTICS")));
113 
114  foreach(cell, stmt->relations)
115  {
116  Node *rln = (Node *) lfirst(cell);
117 
118  if (!IsA(rln, RangeVar))
119  ereport(ERROR,
120  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
121  errmsg("only a single relation is allowed in CREATE STATISTICS")));
122 
123  /*
124  * CREATE STATISTICS will influence future execution plans but does
125  * not interfere with currently executing plans. So it should be
126  * enough to take only ShareUpdateExclusiveLock on relation,
127  * conflicting with ANALYZE and other DDL that sets statistical
128  * information, but not with normal queries.
129  */
131 
132  /* Restrict to allowed relation types */
133  if (rel->rd_rel->relkind != RELKIND_RELATION &&
134  rel->rd_rel->relkind != RELKIND_MATVIEW &&
135  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
136  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
137  ereport(ERROR,
138  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
139  errmsg("relation \"%s\" is not a table, foreign table, or materialized view",
140  RelationGetRelationName(rel))));
141 
142  /* You must own the relation to create stats on it */
143  if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))
146  }
147 
148  Assert(rel);
149  relid = RelationGetRelid(rel);
150 
151  /*
152  * Currently, we only allow simple column references in the expression
153  * list. That will change someday, and again the grammar already supports
154  * it so we have to enforce restrictions here. For now, we can convert
155  * the expression list to a simple array of attnums. While at it, enforce
156  * some constraints.
157  */
158  foreach(cell, stmt->exprs)
159  {
160  Node *expr = (Node *) lfirst(cell);
161  ColumnRef *cref;
162  char *attname;
163  HeapTuple atttuple;
164  Form_pg_attribute attForm;
166 
167  if (!IsA(expr, ColumnRef))
168  ereport(ERROR,
169  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
170  errmsg("only simple column references are allowed in CREATE STATISTICS")));
171  cref = (ColumnRef *) expr;
172 
173  if (list_length(cref->fields) != 1)
174  ereport(ERROR,
175  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
176  errmsg("only simple column references are allowed in CREATE STATISTICS")));
177  attname = strVal((Value *) linitial(cref->fields));
178 
179  atttuple = SearchSysCacheAttName(relid, attname);
180  if (!HeapTupleIsValid(atttuple))
181  ereport(ERROR,
182  (errcode(ERRCODE_UNDEFINED_COLUMN),
183  errmsg("column \"%s\" does not exist",
184  attname)));
185  attForm = (Form_pg_attribute) GETSTRUCT(atttuple);
186 
187  /* Disallow use of system attributes in extended stats */
188  if (attForm->attnum <= 0)
189  ereport(ERROR,
190  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
191  errmsg("statistics creation on system columns is not supported")));
192 
193  /* Disallow data types without a less-than operator */
194  type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
195  if (type->lt_opr == InvalidOid)
196  ereport(ERROR,
197  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
198  errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
199  attname, format_type_be(attForm->atttypid))));
200 
201  /* Make sure no more than STATS_MAX_DIMENSIONS columns are used */
202  if (numcols >= STATS_MAX_DIMENSIONS)
203  ereport(ERROR,
204  (errcode(ERRCODE_TOO_MANY_COLUMNS),
205  errmsg("cannot have more than %d columns in statistics",
207 
208  attnums[numcols] = attForm->attnum;
209  numcols++;
210  ReleaseSysCache(atttuple);
211  }
212 
213  /*
214  * Check that at least two columns were specified in the statement. The
215  * upper bound was already checked in the loop above.
216  */
217  if (numcols < 2)
218  ereport(ERROR,
219  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
220  errmsg("extended statistics require at least 2 columns")));
221 
222  /*
223  * Sort the attnums, which makes detecting duplicates somewhat easier, and
224  * it does not hurt (it does not affect the efficiency, unlike for
225  * indexes, for example).
226  */
227  qsort(attnums, numcols, sizeof(int16), compare_int16);
228 
229  /*
230  * Check for duplicates in the list of columns. The attnums are sorted so
231  * just check consecutive elements.
232  */
233  for (i = 1; i < numcols; i++)
234  {
235  if (attnums[i] == attnums[i - 1])
236  ereport(ERROR,
237  (errcode(ERRCODE_DUPLICATE_COLUMN),
238  errmsg("duplicate column name in statistics definition")));
239  }
240 
241  /* Form an int2vector representation of the sorted column list */
242  stxkeys = buildint2vector(attnums, numcols);
243 
244  /*
245  * Parse the statistics kinds.
246  */
247  build_ndistinct = false;
248  build_dependencies = false;
249  foreach(cell, stmt->stat_types)
250  {
251  char *type = strVal((Value *) lfirst(cell));
252 
253  if (strcmp(type, "ndistinct") == 0)
254  {
255  build_ndistinct = true;
256  requested_type = true;
257  }
258  else if (strcmp(type, "dependencies") == 0)
259  {
260  build_dependencies = true;
261  requested_type = true;
262  }
263  else
264  ereport(ERROR,
265  (errcode(ERRCODE_SYNTAX_ERROR),
266  errmsg("unrecognized statistics kind \"%s\"",
267  type)));
268  }
269  /* If no statistic type was specified, build them all. */
270  if (!requested_type)
271  {
272  build_ndistinct = true;
273  build_dependencies = true;
274  }
275 
276  /* construct the char array of enabled statistic types */
277  ntypes = 0;
278  if (build_ndistinct)
279  types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);
280  if (build_dependencies)
281  types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);
282  Assert(ntypes > 0 && ntypes <= lengthof(types));
283  stxkind = construct_array(types, ntypes, CHAROID, 1, true, 'c');
284 
285  /*
286  * Everything seems fine, so let's build the pg_statistic_ext tuple.
287  */
288  memset(values, 0, sizeof(values));
289  memset(nulls, false, sizeof(nulls));
291  values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);
292  values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
293  values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
294  values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
295  values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);
296 
297  /* no statistics built yet */
298  nulls[Anum_pg_statistic_ext_stxndistinct - 1] = true;
299  nulls[Anum_pg_statistic_ext_stxdependencies - 1] = true;
300 
301  /* insert it into pg_statistic_ext */
303  htup = heap_form_tuple(statrel->rd_att, values, nulls);
304  statoid = CatalogTupleInsert(statrel, htup);
305  heap_freetuple(htup);
307 
308  /*
309  * Invalidate relcache so that others see the new statistics object.
310  */
312 
313  relation_close(rel, NoLock);
314 
315  /*
316  * Add an AUTO dependency on each column used in the stats, so that the
317  * stats object goes away if any or all of them get dropped.
318  */
319  ObjectAddressSet(myself, StatisticExtRelationId, statoid);
320 
321  for (i = 0; i < numcols; i++)
322  {
323  ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
324  recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
325  }
326 
327  /*
328  * Also add dependencies on namespace and owner. These are required
329  * because the stats object might have a different namespace and/or owner
330  * than the underlying table(s).
331  */
332  ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
333  recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);
334 
336 
337  /*
338  * XXX probably there should be a recordDependencyOnCurrentExtension call
339  * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
340  * STATISTICS, which is more work than it seems worth.
341  */
342 
343  /* Return stats object's address */
344  return myself;
345 }
#define Anum_pg_statistic_ext_stxrelid
signed short int16
Definition: c.h:283
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1198
#define STATS_EXT_NDISTINCT
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define NameGetDatum(X)
Definition: postgres.h:601
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
struct typedefs * types
Definition: ecpg.c:29
#define Anum_pg_statistic_ext_stxkind
Oid GetUserId(void)
Definition: miscinit.c:284
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2956
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationRelationId
Definition: pg_class.h:29
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:112
#define RELKIND_MATVIEW
Definition: pg_class.h:165
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3279
Definition: nodes.h:510
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
#define Anum_pg_statistic_ext_stxkeys
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:695
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
#define lengthof(array)
Definition: c.h:600
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:216
#define Anum_pg_statistic_ext_stxowner
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define Anum_pg_statistic_ext_stxnamespace
Definition: c.h:541
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:445
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
static int compare_int16(const void *a, const void *b)
Definition: statscmds.c:36
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define ereport(elevel, rest)
Definition: elog.h:122
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Definition: c.h:515
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define CHAROID
Definition: pg_type.h:296
#define Natts_pg_statistic_ext
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:311
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
#define StatisticExtRelationId
Definition: value.h:42
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
static int list_length(const List *l)
Definition: pg_list.h:89
#define STATS_EXT_DEPENDENCIES
#define Anum_pg_statistic_ext_stxname
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:184
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1248
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define CharGetDatum(X)
Definition: postgres.h:422
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1233
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define Anum_pg_statistic_ext_stxndistinct
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define TYPECACHE_LT_OPR
Definition: typcache.h:125
#define qsort(a, b, c, d)
Definition: port.h:408
#define RELKIND_RELATION
Definition: pg_class.h:160
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
#define RelationGetRelid(relation)
Definition: rel.h:425
List * fields
Definition: parsenodes.h:234
#define Anum_pg_statistic_ext_stxdependencies

◆ CreateTransform()

ObjectAddress CreateTransform ( CreateTransformStmt stmt)

Definition at line 1797 of file functioncmds.c.

References ACL_EXECUTE, ACL_KIND_LANGUAGE, ACL_KIND_PROC, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, Anum_pg_transform_trffromsql, Anum_pg_transform_trflang, Anum_pg_transform_trftosql, Anum_pg_transform_trftype, CatalogTupleInsert(), CatalogTupleUpdate(), check_transform_function(), ObjectAddress::classId, deleteDependencyRecordsFor(), DEPENDENCY_NORMAL, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), CreateTransformStmt::fromsql, get_language_oid(), get_typtype(), GETSTRUCT, GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, INTERNALOID, InvalidOid, InvokeObjectPostCreateHook, CreateTransformStmt::lang, LanguageRelationId, LookupFuncWithArgs(), MemSet, NameListToString(), Natts_pg_transform, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, ObjectWithArgs::objname, OidIsValid, pg_language_aclcheck(), pg_proc_aclcheck(), pg_proc_ownercheck(), pg_type_aclcheck(), pg_type_ownercheck(), ProcedureRelationId, PROCOID, recordDependencyOn(), recordDependencyOnCurrentExtension(), RelationGetDescr, ReleaseSysCache(), CreateTransformStmt::replace, RowExclusiveLock, SearchSysCache1(), SearchSysCache2(), HeapTupleData::t_self, CreateTransformStmt::tosql, TransformRelationId, TRFTYPELANG, CreateTransformStmt::type_name, TypeNameToString(), typenameTypeId(), TypeRelationId, TYPTYPE_DOMAIN, TYPTYPE_PSEUDO, and values.

Referenced by ProcessUtilitySlow().

1798 {
1799  Oid typeid;
1800  char typtype;
1801  Oid langid;
1802  Oid fromsqlfuncid;
1803  Oid tosqlfuncid;
1804  AclResult aclresult;
1805  Form_pg_proc procstruct;
1807  bool nulls[Natts_pg_transform];
1808  bool replaces[Natts_pg_transform];
1809  Oid transformid;
1810  HeapTuple tuple;
1811  HeapTuple newtuple;
1812  Relation relation;
1813  ObjectAddress myself,
1814  referenced;
1815  bool is_replace;
1816 
1817  /*
1818  * Get the type
1819  */
1820  typeid = typenameTypeId(NULL, stmt->type_name);
1821  typtype = get_typtype(typeid);
1822 
1823  if (typtype == TYPTYPE_PSEUDO)
1824  ereport(ERROR,
1825  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1826  errmsg("data type %s is a pseudo-type",
1827  TypeNameToString(stmt->type_name))));
1828 
1829  if (typtype == TYPTYPE_DOMAIN)
1830  ereport(ERROR,
1831  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1832  errmsg("data type %s is a domain",
1833  TypeNameToString(stmt->type_name))));
1834 
1835  if (!pg_type_ownercheck(typeid, GetUserId()))
1837 
1838  aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
1839  if (aclresult != ACLCHECK_OK)
1840  aclcheck_error_type(aclresult, typeid);
1841 
1842  /*
1843  * Get the language
1844  */
1845  langid = get_language_oid(stmt->lang, false);
1846 
1847  aclresult = pg_language_aclcheck(langid, GetUserId(), ACL_USAGE);
1848  if (aclresult != ACLCHECK_OK)
1849  aclcheck_error(aclresult, ACL_KIND_LANGUAGE, stmt->lang);
1850 
1851  /*
1852  * Get the functions
1853  */
1854  if (stmt->fromsql)
1855  {
1856  fromsqlfuncid = LookupFuncWithArgs(stmt->fromsql, false);
1857 
1858  if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
1860 
1861  aclresult = pg_proc_aclcheck(fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1862  if (aclresult != ACLCHECK_OK)
1864 
1865  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1866  if (!HeapTupleIsValid(tuple))
1867  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1868  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1869  if (procstruct->prorettype != INTERNALOID)
1870  ereport(ERROR,
1871  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1872  errmsg("return data type of FROM SQL function must be %s",
1873  "internal")));
1874  check_transform_function(procstruct);
1875  ReleaseSysCache(tuple);
1876  }
1877  else
1878  fromsqlfuncid = InvalidOid;
1879 
1880  if (stmt->tosql)
1881  {
1882  tosqlfuncid = LookupFuncWithArgs(stmt->tosql, false);
1883 
1884  if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
1886 
1887  aclresult = pg_proc_aclcheck(tosqlfuncid, GetUserId(), ACL_EXECUTE);
1888  if (aclresult != ACLCHECK_OK)
1890 
1891  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1892  if (!HeapTupleIsValid(tuple))
1893  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1894  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1895  if (procstruct->prorettype != typeid)
1896  ereport(ERROR,
1897  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1898  errmsg("return data type of TO SQL function must be the transform data type")));
1899  check_transform_function(procstruct);
1900  ReleaseSysCache(tuple);
1901  }
1902  else
1903  tosqlfuncid = InvalidOid;
1904 
1905  /*
1906  * Ready to go
1907  */
1908  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1909  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1910  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1911  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1912 
1913  MemSet(nulls, false, sizeof(nulls));
1914 
1916 
1917  tuple = SearchSysCache2(TRFTYPELANG,
1918  ObjectIdGetDatum(typeid),
1919  ObjectIdGetDatum(langid));
1920  if (HeapTupleIsValid(tuple))
1921  {
1922  if (!stmt->replace)
1923  ereport(ERROR,
1925  errmsg("transform for type %s language \"%s\" already exists",
1926  format_type_be(typeid),
1927  stmt->lang)));
1928 
1929  MemSet(replaces, false, sizeof(replaces));
1930  replaces[Anum_pg_transform_trffromsql - 1] = true;
1931  replaces[Anum_pg_transform_trftosql - 1] = true;
1932 
1933  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1934  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
1935 
1936  transformid = HeapTupleGetOid(tuple);
1937  ReleaseSysCache(tuple);
1938  is_replace = true;
1939  }
1940  else
1941  {
1942  newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1943  transformid = CatalogTupleInsert(relation, newtuple);
1944  is_replace = false;
1945  }
1946 
1947  if (is_replace)
1948  deleteDependencyRecordsFor(TransformRelationId, transformid, true);
1949 
1950  /* make dependency entries */
1951  myself.classId = TransformRelationId;
1952  myself.objectId = transformid;
1953  myself.objectSubId = 0;
1954 
1955  /* dependency on language */
1956  referenced.classId = LanguageRelationId;
1957  referenced.objectId = langid;
1958  referenced.objectSubId = 0;
1959  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1960 
1961  /* dependency on type */
1962  referenced.classId = TypeRelationId;
1963  referenced.objectId = typeid;
1964  referenced.objectSubId = 0;
1965  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1966 
1967  /* dependencies on functions */
1968  if (OidIsValid(fromsqlfuncid))
1969  {
1970  referenced.classId = ProcedureRelationId;
1971  referenced.objectId = fromsqlfuncid;
1972  referenced.objectSubId = 0;
1973  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1974  }
1975  if (OidIsValid(tosqlfuncid))
1976  {
1977  referenced.classId = ProcedureRelationId;
1978  referenced.objectId = tosqlfuncid;
1979  referenced.objectSubId = 0;
1980  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1981  }
1982 
1983  /* dependency on extension */
1984  recordDependencyOnCurrentExtension(&myself, is_replace);
1985 
1986  /* Post creation hook for new transform */
1988 
1989  heap_freetuple(newtuple);
1990 
1991  heap_close(relation, RowExclusiveLock);
1992 
1993  return myself;
1994 }
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
ObjectWithArgs * tosql
Definition: parsenodes.h:3297
static void check_transform_function(Form_pg_proc procstruct)
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define TransformRelationId
Definition: pg_transform.h:25
#define RelationGetDescr(relation)
Definition: rel.h:437
Oid GetUserId(void)
Definition: miscinit.c:284
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:459
#define ProcedureRelationId
Definition: pg_proc.h:33
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:191
Oid get_language_oid(const char *langname, bool missing_ok)
Definition: proclang.c:553
int errcode(int sqlerrcode)
Definition: elog.c:575
char get_typtype(Oid typid)
Definition: lsyscache.c:2379
#define MemSet(start, val, len)
Definition: c.h:853
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
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:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
bool pg_type_ownercheck(Oid type_oid, Oid roleid)
Definition: aclchk.c:4572
#define TypeRelationId
Definition: pg_type.h:34
#define OidIsValid(objectId)
Definition: c.h:576
#define Anum_pg_transform_trftosql
Definition: pg_transform.h:45
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4458
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3457
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define Natts_pg_transform
Definition: pg_transform.h:41
#define Anum_pg_transform_trflang
Definition: pg_transform.h:43
ItemPointerData t_self
Definition: htup.h:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ACL_USAGE
Definition: parsenodes.h:80
#define ereport(elevel, rest)
Definition: elog.h:122
Oid LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
Definition: parse_func.c:1991
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
char * NameListToString(List *names)
Definition: namespace.c:3063
AclResult
Definition: acl.h:178
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
ObjectWithArgs * fromsql
Definition: parsenodes.h:3296
#define Anum_pg_transform_trffromsql
Definition: pg_transform.h:44
#define INTERNALOID
Definition: pg_type.h:698
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1123
#define TYPTYPE_PSEUDO
Definition: pg_type.h:724
#define Anum_pg_transform_trftype
Definition: pg_transform.h:42
TypeName * type_name
Definition: parsenodes.h:3294
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ACL_EXECUTE
Definition: parsenodes.h:79
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4446
#define LanguageRelationId
Definition: pg_language.h:29
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4534
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4624
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274

◆ CreateUserMapping()

ObjectAddress CreateUserMapping ( CreateUserMappingStmt stmt)

Definition at line 1135 of file foreigncmds.c.

References ACL_ID_PUBLIC, Anum_pg_user_mapping_umoptions, Anum_pg_user_mapping_umserver, Anum_pg_user_mapping_umuser, CatalogTupleInsert(), ObjectAddress::classId, DatumGetPointer, DEPENDENCY_NORMAL, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, ForeignServer::fdwid, ForeignDataWrapper::fdwvalidator, ForeignServerRelationId, get_rolespec_oid(), GetForeignDataWrapper(), GetForeignServerByName(), GetSysCacheOid2, heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), CreateUserMappingStmt::if_not_exists, InvalidObjectAddress, InvokeObjectPostCreateHook, MappingUserName, Natts_pg_user_mapping, NOTICE, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, CreateUserMappingStmt::options, PointerGetDatum, PointerIsValid, RelationData::rd_att, recordDependencyOn(), recordDependencyOnCurrentExtension(), recordDependencyOnOwner(), ROLESPEC_PUBLIC, RoleSpec::roletype, RowExclusiveLock, ForeignServer::serverid, CreateUserMappingStmt::servername, transformGenericOptions(), CreateUserMappingStmt::user, user_mapping_ddl_aclcheck(), UserMappingRelationId, and values.

Referenced by ProcessUtilitySlow().

1136 {
1137  Relation rel;
1138  Datum useoptions;
1140  bool nulls[Natts_pg_user_mapping];
1141  HeapTuple tuple;
1142  Oid useId;
1143  Oid umId;
1144  ObjectAddress myself;
1145  ObjectAddress referenced;
1146  ForeignServer *srv;
1147  ForeignDataWrapper *fdw;
1148  RoleSpec *role = (RoleSpec *) stmt->user;
1149 
1151 
1152  if (role->roletype == ROLESPEC_PUBLIC)
1153  useId = ACL_ID_PUBLIC;
1154  else
1155  useId = get_rolespec_oid(stmt->user, false);
1156 
1157  /* Check that the server exists. */
1158  srv = GetForeignServerByName(stmt->servername, false);
1159 
1160  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1161 
1162  /*
1163  * Check that the user mapping is unique within server.
1164  */
1165  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER,
1166  ObjectIdGetDatum(useId),
1167  ObjectIdGetDatum(srv->serverid));
1168 
1169  if (OidIsValid(umId))
1170  {
1171  if (stmt->if_not_exists)
1172  {
1173  ereport(NOTICE,
1175  errmsg("user mapping for \"%s\" already exists for server %s, skipping",
1176  MappingUserName(useId),
1177  stmt->servername)));
1178 
1180  return InvalidObjectAddress;
1181  }
1182  else
1183  ereport(ERROR,
1185  errmsg("user mapping for \"%s\" already exists for server %s",
1186  MappingUserName(useId),
1187  stmt->servername)));
1188  }
1189 
1190  fdw = GetForeignDataWrapper(srv->fdwid);
1191 
1192  /*
1193  * Insert tuple into pg_user_mapping.
1194  */
1195  memset(values, 0, sizeof(values));
1196  memset(nulls, false, sizeof(nulls));
1197 
1198  values[Anum_pg_user_mapping_umuser - 1] = ObjectIdGetDatum(useId);
1200 
1201  /* Add user options */
1203  PointerGetDatum(NULL),
1204  stmt->options,
1205  fdw->fdwvalidator);
1206 
1207  if (PointerIsValid(DatumGetPointer(useoptions)))
1208  values[Anum_pg_user_mapping_umoptions - 1] = useoptions;
1209  else
1210  nulls[Anum_pg_user_mapping_umoptions - 1] = true;
1211 
1212  tuple = heap_form_tuple(rel->rd_att, values, nulls);
1213 
1214  umId = CatalogTupleInsert(rel, tuple);
1215 
1216  heap_freetuple(tuple);
1217 
1218  /* Add dependency on the server */
1219  myself.classId = UserMappingRelationId;
1220  myself.objectId = umId;
1221  myself.objectSubId = 0;
1222 
1223  referenced.classId = ForeignServerRelationId;
1224  referenced.objectId = srv->serverid;
1225  referenced.objectSubId = 0;
1226  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1227 
1228  if (OidIsValid(useId))
1229  {
1230  /* Record the mapped user dependency */
1232  }
1233 
1234  /* dependency on extension */
1235  recordDependencyOnCurrentExtension(&myself, false);
1236 
1237  /* Post creation hook for new user mapping */
1239 
1241 
1242  return myself;
1243 }
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define Anum_pg_user_mapping_umuser
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:109
#define Anum_pg_user_mapping_umserver
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1110
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:695
#define heap_close(r, l)
Definition: heapam.h:97
#define Natts_pg_user_mapping
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define GetSysCacheOid2(cacheId, key1, key2)
Definition: syscache.h:193
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define Anum_pg_user_mapping_umoptions
#define RowExclusiveLock
Definition: lockdefs.h:38
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:148
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
RoleSpecType roletype
Definition: parsenodes.h:327
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5146
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
TupleDesc rd_att
Definition: rel.h:115
#define NOTICE
Definition: elog.h:37