PostgreSQL Source Code  git master
defrem.h File Reference
#include "catalog/objectaddress.h"
#include "nodes/params.h"
#include "parser/parse_node.h"
#include "tcop/dest.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, Oid parentIndexId, Oid parentConstraintId, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
 
void ReindexIndex (RangeVar *indexRelation, int options, bool isTopLevel)
 
Oid ReindexTable (RangeVar *relation, int options, bool isTopLevel)
 
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 isconstraint)
 
bool CheckIndexCompatible (Oid oldId, const char *accessMethodName, List *attributeList, List *exclusionOpNames)
 
Oid GetDefaultOpClass (Oid type_id, Oid am_id)
 
Oid ResolveOpClass (List *opclass, Oid attrType, const char *accessMethodName, Oid accessMethodId)
 
ObjectAddress CreateFunction (ParseState *pstate, CreateFunctionStmt *stmt)
 
void RemoveFunctionById (Oid funcOid)
 
ObjectAddress AlterFunction (ParseState *pstate, AlterFunctionStmt *stmt)
 
ObjectAddress CreateCast (CreateCastStmt *stmt)
 
ObjectAddress CreateTransform (CreateTransformStmt *stmt)
 
void IsThereFunctionInNamespace (const char *proname, int pronargs, oidvector *proargtypes, Oid nspOid)
 
void ExecuteDoStmt (DoStmt *stmt, bool atomic)
 
void ExecuteCallStmt (CallStmt *stmt, ParamListInfo params, bool atomic, DestReceiver *dest)
 
TupleDesc CallStmtResultDesc (CallStmt *stmt)
 
Oid get_transform_oid (Oid type_id, Oid lang_id, bool missing_ok)
 
void interpret_function_parameter_list (ParseState *pstate, List *parameters, Oid languageOid, ObjectType objtype, 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)
 
ObjectAddress AlterStatistics (AlterStatsStmt *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, bool replace)
 
ObjectAddress DefineOpClass (CreateOpClassStmt *stmt)
 
ObjectAddress DefineOpFamily (CreateOpFamilyStmt *stmt)
 
Oid AlterOpFamily (AlterOpFamilyStmt *stmt)
 
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)
 
ObjectAddress DefineTSDictionary (List *names, List *parameters)
 
ObjectAddress AlterTSDictionary (AlterTSDictionaryStmt *stmt)
 
ObjectAddress DefineTSTemplate (List *names, List *parameters)
 
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)
 
ObjectAddress CreateForeignServer (CreateForeignServerStmt *stmt)
 
ObjectAddress AlterForeignServer (AlterForeignServerStmt *stmt)
 
ObjectAddress CreateUserMapping (CreateUserMappingStmt *stmt)
 
ObjectAddress AlterUserMapping (AlterUserMappingStmt *stmt)
 
Oid RemoveUserMapping (DropUserMappingStmt *stmt)
 
void CreateForeignTable (CreateForeignTableStmt *stmt, Oid relid)
 
void ImportForeignSchema (ImportForeignSchemaStmt *stmt)
 
