PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 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, char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
Oid ResolveOpClass (List *opclass, Oid attrType, 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

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, NULL, 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:656
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:429
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:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#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:2174
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
List * func_options
Definition: parsenodes.h:2175
#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:1279
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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
#define NULL
Definition: c.h:229
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:2176
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
#define PointerIsValid(pointer)
Definition: c.h:526
#define Anum_pg_foreign_data_wrapper_fdwoptions
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:1372
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:1284
#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:165
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:695
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:1372
#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:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define ForeignDataWrapperRelationId
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:207
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, NULL, 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:656
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
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:1372
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:1279
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
FormData_pg_foreign_server * Form_pg_foreign_server
#define ForeignServerRelationId
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
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:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define Anum_pg_foreign_server_srvoptions
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
#define PointerIsValid(pointer)
Definition: c.h:526
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:1372
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:1284
#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:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
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:1372
#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:1284
#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:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
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, NULL, 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:656
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
#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:1372
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:1971
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:532
Node * arg
Definition: parsenodes.h:721
char * NameListToString(List *names)
Definition: namespace.c:3020
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:1279
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
ObjectWithArgs * func
Definition: parsenodes.h:2735
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#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:165
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:720
#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:791
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:242
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, NULL, 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:656
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
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:538
#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:721
#define Anum_pg_operator_oprrest
Definition: pg_operator.h:77
ObjectWithArgs * opername
Definition: parsenodes.h:2825
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#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:163
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:165
#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:499
char * defname
Definition: parsenodes.h:720
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
Definition: pg_list.h:45
Oid AlterOpFamily ( AlterOpFamilyStmt stmt)

Definition at line 763 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().

764 {
765  Oid amoid, /* our AM's oid */
766  opfamilyoid; /* oid of opfamily */
767  int maxOpNumber, /* amstrategies value */
768  maxProcNumber; /* amsupport value */
769  HeapTuple tup;
770  IndexAmRoutine *amroutine;
771 
772  /* Get necessary info about access method */
774  if (!HeapTupleIsValid(tup))
775  ereport(ERROR,
776  (errcode(ERRCODE_UNDEFINED_OBJECT),
777  errmsg("access method \"%s\" does not exist",
778  stmt->amname)));
779 
780  amoid = HeapTupleGetOid(tup);
781  amroutine = GetIndexAmRoutineByAmId(amoid, false);
782  ReleaseSysCache(tup);
783 
784  maxOpNumber = amroutine->amstrategies;
785  /* if amstrategies is zero, just enforce that op numbers fit in int16 */
786  if (maxOpNumber <= 0)
787  maxOpNumber = SHRT_MAX;
788  maxProcNumber = amroutine->amsupport;
789 
790  /* XXX Should we make any privilege check against the AM? */
791 
792  /* Look up the opfamily */
793  opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
794 
795  /*
796  * Currently, we require superuser privileges to alter an opfamily.
797  *
798  * XXX re-enable NOT_USED code sections below if you remove this test.
799  */
800  if (!superuser())
801  ereport(ERROR,
802  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
803  errmsg("must be superuser to alter an operator family")));
804 
805  /*
806  * ADD and DROP cases need separate code from here on down.
807  */
808  if (stmt->isDrop)
809  AlterOpFamilyDrop(stmt, amoid, opfamilyoid,
810  maxOpNumber, maxProcNumber, stmt->items);
811  else
812  AlterOpFamilyAdd(stmt, amoid, opfamilyoid,
813  maxOpNumber, maxProcNumber, stmt->items);
814 
815  return opfamilyoid;
816 }
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
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, List *items)
Definition: opclasscmds.c:947
#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
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#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:822
Oid get_opfamily_oid(Oid amID, List *opfamilyname, bool missing_ok)
Definition: opclasscmds.c:141
uint16 amstrategies
Definition: amapi.h:167
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
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:283
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:3020
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#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:695
static void MakeConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1278
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, NULL, 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:656
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:429
Oid GetUserId(void)
Definition: miscinit.c:283
#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:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
Oid get_ts_dict_oid(List *names, bool missing_ok)
Definition: namespace.c:2343
#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:721
List * lappend(List *list, void *datum)
Definition: list.c:128
char * NameListToString(List *names)
Definition: namespace.c:3020
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:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#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:720
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
Definition: pg_list.h:45
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, NULL, 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:429
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:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define GetSysCacheOid2(cacheId, key1, key2)
Definition: syscache.h:185
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:328
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5129
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
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:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define UserMappingRelationId
#define ACL_ID_PUBLIC
Definition: acl.h:39
#define elog
Definition: elog.h:219
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
#define PointerIsValid(pointer)
Definition: c.h:526
Oid serverid
Definition: foreign.h:47
#define MappingUserName(userid)
Definition: foreign.h:20
bool CheckIndexCompatible ( Oid  oldId,
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, tupleDesc::attrs, 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, NULL, ObjectIdGetDatum, op_input_types(), palloc(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), ReleaseSysCache(), SearchSysCache1, SysCacheGetAttr(), 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  irel->rd_att->attrs[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  irel->rd_att->attrs[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:255
#define NIL
Definition: pg_list.h:69
Definition: c.h:478
MemoryContext ii_Context
Definition: execnodes.h:151
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3275
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5054
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
#define PointerGetDatum(X)
Definition: postgres.h:562
ExprState * ii_PredicateState
Definition: execnodes.h:139
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#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
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
List * ii_ExpressionsState
Definition: execnodes.h:137
unsigned short uint16
Definition: c.h:267
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:994
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:486
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:297
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
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_index_indpred
Definition: pg_index.h:92
#define makeNode(_type_)
Definition: nodes.h:557
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
List * ii_Expressions
Definition: execnodes.h:136
#define Assert(condition)
Definition: c.h:675
#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:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
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
char* ChooseRelationName ( const char *  name1,
const char *  name2,
const char *  label,
Oid  namespaceid 
)

Definition at line 1566 of file indexcmds.c.

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

Referenced by ChooseIndexName(), and generateSerialExtraStmts().

1568 {
1569  int pass = 0;
1570  char *relname = NULL;
1571  char modlabel[NAMEDATALEN];
1572 
1573  /* try the unmodified label first */
1574  StrNCpy(modlabel, label, sizeof(modlabel));
1575 
1576  for (;;)
1577  {
1578  relname = makeObjectName(name1, name2, modlabel);
1579 
1580  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
1581  break;
1582 
1583  /* found a conflict, so try a new name component */
1584  pfree(relname);
1585  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
1586  }
1587 
1588  return relname;
1589 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define OidIsValid(objectId)
Definition: c.h:538
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:1486
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:950
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1683
static char * label
Definition: pg_basebackup.c:81
#define NULL
Definition: c.h:229
#define StrNCpy(dst, src, len)
Definition: c.h:830
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:429
#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:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define GetSysCacheOid1(cacheId, key1)
Definition: syscache.h:183
#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:2306
#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:2307
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#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:163
#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:31
ObjectAddress CreateCast ( CreateCastStmt stmt)

Definition at line 1378 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, NULL, 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().

1379 {
1380  Oid sourcetypeid;
1381  Oid targettypeid;
1382  char sourcetyptype;
1383  char targettyptype;
1384  Oid funcid;
1385  Oid castid;
1386  int nargs;
1387  char castcontext;
1388  char castmethod;
1389  Relation relation;
1390  HeapTuple tuple;
1392  bool nulls[Natts_pg_cast];
1393  ObjectAddress myself,
1394  referenced;
1395  AclResult aclresult;
1396 
1397  sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1398  targettypeid = typenameTypeId(NULL, stmt->targettype);
1399  sourcetyptype = get_typtype(sourcetypeid);
1400  targettyptype = get_typtype(targettypeid);
1401 
1402  /* No pseudo-types allowed */
1403  if (sourcetyptype == TYPTYPE_PSEUDO)
1404  ereport(ERROR,
1405  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1406  errmsg("source data type %s is a pseudo-type",
1407  TypeNameToString(stmt->sourcetype))));
1408 
1409  if (targettyptype == TYPTYPE_PSEUDO)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1412  errmsg("target data type %s is a pseudo-type",
1413  TypeNameToString(stmt->targettype))));
1414 
1415  /* Permission check */
1416  if (!pg_type_ownercheck(sourcetypeid, GetUserId())
1417  && !pg_type_ownercheck(targettypeid, GetUserId()))
1418  ereport(ERROR,
1419  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1420  errmsg("must be owner of type %s or type %s",
1421  format_type_be(sourcetypeid),
1422  format_type_be(targettypeid))));
1423 
1424  aclresult = pg_type_aclcheck(sourcetypeid, GetUserId(), ACL_USAGE);
1425  if (aclresult != ACLCHECK_OK)
1426  aclcheck_error_type(aclresult, sourcetypeid);
1427 
1428  aclresult = pg_type_aclcheck(targettypeid, GetUserId(), ACL_USAGE);
1429  if (aclresult != ACLCHECK_OK)
1430  aclcheck_error_type(aclresult, targettypeid);
1431 
1432  /* Domains are allowed for historical reasons, but we warn */
1433  if (sourcetyptype == TYPTYPE_DOMAIN)
1434  ereport(WARNING,
1435  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1436  errmsg("cast will be ignored because the source data type is a domain")));
1437 
1438  else if (targettyptype == TYPTYPE_DOMAIN)
1439  ereport(WARNING,
1440  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1441  errmsg("cast will be ignored because the target data type is a domain")));
1442 
1443  /* Determine the cast method */
1444  if (stmt->func != NULL)
1445  castmethod = COERCION_METHOD_FUNCTION;
1446  else if (stmt->inout)
1447  castmethod = COERCION_METHOD_INOUT;
1448  else
1449  castmethod = COERCION_METHOD_BINARY;
1450 
1451  if (castmethod == COERCION_METHOD_FUNCTION)
1452  {
1453  Form_pg_proc procstruct;
1454 
1455  funcid = LookupFuncWithArgs(stmt->func, false);
1456 
1457  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1458  if (!HeapTupleIsValid(tuple))
1459  elog(ERROR, "cache lookup failed for function %u", funcid);
1460 
1461  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1462  nargs = procstruct->pronargs;
1463  if (nargs < 1 || nargs > 3)
1464  ereport(ERROR,
1465  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1466  errmsg("cast function must take one to three arguments")));
1467  if (!IsBinaryCoercible(sourcetypeid, procstruct->proargtypes.values[0]))
1468  ereport(ERROR,
1469  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1470  errmsg("argument of cast function must match or be binary-coercible from source data type")));
1471  if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1472  ereport(ERROR,
1473  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1474  errmsg("second argument of cast function must be type %s",
1475  "integer")));
1476  if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1477  ereport(ERROR,
1478  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1479  errmsg("third argument of cast function must be type %s",
1480  "boolean")));
1481  if (!IsBinaryCoercible(procstruct->prorettype, targettypeid))
1482  ereport(ERROR,
1483  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1484  errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1485 
1486  /*
1487  * Restricting the volatility of a cast function may or may not be a
1488  * good idea in the abstract, but it definitely breaks many old
1489  * user-defined types. Disable this check --- tgl 2/1/03
1490  */
1491 #ifdef NOT_USED
1492  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1493  ereport(ERROR,
1494  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1495  errmsg("cast function must not be volatile")));
1496 #endif
1497  if (procstruct->proisagg)
1498  ereport(ERROR,
1499  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1500  errmsg("cast function must not be an aggregate function")));
1501  if (procstruct->proiswindow)
1502  ereport(ERROR,
1503  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1504  errmsg("cast function must not be a window function")));
1505  if (procstruct->proretset)
1506  ereport(ERROR,
1507  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1508  errmsg("cast function must not return a set")));
1509 
1510  ReleaseSysCache(tuple);
1511  }
1512  else
1513  {
1514  funcid = InvalidOid;
1515  nargs = 0;
1516  }
1517 
1518  if (castmethod == COERCION_METHOD_BINARY)
1519  {
1520  int16 typ1len;
1521  int16 typ2len;
1522  bool typ1byval;
1523  bool typ2byval;
1524  char typ1align;
1525  char typ2align;
1526 
1527  /*
1528  * Must be superuser to create binary-compatible casts, since
1529  * erroneous casts can easily crash the backend.
1530  */
1531  if (!superuser())
1532  ereport(ERROR,
1533  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1534  errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1535 
1536  /*
1537  * Also, insist that the types match as to size, alignment, and
1538  * pass-by-value attributes; this provides at least a crude check that
1539  * they have similar representations. A pair of types that fail this
1540  * test should certainly not be equated.
1541  */
1542  get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1543  get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1544  if (typ1len != typ2len ||
1545  typ1byval != typ2byval ||
1546  typ1align != typ2align)
1547  ereport(ERROR,
1548  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1549  errmsg("source and target data types are not physically compatible")));
1550 
1551  /*
1552  * We know that composite, enum and array types are never binary-
1553  * compatible with each other. They all have OIDs embedded in them.
1554  *
1555  * Theoretically you could build a user-defined base type that is
1556  * binary-compatible with a composite, enum, or array type. But we
1557  * disallow that too, as in practice such a cast is surely a mistake.
1558  * You can always work around that by writing a cast function.
1559  */
1560  if (sourcetyptype == TYPTYPE_COMPOSITE ||
1561  targettyptype == TYPTYPE_COMPOSITE)
1562  ereport(ERROR,
1563  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1564  errmsg("composite data types are not binary-compatible")));
1565 
1566  if (sourcetyptype == TYPTYPE_ENUM ||
1567  targettyptype == TYPTYPE_ENUM)
1568  ereport(ERROR,
1569  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1570  errmsg("enum data types are not binary-compatible")));
1571 
1572  if (OidIsValid(get_element_type(sourcetypeid)) ||
1573  OidIsValid(get_element_type(targettypeid)))
1574  ereport(ERROR,
1575  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1576  errmsg("array data types are not binary-compatible")));
1577 
1578  /*
1579  * We also disallow creating binary-compatibility casts involving
1580  * domains. Casting from a domain to its base type is already
1581  * allowed, and casting the other way ought to go through domain
1582  * coercion to permit constraint checking. Again, if you're intent on
1583  * having your own semantics for that, create a no-op cast function.
1584  *
1585  * NOTE: if we were to relax this, the above checks for composites
1586  * etc. would have to be modified to look through domains to their
1587  * base types.
1588  */
1589  if (sourcetyptype == TYPTYPE_DOMAIN ||
1590  targettyptype == TYPTYPE_DOMAIN)
1591  ereport(ERROR,
1592  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1593  errmsg("domain data types must not be marked binary-compatible")));
1594  }
1595 
1596  /*
1597  * Allow source and target types to be same only for length coercion
1598  * functions. We assume a multi-arg function does length coercion.
1599  */
1600  if (sourcetypeid == targettypeid && nargs < 2)
1601  ereport(ERROR,
1602  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1603  errmsg("source data type and target data type are the same")));
1604 
1605  /* convert CoercionContext enum to char value for castcontext */
1606  switch (stmt->context)
1607  {
1608  case COERCION_IMPLICIT:
1609  castcontext = COERCION_CODE_IMPLICIT;
1610  break;
1611  case COERCION_ASSIGNMENT:
1612  castcontext = COERCION_CODE_ASSIGNMENT;
1613  break;
1614  case COERCION_EXPLICIT:
1615  castcontext = COERCION_CODE_EXPLICIT;
1616  break;
1617  default:
1618  elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1619  castcontext = 0; /* keep compiler quiet */
1620  break;
1621  }
1622 
1624 
1625  /*
1626  * Check for duplicate. This is just to give a friendly error message,
1627  * the unique index would catch it anyway (so no need to sweat about race
1628  * conditions).
1629  */
1631  ObjectIdGetDatum(sourcetypeid),
1632  ObjectIdGetDatum(targettypeid));
1633  if (HeapTupleIsValid(tuple))
1634  ereport(ERROR,
1636  errmsg("cast from type %s to type %s already exists",
1637  format_type_be(sourcetypeid),
1638  format_type_be(targettypeid))));
1639 
1640  /* ready to go */
1641  values[Anum_pg_cast_castsource - 1] = ObjectIdGetDatum(sourcetypeid);
1642  values[Anum_pg_cast_casttarget - 1] = ObjectIdGetDatum(targettypeid);
1643  values[Anum_pg_cast_castfunc - 1] = ObjectIdGetDatum(funcid);
1644  values[Anum_pg_cast_castcontext - 1] = CharGetDatum(castcontext);
1645  values[Anum_pg_cast_castmethod - 1] = CharGetDatum(castmethod);
1646 
1647  MemSet(nulls, false, sizeof(nulls));
1648 
1649  tuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1650 
1651  castid = CatalogTupleInsert(relation, tuple);
1652 
1653  /* make dependency entries */
1654  myself.classId = CastRelationId;
1655  myself.objectId = castid;
1656  myself.objectSubId = 0;
1657 
1658  /* dependency on source type */
1659  referenced.classId = TypeRelationId;
1660  referenced.objectId = sourcetypeid;
1661  referenced.objectSubId = 0;
1662  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1663 
1664  /* dependency on target type */
1665  referenced.classId = TypeRelationId;
1666  referenced.objectId = targettypeid;
1667  referenced.objectSubId = 0;
1668  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1669 
1670  /* dependency on function */
1671  if (OidIsValid(funcid))
1672  {
1673  referenced.classId = ProcedureRelationId;
1674  referenced.objectId = funcid;
1675  referenced.objectSubId = 0;
1676  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1677  }
1678 
1679  /* dependency on extension */
1680  recordDependencyOnCurrentExtension(&myself, false);
1681 
1682  /* Post creation hook for new cast */
1684 
1685  heap_freetuple(tuple);
1686 
1687  heap_close(relation, RowExclusiveLock);
1688 
1689  return myself;
1690 }
signed short int16
Definition: c.h:255
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
TypeName * sourcetype
Definition: parsenodes.h:3222
#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:656
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2484
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:857
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:692
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
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:538
#define Anum_pg_cast_castmethod
Definition: pg_cast.h:82
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
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:3225
#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:1971
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5485
#define WARNING
Definition: elog.h:40
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
ObjectWithArgs * func
Definition: parsenodes.h:3224
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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
#define NULL
Definition: c.h:229
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
#define CastRelationId
Definition: pg_cast.h:31
#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:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
TypeName * targettype
Definition: parsenodes.h:3223
#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:31
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:158
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, NULL, 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 
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:283
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:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define Anum_pg_foreign_data_wrapper_fdwacl
List * options
Definition: parsenodes.h:2168
#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:2166
#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:1284
TupleDesc rd_att
Definition: rel.h:115
#define Anum_pg_foreign_data_wrapper_fdwvalidator
#define Natts_pg_foreign_data_wrapper
#define NULL
Definition: c.h:229
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:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define PointerIsValid(pointer)
Definition: c.h:526
#define Anum_pg_foreign_data_wrapper_fdwoptions
List * func_options
Definition: parsenodes.h:2167
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, NULL, 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 */
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:283
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:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
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:170
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
TupleDesc rd_att
Definition: rel.h:115
#define NOTICE
Definition: elog.h:37
#define ForeignServerRelationId
#define NULL
Definition: c.h:229
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:163
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:31
#define PointerIsValid(pointer)
Definition: c.h:526
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, NULL, 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 */
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:283
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:692
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
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:170
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
TupleDesc rd_att
Definition: rel.h:115
#define ForeignServerRelationId
#define NULL
Definition: c.h:229
#define DatumGetPointer(X)
Definition: postgres.h:555
static Datum values[MAXATTR]
Definition: bootstrap.c:163
char * servername
Definition: foreign.h:50
#define ForeignTableRelationId
#define PointerIsValid(pointer)
Definition: c.h:526
Oid serverid
Definition: foreign.h:47
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, NULL, 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:478
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
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:283
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
#define OIDOID
Definition: pg_type.h:328
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2913
#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:3306
Definition: nodes.h:509
#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:538
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
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
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:3033
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:5494
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5485
float float4
Definition: c.h:380
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
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
#define NULL
Definition: c.h:229
TypeName * returnType
Definition: parsenodes.h:2708
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:2557
FormData_pg_language * Form_pg_language
Definition: pg_language.h:51
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:499
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
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
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, GETSTRUCT, GetUserId(), heap_form_tuple(), heap_freetuple(), heap_open(), HeapTupleGetOid, 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, NULL, 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, 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;
165  TypeCacheEntry *type;
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\" referenced in statistics 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 has no default btree operator class",
199  attname)));
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 types.
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 statistic type \"%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  CatalogTupleInsert(statrel, htup);
305  statoid = HeapTupleGetOid(htup);
306  heap_freetuple(htup);
308 
309  /*
310  * Invalidate relcache so that others see the new statistics object.
311  */
313 
314  relation_close(rel, NoLock);
315 
316  /*
317  * Add an AUTO dependency on each column used in the stats, so that the
318  * stats object goes away if any or all of them get dropped.
319  */
320  ObjectAddressSet(myself, StatisticExtRelationId, statoid);
321 
322  for (i = 0; i < numcols; i++)
323  {
324  ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
325  recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
326  }
327 
328  /*
329  * Also add dependencies on namespace and owner. These are required
330  * because the stats object might have a different namespace and/or owner
331  * than the underlying table(s).
332  */
333  ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
334  recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);
335 
337 
338  /*
339  * XXX probably there should be a recordDependencyOnCurrentExtension call
340  * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
341  * STATISTICS, which is more work than it seems worth.
342  */
343 
344  /* Return stats object's address */
345  return myself;
346 }
#define Anum_pg_statistic_ext_stxrelid
signed short int16
Definition: c.h:255
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1192
#define STATS_EXT_NDISTINCT
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define NameGetDatum(X)
Definition: postgres.h:601
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
struct typedefs * types
Definition: ecpg.c:29
#define Anum_pg_statistic_ext_stxkind
Oid GetUserId(void)
Definition: miscinit.c:283
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2913
#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:3306
Definition: nodes.h:509
#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:1260
#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:692
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
#define lengthof(array)
Definition: c.h:562
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#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:493
#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:437
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:467
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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:191
#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 NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:176
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1205
#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:163
#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:111
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define qsort(a, b, c, d)
Definition: port.h:440
#define RELKIND_RELATION
Definition: pg_class.h:160
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
#define RelationGetRelid(relation)
Definition: rel.h:417
List * fields
Definition: parsenodes.h:235
#define Anum_pg_statistic_ext_stxdependencies
ObjectAddress CreateTransform ( CreateTransformStmt stmt)