Datum transformGenericOptions (Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
 
ObjectAddress CreateAccessMethod (CreateAmStmt *stmt)
 
Oid get_index_am_oid (const char *amname, bool missing_ok)
 
Oid get_table_am_oid (const char *amname, bool missing_ok)
 
Oid get_am_oid (const char *amname, bool missing_ok)
 
char * get_am_name (Oid amOid)
 
char * defGetString (DefElem *def)
 
double defGetNumeric (DefElem *def)
 
bool defGetBoolean (DefElem *def)
 
int32 defGetInt32 (DefElem *def)
 
int64 defGetInt64 (DefElem *def)
 
ListdefGetQualifiedName (DefElem *def)
 
TypeNamedefGetTypeName (DefElem *def)
 
int defGetTypeLength (DefElem *def)
 
ListdefGetStringList (DefElem *def)
 

Function Documentation

◆ AlterForeignDataWrapper()

ObjectAddress AlterForeignDataWrapper ( AlterFdwStmt stmt)

Definition at line 678 of file foreigncmds.c.

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

Referenced by ProcessUtilitySlow().

679 {
680  Relation rel;
681  HeapTuple tp;
683  Datum repl_val[Natts_pg_foreign_data_wrapper];
684  bool repl_null[Natts_pg_foreign_data_wrapper];
685  bool repl_repl[Natts_pg_foreign_data_wrapper];
686  Oid fdwId;
687  bool isnull;
688  Datum datum;
689  bool handler_given;
690  bool validator_given;
691  Oid fdwhandler;
692  Oid fdwvalidator;
693  ObjectAddress myself;
694 
695  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
696 
697  /* Must be super user */
698  if (!superuser())
699  ereport(ERROR,
700  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
701  errmsg("permission denied to alter foreign-data wrapper \"%s\"",
702  stmt->fdwname),
703  errhint("Must be superuser to alter a foreign-data wrapper.")));
704 
706  CStringGetDatum(stmt->fdwname));
707 
708  if (!HeapTupleIsValid(tp))
709  ereport(ERROR,
710  (errcode(ERRCODE_UNDEFINED_OBJECT),
711  errmsg("foreign-data wrapper \"%s\" does not exist", stmt->fdwname)));
712 
713  fdwForm = (Form_pg_foreign_data_wrapper) GETSTRUCT(tp);
714  fdwId = fdwForm->oid;
715 
716  memset(repl_val, 0, sizeof(repl_val));
717  memset(repl_null, false, sizeof(repl_null));
718  memset(repl_repl, false, sizeof(repl_repl));
719 
721  &handler_given, &fdwhandler,
722  &validator_given, &fdwvalidator);
723 
724  if (handler_given)
725  {
726  repl_val[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
727  repl_repl[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = true;
728 
729  /*
730  * It could be that the behavior of accessing foreign table changes
731  * with the new handler. Warn about this.
732  */
734  (errmsg("changing the foreign-data wrapper handler can change behavior of existing foreign tables")));
735  }
736 
737  if (validator_given)
738  {
739  repl_val[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
740  repl_repl[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = true;
741 
742  /*
743  * It could be that existing options for the FDW or dependent SERVER,
744  * USER MAPPING or FOREIGN TABLE objects are no longer valid according
745  * to the new validator. Warn about this.
746  */
747  if (OidIsValid(fdwvalidator))
749  (errmsg("changing the foreign-data wrapper validator can cause "
750  "the options for dependent objects to become invalid")));
751  }
752  else
753  {
754  /*
755  * Validator is not changed, but we need it for validating options.
756  */
757  fdwvalidator = fdwForm->fdwvalidator;
758  }
759 
760  /*
761  * If options specified, validate and update.
762  */
763  if (stmt->options)
764  {
765  /* Extract the current options */
767  tp,
768  Anum_pg_foreign_data_wrapper_fdwoptions,
769  &isnull);
770  if (isnull)
771  datum = PointerGetDatum(NULL);
772 
773  /* Transform the options */
774  datum = transformGenericOptions(ForeignDataWrapperRelationId,
775  datum,
776  stmt->options,
777  fdwvalidator);
778 
779  if (PointerIsValid(DatumGetPointer(datum)))
780  repl_val[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = datum;
781  else
782  repl_null[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
783 
784  repl_repl[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
785  }
786 
787  /* Everything looks good - update the tuple */
788  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
789  repl_val, repl_null, repl_repl);
790 
791  CatalogTupleUpdate(rel, &tp->t_self, tp);
792 
793  heap_freetuple(tp);
794 
795  ObjectAddressSet(myself, ForeignDataWrapperRelationId, fdwId);
796 
797  /* Update function dependencies if we changed them */
798  if (handler_given || validator_given)
799  {
800  ObjectAddress referenced;
801 
802  /*
803  * Flush all existing dependency records of this FDW on functions; we
804  * assume there can be none other than the ones we are fixing.
805  */
806  deleteDependencyRecordsForClass(ForeignDataWrapperRelationId,
807  fdwId,
808  ProcedureRelationId,
810 
811  /* And build new ones. */
812 
813  if (OidIsValid(fdwhandler))
814  {
815  referenced.classId = ProcedureRelationId;
816  referenced.objectId = fdwhandler;
817  referenced.objectSubId = 0;
818  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
819  }
820 
821  if (OidIsValid(fdwvalidator))
822  {
823  referenced.classId = ProcedureRelationId;
824  referenced.objectId = fdwvalidator;
825  referenced.objectSubId = 0;
826  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
827  }
828  }
829 
830  InvokeObjectPostAlterHook(ForeignDataWrapperRelationId, fdwId, 0);
831 
833 
834  return myself;
835 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static void parse_func_options(List *func_options, bool *handler_given, Oid *fdwhandler, bool *validator_given, Oid *fdwvalidator)
Definition: foreigncmds.c:518
#define RelationGetDescr(relation)
Definition: rel.h:482
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#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:578
char * fdwname
Definition: parsenodes.h:2288
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
List * func_options
Definition: parsenodes.h:2289
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:282
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_foreign_data_wrapper * Form_pg_foreign_data_wrapper
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:549
List * options
Definition: parsenodes.h:2290
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define PointerIsValid(pointer)
Definition: c.h:639

◆ AlterForeignDataWrapperOwner()

ObjectAddress AlterForeignDataWrapperOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 275 of file foreigncmds.c.

References AlterForeignDataWrapperOwner_internal(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, FOREIGNDATAWRAPPERNAME, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ObjectAddressSet, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

276 {
277  Oid fdwId;
278  HeapTuple tup;
279  Relation rel;
280  ObjectAddress address;
282 
283 
284  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
285 
287 
288  if (!HeapTupleIsValid(tup))
289  ereport(ERROR,
290  (errcode(ERRCODE_UNDEFINED_OBJECT),
291  errmsg("foreign-data wrapper \"%s\" does not exist", name)));
292 
294  fdwId = form->oid;
295 
296  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
297 
298  ObjectAddressSet(address, ForeignDataWrapperRelationId, fdwId);
299 
300  heap_freetuple(tup);
301 
303 
304  return address;
305 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
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:578
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_foreign_data_wrapper * Form_pg_foreign_data_wrapper
const char * name
Definition: encode.c:561
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:205
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterForeignDataWrapperOwner_oid()

void AlterForeignDataWrapperOwner_oid ( Oid  fwdId,
Oid  newOwnerId 
)

Definition at line 313 of file foreigncmds.c.

References AlterForeignDataWrapperOwner_internal(), ereport, errcode(), errmsg(), ERROR, FOREIGNDATAWRAPPEROID, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by shdepReassignOwned().

314 {
315  HeapTuple tup;
316  Relation rel;
317 
318  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
319 
321 
322  if (!HeapTupleIsValid(tup))
323  ereport(ERROR,
324  (errcode(ERRCODE_UNDEFINED_OBJECT),
325  errmsg("foreign-data wrapper with OID %u does not exist", fwdId)));
326 
327  AlterForeignDataWrapperOwner_internal(rel, tup, newOwnerId);
328 
329  heap_freetuple(tup);
330 
332 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:205
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterForeignServer()

ObjectAddress AlterForeignServer ( AlterForeignServerStmt stmt)

Definition at line 969 of file foreigncmds.c.

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

Referenced by ProcessUtilitySlow().

970 {
971  Relation rel;
972  HeapTuple tp;
973  Datum repl_val[Natts_pg_foreign_server];
974  bool repl_null[Natts_pg_foreign_server];
975  bool repl_repl[Natts_pg_foreign_server];
976  Oid srvId;
977  Form_pg_foreign_server srvForm;
978  ObjectAddress address;
979 
980  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
981 
983  CStringGetDatum(stmt->servername));
984 
985  if (!HeapTupleIsValid(tp))
986  ereport(ERROR,
987  (errcode(ERRCODE_UNDEFINED_OBJECT),
988  errmsg("server \"%s\" does not exist", stmt->servername)));
989 
990  srvForm = (Form_pg_foreign_server) GETSTRUCT(tp);
991  srvId = srvForm->oid;
992 
993  /*
994  * Only owner or a superuser can ALTER a SERVER.
995  */
998  stmt->servername);
999 
1000  memset(repl_val, 0, sizeof(repl_val));
1001  memset(repl_null, false, sizeof(repl_null));
1002  memset(repl_repl, false, sizeof(repl_repl));
1003 
1004  if (stmt->has_version)
1005  {
1006  /*
1007  * Change the server VERSION string.
1008  */
1009  if (stmt->version)
1010  repl_val[Anum_pg_foreign_server_srvversion - 1] =
1012  else
1013  repl_null[Anum_pg_foreign_server_srvversion - 1] = true;
1014 
1015  repl_repl[Anum_pg_foreign_server_srvversion - 1] = true;
1016  }
1017 
1018  if (stmt->options)
1019  {
1020  ForeignDataWrapper *fdw = GetForeignDataWrapper(srvForm->srvfdw);
1021  Datum datum;
1022  bool isnull;
1023 
1024  /* Extract the current srvoptions */
1026  tp,
1027  Anum_pg_foreign_server_srvoptions,
1028  &isnull);
1029  if (isnull)
1030  datum = PointerGetDatum(NULL);
1031 
1032  /* Prepare the options array */
1033  datum = transformGenericOptions(ForeignServerRelationId,
1034  datum,
1035  stmt->options,
1036  fdw->fdwvalidator);
1037 
1038  if (PointerIsValid(DatumGetPointer(datum)))
1039  repl_val[Anum_pg_foreign_server_srvoptions - 1] = datum;
1040  else
1041  repl_null[Anum_pg_foreign_server_srvoptions - 1] = true;
1042 
1043  repl_repl[Anum_pg_foreign_server_srvoptions - 1] = true;
1044  }
1045 
1046  /* Everything looks good - update the tuple */
1047  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1048  repl_val, repl_null, repl_repl);
1049 
1050  CatalogTupleUpdate(rel, &tp->t_self, tp);
1051 
1052  InvokeObjectPostAlterHook(ForeignServerRelationId, srvId, 0);
1053 
1054  ObjectAddressSet(address, ForeignServerRelationId, srvId);
1055 
1056  heap_freetuple(tp);
1057 
1059 
1060  return address;
1061 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
bool pg_foreign_server_ownercheck(Oid srv_oid, Oid roleid)
Definition: aclchk.c:5051
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#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:578
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
FormData_pg_foreign_server * Form_pg_foreign_server
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:549
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define CStringGetTextDatum(s)
Definition: builtins.h:86
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define PointerIsValid(pointer)
Definition: c.h:639

◆ AlterForeignServerOwner()

ObjectAddress AlterForeignServerOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 415 of file foreigncmds.c.

References AlterForeignServerOwner_internal(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, FOREIGNSERVERNAME, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, ObjectAddressSet, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

416 {
417  Oid servOid;
418  HeapTuple tup;
419  Relation rel;
420  ObjectAddress address;
422 
423  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
424 
426 
427  if (!HeapTupleIsValid(tup))
428  ereport(ERROR,
429  (errcode(ERRCODE_UNDEFINED_OBJECT),
430  errmsg("server \"%s\" does not exist", name)));
431 
432  form = (Form_pg_foreign_server) GETSTRUCT(tup);
433  servOid = form->oid;
434 
435  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
436 
437  ObjectAddressSet(address, ForeignServerRelationId, servOid);
438 
439  heap_freetuple(tup);
440 
442 
443  return address;
444 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
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:578
FormData_pg_foreign_server * Form_pg_foreign_server
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:338
const char * name
Definition: encode.c:561
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterForeignServerOwner_oid()

void AlterForeignServerOwner_oid ( Oid  ,
Oid  newOwnerId 
)

Definition at line 450 of file foreigncmds.c.

References AlterForeignServerOwner_internal(), ereport, errcode(), errmsg(), ERROR, FOREIGNSERVEROID, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum, RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by shdepReassignOwned().

451 {
452  HeapTuple tup;
453  Relation rel;
454 
455  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
456 
458 
459  if (!HeapTupleIsValid(tup))
460  ereport(ERROR,
461  (errcode(ERRCODE_UNDEFINED_OBJECT),
462  errmsg("foreign server with OID %u does not exist", srvId)));
463 
464  AlterForeignServerOwner_internal(rel, tup, newOwnerId);
465 
466  heap_freetuple(tup);
467 
469 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:338
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterFunction()

ObjectAddress AlterFunction ( ParseState pstate,
AlterFunctionStmt stmt 
)

Definition at line 1235 of file functioncmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, AlterFunctionStmt::actions, DefElem::arg, CatalogTupleUpdate(), changeDependencyFor(), ObjectAddress::classId, compute_common_attribute(), DatumGetArrayTypeP, defGetNumeric(), DefElem::defname, DEPENDENCY_NORMAL, elog, ereport, errcode(), errmsg(), ERROR, AlterFunctionStmt::func, GETSTRUCT, GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, interpret_func_parallel(), interpret_func_support(), interpret_func_volatility(), intVal, InvokeObjectPostAlterHook, lfirst, LookupFuncWithArgs(), NameListToString(), NIL, NoLock, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, ObjectWithArgs::objname, AlterFunctionStmt::objtype, OidIsValid, pg_proc_ownercheck(), PointerGetDatum, PROCOID, recordDependencyOn(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and update_proconfig_value().

Referenced by ProcessUtilitySlow().

1236 {
1237  HeapTuple tup;
1238  Oid funcOid;
1239  Form_pg_proc procForm;
1240  bool is_procedure;
1241  Relation rel;
1242  ListCell *l;
1243  DefElem *volatility_item = NULL;
1244  DefElem *strict_item = NULL;
1245  DefElem *security_def_item = NULL;
1246  DefElem *leakproof_item = NULL;
1247  List *set_items = NIL;
1248  DefElem *cost_item = NULL;
1249  DefElem *rows_item = NULL;
1250  DefElem *support_item = NULL;
1251  DefElem *parallel_item = NULL;
1252  ObjectAddress address;
1253 
1254  rel = table_open(ProcedureRelationId, RowExclusiveLock);
1255 
1256  funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
1257 
1258  ObjectAddressSet(address, ProcedureRelationId, funcOid);
1259 
1260  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1261  if (!HeapTupleIsValid(tup)) /* should not happen */
1262  elog(ERROR, "cache lookup failed for function %u", funcOid);
1263 
1264  procForm = (Form_pg_proc) GETSTRUCT(tup);
1265 
1266  /* Permission check: must own function */
1267  if (!pg_proc_ownercheck(funcOid, GetUserId()))
1269  NameListToString(stmt->func->objname));
1270 
1271  if (procForm->prokind == PROKIND_AGGREGATE)
1272  ereport(ERROR,
1273  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1274  errmsg("\"%s\" is an aggregate function",
1275  NameListToString(stmt->func->objname))));
1276 
1277  is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
1278 
1279  /* Examine requested actions. */
1280  foreach(l, stmt->actions)
1281  {
1282  DefElem *defel = (DefElem *) lfirst(l);
1283 
1284  if (compute_common_attribute(pstate,
1285  is_procedure,
1286  defel,
1287  &volatility_item,
1288  &strict_item,
1289  &security_def_item,
1290  &leakproof_item,
1291  &set_items,
1292  &cost_item,
1293  &rows_item,
1294  &support_item,
1295  &parallel_item) == false)
1296  elog(ERROR, "option \"%s\" not recognized", defel->defname);
1297  }
1298 
1299  if (volatility_item)
1300  procForm->provolatile = interpret_func_volatility(volatility_item);
1301  if (strict_item)
1302  procForm->proisstrict = intVal(strict_item->arg);
1303  if (security_def_item)
1304  procForm->prosecdef = intVal(security_def_item->arg);
1305  if (leakproof_item)
1306  {
1307  procForm->proleakproof = intVal(leakproof_item->arg);
1308  if (procForm->proleakproof && !superuser())
1309  ereport(ERROR,
1310  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1311  errmsg("only superuser can define a leakproof function")));
1312  }
1313  if (cost_item)
1314  {
1315  procForm->procost = defGetNumeric(cost_item);
1316  if (procForm->procost <= 0)
1317  ereport(ERROR,
1318  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1319  errmsg("COST must be positive")));
1320  }
1321  if (rows_item)
1322  {
1323  procForm->prorows = defGetNumeric(rows_item);
1324  if (procForm->prorows <= 0)
1325  ereport(ERROR,
1326  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1327  errmsg("ROWS must be positive")));
1328  if (!procForm->proretset)
1329  ereport(ERROR,
1330  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1331  errmsg("ROWS is not applicable when function does not return a set")));
1332  }
1333  if (support_item)
1334  {
1335  /* interpret_func_support handles the privilege check */
1336  Oid newsupport = interpret_func_support(support_item);
1337 
1338  /* Add or replace dependency on support function */
1339  if (OidIsValid(procForm->prosupport))
1340  changeDependencyFor(ProcedureRelationId, funcOid,
1341  ProcedureRelationId, procForm->prosupport,
1342  newsupport);
1343  else
1344  {
1345  ObjectAddress referenced;
1346 
1347  referenced.classId = ProcedureRelationId;
1348  referenced.objectId = newsupport;
1349  referenced.objectSubId = 0;
1350  recordDependencyOn(&address, &referenced, DEPENDENCY_NORMAL);
1351  }
1352 
1353  procForm->prosupport = newsupport;
1354  }
1355  if (set_items)
1356  {
1357  Datum datum;
1358  bool isnull;
1359  ArrayType *a;
1360  Datum repl_val[Natts_pg_proc];
1361  bool repl_null[Natts_pg_proc];
1362  bool repl_repl[Natts_pg_proc];
1363 
1364  /* extract existing proconfig setting */
1365  datum = SysCacheGetAttr(PROCOID, tup, Anum_pg_proc_proconfig, &isnull);
1366  a = isnull ? NULL : DatumGetArrayTypeP(datum);
1367 
1368  /* update according to each SET or RESET item, left to right */
1369  a = update_proconfig_value(a, set_items);
1370 
1371  /* update the tuple */
1372  memset(repl_repl, false, sizeof(repl_repl));
1373  repl_repl[Anum_pg_proc_proconfig - 1] = true;
1374 
1375  if (a == NULL)
1376  {
1377  repl_val[Anum_pg_proc_proconfig - 1] = (Datum) 0;
1378  repl_null[Anum_pg_proc_proconfig - 1] = true;
1379  }
1380  else
1381  {
1382  repl_val[Anum_pg_proc_proconfig - 1] = PointerGetDatum(a);
1383  repl_null[Anum_pg_proc_proconfig - 1] = false;
1384  }
1385 
1386  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1387  repl_val, repl_null, repl_repl);
1388  }
1389  if (parallel_item)
1390  procForm->proparallel = interpret_func_parallel(parallel_item);
1391 
1392  /* Do the update */
1393  CatalogTupleUpdate(rel, &tup->t_self, tup);
1394 
1395  InvokeObjectPostAlterHook(ProcedureRelationId, funcOid, 0);
1396 
1397  table_close(rel, NoLock);
1398  heap_freetuple(tup);
1399 
1400  return address;
1401 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
#define PointerGetDatum(X)
Definition: postgres.h:556
double defGetNumeric(DefElem *def)
Definition: define.c:85
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static Oid interpret_func_support(DefElem *defel)
Definition: functioncmds.c:651
ItemPointerData t_self
Definition: htup.h:65
ObjectType objtype
Definition: parsenodes.h:2869
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:583
Node * arg
Definition: parsenodes.h:734
char * NameListToString(List *names)
Definition: namespace.c:3101
uintptr_t Datum
Definition: postgres.h:367
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:626
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define ereport(elevel,...)
Definition: elog.h:144
ObjectWithArgs * func
Definition: parsenodes.h:2870
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:824
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:388
#define elog(elevel,...)
Definition: elog.h:214
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2163
char * defname
Definition: parsenodes.h:733
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
static bool compute_common_attribute(ParseState *pstate, bool is_procedure, DefElem *defel, DefElem **volatility_item, DefElem **strict_item, DefElem **security_item, DefElem **leakproof_item, List **set_items, DefElem **cost_item, DefElem **rows_item, DefElem **support_item, DefElem **parallel_item)
Definition: functioncmds.c:474
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4765
static char interpret_func_parallel(DefElem *defel)
Definition: functioncmds.c:601
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ AlterOperator()

ObjectAddress AlterOperator ( AlterOperatorStmt stmt)

Definition at line 409 of file operatorcmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, CatalogTupleUpdate(), defGetQualifiedName(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), heap_modify_tuple(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostAlterHook, lfirst, LookupOperWithArgs(), makeOperatorDependencies(), NameStr, NIL, NoLock, OBJECT_OPERATOR, ObjectIdGetDatum, OidIsValid, AlterOperatorStmt::opername, OPEROID, AlterOperatorStmt::options, pg_oper_ownercheck(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), table_open(), ValidateJoinEstimator(), ValidateRestrictionEstimator(), and values.

Referenced by ProcessUtilitySlow().

410 {
411  ObjectAddress address;
412  Oid oprId;
413  Relation catalog;
414  HeapTuple tup;
415  Form_pg_operator oprForm;
416  int i;
417  ListCell *pl;
418  Datum values[Natts_pg_operator];
419  bool nulls[Natts_pg_operator];
420  bool replaces[Natts_pg_operator];
421  List *restrictionName = NIL; /* optional restrict. sel. function */
422  bool updateRestriction = false;
423  Oid restrictionOid;
424  List *joinName = NIL; /* optional join sel. function */
425  bool updateJoin = false;
426  Oid joinOid;
427 
428  /* Look up the operator */
429  oprId = LookupOperWithArgs(stmt->opername, false);
430  catalog = table_open(OperatorRelationId, RowExclusiveLock);
432  if (!HeapTupleIsValid(tup))
433  elog(ERROR, "cache lookup failed for operator %u", oprId);
434  oprForm = (Form_pg_operator) GETSTRUCT(tup);
435 
436  /* Process options */
437  foreach(pl, stmt->options)
438  {
439  DefElem *defel = (DefElem *) lfirst(pl);
440  List *param;
441 
442  if (defel->arg == NULL)
443  param = NIL; /* NONE, removes the function */
444  else
445  param = defGetQualifiedName(defel);
446 
447  if (strcmp(defel->defname, "restrict") == 0)
448  {
449  restrictionName = param;
450  updateRestriction = true;
451  }
452  else if (strcmp(defel->defname, "join") == 0)
453  {
454  joinName = param;
455  updateJoin = true;
456  }
457 
458  /*
459  * The rest of the options that CREATE accepts cannot be changed.
460  * Check for them so that we can give a meaningful error message.
461  */
462  else if (strcmp(defel->defname, "leftarg") == 0 ||
463  strcmp(defel->defname, "rightarg") == 0 ||
464  strcmp(defel->defname, "function") == 0 ||
465  strcmp(defel->defname, "procedure") == 0 ||
466  strcmp(defel->defname, "commutator") == 0 ||
467  strcmp(defel->defname, "negator") == 0 ||
468  strcmp(defel->defname, "hashes") == 0 ||
469  strcmp(defel->defname, "merges") == 0)
470  {
471  ereport(ERROR,
472  (errcode(ERRCODE_SYNTAX_ERROR),
473  errmsg("operator attribute \"%s\" cannot be changed",
474  defel->defname)));
475  }
476  else
477  ereport(ERROR,
478  (errcode(ERRCODE_SYNTAX_ERROR),
479  errmsg("operator attribute \"%s\" not recognized",
480  defel->defname)));
481  }
482 
483  /* Check permissions. Must be owner. */
484  if (!pg_oper_ownercheck(oprId, GetUserId()))
486  NameStr(oprForm->oprname));
487 
488  /*
489  * Look up restriction and join estimators if specified
490  */
491  if (restrictionName)
492  restrictionOid = ValidateRestrictionEstimator(restrictionName);
493  else
494  restrictionOid = InvalidOid;
495  if (joinName)
496  joinOid = ValidateJoinEstimator(joinName);
497  else
498  joinOid = InvalidOid;
499 
500  /* Perform additional checks, like OperatorCreate does */
501  if (!(OidIsValid(oprForm->oprleft) && OidIsValid(oprForm->oprright)))
502  {
503  /* If it's not a binary op, these things mustn't be set: */
504  if (OidIsValid(joinOid))
505  ereport(ERROR,
506  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
507  errmsg("only binary operators can have join selectivity")));
508  }
509 
510  if (oprForm->oprresult != BOOLOID)
511  {
512  if (OidIsValid(restrictionOid))
513  ereport(ERROR,
514  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
515  errmsg("only boolean operators can have restriction selectivity")));
516  if (OidIsValid(joinOid))
517  ereport(ERROR,
518  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
519  errmsg("only boolean operators can have join selectivity")));
520  }
521 
522  /* Update the tuple */
523  for (i = 0; i < Natts_pg_operator; ++i)
524  {
525  values[i] = (Datum) 0;
526  replaces[i] = false;
527  nulls[i] = false;
528  }
529  if (updateRestriction)
530  {
531  replaces[Anum_pg_operator_oprrest - 1] = true;
532  values[Anum_pg_operator_oprrest - 1] = restrictionOid;
533  }
534  if (updateJoin)
535  {
536  replaces[Anum_pg_operator_oprjoin - 1] = true;
537  values[Anum_pg_operator_oprjoin - 1] = joinOid;
538  }
539 
540  tup = heap_modify_tuple(tup, RelationGetDescr(catalog),
541  values, nulls, replaces);
542 
543  CatalogTupleUpdate(catalog, &tup->t_self, tup);
544 
545  address = makeOperatorDependencies(tup, true);
546 
547  InvokeObjectPostAlterHook(OperatorRelationId, oprId, 0);
548 
549  table_close(catalog, NoLock);
550 
551  return address;
552 }
Oid LookupOperWithArgs(ObjectWithArgs *oper, bool noError)
Definition: parse_oper.c:145
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
ObjectAddress makeOperatorDependencies(HeapTuple tuple, bool isUpdate)
Definition: pg_operator.c:773
static Oid ValidateJoinEstimator(List *joinName)
Definition: operatorcmds.c:308
bool pg_oper_ownercheck(Oid oper_oid, Oid roleid)
Definition: aclchk.c:4739
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
static Oid ValidateRestrictionEstimator(List *restrictionName)
Definition: operatorcmds.c:273
Node * arg
Definition: parsenodes.h:734
ObjectWithArgs * opername
Definition: parsenodes.h:2978
uintptr_t Datum
Definition: postgres.h:367
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
List * defGetQualifiedName(DefElem *def)
Definition: define.c:223
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:622
char * defname
Definition: parsenodes.h:733
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50

◆ AlterOpFamily()

Oid AlterOpFamily ( AlterOpFamilyStmt stmt)

Definition at line 808 of file opclasscmds.c.

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

Referenced by ProcessUtilitySlow().

809 {
810  Oid amoid, /* our AM's oid */
811  opfamilyoid; /* oid of opfamily */
812  int maxOpNumber, /* amstrategies value */
813  optsProcNumber, /* amopclassopts value */
814  maxProcNumber; /* amsupport value */
815  HeapTuple tup;
816  Form_pg_am amform;
817  IndexAmRoutine *amroutine;
818 
819  /* Get necessary info about access method */
821  if (!HeapTupleIsValid(tup))
822  ereport(ERROR,
823  (errcode(ERRCODE_UNDEFINED_OBJECT),
824  errmsg("access method \"%s\" does not exist",
825  stmt->amname)));
826 
827  amform = (Form_pg_am) GETSTRUCT(tup);
828  amoid = amform->oid;
829  amroutine = GetIndexAmRoutineByAmId(amoid, false);
830  ReleaseSysCache(tup);
831 
832  maxOpNumber = amroutine->amstrategies;
833  /* if amstrategies is zero, just enforce that op numbers fit in int16 */
834  if (maxOpNumber <= 0)
835  maxOpNumber = SHRT_MAX;
836  maxProcNumber = amroutine->amsupport;
837  optsProcNumber = amroutine->amoptsprocnum;
838 
839  /* XXX Should we make any privilege check against the AM? */
840 
841  /* Look up the opfamily */
842  opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
843 
844  /*
845  * Currently, we require superuser privileges to alter an opfamily.
846  *
847  * XXX re-enable NOT_USED code sections below if you remove this test.
848  */
849  if (!superuser())
850  ereport(ERROR,
851  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
852  errmsg("must be superuser to alter an operator family")));
853 
854  /*
855  * ADD and DROP cases need separate code from here on down.
856  */
857  if (stmt->isDrop)
858  AlterOpFamilyDrop(stmt, amoid, opfamilyoid,
859  maxOpNumber, maxProcNumber, stmt->items);
860  else
861  AlterOpFamilyAdd(stmt, amoid, opfamilyoid,
862  maxOpNumber, maxProcNumber, optsProcNumber,
863  stmt->items);
864 
865  return opfamilyoid;
866 }
uint16 amsupport
Definition: amapi.h:215
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
unsigned int Oid
Definition: postgres_ext.h:31
static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, List *items)
Definition: opclasscmds.c:1021
#define ERROR
Definition: elog.h:43
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
#define CStringGetDatum(X)
Definition: postgres.h:578
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
static void AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, int opclassOptsProcNumber, List *items)
Definition: opclasscmds.c:872
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid get_opfamily_oid(Oid amID, List *opfamilyname, bool missing_ok)
Definition: opclasscmds.c:139
uint16 amstrategies
Definition: amapi.h:213
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:824
uint16 amoptsprocnum
Definition: amapi.h:217

◆ AlterStatistics()

ObjectAddress AlterStatistics ( AlterStatsStmt stmt)

Definition at line 427 of file statscmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, CatalogTupleUpdate(), DeconstructQualifiedName(), AlterStatsStmt::defnames, ereport, errcode(), errmsg(), ERROR, get_statistics_object_oid(), GetUserId(), heap_freetuple(), heap_modify_tuple(), Int32GetDatum, InvalidObjectAddress, InvokeObjectPostAlterHook, AlterStatsStmt::missing_ok, NameListToString(), NOTICE, OBJECT_STATISTIC_EXT, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, pg_statistics_object_ownercheck(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), STATEXTOID, AlterStatsStmt::stxstattarget, HeapTupleData::t_self, table_close(), table_open(), and WARNING.

Referenced by ProcessUtilitySlow().

428 {
429  Relation rel;
430  Oid stxoid;
431  HeapTuple oldtup;
432  HeapTuple newtup;
433  Datum repl_val[Natts_pg_statistic_ext];
434  bool repl_null[Natts_pg_statistic_ext];
435  bool repl_repl[Natts_pg_statistic_ext];
436  ObjectAddress address;
437  int newtarget = stmt->stxstattarget;
438 
439  /* Limit statistics target to a sane range */
440  if (newtarget < -1)
441  {
442  ereport(ERROR,
443  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
444  errmsg("statistics target %d is too low",
445  newtarget)));
446  }
447  else if (newtarget > 10000)
448  {
449  newtarget = 10000;
451  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
452  errmsg("lowering statistics target to %d",
453  newtarget)));
454  }
455 
456  /* lookup OID of the statistics object */
457  stxoid = get_statistics_object_oid(stmt->defnames, stmt->missing_ok);
458 
459  /*
460  * If we got here and the OID is not valid, it means the statistics does
461  * not exist, but the command specified IF EXISTS. So report this as a
462  * simple NOTICE and we're done.
463  */
464  if (!OidIsValid(stxoid))
465  {
466  char *schemaname;
467  char *statname;
468 
469  Assert(stmt->missing_ok);
470 
471  DeconstructQualifiedName(stmt->defnames, &schemaname, &statname);
472 
473  if (schemaname)
474  ereport(NOTICE,
475  (errmsg("statistics object \"%s.%s\" does not exist, skipping",
476  schemaname, statname)));
477  else
478  ereport(NOTICE,
479  (errmsg("statistics object \"%s\" does not exist, skipping",
480  statname)));
481 
482  return InvalidObjectAddress;
483  }
484 
485  /* Search pg_statistic_ext */
486  rel = table_open(StatisticExtRelationId, RowExclusiveLock);
487 
488  oldtup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
489 
490  /* Must be owner of the existing statistics object */
493  NameListToString(stmt->defnames));
494 
495  /* Build new tuple. */
496  memset(repl_val, 0, sizeof(repl_val));
497  memset(repl_null, false, sizeof(repl_null));
498  memset(repl_repl, false, sizeof(repl_repl));
499 
500  /* replace the stxstattarget column */
501  repl_repl[Anum_pg_statistic_ext_stxstattarget - 1] = true;
502  repl_val[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(newtarget);
503 
504  newtup = heap_modify_tuple(oldtup, RelationGetDescr(rel),
505  repl_val, repl_null, repl_repl);
506 
507  /* Update system catalog. */
508  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
509 
510  InvokeObjectPostAlterHook(StatisticExtRelationId, stxoid, 0);
511 
512  ObjectAddressSet(address, StatisticExtRelationId, stxoid);
513 
514  /*
515  * NOTE: because we only support altering the statistics target, not the
516  * other fields, there is no need to update dependencies.
517  */
518 
519  heap_freetuple(newtup);
520  ReleaseSysCache(oldtup);
521 
523 
524  return address;
525 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
int errcode(int sqlerrcode)
Definition: elog.c:610
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2808
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
Oid get_statistics_object_oid(List *names, bool missing_ok)
Definition: namespace.c:2177
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
char * NameListToString(List *names)
Definition: namespace.c:3101
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define Assert(condition)
Definition: c.h:745
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define Int32GetDatum(X)
Definition: postgres.h:479
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
bool pg_statistics_object_ownercheck(Oid stat_oid, Oid roleid)
Definition: aclchk.c:5277

◆ AlterTSConfiguration()

ObjectAddress AlterTSConfiguration ( AlterTSConfigurationStmt stmt)

Definition at line 1109 of file tsearchcmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, AlterTSConfigurationStmt::cfgname, AlterTSConfigurationStmt::dicts, DropConfigurationMapping(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetTSConfigTuple(), GetUserId(), HeapTupleIsValid, InvokeObjectPostAlterHook, makeConfigurationDependencies(), MakeConfigurationMapping(), NameListToString(), OBJECT_TSCONFIGURATION, ObjectAddressSet, pg_ts_config_ownercheck(), ReleaseSysCache(), RowExclusiveLock, table_close(), table_open(), and AlterTSConfigurationStmt::tokentype.

Referenced by ProcessUtilitySlow().

1110 {
1111  HeapTuple tup;
1112  Oid cfgId;
1113  Relation relMap;
1114  ObjectAddress address;
1115 
1116  /* Find the configuration */
1117  tup = GetTSConfigTuple(stmt->cfgname);
1118  if (!HeapTupleIsValid(tup))
1119  ereport(ERROR,
1120  (errcode(ERRCODE_UNDEFINED_OBJECT),
1121  errmsg("text search configuration \"%s\" does not exist",
1122  NameListToString(stmt->cfgname))));
1123 
1124  cfgId = ((Form_pg_ts_config) GETSTRUCT(tup))->oid;
1125 
1126  /* must be owner */
1127  if (!pg_ts_config_ownercheck(cfgId, GetUserId()))
1129  NameListToString(stmt->cfgname));
1130 
1131  relMap = table_open(TSConfigMapRelationId, RowExclusiveLock);
1132 
1133  /* Add or drop mappings */
1134  if (stmt->dicts)
1135  MakeConfigurationMapping(stmt, tup, relMap);
1136  else if (stmt->tokentype)
1137  DropConfigurationMapping(stmt, tup, relMap);
1138 
1139  /* Update dependencies */
1140  makeConfigurationDependencies(tup, true, relMap);
1141 
1142  InvokeObjectPostAlterHook(TSConfigRelationId, cfgId, 0);
1143 
1144  ObjectAddressSet(address, TSConfigRelationId, cfgId);
1145 
1146  table_close(relMap, RowExclusiveLock);
1147 
1148  ReleaseSysCache(tup);
1149 
1150  return address;
1151 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_ts_config * Form_pg_ts_config
Definition: pg_ts_config.h:48
Oid GetUserId(void)
Definition: miscinit.c:476
bool pg_ts_config_ownercheck(Oid cfg_oid, Oid roleid)
Definition: aclchk.c:4997
static ObjectAddress makeConfigurationDependencies(HeapTuple tuple, bool removeOld, Relation mapRel)
Definition: tsearchcmds.c:806
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
static void DropConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1376
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
static HeapTuple GetTSConfigTuple(List *names)
Definition: tsearchcmds.c:781
char * NameListToString(List *names)
Definition: namespace.c:3101
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static void MakeConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1212

◆ AlterTSDictionary()

ObjectAddress AlterTSDictionary ( AlterTSDictionaryStmt stmt)

Definition at line 487 of file tsearchcmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, CatalogTupleUpdate(), DefElem::defname, deserialize_deflist(), AlterTSDictionaryStmt::dictname, elog, ERROR, foreach_delete_current, get_ts_dict_oid(), GETSTRUCT, GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, lappend(), lfirst, NameListToString(), NIL, OBJECT_TSDICTIONARY, ObjectAddressSet, ObjectIdGetDatum, AlterTSDictionaryStmt::options, pg_ts_dict_ownercheck(), PointerGetDatum, RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), serialize_deflist(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), TSDICTOID, and verify_dictoptions().

Referenced by ProcessUtilitySlow().

488 {
489  HeapTuple tup,
490  newtup;
491  Relation rel;
492  Oid dictId;
493  ListCell *pl;
494  List *dictoptions;
495  Datum opt;
496  bool isnull;
497  Datum repl_val[Natts_pg_ts_dict];
498  bool repl_null[Natts_pg_ts_dict];
499  bool repl_repl[Natts_pg_ts_dict];
500  ObjectAddress address;
501 
502  dictId = get_ts_dict_oid(stmt->dictname, false);
503 
504  rel = table_open(TSDictionaryRelationId, RowExclusiveLock);
505 
507 
508  if (!HeapTupleIsValid(tup))
509  elog(ERROR, "cache lookup failed for text search dictionary %u",
510  dictId);
511 
512  /* must be owner */
513  if (!pg_ts_dict_ownercheck(dictId, GetUserId()))
515  NameListToString(stmt->dictname));
516 
517  /* deserialize the existing set of options */
518  opt = SysCacheGetAttr(TSDICTOID, tup,
519  Anum_pg_ts_dict_dictinitoption,
520  &isnull);
521  if (isnull)
522  dictoptions = NIL;
523  else
524  dictoptions = deserialize_deflist(opt);
525 
526  /*
527  * Modify the options list as per specified changes
528  */
529  foreach(pl, stmt->options)
530  {
531  DefElem *defel = (DefElem *) lfirst(pl);
532  ListCell *cell;
533 
534  /*
535  * Remove any matches ...
536  */
537  foreach(cell, dictoptions)
538  {
539  DefElem *oldel = (DefElem *) lfirst(cell);
540 
541  if (strcmp(oldel->defname, defel->defname) == 0)
542  dictoptions = foreach_delete_current(dictoptions, cell);
543  }
544 
545  /*
546  * and add new value if it's got one
547  */
548  if (defel->arg)
549  dictoptions = lappend(dictoptions, defel);
550  }
551 
552  /*
553  * Validate
554  */
555  verify_dictoptions(((Form_pg_ts_dict) GETSTRUCT(tup))->dicttemplate,
556  dictoptions);
557 
558  /*
559  * Looks good, update
560  */
561  memset(repl_val, 0, sizeof(repl_val));
562  memset(repl_null, false, sizeof(repl_null));
563  memset(repl_repl, false, sizeof(repl_repl));
564 
565  if (dictoptions)
566  repl_val[Anum_pg_ts_dict_dictinitoption - 1] =
567  PointerGetDatum(serialize_deflist(dictoptions));
568  else
569  repl_null[Anum_pg_ts_dict_dictinitoption - 1] = true;
570  repl_repl[Anum_pg_ts_dict_dictinitoption - 1] = true;
571 
572  newtup = heap_modify_tuple(tup, RelationGetDescr(rel),
573  repl_val, repl_null, repl_repl);
574 
575  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
576 
577  InvokeObjectPostAlterHook(TSDictionaryRelationId, dictId, 0);
578 
579  ObjectAddressSet(address, TSDictionaryRelationId, dictId);
580 
581  /*
582  * NOTE: because we only support altering the options, not the template,
583  * there is no need to update dependencies. This might have to change if
584  * the options ever reference inside-the-database objects.
585  */
586 
587  heap_freetuple(newtup);
588  ReleaseSysCache(tup);
589 
591 
592  return address;
593 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool pg_ts_dict_ownercheck(Oid dict_oid, Oid roleid)
Definition: aclchk.c:4970
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
#define PointerGetDatum(X)
Definition: postgres.h:556
List * deserialize_deflist(Datum txt)
Definition: tsearchcmds.c:1510
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
Oid get_ts_dict_oid(List *names, bool missing_ok)
Definition: namespace.c:2425
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
FormData_pg_ts_dict * Form_pg_ts_dict
Definition: pg_ts_dict.h:52
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
Node * arg
Definition: parsenodes.h:734
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
char * NameListToString(List *names)
Definition: namespace.c:3101
text * serialize_deflist(List *deflist)
Definition: tsearchcmds.c:1454
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
static void verify_dictoptions(Oid tmplId, List *dictoptions)
Definition: tsearchcmds.c:336
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define elog(elevel,...)
Definition: elog.h:214
char * defname
Definition: parsenodes.h:733
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50

◆ AlterUserMapping()

ObjectAddress AlterUserMapping ( AlterUserMappingStmt stmt)

Definition at line 1217 of file foreigncmds.c.

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

Referenced by ProcessUtilitySlow().

1218 {
1219  Relation rel;
1220  HeapTuple tp;
1221  Datum repl_val[Natts_pg_user_mapping];
1222  bool repl_null[Natts_pg_user_mapping];
1223  bool repl_repl[Natts_pg_user_mapping];
1224  Oid useId;
1225  Oid umId;
1226  ForeignServer *srv;
1227  ObjectAddress address;
1228  RoleSpec *role = (RoleSpec *) stmt->user;
1229 
1230  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1231 
1232  if (role->roletype == ROLESPEC_PUBLIC)
1233  useId = ACL_ID_PUBLIC;
1234  else
1235  useId = get_rolespec_oid(stmt->user, false);
1236 
1237  srv = GetForeignServerByName(stmt->servername, false);
1238 
1239  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1240  ObjectIdGetDatum(useId),
1241  ObjectIdGetDatum(srv->serverid));
1242  if (!OidIsValid(umId))
1243  ereport(ERROR,
1244  (errcode(ERRCODE_UNDEFINED_OBJECT),
1245  errmsg("user mapping for \"%s\" does not exist for server \"%s\"",
1246  MappingUserName(useId), stmt->servername)));
1247 
1248  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1249 
1251 
1252  if (!HeapTupleIsValid(tp))
1253  elog(ERROR, "cache lookup failed for user mapping %u", umId);
1254 
1255  memset(repl_val, 0, sizeof(repl_val));
1256  memset(repl_null, false, sizeof(repl_null));
1257  memset(repl_repl, false, sizeof(repl_repl));
1258 
1259  if (stmt->options)
1260  {
1261  ForeignDataWrapper *fdw;
1262  Datum datum;
1263  bool isnull;
1264 
1265  /*
1266  * Process the options.
1267  */
1268 
1269  fdw = GetForeignDataWrapper(srv->fdwid);
1270 
1271  datum = SysCacheGetAttr(USERMAPPINGUSERSERVER,
1272  tp,
1273  Anum_pg_user_mapping_umoptions,
1274  &isnull);
1275  if (isnull)
1276  datum = PointerGetDatum(NULL);
1277 
1278  /* Prepare the options array */
1279  datum = transformGenericOptions(UserMappingRelationId,
1280  datum,
1281  stmt->options,
1282  fdw->fdwvalidator);
1283 
1284  if (PointerIsValid(DatumGetPointer(datum)))
1285  repl_val[Anum_pg_user_mapping_umoptions - 1] = datum;
1286  else
1287  repl_null[Anum_pg_user_mapping_umoptions - 1] = true;
1288 
1289  repl_repl[Anum_pg_user_mapping_umoptions - 1] = true;
1290  }
1291 
1292  /* Everything looks good - update the tuple */
1293  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1294  repl_val, repl_null, repl_repl);
1295 
1296  CatalogTupleUpdate(rel, &tp->t_self, tp);
1297 
1298  InvokeObjectPostAlterHook(UserMappingRelationId,
1299  umId, 0);
1300 
1301  ObjectAddressSet(address, UserMappingRelationId, umId);
1302 
1303  heap_freetuple(tp);
1304 
1306 
1307  return address;
1308 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:482
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:610
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1070
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
uintptr_t Datum
Definition: postgres.h:367
RoleSpecType roletype
Definition: parsenodes.h:330
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5209
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:194
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define DatumGetPointer(X)
Definition: postgres.h:549
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
#define ACL_ID_PUBLIC
Definition: acl.h:46
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define PointerIsValid(pointer)
Definition: c.h:639
Oid serverid
Definition: foreign.h:36
#define MappingUserName(userid)
Definition: foreign.h:20