Definition at line 1777 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, NULL, 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().

1778 {
1779  Oid typeid;
1780  char typtype;
1781  Oid langid;
1782  Oid fromsqlfuncid;
1783  Oid tosqlfuncid;
1784  AclResult aclresult;
1785  Form_pg_proc procstruct;
1787  bool nulls[Natts_pg_transform];
1788  bool replaces[Natts_pg_transform];
1789  Oid transformid;
1790  HeapTuple tuple;
1791  HeapTuple newtuple;
1792  Relation relation;
1793  ObjectAddress myself,
1794  referenced;
1795  bool is_replace;
1796 
1797  /*
1798  * Get the type
1799  */
1800  typeid = typenameTypeId(NULL, stmt->type_name);
1801  typtype = get_typtype(typeid);
1802 
1803  if (typtype == TYPTYPE_PSEUDO)
1804  ereport(ERROR,
1805  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1806  errmsg("data type %s is a pseudo-type",
1807  TypeNameToString(stmt->type_name))));
1808 
1809  if (typtype == TYPTYPE_DOMAIN)
1810  ereport(ERROR,
1811  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1812  errmsg("data type %s is a domain",
1813  TypeNameToString(stmt->type_name))));
1814 
1815  if (!pg_type_ownercheck(typeid, GetUserId()))
1817 
1818  aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
1819  if (aclresult != ACLCHECK_OK)
1820  aclcheck_error_type(aclresult, typeid);
1821 
1822  /*
1823  * Get the language
1824  */
1825  langid = get_language_oid(stmt->lang, false);
1826 
1827  aclresult = pg_language_aclcheck(langid, GetUserId(), ACL_USAGE);
1828  if (aclresult != ACLCHECK_OK)
1829  aclcheck_error(aclresult, ACL_KIND_LANGUAGE, stmt->lang);
1830 
1831  /*
1832  * Get the functions
1833  */
1834  if (stmt->fromsql)
1835  {
1836  fromsqlfuncid = LookupFuncWithArgs(stmt->fromsql, false);
1837 
1838  if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
1840 
1841  aclresult = pg_proc_aclcheck(fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1842  if (aclresult != ACLCHECK_OK)
1844 
1845  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1846  if (!HeapTupleIsValid(tuple))
1847  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1848  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1849  if (procstruct->prorettype != INTERNALOID)
1850  ereport(ERROR,
1851  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1852  errmsg("return data type of FROM SQL function must be %s",
1853  "internal")));
1854  check_transform_function(procstruct);
1855  ReleaseSysCache(tuple);
1856  }
1857  else
1858  fromsqlfuncid = InvalidOid;
1859 
1860  if (stmt->tosql)
1861  {
1862  tosqlfuncid = LookupFuncWithArgs(stmt->tosql, false);
1863 
1864  if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
1866 
1867  aclresult = pg_proc_aclcheck(tosqlfuncid, GetUserId(), ACL_EXECUTE);
1868  if (aclresult != ACLCHECK_OK)
1870 
1871  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1872  if (!HeapTupleIsValid(tuple))
1873  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1874  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1875  if (procstruct->prorettype != typeid)
1876  ereport(ERROR,
1877  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1878  errmsg("return data type of TO SQL function must be the transform data type")));
1879  check_transform_function(procstruct);
1880  ReleaseSysCache(tuple);
1881  }
1882  else
1883  tosqlfuncid = InvalidOid;
1884 
1885  /*
1886  * Ready to go
1887  */
1888  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1889  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1890  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1891  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1892 
1893  MemSet(nulls, false, sizeof(nulls));
1894 
1896 
1897  tuple = SearchSysCache2(TRFTYPELANG,
1898  ObjectIdGetDatum(typeid),
1899  ObjectIdGetDatum(langid));
1900  if (HeapTupleIsValid(tuple))
1901  {
1902  if (!stmt->replace)
1903  ereport(ERROR,
1905  errmsg("transform for type %s language \"%s\" already exists",
1906  format_type_be(typeid),
1907  stmt->lang)));
1908 
1909  MemSet(replaces, false, sizeof(replaces));
1910  replaces[Anum_pg_transform_trffromsql - 1] = true;
1911  replaces[Anum_pg_transform_trftosql - 1] = true;
1912 
1913  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1914  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
1915 
1916  transformid = HeapTupleGetOid(tuple);
1917  ReleaseSysCache(tuple);
1918  is_replace = true;
1919  }
1920  else
1921  {
1922  newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1923  transformid = CatalogTupleInsert(relation, newtuple);
1924  is_replace = false;
1925  }
1926 
1927  if (is_replace)
1928  deleteDependencyRecordsFor(TransformRelationId, transformid, true);
1929 
1930  /* make dependency entries */
1931  myself.classId = TransformRelationId;
1932  myself.objectId = transformid;
1933  myself.objectSubId = 0;
1934 
1935  /* dependency on language */
1936  referenced.classId = LanguageRelationId;
1937  referenced.objectId = langid;
1938  referenced.objectSubId = 0;
1939  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1940 
1941  /* dependency on type */
1942  referenced.classId = TypeRelationId;
1943  referenced.objectId = typeid;
1944  referenced.objectSubId = 0;
1945  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1946 
1947  /* dependencies on functions */
1948  if (OidIsValid(fromsqlfuncid))
1949  {
1950  referenced.classId = ProcedureRelationId;
1951  referenced.objectId = fromsqlfuncid;
1952  referenced.objectSubId = 0;
1953  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1954  }
1955  if (OidIsValid(tosqlfuncid))
1956  {
1957  referenced.classId = ProcedureRelationId;
1958  referenced.objectId = tosqlfuncid;
1959  referenced.objectSubId = 0;
1960  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1961  }
1962 
1963  /* dependency on extension */
1964  recordDependencyOnCurrentExtension(&myself, is_replace);
1965 
1966  /* Post creation hook for new transform */
1968 
1969  heap_freetuple(newtuple);
1970 
1971  heap_close(relation, RowExclusiveLock);
1972 
1973  return myself;
1974 }
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
ObjectWithArgs * tosql
Definition: parsenodes.h:3240
static void check_transform_function(Form_pg_proc procstruct)
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define TransformRelationId
Definition: pg_transform.h:25
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
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:857
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:692
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
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:538
#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
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
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:1971
char * NameListToString(List *names)
Definition: namespace.c:3020
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
ObjectWithArgs * fromsql
Definition: parsenodes.h:3239
#define Anum_pg_transform_trffromsql
Definition: pg_transform.h:44
#define INTERNALOID
Definition: pg_type.h:698
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define TYPTYPE_PSEUDO
Definition: pg_type.h:724
#define Anum_pg_transform_trftype
Definition: pg_transform.h:42
TypeName * type_name
Definition: parsenodes.h:3237
static Datum values[MAXATTR]
Definition: bootstrap.c:163
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:695
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:791
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
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
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:158
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, NULL, 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 */
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:692
#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:1372
unsigned int Oid