◆ CallStmtResultDesc()

TupleDesc CallStmtResultDesc ( CallStmt stmt)

Definition at line 2229 of file functioncmds.c.

References build_function_result_tupdesc_t(), elog, ERROR, CallStmt::funcexpr, FuncExpr::funcid, HeapTupleIsValid, ObjectIdGetDatum, PROCOID, ReleaseSysCache(), and SearchSysCache1().

Referenced by UtilityTupleDescriptor().

2230 {
2231  FuncExpr *fexpr;
2232  HeapTuple tuple;
2233  TupleDesc tupdesc;
2234 
2235  fexpr = stmt->funcexpr;
2236 
2237  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
2238  if (!HeapTupleIsValid(tuple))
2239  elog(ERROR, "cache lookup failed for procedure %u", fexpr->funcid);
2240 
2241  tupdesc = build_function_result_tupdesc_t(tuple);
2242 
2243  ReleaseSysCache(tuple);
2244 
2245  return tupdesc;
2246 }
FuncExpr * funcexpr
Definition: parsenodes.h:2903
TupleDesc build_function_result_tupdesc_t(HeapTuple procTuple)
Definition: funcapi.c:1424
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:214

◆ CheckIndexCompatible()

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

Definition at line 155 of file indexcmds.c.

References AccessShareLock, IndexAmRoutine::amcanorder, AMNAME, Assert, CompareOpclassOptions(), ComputeIndexAttrs(), DatumGetPointer, elog, ereport, errcode(), errmsg(), ERROR, get_opclass_input_type(), GetIndexAmRoutine(), GETSTRUCT, heap_attisnull(), HeapTupleIsValid, i, IndexInfo::ii_ExclusionOps, IndexInfo::ii_OpclassOptions, index_close(), INDEX_MAX_KEYS, index_open(), IndexGetRelation(), INDEXRELID, list_length(), makeIndexInfo(), NIL, NoLock, ObjectIdGetDatum, op_input_types(), palloc(), pfree(), PointerGetDatum, RelationData::rd_att, RelationGetExclusionInfo(), RelationGetIndexRawAttOptions(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, and oidvector::values.

Referenced by TryReuseIndex().

159 {
160  bool isconstraint;
161  Oid *typeObjectId;
162  Oid *collationObjectId;
163  Oid *classObjectId;
164  Oid accessMethodId;
165  Oid relationId;
166  HeapTuple tuple;
167  Form_pg_index indexForm;
168  Form_pg_am accessMethodForm;
169  IndexAmRoutine *amRoutine;
170  bool amcanorder;
171  int16 *coloptions;
172  IndexInfo *indexInfo;
173  int numberOfAttributes;
174  int old_natts;
175  bool isnull;
176  bool ret = true;
177  oidvector *old_indclass;
178  oidvector *old_indcollation;
179  Relation irel;
180  int i;
181  Datum d;
182 
183  /* Caller should already have the relation locked in some way. */
184  relationId = IndexGetRelation(oldId, false);
185 
186  /*
187  * We can pretend isconstraint = false unconditionally. It only serves to
188  * decide the text of an error message that should never happen for us.
189  */
190  isconstraint = false;
191 
192  numberOfAttributes = list_length(attributeList);
193  Assert(numberOfAttributes > 0);
194  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
195 
196  /* look up the access method */
197  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
198  if (!HeapTupleIsValid(tuple))
199  ereport(ERROR,
200  (errcode(ERRCODE_UNDEFINED_OBJECT),
201  errmsg("access method \"%s\" does not exist",
202  accessMethodName)));
203  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
204  accessMethodId = accessMethodForm->oid;
205  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
206  ReleaseSysCache(tuple);
207 
208  amcanorder = amRoutine->amcanorder;
209 
210  /*
211  * Compute the operator classes, collations, and exclusion operators for
212  * the new index, so we can test whether it's compatible with the existing
213  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
214  * DefineIndex would have called this function with the same arguments
215  * later on, and it would have failed then anyway. Our attributeList
216  * contains only key attributes, thus we're filling ii_NumIndexAttrs and
217  * ii_NumIndexKeyAttrs with same value.
218  */
219  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
220  accessMethodId, NIL, NIL, false, false, false);
221  typeObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
222  collationObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
223  classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
224  coloptions = (int16 *) palloc(numberOfAttributes * sizeof(int16));
225  ComputeIndexAttrs(indexInfo,
226  typeObjectId, collationObjectId, classObjectId,
227  coloptions, attributeList,
228  exclusionOpNames, relationId,
229  accessMethodName, accessMethodId,
230  amcanorder, isconstraint);
231 
232 
233  /* Get the soon-obsolete pg_index tuple. */
235  if (!HeapTupleIsValid(tuple))
236  elog(ERROR, "cache lookup failed for index %u", oldId);
237  indexForm = (Form_pg_index) GETSTRUCT(tuple);
238 
239  /*
240  * We don't assess expressions or predicates; assume incompatibility.
241  * Also, if the index is invalid for any reason, treat it as incompatible.
242  */
243  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
244  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
245  indexForm->indisvalid))
246  {
247  ReleaseSysCache(tuple);
248  return false;
249  }
250 
251  /* Any change in operator class or collation breaks compatibility. */
252  old_natts = indexForm->indnkeyatts;
253  Assert(old_natts == numberOfAttributes);
254 
255  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
256  Assert(!isnull);
257  old_indcollation = (oidvector *) DatumGetPointer(d);
258 
259  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
260  Assert(!isnull);
261  old_indclass = (oidvector *) DatumGetPointer(d);
262 
263  ret = (memcmp(old_indclass->values, classObjectId,
264  old_natts * sizeof(Oid)) == 0 &&
265  memcmp(old_indcollation->values, collationObjectId,
266  old_natts * sizeof(Oid)) == 0);
267 
268  ReleaseSysCache(tuple);
269 
270  if (!ret)
271  return false;
272 
273  /* For polymorphic opcintype, column type changes break compatibility. */
274  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
275  for (i = 0; i < old_natts; i++)
276  {
277  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
278  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
279  {
280  ret = false;
281  break;
282  }
283  }
284 
285  /* Any change in opclass options break compatibility. */
286  if (ret)
287  {
288  Datum *opclassOptions = RelationGetIndexRawAttOptions(irel);
289 
290  ret = CompareOpclassOptions(opclassOptions,
291  indexInfo->ii_OpclassOptions, old_natts);
292 
293  if (opclassOptions)
294  pfree(opclassOptions);
295  }
296 
297  /* Any change in exclusion operator selections breaks compatibility. */
298  if (ret && indexInfo->ii_ExclusionOps != NULL)
299  {
300  Oid *old_operators,
301  *old_procs;
302  uint16 *old_strats;
303 
304  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
305  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
306  old_natts * sizeof(Oid)) == 0;
307 
308  /* Require an exact input type match for polymorphic operators. */
309  if (ret)
310  {
311  for (i = 0; i < old_natts && ret; i++)
312  {
313  Oid left,
314  right;
315 
316  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
317  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
318  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
319  {
320  ret = false;
321  break;
322  }
323  }
324  }
325  }
326 
327  index_close(irel, NoLock);
328  return ret;
329 }
signed short int16
Definition: c.h:361
#define NIL
Definition: pg_list.h:65
Definition: c.h:601
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3401
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5182
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts)
Definition: indexcmds.c:338
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
unsigned int Oid
Definition: postgres_ext.h:31
unsigned short uint16
Definition: c.h:373
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
#define NoLock
Definition: lockdefs.h:34
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:609
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1275
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool isready, bool concurrent)
Definition: makefuncs.c:742
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5390
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define INDEX_MAX_KEYS
static int list_length(const List *l)
Definition: pg_list.h:169
bool amcanorder
Definition: amapi.h:219
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:549
Oid * ii_ExclusionOps
Definition: execnodes.h:165
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *typeOidP, Oid *collationOidP, Oid *classOidP, int16 *colOptionP, List *attList, List *exclusionOpNames, Oid relId, const char *accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint)
Definition: indexcmds.c:1651
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
Datum * ii_OpclassOptions
Definition: execnodes.h:171
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1151

◆ ChooseRelationName()

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

Definition at line 2253 of file indexcmds.c.

References ConstraintNameExists(), get_relname_relid(), makeObjectName(), NAMEDATALEN, OidIsValid, pfree(), relname, snprintf, and strlcpy().

Referenced by ChooseIndexName(), generateSerialExtraStmts(), and ReindexRelationConcurrently().

2256 {
2257  int pass = 0;
2258  char *relname = NULL;
2259  char modlabel[NAMEDATALEN];
2260 
2261  /* try the unmodified label first */
2262  strlcpy(modlabel, label, sizeof(modlabel));
2263 
2264  for (;;)
2265  {
2266  relname = makeObjectName(name1, name2, modlabel);
2267 
2268  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2269  {
2270  if (!isconstraint ||
2271  !ConstraintNameExists(relname, namespaceid))
2272  break;
2273  }
2274 
2275  /* found a conflict, so try a new name component */
2276  pfree(relname);
2277  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2278  }
2279 
2280  return relname;
2281 }
bool ConstraintNameExists(const char *conname, Oid namespaceid)
NameData relname
Definition: pg_class.h:38
#define OidIsValid(objectId)
Definition: c.h:651
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2167
#define NAMEDATALEN
void pfree(void *pointer)
Definition: mcxt.c:1057
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
static char * label
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define snprintf
Definition: port.h:193

◆ CreateAccessMethod()

ObjectAddress CreateAccessMethod ( CreateAmStmt stmt)

Definition at line 43 of file amcmds.c.

References AMNAME, CreateAmStmt::amname, AmOidIndexId, CreateAmStmt::amtype, CatalogTupleInsert(), CharGetDatum, ObjectAddress::classId, CStringGetDatum, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, GetNewOidWithIndex(), GetSysCacheOid1, CreateAmStmt::handler_name, heap_form_tuple(), heap_freetuple(), InvokeObjectPostCreateHook, lookup_am_handler_func(), namein(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, recordDependencyOn(), recordDependencyOnCurrentExtension(), RelationGetDescr, RowExclusiveLock, superuser(), table_close(), table_open(), and values.

Referenced by ProcessUtilitySlow().

44 {
45  Relation rel;
46  ObjectAddress myself;
47  ObjectAddress referenced;
48  Oid amoid;
49  Oid amhandler;
50  bool nulls[Natts_pg_am];
51  Datum values[Natts_pg_am];
52  HeapTuple tup;
53 
54  rel = table_open(AccessMethodRelationId, RowExclusiveLock);
55 
56  /* Must be super user */
57  if (!superuser())
58  ereport(ERROR,
59  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
60  errmsg("permission denied to create access method \"%s\"",
61  stmt->amname),
62  errhint("Must be superuser to create an access method.")));
63 
64  /* Check if name is used */
65  amoid = GetSysCacheOid1(AMNAME, Anum_pg_am_oid,
66  CStringGetDatum(stmt->amname));
67  if (OidIsValid(amoid))
68  {
69  ereport(ERROR,
71  errmsg("access method \"%s\" already exists",
72  stmt->amname)));
73  }
74 
75  /*
76  * Get the handler function oid, verifying the AM type while at it.
77  */
78  amhandler = lookup_am_handler_func(stmt->handler_name, stmt->amtype);
79 
80  /*
81  * Insert tuple into pg_am.
82  */
83  memset(values, 0, sizeof(values));
84  memset(nulls, false, sizeof(nulls));
85 
86  amoid = GetNewOidWithIndex(rel, AmOidIndexId, Anum_pg_am_oid);
87  values[Anum_pg_am_oid - 1] = ObjectIdGetDatum(amoid);
88  values[Anum_pg_am_amname - 1] =
90  values[Anum_pg_am_amhandler - 1] = ObjectIdGetDatum(amhandler);
91  values[Anum_pg_am_amtype - 1] = CharGetDatum(stmt->amtype);
92 
93  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
94 
95  CatalogTupleInsert(rel, tup);
96  heap_freetuple(tup);
97 
98  myself.classId = AccessMethodRelationId;
99  myself.objectId = amoid;
100  myself.objectSubId = 0;
101 
102  /* Record dependency on handler function */
103  referenced.classId = ProcedureRelationId;
104  referenced.objectId = amhandler;
105  referenced.objectSubId = 0;
106 
107  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
108 
109  recordDependencyOnCurrentExtension(&myself, false);
110 
111  InvokeObjectPostCreateHook(AccessMethodRelationId, amoid, 0);
112 
114 
115  return myself;
116 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1071
static Oid lookup_am_handler_func(List *handler_name, char amtype)
Definition: amcmds.c:234
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
#define RelationGetDescr(relation)
Definition: rel.h:482
#define GetSysCacheOid1(cacheId, oidcol, key1)
Definition: syscache.h:192
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:624
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * amname
Definition: parsenodes.h:2420
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
uintptr_t Datum
Definition: postgres.h:367
List * handler_name
Definition: parsenodes.h:2421
#define ereport(elevel,...)
Definition: elog.h:144
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:180
#define CharGetDatum(X)
Definition: postgres.h:416
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define AmOidIndexId
Definition: indexing.h:85
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221

◆ CreateCast()

ObjectAddress CreateCast ( CreateCastStmt stmt)

Definition at line 1408 of file functioncmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, CastCreate(), COERCION_ASSIGNMENT, COERCION_EXPLICIT, COERCION_IMPLICIT, CreateCastStmt::context, DEPENDENCY_NORMAL, elog, ereport, errcode(), errmsg(), ERROR, format_type_be(), CreateCastStmt::func, get_element_type(), get_typlenbyvalalign(), get_typtype(), GETSTRUCT, GetUserId(), HeapTupleIsValid, CreateCastStmt::inout, InvalidOid, IsBinaryCoercible(), LookupFuncWithArgs(), OBJECT_FUNCTION, ObjectIdGetDatum, OidIsValid, pg_type_aclcheck(), pg_type_ownercheck(), PROCOID, ReleaseSysCache(), SearchSysCache1(), CreateCastStmt::sourcetype, superuser(), CreateCastStmt::targettype, TypeNameToString(), typenameTypeId(), and WARNING.

Referenced by ProcessUtilitySlow().

1409 {
1410  Oid sourcetypeid;
1411  Oid targettypeid;
1412  char sourcetyptype;
1413  char targettyptype;
1414  Oid funcid;
1415  int nargs;
1416  char castcontext;
1417  char castmethod;
1418  HeapTuple tuple;
1419  AclResult aclresult;
1420  ObjectAddress myself;
1421 
1422  sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1423  targettypeid = typenameTypeId(NULL, stmt->targettype);
1424  sourcetyptype = get_typtype(sourcetypeid);
1425  targettyptype = get_typtype(targettypeid);
1426 
1427  /* No pseudo-types allowed */
1428  if (sourcetyptype == TYPTYPE_PSEUDO)
1429  ereport(ERROR,
1430  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1431  errmsg("source data type %s is a pseudo-type",
1432  TypeNameToString(stmt->sourcetype))));
1433 
1434  if (targettyptype == TYPTYPE_PSEUDO)
1435  ereport(ERROR,
1436  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1437  errmsg("target data type %s is a pseudo-type",
1438  TypeNameToString(stmt->targettype))));
1439 
1440  /* Permission check */
1441  if (!pg_type_ownercheck(sourcetypeid, GetUserId())
1442  && !pg_type_ownercheck(targettypeid, GetUserId()))
1443  ereport(ERROR,
1444  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1445  errmsg("must be owner of type %s or type %s",
1446  format_type_be(sourcetypeid),
1447  format_type_be(targettypeid))));
1448 
1449  aclresult = pg_type_aclcheck(sourcetypeid, GetUserId(), ACL_USAGE);
1450  if (aclresult != ACLCHECK_OK)
1451  aclcheck_error_type(aclresult, sourcetypeid);
1452 
1453  aclresult = pg_type_aclcheck(targettypeid, GetUserId(), ACL_USAGE);
1454  if (aclresult != ACLCHECK_OK)
1455  aclcheck_error_type(aclresult, targettypeid);
1456 
1457  /* Domains are allowed for historical reasons, but we warn */
1458  if (sourcetyptype == TYPTYPE_DOMAIN)
1459  ereport(WARNING,
1460  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1461  errmsg("cast will be ignored because the source data type is a domain")));
1462 
1463  else if (targettyptype == TYPTYPE_DOMAIN)
1464  ereport(WARNING,
1465  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1466  errmsg("cast will be ignored because the target data type is a domain")));
1467 
1468  /* Determine the cast method */
1469  if (stmt->func != NULL)
1470  castmethod = COERCION_METHOD_FUNCTION;
1471  else if (stmt->inout)
1472  castmethod = COERCION_METHOD_INOUT;
1473  else
1474  castmethod = COERCION_METHOD_BINARY;
1475 
1476  if (castmethod == COERCION_METHOD_FUNCTION)
1477  {
1478  Form_pg_proc procstruct;
1479 
1480  funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
1481 
1482  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1483  if (!HeapTupleIsValid(tuple))
1484  elog(ERROR, "cache lookup failed for function %u", funcid);
1485 
1486  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1487  nargs = procstruct->pronargs;
1488  if (nargs < 1 || nargs > 3)
1489  ereport(ERROR,
1490  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1491  errmsg("cast function must take one to three arguments")));
1492  if (!IsBinaryCoercible(sourcetypeid, procstruct->proargtypes.values[0]))
1493  ereport(ERROR,
1494  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1495  errmsg("argument of cast function must match or be binary-coercible from source data type")));
1496  if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1497  ereport(ERROR,
1498  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1499  errmsg("second argument of cast function must be type %s",
1500  "integer")));
1501  if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1502  ereport(ERROR,
1503  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1504  errmsg("third argument of cast function must be type %s",
1505  "boolean")));
1506  if (!IsBinaryCoercible(procstruct->prorettype, targettypeid))
1507  ereport(ERROR,
1508  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1509  errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1510 
1511  /*
1512  * Restricting the volatility of a cast function may or may not be a
1513  * good idea in the abstract, but it definitely breaks many old
1514  * user-defined types. Disable this check --- tgl 2/1/03
1515  */
1516 #ifdef NOT_USED
1517  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1518  ereport(ERROR,
1519  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1520  errmsg("cast function must not be volatile")));
1521 #endif
1522  if (procstruct->prokind != PROKIND_FUNCTION)
1523  ereport(ERROR,
1524  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1525  errmsg("cast function must be a normal function")));
1526  if (procstruct->proretset)
1527  ereport(ERROR,
1528  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1529  errmsg("cast function must not return a set")));
1530 
1531  ReleaseSysCache(tuple);
1532  }
1533  else
1534  {
1535  funcid = InvalidOid;
1536  nargs = 0;
1537  }
1538 
1539  if (castmethod == COERCION_METHOD_BINARY)
1540  {
1541  int16 typ1len;
1542  int16 typ2len;
1543  bool typ1byval;
1544  bool typ2byval;
1545  char typ1align;
1546  char typ2align;
1547 
1548  /*
1549  * Must be superuser to create binary-compatible casts, since
1550  * erroneous casts can easily crash the backend.
1551  */
1552  if (!superuser())
1553  ereport(ERROR,
1554  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1555  errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1556 
1557  /*
1558  * Also, insist that the types match as to size, alignment, and
1559  * pass-by-value attributes; this provides at least a crude check that
1560  * they have similar representations. A pair of types that fail this
1561  * test should certainly not be equated.
1562  */
1563  get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1564  get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1565  if (typ1len != typ2len ||
1566  typ1byval != typ2byval ||
1567  typ1align != typ2align)
1568  ereport(ERROR,
1569  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1570  errmsg("source and target data types are not physically compatible")));
1571 
1572  /*
1573  * We know that composite, enum and array types are never binary-
1574  * compatible with each other. They all have OIDs embedded in them.
1575  *
1576  * Theoretically you could build a user-defined base type that is
1577  * binary-compatible with a composite, enum, or array type. But we
1578  * disallow that too, as in practice such a cast is surely a mistake.
1579  * You can always work around that by writing a cast function.
1580  */
1581  if (sourcetyptype == TYPTYPE_COMPOSITE ||
1582  targettyptype == TYPTYPE_COMPOSITE)
1583  ereport(ERROR,
1584  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1585  errmsg("composite data types are not binary-compatible")));
1586 
1587  if (sourcetyptype == TYPTYPE_ENUM ||
1588  targettyptype == TYPTYPE_ENUM)
1589  ereport(ERROR,
1590  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1591  errmsg("enum data types are not binary-compatible")));
1592 
1593  if (OidIsValid(get_element_type(sourcetypeid)) ||
1594  OidIsValid(get_element_type(targettypeid)))
1595  ereport(ERROR,
1596  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1597  errmsg("array data types are not binary-compatible")));
1598 
1599  /*
1600  * We also disallow creating binary-compatibility casts involving
1601  * domains. Casting from a domain to its base type is already
1602  * allowed, and casting the other way ought to go through domain
1603  * coercion to permit constraint checking. Again, if you're intent on
1604  * having your own semantics for that, create a no-op cast function.
1605  *
1606  * NOTE: if we were to relax this, the above checks for composites
1607  * etc. would have to be modified to look through domains to their
1608  * base types.
1609  */
1610  if (sourcetyptype == TYPTYPE_DOMAIN ||
1611  targettyptype == TYPTYPE_DOMAIN)
1612  ereport(ERROR,
1613  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1614  errmsg("domain data types must not be marked binary-compatible")));
1615  }
1616 
1617  /*
1618  * Allow source and target types to be same only for length coercion
1619  * functions. We assume a multi-arg function does length coercion.
1620  */
1621  if (sourcetypeid == targettypeid && nargs < 2)
1622  ereport(ERROR,
1623  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1624  errmsg("source data type and target data type are the same")));
1625 
1626  /* convert CoercionContext enum to char value for castcontext */
1627  switch (stmt->context)
1628  {
1629  case COERCION_IMPLICIT:
1630  castcontext = COERCION_CODE_IMPLICIT;
1631  break;
1632  case COERCION_ASSIGNMENT:
1633  castcontext = COERCION_CODE_ASSIGNMENT;
1634  break;
1635  case COERCION_EXPLICIT:
1636  castcontext = COERCION_CODE_EXPLICIT;
1637  break;
1638  default:
1639  elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1640  castcontext = 0; /* keep compiler quiet */
1641  break;
1642  }
1643 
1644  myself = CastCreate(sourcetypeid, targettypeid, funcid, castcontext,
1645  castmethod, DEPENDENCY_NORMAL);
1646  return myself;
1647 }
signed short int16
Definition: c.h:361
TypeName * sourcetype
Definition: parsenodes.h:3399
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
ObjectAddress CastCreate(Oid sourcetypeid, Oid targettypeid, Oid funcid, char castcontext, char castmethod, DependencyType behavior)
Definition: pg_cast.c:43
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2636
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2159
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
char get_typtype(Oid typid)
Definition: lsyscache.c:2517
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
bool pg_type_ownercheck(Oid type_oid, Oid roleid)
Definition: aclchk.c:4713
#define OidIsValid(objectId)
Definition: c.h:651
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3607
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
CoercionContext context
Definition: parsenodes.h:3402
#define ACL_USAGE
Definition: parsenodes.h:82
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
AclResult
Definition: acl.h:177
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
ObjectWithArgs * func
Definition: parsenodes.h:3401
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2163
TypeName * targettype
Definition: parsenodes.h:3400
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4675
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ CreateForeignDataWrapper()

ObjectAddress CreateForeignDataWrapper ( CreateFdwStmt stmt)

Definition at line 562 of file foreigncmds.c.

References CatalogTupleInsert(), ObjectAddress::classId, CStringGetDatum, DatumGetPointer, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, CreateFdwStmt::fdwname, ForeignDataWrapperOidIndexId, CreateFdwStmt::func_options, GetForeignDataWrapperByName(), GetNewOidWithIndex(), GetUserId(), heap_form_tuple(), heap_freetuple(), InvokeObjectPostCreateHook, namein(), ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, CreateFdwStmt::options, parse_func_options(), PointerGetDatum, PointerIsValid, RelationData::rd_att, recordDependencyOn(), recordDependencyOnCurrentExtension(), recordDependencyOnOwner(), RowExclusiveLock, superuser(), table_close(), table_open(), transformGenericOptions(), and values.

Referenced by ProcessUtilitySlow().

563 {
564  Relation rel;
565  Datum values[Natts_pg_foreign_data_wrapper];
566  bool nulls[Natts_pg_foreign_data_wrapper];
567  HeapTuple tuple;
568  Oid fdwId;
569  bool handler_given;
570  bool validator_given;
571  Oid fdwhandler;
572  Oid fdwvalidator;
573  Datum fdwoptions;
574  Oid ownerId;
575  ObjectAddress myself;
576  ObjectAddress referenced;
577 
578  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
579 
580  /* Must be super user */
581  if (!superuser())
582  ereport(ERROR,
583  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
584  errmsg("permission denied to create foreign-data wrapper \"%s\"",
585  stmt->fdwname),
586  errhint("Must be superuser to create a foreign-data wrapper.")));
587 
588  /* For now the owner cannot be specified on create. Use effective user ID. */
589  ownerId = GetUserId();
590 
591  /*
592  * Check that there is no other foreign-data wrapper by this name.
593  */
594  if (GetForeignDataWrapperByName(stmt->fdwname, true) != NULL)
595  ereport(ERROR,
597  errmsg("foreign-data wrapper \"%s\" already exists",
598  stmt->fdwname)));
599 
600  /*
601  * Insert tuple into pg_foreign_data_wrapper.
602  */
603  memset(values, 0, sizeof(values));
604  memset(nulls, false, sizeof(nulls));
605 
607  Anum_pg_foreign_data_wrapper_oid);
608  values[Anum_pg_foreign_data_wrapper_oid - 1] = ObjectIdGetDatum(fdwId);
609  values[Anum_pg_foreign_data_wrapper_fdwname - 1] =
611  values[Anum_pg_foreign_data_wrapper_fdwowner - 1] = ObjectIdGetDatum(ownerId);
612 
613  /* Lookup handler and validator functions, if given */
615  &handler_given, &fdwhandler,
616  &validator_given, &fdwvalidator);
617 
618  values[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
619  values[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
620 
621  nulls[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
622 
623  fdwoptions = transformGenericOptions(ForeignDataWrapperRelationId,
624  PointerGetDatum(NULL),
625  stmt->options,
626  fdwvalidator);
627 
628  if (PointerIsValid(DatumGetPointer(fdwoptions)))
629  values[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = fdwoptions;
630  else
631  nulls[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
632 
633  tuple = heap_form_tuple(rel->rd_att, values, nulls);
634 
635  CatalogTupleInsert(rel, tuple);
636 
637  heap_freetuple(tuple);
638 
639  /* record dependencies */
640  myself.classId = ForeignDataWrapperRelationId;
641  myself.objectId = fdwId;
642  myself.objectSubId = 0;
643 
644  if (OidIsValid(fdwhandler))
645  {
646  referenced.classId = ProcedureRelationId;
647  referenced.objectId = fdwhandler;
648  referenced.objectSubId = 0;
649  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
650  }
651 
652  if (OidIsValid(fdwvalidator))
653  {
654  referenced.classId = ProcedureRelationId;
655  referenced.objectId = fdwvalidator;
656  referenced.objectSubId = 0;
657  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
658  }
659 
660  recordDependencyOnOwner(ForeignDataWrapperRelationId, fdwId, ownerId);
661 
662  /* dependency on extension */
663  recordDependencyOnCurrentExtension(&myself, false);
664 
665  /* Post creation hook for new foreign data wrapper */
666  InvokeObjectPostCreateHook(ForeignDataWrapperRelationId, fdwId, 0);
667 
669 
670  return myself;
671 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1071
static void parse_func_options(List *func_options, bool *handler_given, Oid *fdwhandler, bool *validator_given, Oid *fdwvalidator)
Definition: foreigncmds.c:518
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
Oid GetUserId(void)
Definition: miscinit.c:476
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:624
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
List * options
Definition: parsenodes.h:2282
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
char * fdwname
Definition: parsenodes.h:2280
#define CStringGetDatum(X)
Definition: postgres.h:578
uintptr_t Datum
Definition: postgres.h:367
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define ForeignDataWrapperOidIndexId
Definition: indexing.h:302
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:94
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:180
#define DatumGetPointer(X)
Definition: postgres.h:549
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define PointerIsValid(pointer)
Definition: c.h:639
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
List * func_options
Definition: parsenodes.h:2281

◆ CreateForeignServer()

ObjectAddress CreateForeignServer ( CreateForeignServerStmt stmt)

Definition at line 842 of file foreigncmds.c.

References ACL_USAGE, aclcheck_error(), ACLCHECK_OK, CatalogTupleInsert(), ObjectAddress::classId, CStringGetDatum, CStringGetTextDatum, DatumGetPointer, DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, ForeignDataWrapper::fdwid, ForeignDataWrapper::fdwname, CreateForeignServerStmt::fdwname, ForeignDataWrapper::fdwvalidator, ForeignServerOidIndexId, GetForeignDataWrapperByName(), GetForeignServerByName(), GetNewOidWithIndex(), GetUserId(), heap_form_tuple(), heap_freetuple(), CreateForeignServerStmt::if_not_exists, InvalidObjectAddress, InvokeObjectPostCreateHook, namein(), NOTICE, OBJECT_FDW, 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, table_close(), table_open(), transformGenericOptions(), values, and CreateForeignServerStmt::version.

Referenced by ProcessUtilitySlow().

843 {
844  Relation rel;
845  Datum srvoptions;
846  Datum values[Natts_pg_foreign_server];
847  bool nulls[Natts_pg_foreign_server];
848  HeapTuple tuple;
849  Oid srvId;
850  Oid ownerId;
851  AclResult aclresult;
852  ObjectAddress myself;
853  ObjectAddress referenced;
854  ForeignDataWrapper *fdw;
855 
856  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
857 
858  /* For now the owner cannot be specified on create. Use effective user ID. */
859  ownerId = GetUserId();
860 
861  /*
862  * Check that there is no other foreign server by this name. Do nothing if
863  * IF NOT EXISTS was enforced.
864  */
865  if (GetForeignServerByName(stmt->servername, true) != NULL)
866  {
867  if (stmt->if_not_exists)
868  {
869  ereport(NOTICE,
871  errmsg("server \"%s\" already exists, skipping",
872  stmt->servername)));
874  return InvalidObjectAddress;
875  }
876  else
877  ereport(ERROR,
879  errmsg("server \"%s\" already exists",
880  stmt->servername)));
881  }
882 
883  /*
884  * Check that the FDW exists and that we have USAGE on it. Also get the
885  * actual FDW for option validation etc.
886  */
887  fdw = GetForeignDataWrapperByName(stmt->fdwname, false);
888 
889  aclresult = pg_foreign_data_wrapper_aclcheck(fdw->fdwid, ownerId, ACL_USAGE);
890  if (aclresult != ACLCHECK_OK)
891  aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);
892 
893  /*
894  * Insert tuple into pg_foreign_server.
895  */
896  memset(values, 0, sizeof(values));
897  memset(nulls, false, sizeof(nulls));
898 
900  Anum_pg_foreign_server_oid);
901  values[Anum_pg_foreign_server_oid - 1] = ObjectIdGetDatum(srvId);
902  values[Anum_pg_foreign_server_srvname - 1] =
904  values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);
905  values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid);
906 
907  /* Add server type if supplied */
908  if (stmt->servertype)
909  values[Anum_pg_foreign_server_srvtype - 1] =
911  else
912  nulls[Anum_pg_foreign_server_srvtype - 1] = true;
913 
914  /* Add server version if supplied */
915  if (stmt->version)
916  values[Anum_pg_foreign_server_srvversion - 1] =
918  else
919  nulls[Anum_pg_foreign_server_srvversion - 1] = true;
920 
921  /* Start with a blank acl */
922  nulls[Anum_pg_foreign_server_srvacl - 1] = true;
923 
924  /* Add server options */
925  srvoptions = transformGenericOptions(ForeignServerRelationId,
926  PointerGetDatum(NULL),
927  stmt->options,
928  fdw->fdwvalidator);
929 
930  if (PointerIsValid(DatumGetPointer(srvoptions)))
931  values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;
932  else
933  nulls[Anum_pg_foreign_server_srvoptions - 1] = true;
934 
935  tuple = heap_form_tuple(rel->rd_att, values, nulls);
936 
937  CatalogTupleInsert(rel, tuple);
938 
939  heap_freetuple(tuple);
940 
941  /* record dependencies */
942  myself.classId = ForeignServerRelationId;
943  myself.objectId = srvId;
944  myself.objectSubId = 0;
945 
946  referenced.classId = ForeignDataWrapperRelationId;
947  referenced.objectId = fdw->fdwid;
948  referenced.objectSubId = 0;
949  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
950 
951  recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId);
952 
953  /* dependency on extension */
954  recordDependencyOnCurrentExtension(&myself, false);
955 
956  /* Post creation hook for new foreign server */
957  InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0);
958 
960 
961  return myself;
962 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
Oid GetUserId(void)
Definition: miscinit.c:476
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
char * fdwname
Definition: foreign.h:28
#define PointerGetDatum(X)
Definition: postgres.h:556
AclResult pg_foreign_data_wrapper_aclcheck(Oid fdw_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4650
int errcode(int sqlerrcode)
Definition: elog.c:610
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:624
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
#define ACL_USAGE
Definition: parsenodes.h:82
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:94
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:180
#define DatumGetPointer(X)
Definition: postgres.h:549
static Datum values[MAXATTR]
Definition: bootstrap.c:165
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define CStringGetTextDatum(s)
Definition: builtins.h:86
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define PointerIsValid(pointer)
Definition: c.h:639
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define ForeignServerOidIndexId
Definition: indexing.h:307

◆ CreateForeignTable()

void CreateForeignTable ( CreateForeignTableStmt stmt,
Oid  relid 
)

Definition at line 1395 of file foreigncmds.c.

References ACL_USAGE, aclcheck_error(), ACLCHECK_OK, CatalogTupleInsert(), ObjectAddress::classId, CommandCounterIncrement(), DatumGetPointer, DEPENDENCY_NORMAL, ForeignServer::fdwid, ForeignDataWrapper::fdwvalidator, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), heap_form_tuple(), heap_freetuple(), OBJECT_FOREIGN_SERVER, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, CreateForeignTableStmt::options, pg_foreign_server_aclcheck(), PointerGetDatum, PointerIsValid, RelationData::rd_att, recordDependencyOn(), RowExclusiveLock, ForeignServer::serverid, ForeignServer::servername, CreateForeignTableStmt::servername, table_close(), table_open(), transformGenericOptions(), and values.

Referenced by ProcessUtilitySlow().

1396 {
1397  Relation ftrel;
1398  Datum ftoptions;
1399  Datum values[Natts_pg_foreign_table];
1400  bool nulls[Natts_pg_foreign_table];
1401  HeapTuple tuple;
1402  AclResult aclresult;
1403  ObjectAddress myself;
1404  ObjectAddress referenced;
1405  Oid ownerId;
1406  ForeignDataWrapper *fdw;
1407  ForeignServer *server;
1408 
1409  /*
1410  * Advance command counter to ensure the pg_attribute tuple is visible;
1411  * the tuple might be updated to add constraints in previous step.
1412  */
1414 
1415  ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
1416 
1417  /*
1418  * For now the owner cannot be specified on create. Use effective user ID.
1419  */
1420  ownerId = GetUserId();
1421 
1422  /*
1423  * Check that the foreign server exists and that we have USAGE on it. Also
1424  * get the actual FDW for option validation etc.
1425  */
1426  server = GetForeignServerByName(stmt->servername, false);
1427  aclresult = pg_foreign_server_aclcheck(server->serverid, ownerId, ACL_USAGE);
1428  if (aclresult != ACLCHECK_OK)
1429  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
1430 
1431  fdw = GetForeignDataWrapper(server->fdwid);
1432 
1433  /*
1434  * Insert tuple into pg_foreign_table.
1435  */
1436  memset(values, 0, sizeof(values));
1437  memset(nulls, false, sizeof(nulls));
1438 
1439  values[Anum_pg_foreign_table_ftrelid - 1] = ObjectIdGetDatum(relid);
1440  values[Anum_pg_foreign_table_ftserver - 1] = ObjectIdGetDatum(server->serverid);
1441  /* Add table generic options */
1442  ftoptions = transformGenericOptions(ForeignTableRelationId,
1443  PointerGetDatum(NULL),
1444  stmt->options,
1445  fdw->fdwvalidator);
1446 
1447  if (PointerIsValid(DatumGetPointer(ftoptions)))
1448  values[Anum_pg_foreign_table_ftoptions - 1] = ftoptions;
1449  else
1450  nulls[Anum_pg_foreign_table_ftoptions - 1] = true;
1451 
1452  tuple = heap_form_tuple(ftrel->rd_att, values, nulls);
1453 
1454  CatalogTupleInsert(ftrel, tuple);
1455 
1456  heap_freetuple(tuple);
1457 
1458  /* Add pg_class dependency on the server */
1459  myself.classId = RelationRelationId;
1460  myself.objectId = relid;
1461  myself.objectSubId = 0;
1462 
1463  referenced.classId = ForeignServerRelationId;
1464  referenced.objectId = server->serverid;
1465  referenced.objectSubId = 0;
1466  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1467 
1468  table_close(ftrel, RowExclusiveLock);
1469 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid GetUserId(void)
Definition: miscinit.c:476
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4663
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ACL_USAGE
Definition: parsenodes.h:82
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
TupleDesc rd_att
Definition: rel.h:110
#define DatumGetPointer(X)
Definition: postgres.h:549
static Datum values[MAXATTR]
Definition: bootstrap.c:165
char * servername
Definition: foreign.h:39
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PointerIsValid(pointer)
Definition: c.h:639
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
Oid serverid
Definition: foreign.h:36

◆ CreateFunction()

ObjectAddress CreateFunction ( ParseState pstate,
CreateFunctionStmt stmt 
)

Definition at line 922 of file functioncmds.c.

References ACL_CREATE, ACL_USAGE, aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_OK, Assert, castNode, compute_function_attributes(), compute_return_type(), construct_array(), ereport, errcode(), errhint(), errmsg(), ERROR, extension_file_exists(), format_type_be(), CreateFunctionStmt::funcname, get_base_element_type(), get_namespace_name(), get_transform_oid(), GETSTRUCT, GetUserId(), HeapTupleIsValid, i, interpret_AS_clause(), interpret_function_parameter_list(), InvalidOid, CreateFunctionStmt::is_procedure, LANGNAME, lappend_oid(), lfirst_node, lfirst_oid, list_length(), NameStr, NIL, OBJECT_FUNCTION, OBJECT_LANGUAGE, OBJECT_PROCEDURE, OBJECT_SCHEMA, ObjectIdGetDatum, OidIsValid, CreateFunctionStmt::options, palloc(), CreateFunctionStmt::parameters, pg_language_aclcheck(), pg_namespace_aclcheck(), PointerGetDatum, ProcedureCreate(), QualifiedNameGetCreationNamespace(), ReleaseSysCache(), CreateFunctionStmt::replace, CreateFunctionStmt::returnType, SearchSysCache1(), superuser(), and typenameTypeId().

Referenced by ProcessUtilitySlow().

923 {
924  char *probin_str;
925  char *prosrc_str;
926  Oid prorettype;
927  bool returnsSet;
928  char *language;
929  Oid languageOid;
930  Oid languageValidator;
931  Node *transformDefElem = NULL;
932  char *funcname;
933  Oid namespaceId;
934  AclResult aclresult;
935  oidvector *parameterTypes;
936  ArrayType *allParameterTypes;
937  ArrayType *parameterModes;
938  ArrayType *parameterNames;
939  List *parameterDefaults;
940  Oid variadicArgType;
941  List *trftypes_list = NIL;
942  ArrayType *trftypes;
943  Oid requiredResultType;
944  bool isWindowFunc,
945  isStrict,
946  security,
947  isLeakProof;
948  char volatility;
949  ArrayType *proconfig;
950  float4 procost;
951  float4 prorows;
952  Oid prosupport;
953  HeapTuple languageTuple;
954  Form_pg_language languageStruct;
955  List *as_clause;
956  char parallel;
957 
958  /* Convert list of names to a name and namespace */
959  namespaceId = QualifiedNameGetCreationNamespace(stmt->funcname,
960  &funcname);
961 
962  /* Check we have creation rights in target namespace */
963  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
964  if (aclresult != ACLCHECK_OK)
965  aclcheck_error(aclresult, OBJECT_SCHEMA,
966  get_namespace_name(namespaceId));
967 
968  /* Set default attributes */
969  isWindowFunc = false;
970  isStrict = false;
971  security = false;
972  isLeakProof = false;
973  volatility = PROVOLATILE_VOLATILE;
974  proconfig = NULL;
975  procost = -1; /* indicates not set */
976  prorows = -1; /* indicates not set */
977  prosupport = InvalidOid;
978  parallel = PROPARALLEL_UNSAFE;
979 
980  /* Extract non-default attributes from stmt->options list */
982  stmt->is_procedure,
983  stmt->options,
984  &as_clause, &language, &transformDefElem,
985  &isWindowFunc, &volatility,
986  &isStrict, &security, &isLeakProof,
987  &proconfig, &procost, &prorows,
988  &prosupport, &parallel);
989 
990  /* Look up the language and validate permissions */
991  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
992  if (!HeapTupleIsValid(languageTuple))
993  ereport(ERROR,
994  (errcode(ERRCODE_UNDEFINED_OBJECT),
995  errmsg("language \"%s\" does not exist", language),
996  (extension_file_exists(language) ?
997  errhint("Use CREATE EXTENSION to load the language into the database.") : 0)));
998 
999  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
1000  languageOid = languageStruct->oid;
1001 
1002  if (languageStruct->lanpltrusted)
1003  {
1004  /* if trusted language, need USAGE privilege */
1005  AclResult aclresult;
1006 
1007  aclresult = pg_language_aclcheck(languageOid, GetUserId(), ACL_USAGE);
1008  if (aclresult != ACLCHECK_OK)
1009  aclcheck_error(aclresult, OBJECT_LANGUAGE,
1010  NameStr(languageStruct->lanname));
1011  }
1012  else
1013  {
1014  /* if untrusted language, must be superuser */
1015  if (!superuser())
1017  NameStr(languageStruct->lanname));
1018  }
1019 
1020  languageValidator = languageStruct->lanvalidator;
1021 
1022  ReleaseSysCache(languageTuple);
1023 
1024  /*
1025  * Only superuser is allowed to create leakproof functions because
1026  * leakproof functions can see tuples which have not yet been filtered out
1027  * by security barrier views or row level security policies.
1028  */
1029  if (isLeakProof && !superuser())
1030  ereport(ERROR,
1031  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1032  errmsg("only superuser can define a leakproof function")));
1033 
1034  if (transformDefElem)
1035  {
1036  ListCell *lc;
1037 
1038  foreach(lc, castNode(List, transformDefElem))
1039  {
1040  Oid typeid = typenameTypeId(NULL,
1041  lfirst_node(TypeName, lc));
1042  Oid elt = get_base_element_type(typeid);
1043 
1044  typeid = elt ? elt : typeid;
1045 
1046  get_transform_oid(typeid, languageOid, false);
1047  trftypes_list = lappend_oid(trftypes_list, typeid);
1048  }
1049  }
1050 
1051  /*
1052  * Convert remaining parameters of CREATE to form wanted by
1053  * ProcedureCreate.
1054  */
1056  stmt->parameters,
1057  languageOid,
1059  &parameterTypes,
1060  &allParameterTypes,
1061  &parameterModes,
1062  &parameterNames,
1063  &parameterDefaults,
1064  &variadicArgType,
1065  &requiredResultType);
1066 
1067  if (stmt->is_procedure)
1068  {
1069  Assert(!stmt->returnType);
1070  prorettype = requiredResultType ? requiredResultType : VOIDOID;
1071  returnsSet = false;
1072  }
1073  else if (stmt->returnType)
1074  {
1075  /* explicit RETURNS clause */
1076  compute_return_type(stmt->returnType, languageOid,
1077  &prorettype, &returnsSet);
1078  if (OidIsValid(requiredResultType) && prorettype != requiredResultType)
1079  ereport(ERROR,
1080  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1081  errmsg("function result type must be %s because of OUT parameters",
1082  format_type_be(requiredResultType))));
1083  }
1084  else if (OidIsValid(requiredResultType))
1085  {
1086  /* default RETURNS clause from OUT parameters */
1087  prorettype = requiredResultType;
1088  returnsSet = false;
1089  }
1090  else
1091  {
1092  ereport(ERROR,
1093  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1094  errmsg("function result type must be specified")));
1095  /* Alternative possibility: default to RETURNS VOID */
1096  prorettype = VOIDOID;
1097  returnsSet = false;
1098  }
1099 
1100  if (list_length(trftypes_list) > 0)
1101  {
1102  ListCell *lc;
1103  Datum *arr;
1104  int i;
1105 
1106  arr = palloc(list_length(trftypes_list) * sizeof(Datum));
1107  i = 0;
1108  foreach(lc, trftypes_list)
1109  arr[i++] = ObjectIdGetDatum(lfirst_oid(lc));
1110  trftypes = construct_array(arr, list_length(trftypes_list),
1111  OIDOID, sizeof(Oid), true, TYPALIGN_INT);
1112  }
1113  else
1114  {
1115  /* store SQL NULL instead of empty array */
1116  trftypes = NULL;
1117  }
1118 
1119  interpret_AS_clause(languageOid, language, funcname, as_clause,
1120  &prosrc_str, &probin_str);
1121 
1122  /*
1123  * Set default values for COST and ROWS depending on other parameters;
1124  * reject ROWS if it's not returnsSet. NB: pg_dump knows these default
1125  * values, keep it in sync if you change them.
1126  */
1127  if (procost < 0)
1128  {
1129  /* SQL and PL-language functions are assumed more expensive */
1130  if (languageOid == INTERNALlanguageId ||
1131  languageOid == ClanguageId)
1132  procost = 1;
1133  else
1134  procost = 100;
1135  }
1136  if (prorows < 0)
1137  {
1138  if (returnsSet)
1139  prorows = 1000;
1140  else
1141  prorows = 0; /* dummy value if not returnsSet */
1142  }
1143  else if (!returnsSet)
1144  ereport(ERROR,
1145  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1146  errmsg("ROWS is not applicable when function does not return a set")));
1147 
1148  /*
1149  * And now that we have all the parameters, and know we're permitted to do
1150  * so, go ahead and create the function.
1151  */
1152  return ProcedureCreate(funcname,
1153  namespaceId,
1154  stmt->replace,
1155  returnsSet,
1156  prorettype,
1157  GetUserId(),
1158  languageOid,
1159  languageValidator,
1160  prosrc_str, /* converted to text later */
1161  probin_str, /* converted to text later */
1162  stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
1163  security,
1164  isLeakProof,
1165  isStrict,
1166  volatility,
1167  parallel,
1168  parameterTypes,
1169  PointerGetDatum(allParameterTypes),
1170  PointerGetDatum(parameterModes),
1171  PointerGetDatum(parameterNames),
1172  parameterDefaults,
1173  PointerGetDatum(trftypes),
1174  PointerGetDatum(proconfig),
1175  prosupport,
1176  procost,
1177  prorows);
1178 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:601
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2994
#define PointerGetDatum(X)
Definition: postgres.h:556
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, char prokind, 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, Oid prosupport, float4 procost, float4 prorows)
Definition: pg_proc.c:69
static void compute_return_type(TypeName *returnType, Oid languageOid, Oid *prorettype_p, bool *returnsSet_p)
Definition: functioncmds.c:88
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3313
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
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:862
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:651
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4625
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4599
Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
#define lfirst_node(type, lc)
Definition: pg_list.h:193
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
static void compute_function_attributes(ParseState *pstate, bool is_procedure, 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, Oid *prosupport, char *parallel_p)
Definition: functioncmds.c:695
#define ACL_USAGE
Definition: parsenodes.h:82
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
float float4
Definition: c.h:497
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
TypeName * returnType
Definition: parsenodes.h:2843
void interpret_function_parameter_list(ParseState *pstate, List *parameters, Oid languageOid, ObjectType objtype, oidvector **parameterTypes, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:184
static int list_length(const List *l)
Definition: pg_list.h:169
bool extension_file_exists(const char *extensionName)
Definition: extension.c:2237
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2709
FormData_pg_language * Form_pg_language
Definition: pg_language.h:65
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
#define NameStr(name)
Definition: c.h:622
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ CreateStatistics()

ObjectAddress CreateStatistics ( CreateStatsStmt stmt)

Definition at line 62 of file statscmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, attname, buildint2vector(), CacheInvalidateRelcache(), CatalogTupleInsert(), CharGetDatum, ChooseExtendedStatisticName(), ChooseExtendedStatisticNameAddition(), compare_int16(), construct_array(), CreateComments(), CStringGetDatum, CreateStatsStmt::defnames, DEPENDENCY_AUTO, DEPENDENCY_NORMAL, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, CreateStatsStmt::exprs, ColumnRef::fields, format_type_be(), get_relkind_objtype(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), heap_form_tuple(), heap_freetuple(), HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, Int32GetDatum, InvalidObjectAddress, InvalidOid, InvokeObjectPostCreateHook, IsA, lengthof, lfirst, linitial, list_length(), lookup_type_cache(), TypeCacheEntry::lt_opr, NameGetDatum, namestrcpy(), NoLock, NOTICE, ObjectAddressSet, ObjectAddressSubSet, ObjectIdGetDatum, pg_class_ownercheck(), PointerGetDatum, qsort, QualifiedNameGetCreationNamespace(), RelationData::rd_att, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnOwner(), relation_close(), relation_openrv(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, CreateStatsStmt::relations, ReleaseSysCache(), RowExclusiveLock, SearchSysCacheAttName(), SearchSysCacheExists2, ShareUpdateExclusiveLock, CreateStatsStmt::stat_types, STATEXTNAMENSP, StatisticExtOidIndexId, STATS_MAX_DIMENSIONS, strVal, CreateStatsStmt::stxcomment, table_open(), generate_unaccent_rules::type, TYPECACHE_LT_OPR, types, and values.

Referenced by ProcessUtilitySlow().

63 {
64  int16 attnums[STATS_MAX_DIMENSIONS];
65  int numcols = 0;
66  char *namestr;
67  NameData stxname;
68  Oid statoid;
69  Oid namespaceId;
70  Oid stxowner = GetUserId();
71  HeapTuple htup;
72  Datum values[Natts_pg_statistic_ext];
73  bool nulls[Natts_pg_statistic_ext];
74  Datum datavalues[Natts_pg_statistic_ext_data];
75  bool datanulls[Natts_pg_statistic_ext_data];
76  int2vector *stxkeys;
77  Relation statrel;
78  Relation datarel;
79  Relation rel = NULL;
80  Oid relid;
81  ObjectAddress parentobject,
82  myself;
83  Datum types[3]; /* one for each possible type of statistic */
84  int ntypes;
85  ArrayType *stxkind;
86  bool build_ndistinct;
87  bool build_dependencies;
88  bool build_mcv;
89  bool requested_type = false;
90  int i;
91  ListCell *cell;
92 
93  Assert(IsA(stmt, CreateStatsStmt));
94 
95  /*
96  * Examine the FROM clause. Currently, we only allow it to be a single
97  * simple table, but later we'll probably allow multiple tables and JOIN
98  * syntax. The grammar is already prepared for that, so we have to check
99  * here that what we got is what we can support.
100  */
101  if (list_length(stmt->relations) != 1)
102  ereport(ERROR,
103  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
104  errmsg("only a single relation is allowed in CREATE STATISTICS")));
105 
106  foreach(cell, stmt->relations)
107  {
108  Node *rln = (Node *) lfirst(cell);
109 
110  if (!IsA(rln, RangeVar))
111  ereport(ERROR,
112  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
113  errmsg("only a single relation is allowed in CREATE STATISTICS")));
114 
115  /*
116  * CREATE STATISTICS will influence future execution plans but does
117  * not interfere with currently executing plans. So it should be
118  * enough to take only ShareUpdateExclusiveLock on relation,
119  * conflicting with ANALYZE and other DDL that sets statistical
120  * information, but not with normal queries.
121  */
123 
124  /* Restrict to allowed relation types */
125  if (rel->rd_rel->relkind != RELKIND_RELATION &&
126  rel->rd_rel->relkind != RELKIND_MATVIEW &&
127  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
128  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
129  ereport(ERROR,
130  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
131  errmsg("relation \"%s\" is not a table, foreign table, or materialized view",
132  RelationGetRelationName(rel))));
133 
134  /* You must own the relation to create stats on it */
135  if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))
138  }
139 
140  Assert(rel);
141  relid = RelationGetRelid(rel);
142 
143  /*
144  * If the node has a name, split it up and determine creation namespace.
145  * If not (a possibility not considered by the grammar, but one which can
146  * occur via the "CREATE TABLE ... (LIKE)" command), then we put the
147  * object in the same namespace as the relation, and cons up a name for
148  * it.
149  */
150  if (stmt->defnames)
151  namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,
152  &namestr);
153  else
154  {
155  namespaceId = RelationGetNamespace(rel);
158  "stat",
159  namespaceId);
160  }
161  namestrcpy(&stxname, namestr);
162 
163  /*
164  * Deal with the possibility that the statistics object already exists.
165  */
167  CStringGetDatum(namestr),
168  ObjectIdGetDatum(namespaceId)))
169  {
170  if (stmt->if_not_exists)
171  {
172  ereport(NOTICE,
174  errmsg("statistics object \"%s\" already exists, skipping",
175  namestr)));
176  relation_close(rel, NoLock);
177  return InvalidObjectAddress;
178  }
179 
180  ereport(ERROR,
182  errmsg("statistics object \"%s\" already exists", namestr)));
183  }
184 
185  /*
186  * Currently, we only allow simple column references in the expression
187  * list. That will change someday, and again the grammar already supports
188  * it so we have to enforce restrictions here. For now, we can convert
189  * the expression list to a simple array of attnums. While at it, enforce
190  * some constraints.
191  */
192  foreach(cell, stmt->exprs)
193  {
194  Node *expr = (Node *) lfirst(cell);
195  ColumnRef *cref;
196  char *attname;
197  HeapTuple atttuple;
198  Form_pg_attribute attForm;
200 
201  if (!IsA(expr, ColumnRef))
202  ereport(ERROR,
203  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
204  errmsg("only simple column references are allowed in CREATE STATISTICS")));
205  cref = (ColumnRef *) expr;
206 
207  if (list_length(cref->fields) != 1)
208  ereport(ERROR,
209  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
210  errmsg("only simple column references are allowed in CREATE STATISTICS")));
211  attname = strVal((Value *) linitial(cref->fields));
212 
213  atttuple = SearchSysCacheAttName(relid, attname);
214  if (!HeapTupleIsValid(atttuple))
215  ereport(ERROR,
216  (errcode(ERRCODE_UNDEFINED_COLUMN),
217  errmsg("column \"%s\" does not exist",
218  attname)));
219  attForm = (Form_pg_attribute) GETSTRUCT(atttuple);
220 
221  /* Disallow use of system attributes in extended stats */
222  if (attForm->attnum <= 0)
223  ereport(ERROR,
224  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
225  errmsg("statistics creation on system columns is not supported")));
226 
227  /* Disallow data types without a less-than operator */
228  type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
229  if (type->lt_opr == InvalidOid)
230  ereport(ERROR,
231  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
232  errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
233  attname, format_type_be(attForm->atttypid))));
234 
235  /* Make sure no more than STATS_MAX_DIMENSIONS columns are used */
236  if (numcols >= STATS_MAX_DIMENSIONS)
237  ereport(ERROR,
238  (errcode(ERRCODE_TOO_MANY_COLUMNS),
239  errmsg("cannot have more than %d columns in statistics",
241 
242  attnums[numcols] = attForm->attnum;
243  numcols++;
244  ReleaseSysCache(atttuple);
245  }
246 
247  /*
248  * Check that at least two columns were specified in the statement. The
249  * upper bound was already checked in the loop above.
250  */
251  if (numcols < 2)
252  ereport(ERROR,
253  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
254  errmsg("extended statistics require at least 2 columns")));
255 
256  /*
257  * Sort the attnums, which makes detecting duplicates somewhat easier, and
258  * it does not hurt (it does not affect the efficiency, unlike for
259  * indexes, for example).
260  */
261  qsort(attnums, numcols, sizeof(int16), compare_int16);
262 
263  /*
264  * Check for duplicates in the list of columns. The attnums are sorted so
265  * just check consecutive elements.
266  */
267  for (i = 1; i < numcols; i++)
268  {
269  if (attnums[i] == attnums[i - 1])
270  ereport(ERROR,
271  (errcode(ERRCODE_DUPLICATE_COLUMN),
272  errmsg("duplicate column name in statistics definition")));
273  }
274 
275  /* Form an int2vector representation of the sorted column list */
276  stxkeys = buildint2vector(attnums, numcols);
277 
278  /*
279  * Parse the statistics kinds.
280  */
281  build_ndistinct = false;
282  build_dependencies = false;
283  build_mcv = false;
284  foreach(cell, stmt->stat_types)
285  {
286  char *type = strVal((Value *) lfirst(cell));
287 
288  if (strcmp(type, "ndistinct") == 0)
289  {
290  build_ndistinct = true;
291  requested_type = true;
292  }
293  else if (strcmp(type, "dependencies") == 0)
294  {
295  build_dependencies = true;
296  requested_type = true;
297  }
298  else if (strcmp(type, "mcv") == 0)
299  {
300  build_mcv = true;
301  requested_type = true;
302  }
303  else
304  ereport(ERROR,
305  (errcode(ERRCODE_SYNTAX_ERROR),
306  errmsg("unrecognized statistics kind \"%s\"",
307  type)));
308  }
309  /* If no statistic type was specified, build them all. */
310  if (!requested_type)
311  {
312  build_ndistinct = true;
313  build_dependencies = true;
314  build_mcv = true;
315  }
316 
317  /* construct the char array of enabled statistic types */
318  ntypes = 0;
319  if (build_ndistinct)
320  types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);
321  if (build_dependencies)
322  types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);
323  if (build_mcv)
324  types[ntypes++] = CharGetDatum(STATS_EXT_MCV);
325  Assert(ntypes > 0 && ntypes <= lengthof(types));
326  stxkind = construct_array(types, ntypes, CHAROID, 1, true, TYPALIGN_CHAR);
327 
328  statrel = table_open(StatisticExtRelationId, RowExclusiveLock);
329 
330  /*
331  * Everything seems fine, so let's build the pg_statistic_ext tuple.
332  */
333  memset(values, 0, sizeof(values));
334  memset(nulls, false, sizeof(nulls));
335 
336  statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,
337  Anum_pg_statistic_ext_oid);
338  values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);
339  values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);
340  values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);
341  values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
342  values[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1);
343  values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
344  values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
345  values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);
346 
347  /* insert it into pg_statistic_ext */
348  htup = heap_form_tuple(statrel->rd_att, values, nulls);
349  CatalogTupleInsert(statrel, htup);
350  heap_freetuple(htup);
351 
353 
354  /*
355  * Also build the pg_statistic_ext_data tuple, to hold the actual
356  * statistics data.
357  */
358  datarel = table_open(StatisticExtDataRelationId, RowExclusiveLock);
359 
360  memset(datavalues, 0, sizeof(datavalues));
361  memset(datanulls, false, sizeof(datanulls));
362 
363  datavalues[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statoid);
364 
365  /* no statistics built yet */
366  datanulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;
367  datanulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;
368  datanulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;
369 
370  /* insert it into pg_statistic_ext_data */
371  htup = heap_form_tuple(datarel->rd_att, datavalues, datanulls);
372  CatalogTupleInsert(datarel, htup);
373  heap_freetuple(htup);
374 
376 
377  InvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0);
378 
379  /*
380  * Invalidate relcache so that others see the new statistics object.
381  */
383 
384  relation_close(rel, NoLock);
385 
386  /*
387  * Add an AUTO dependency on each column used in the stats, so that the
388  * stats object goes away if any or all of them get dropped.
389  */
390  ObjectAddressSet(myself, StatisticExtRelationId, statoid);
391 
392  for (i = 0; i < numcols; i++)
393  {
394  ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
395  recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
396  }
397 
398  /*
399  * Also add dependencies on namespace and owner. These are required
400  * because the stats object might have a different namespace and/or owner
401  * than the underlying table(s).
402  */
403  ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
404  recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);
405 
406  recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);
407 
408  /*
409  * XXX probably there should be a recordDependencyOnCurrentExtension call
410  * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
411  * STATISTICS, which is more work than it seems worth.
412  */
413 
414  /* Add any requested comment */
415  if (stmt->stxcomment != NULL)
416  CreateComments(statoid, StatisticExtRelationId, 0,
417  stmt->stxcomment);
418 
419  /* Return stats object's address */
420  return myself;
421 }
signed short int16
Definition: c.h:361
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:142
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
#define NameGetDatum(X)
Definition: postgres.h:595
static char * ChooseExtendedStatisticName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: statscmds.c:676
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
struct typedefs * types
Definition: ecpg.c:29
Oid GetUserId(void)
Definition: miscinit.c:476
void namestrcpy(Name name, const char *str)
Definition: name.c:233
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2994
#define PointerGetDatum(X)
Definition: postgres.h:556
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3313
Definition: nodes.h:529
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
#define lengthof(array)
Definition: c.h:675
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define linitial(l)
Definition: pg_list.h:195
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
Definition: c.h:616
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
static int compare_int16(const void *a, const void *b)
Definition: statscmds.c:49
Definition: c.h:590
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
TupleDesc rd_att
Definition: rel.h:110
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:331
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
Definition: value.h:42
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
static char * ChooseExtendedStatisticNameAddition(List *exprs)
Definition: statscmds.c:718
static int list_length(const List *l)
Definition: pg_list.h:169
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:185
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:1257
#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:416
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define Int32GetDatum(X)
Definition: postgres.h:479
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
ObjectType get_relkind_objtype(char relkind)
#define TYPECACHE_LT_OPR
Definition: typcache.h:131
#define StatisticExtOidIndexId
Definition: indexing.h:242
#define qsort(a, b, c, d)
Definition: port.h:475
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define RelationGetRelid(relation)
Definition: rel.h:456
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
List * fields
Definition: parsenodes.h:236
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ CreateTransform()

ObjectAddress CreateTransform ( CreateTransformStmt stmt)

Definition at line 1681 of file functioncmds.c.

References ACL_EXECUTE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, add_exact_object_address(), CatalogTupleInsert(), CatalogTupleUpdate(), check_transform_function(), deleteDependencyRecordsFor(), DEPENDENCY_NORMAL, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, format_type_be(), free_object_addresses(), CreateTransformStmt::fromsql, get_language_oid(), get_typtype(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, InvalidOid, InvokeObjectPostCreateHook, CreateTransformStmt::lang, LookupFuncWithArgs(), MemSet, NameListToString(), new_object_addresses(), OBJECT_FUNCTION, OBJECT_LANGUAGE, ObjectAddressSet, ObjectIdGetDatum, ObjectWithArgs::objname, OidIsValid, pg_language_aclcheck(), pg_proc_aclcheck(), pg_proc_ownercheck(), pg_type_aclcheck(), pg_type_ownercheck(), PROCOID, record_object_address_dependencies(), recordDependencyOnCurrentExtension(), RelationGetDescr, ReleaseSysCache(), CreateTransformStmt::replace, RowExclusiveLock, SearchSysCache1(), SearchSysCache2(), HeapTupleData::t_self, table_close(), table_open(), CreateTransformStmt::tosql, TransformOidIndexId, TRFTYPELANG, CreateTransformStmt::type_name, TypeNameToString(), typenameTypeId(), and values.

Referenced by ProcessUtilitySlow().

1682 {
1683  Oid typeid;
1684  char typtype;
1685  Oid langid;
1686  Oid fromsqlfuncid;
1687  Oid tosqlfuncid;
1688  AclResult aclresult;
1689  Form_pg_proc procstruct;
1690  Datum values[Natts_pg_transform];
1691  bool nulls[Natts_pg_transform];
1692  bool replaces[Natts_pg_transform];
1693  Oid transformid;
1694  HeapTuple tuple;
1695  HeapTuple newtuple;
1696  Relation relation;
1697  ObjectAddress myself,
1698  referenced;
1699  ObjectAddresses *addrs;
1700  bool is_replace;
1701 
1702  /*
1703  * Get the type
1704  */
1705  typeid = typenameTypeId(NULL, stmt->type_name);
1706  typtype = get_typtype(typeid);
1707 
1708  if (typtype == TYPTYPE_PSEUDO)
1709  ereport(ERROR,
1710  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1711  errmsg("data type %s is a pseudo-type",
1712  TypeNameToString(stmt->type_name))));
1713 
1714  if (typtype == TYPTYPE_DOMAIN)
1715  ereport(ERROR,
1716  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1717  errmsg("data type %s is a domain",
1718  TypeNameToString(stmt->type_name))));
1719 
1720  if (!pg_type_ownercheck(typeid, GetUserId()))
1722 
1723  aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
1724  if (aclresult != ACLCHECK_OK)
1725  aclcheck_error_type(aclresult, typeid);
1726 
1727  /*
1728  * Get the language
1729  */
1730  langid = get_language_oid(stmt->lang, false);
1731 
1732  aclresult = pg_language_aclcheck(langid, GetUserId(), ACL_USAGE);
1733  if (aclresult != ACLCHECK_OK)
1734  aclcheck_error(aclresult, OBJECT_LANGUAGE, stmt->lang);
1735 
1736  /*
1737  * Get the functions
1738  */
1739  if (stmt->fromsql)
1740  {
1741  fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
1742 
1743  if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
1745 
1746  aclresult = pg_proc_aclcheck(fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1747  if (aclresult != ACLCHECK_OK)
1749 
1750  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1751  if (!HeapTupleIsValid(tuple))
1752  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1753  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1754  if (procstruct->prorettype != INTERNALOID)
1755  ereport(ERROR,
1756  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1757  errmsg("return data type of FROM SQL function must be %s",
1758  "internal")));
1759  check_transform_function(procstruct);
1760  ReleaseSysCache(tuple);
1761  }
1762  else
1763  fromsqlfuncid = InvalidOid;
1764 
1765  if (stmt->tosql)
1766  {
1767  tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
1768 
1769  if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
1771 
1772  aclresult = pg_proc_aclcheck(tosqlfuncid, GetUserId(), ACL_EXECUTE);
1773  if (aclresult != ACLCHECK_OK)
1775 
1776  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1777  if (!HeapTupleIsValid(tuple))
1778  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1779  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1780  if (procstruct->prorettype != typeid)
1781  ereport(ERROR,
1782  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1783  errmsg("return data type of TO SQL function must be the transform data type")));
1784  check_transform_function(procstruct);
1785  ReleaseSysCache(tuple);
1786  }
1787  else
1788  tosqlfuncid = InvalidOid;
1789 
1790  /*
1791  * Ready to go
1792  */
1793  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1794  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1795  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1796  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1797 
1798  MemSet(nulls, false, sizeof(nulls));
1799 
1800  relation = table_open(TransformRelationId, RowExclusiveLock);
1801 
1802  tuple = SearchSysCache2(TRFTYPELANG,
1803  ObjectIdGetDatum(typeid),
1804  ObjectIdGetDatum(langid));
1805  if (HeapTupleIsValid(tuple))
1806  {
1808 
1809  if (!stmt->replace)
1810  ereport(ERROR,
1812  errmsg("transform for type %s language \"%s\" already exists",
1813  format_type_be(typeid),
1814  stmt->lang)));
1815 
1816  MemSet(replaces, false, sizeof(replaces));
1817  replaces[Anum_pg_transform_trffromsql - 1] = true;
1818  replaces[Anum_pg_transform_trftosql - 1] = true;
1819 
1820  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1821  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
1822 
1823  transformid = form->oid;
1824  ReleaseSysCache(tuple);
1825  is_replace = true;
1826  }
1827  else
1828  {
1829  transformid = GetNewOidWithIndex(relation, TransformOidIndexId,
1830  Anum_pg_transform_oid);
1831  values[Anum_pg_transform_oid - 1] = ObjectIdGetDatum(transformid);
1832  newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1833  CatalogTupleInsert(relation, newtuple);
1834  is_replace = false;
1835  }
1836 
1837  if (is_replace)
1838  deleteDependencyRecordsFor(TransformRelationId, transformid, true);
1839 
1840  addrs = new_object_addresses();
1841 
1842  /* make dependency entries */
1843  ObjectAddressSet(myself, TransformRelationId, transformid);
1844 
1845  /* dependency on language */
1846  ObjectAddressSet(referenced, LanguageRelationId, langid);
1847  add_exact_object_address(&referenced, addrs);
1848 
1849  /* dependency on type */
1850  ObjectAddressSet(referenced, TypeRelationId, typeid);
1851  add_exact_object_address(&referenced, addrs);
1852 
1853  /* dependencies on functions */
1854  if (OidIsValid(fromsqlfuncid))
1855  {
1856  ObjectAddressSet(referenced, ProcedureRelationId, fromsqlfuncid);
1857  add_exact_object_address(&referenced, addrs);
1858  }
1859  if (OidIsValid(tosqlfuncid))
1860  {
1861  ObjectAddressSet(referenced, ProcedureRelationId, tosqlfuncid);
1862  add_exact_object_address(&referenced, addrs);
1863  }
1864 
1866  free_object_addresses(addrs);
1867 
1868  /* dependency on extension */
1869  recordDependencyOnCurrentExtension(&myself, is_replace);
1870 
1871  /* Post creation hook for new transform */
1872  InvokeObjectPostCreateHook(TransformRelationId, transformid, 0);
1873 
1874  heap_freetuple(newtuple);
1875 
1876  table_close(relation, RowExclusiveLock);
1877 
1878  return myself;
1879 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
ObjectWithArgs * tosql
Definition: parsenodes.h:3417
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static void check_transform_function(Form_pg_proc procstruct)
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid GetUserId(void)
Definition: miscinit.c:476
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2676
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:232
Oid get_language_oid(const char *langname, bool missing_ok)
Definition: proclang.c:228
int errcode(int sqlerrcode)
Definition: elog.c:610
char get_typtype(Oid typid)
Definition: lsyscache.c:2517
#define MemSet(start, val, len)
Definition: c.h:949
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2467
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2412
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2707
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
bool pg_type_ownercheck(Oid type_oid, Oid roleid)
Definition: aclchk.c:4713
#define OidIsValid(objectId)
Definition: c.h:651
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4599
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3607
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
FormData_pg_transform * Form_pg_transform
Definition: pg_transform.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define TransformOidIndexId
Definition: indexing.h:257
#define ACL_USAGE
Definition: parsenodes.h:82
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
char * NameListToString(List *names)
Definition: namespace.c:3101
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
ObjectWithArgs * fromsql
Definition: parsenodes.h:3416
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:180
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1127
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
TypeName * type_name
Definition: parsenodes.h:3414
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define ACL_EXECUTE
Definition: parsenodes.h:81
#define elog(elevel,...)
Definition: elog.h:214
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4587
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2163
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4675
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4765
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ CreateUserMapping()

ObjectAddress CreateUserMapping ( CreateUserMappingStmt stmt)

Definition at line 1095 of file foreigncmds.c.

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

Referenced by ProcessUtilitySlow().

1096 {
1097  Relation rel;
1098  Datum useoptions;
1099  Datum values[Natts_pg_user_mapping];
1100  bool nulls[Natts_pg_user_mapping];
1101  HeapTuple tuple;
1102  Oid useId;
1103  Oid umId;
1104  ObjectAddress myself;
1105  ObjectAddress referenced;
1106  ForeignServer *srv;
1107  ForeignDataWrapper *fdw;
1108  RoleSpec *role = (RoleSpec *) stmt->user;
1109 
1110  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1111 
1112  if (role->roletype == ROLESPEC_PUBLIC)
1113  useId = ACL_ID_PUBLIC;
1114  else
1115  useId = get_rolespec_oid(stmt->user, false);
1116 
1117  /* Check that the server exists. */
1118  srv = GetForeignServerByName(stmt->servername, false);
1119 
1120  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1121 
1122  /*
1123  * Check that the user mapping is unique within server.
1124  */
1125  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1126  ObjectIdGetDatum(useId),
1127  ObjectIdGetDatum(srv->serverid));
1128 
1129  if (OidIsValid(umId))
1130  {
1131  if (stmt->if_not_exists)
1132  {
1133  ereport(NOTICE,
1135  errmsg("user mapping for \"%s\" already exists for server \"%s\", skipping",
1136  MappingUserName(useId),
1137  stmt->servername)));
1138 
1140  return InvalidObjectAddress;
1141  }
1142  else
1143  ereport(ERROR,
1145  errmsg("user mapping for \"%s\" already exists for server \"%s\"",
1146  MappingUserName(useId),
1147  stmt->servername)));
1148  }
1149 
1150  fdw = GetForeignDataWrapper(srv->fdwid);
1151 
1152  /*
1153  * Insert tuple into pg_user_mapping.
1154  */
1155  memset(values, 0, sizeof(values));
1156  memset(nulls, false, sizeof(nulls));
1157 
1159  Anum_pg_user_mapping_oid);
1160  values[Anum_pg_user_mapping_oid - 1] = ObjectIdGetDatum(umId);
1161  values[Anum_pg_user_mapping_umuser - 1] = ObjectIdGetDatum(useId);
1162  values[Anum_pg_user_mapping_umserver - 1] = ObjectIdGetDatum(srv->serverid);
1163 
1164  /* Add user options */
1165  useoptions = transformGenericOptions(UserMappingRelationId,
1166  PointerGetDatum(NULL),
1167  stmt->options,
1168  fdw->fdwvalidator);
1169 
1170  if (PointerIsValid(DatumGetPointer(useoptions)))
1171  values[Anum_pg_user_mapping_umoptions - 1] = useoptions;
1172  else
1173  nulls[Anum_pg_user_mapping_umoptions - 1] = true;
1174 
1175  tuple = heap_form_tuple(rel->rd_att, values, nulls);
1176 
1177  CatalogTupleInsert(rel, tuple);
1178 
1179  heap_freetuple(tuple);
1180 
1181  /* Add dependency on the server */
1182  myself.classId = UserMappingRelationId;
1183  myself.objectId = umId;
1184  myself.objectSubId = 0;
1185 
1186  referenced.classId = ForeignServerRelationId;
1187  referenced.objectId = srv->serverid;
1188  referenced.objectSubId = 0;
1189  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1190 
1191  if (OidIsValid(useId))
1192  {
1193  /* Record the mapped user dependency */
1194  recordDependencyOnOwner(UserMappingRelationId, umId, useId);
1195  }
1196 
1197  /*
1198  * Perhaps someday there should be a recordDependencyOnCurrentExtension
1199  * call here; but since roles aren't members of extensions, it seems like
1200  * user mappings shouldn't be either. Note that the grammar and pg_dump
1201  * would need to be extended too if we change this.
1202  */
1203 
1204  /* Post creation hook for new user mapping */
1205  InvokeObjectPostCreateHook(UserMappingRelationId, umId, 0);
1206 
1208 
1209  return myself;
1210 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:317
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
Datum transformGenericOptions(Oid catalogId, Datum oldOptions, List *options, Oid fdwvalidator)
Definition: foreigncmds.c:110
#define PointerGetDatum(X)
Definition: postgres.h:556
int errcode(int sqlerrcode)
Definition: elog.c:610
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1070
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
uintptr_t Datum
Definition: postgres.h:367
RoleSpecType roletype
Definition: parsenodes.h:330
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5209
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:194
#define UserMappingOidIndexId
Definition: indexing.h:312
#define DatumGetPointer(X)
Definition: postgres.h:549
static Datum values[MAXATTR]
Definition: bootstrap.c:165
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define ACL_ID_PUBLIC
Definition: acl.h:46
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define PointerIsValid(pointer)
Definition: c.h:639
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
Oid serverid
Definition: foreign.h:36
#define MappingUserName(userid)
Definition: foreign.h:20

◆ defGetBoolean()

bool defGetBoolean ( DefElem def)

Definition at line 111 of file define.c.

References DefElem::arg, defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, intVal, nodeTag, pg_strcasecmp(), and T_Integer.

Referenced by AlterDatabase(), apply_server_options(), apply_table_options(), createdb(), CreateExtension(), DefineAggregate(), DefineCollation(), DefineOperator(), DefineType(), dintdict_init(), dsimple_init(), dsynonym_init(), dxsyn_init(), ExecVacuum(), ExplainQuery(), file_fdw_validator(), get_file_fdw_attribute_options(), get_vacopt_ternary_value(), GetCommandLogLevel(), parse_output_parameters(), parse_publication_options(), parse_subscription_options(), parseCreateReplSlotOptions(), postgres_fdw_validator(), postgresImportForeignSchema(), postgresIsForeignRelUpdatable(), ProcessCopyOptions(), transformRelOptions(), and UserMappingPasswordRequired().

112 {
113  /*
114  * If no parameter given, assume "true" is meant.
115  */
116  if (def->arg == NULL)
117  return true;
118 
119  /*
120  * Allow 0, 1, "true", "false", "on", "off"
121  */
122  switch (nodeTag(def->arg))
123  {
124  case T_Integer:
125  switch (intVal(def->arg))
126  {
127  case 0:
128  return false;
129  case 1:
130  return true;
131  default:
132  /* otherwise, error out below */
133  break;
134  }
135  break;
136  default:
137  {
138  char *sval = defGetString(def);
139 
140  /*
141  * The set of strings accepted here should match up with the
142  * grammar's opt_boolean_or_string production.
143  */
144  if (pg_strcasecmp(sval, "true") == 0)
145  return true;
146  if (pg_strcasecmp(sval, "false") == 0)
147  return false;
148  if (pg_strcasecmp(sval, "on") == 0)
149  return true;
150  if (pg_strcasecmp(sval, "off") == 0)
151  return false;
152  }
153  break;
154  }
155  ereport(ERROR,
156  (errcode(ERRCODE_SYNTAX_ERROR),
157  errmsg("%s requires a Boolean value",
158  def->defname)));
159  return false; /* keep compiler quiet */
160 }
int errcode(int sqlerrcode)
Definition: elog.c:610
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define ERROR
Definition: elog.h:43
char * defGetString(DefElem *def)
Definition: define.c:49
Node * arg
Definition: parsenodes.h:734
#define ereport(elevel,...)
Definition: elog.h:144
#define nodeTag(nodeptr)
Definition: nodes.h:534
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * defname
Definition: parsenodes.h:733

◆ defGetInt32()

int32 defGetInt32 ( DefElem def)

Definition at line 166 of file define.c.

References DefElem::arg, DefElem::defname, ereport, errcode(), errmsg(), ERROR, intVal, nodeTag, and T_Integer.

Referenced by AlterDatabase(), ATExecSetIdentity(), createdb(), DefineAggregate(), and ExecVacuum().

167 {
168  if (def->arg == NULL)
169  ereport(ERROR,
170  (errcode(ERRCODE_SYNTAX_ERROR),
171  errmsg("%s requires an integer value",
172  def->defname)));
173  switch (nodeTag(def->arg))
174  {