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 ExecReindex (ParseState *pstate, ReindexStmt *stmt, bool isTopLevel)
 
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 (ParseState *pstate, 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, List **parameterTypes_list, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **inParameterNames_list, 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 RemoveStatisticsDataById (Oid statsOid, bool inh)
 
Oid StatisticsGetRelation (Oid statId, bool missing_ok)
 
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 (ParseState *pstate, CreateFdwStmt *stmt)
 
ObjectAddress AlterForeignDataWrapper (ParseState *pstate, 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)
 
Oid defGetObjectId (DefElem *def)
 
ListdefGetQualifiedName (DefElem *def)
 
TypeNamedefGetTypeName (DefElem *def)
 
int defGetTypeLength (DefElem *def)
 
ListdefGetStringList (DefElem *def)
 
void errorConflictingDefElem (DefElem *defel, ParseState *pstate) pg_attribute_noreturn()
 

Function Documentation

◆ AlterForeignDataWrapper()

ObjectAddress AlterForeignDataWrapper ( ParseState pstate,
AlterFdwStmt stmt 
)

Definition at line 674 of file foreigncmds.c.

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

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().

◆ AlterForeignDataWrapperOwner()

ObjectAddress AlterForeignDataWrapperOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 275 of file foreigncmds.c.

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 }
const char * name
Definition: encode.c:571
static void AlterForeignDataWrapperOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:205

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

Referenced by ExecAlterOwnerStmt().

◆ AlterForeignDataWrapperOwner_oid()

void AlterForeignDataWrapperOwner_oid ( Oid  fwdId,
Oid  newOwnerId 
)

Definition at line 313 of file foreigncmds.c.

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 }

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

Referenced by shdepReassignOwned().

◆ AlterForeignServer()

ObjectAddress AlterForeignServer ( AlterForeignServerStmt stmt)

Definition at line 974 of file foreigncmds.c.

975 {
976  Relation rel;
977  HeapTuple tp;
978  Datum repl_val[Natts_pg_foreign_server];
979  bool repl_null[Natts_pg_foreign_server];
980  bool repl_repl[Natts_pg_foreign_server];
981  Oid srvId;
982  Form_pg_foreign_server srvForm;
983  ObjectAddress address;
984 
985  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
986 
988  CStringGetDatum(stmt->servername));
989 
990  if (!HeapTupleIsValid(tp))
991  ereport(ERROR,
992  (errcode(ERRCODE_UNDEFINED_OBJECT),
993  errmsg("server \"%s\" does not exist", stmt->servername)));
994 
995  srvForm = (Form_pg_foreign_server) GETSTRUCT(tp);
996  srvId = srvForm->oid;
997 
998  /*
999  * Only owner or a superuser can ALTER a SERVER.
1000  */
1001  if (!object_ownercheck(ForeignServerRelationId, srvId, GetUserId()))
1003  stmt->servername);
1004 
1005  memset(repl_val, 0, sizeof(repl_val));
1006  memset(repl_null, false, sizeof(repl_null));
1007  memset(repl_repl, false, sizeof(repl_repl));
1008 
1009  if (stmt->has_version)
1010  {
1011  /*
1012  * Change the server VERSION string.
1013  */
1014  if (stmt->version)
1015  repl_val[Anum_pg_foreign_server_srvversion - 1] =
1017  else
1018  repl_null[Anum_pg_foreign_server_srvversion - 1] = true;
1019 
1020  repl_repl[Anum_pg_foreign_server_srvversion - 1] = true;
1021  }
1022 
1023  if (stmt->options)
1024  {
1025  ForeignDataWrapper *fdw = GetForeignDataWrapper(srvForm->srvfdw);
1026  Datum datum;
1027  bool isnull;
1028 
1029  /* Extract the current srvoptions */
1031  tp,
1032  Anum_pg_foreign_server_srvoptions,
1033  &isnull);
1034  if (isnull)
1035  datum = PointerGetDatum(NULL);
1036 
1037  /* Prepare the options array */
1038  datum = transformGenericOptions(ForeignServerRelationId,
1039  datum,
1040  stmt->options,
1041  fdw->fdwvalidator);
1042 
1043  if (PointerIsValid(DatumGetPointer(datum)))
1044  repl_val[Anum_pg_foreign_server_srvoptions - 1] = datum;
1045  else
1046  repl_null[Anum_pg_foreign_server_srvoptions - 1] = true;
1047 
1048  repl_repl[Anum_pg_foreign_server_srvoptions - 1] = true;
1049  }
1050 
1051  /* Everything looks good - update the tuple */
1052  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1053  repl_val, repl_null, repl_repl);
1054 
1055  CatalogTupleUpdate(rel, &tp->t_self, tp);
1056 
1057  InvokeObjectPostAlterHook(ForeignServerRelationId, srvId, 0);
1058 
1059  ObjectAddressSet(address, ForeignServerRelationId, srvId);
1060 
1061  heap_freetuple(tp);
1062 
1064 
1065  return address;
1066 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2679
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3984
#define CStringGetTextDatum(s)
Definition: builtins.h:94
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:37
Oid GetUserId(void)
Definition: miscinit.c:502
@ OBJECT_FOREIGN_SERVER
Definition: parsenodes.h:1986
FormData_pg_foreign_server * Form_pg_foreign_server
@ FOREIGNSERVEROID
Definition: syscache.h:64
@ FOREIGNSERVERNAME
Definition: syscache.h:63

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, object_ownercheck(), ObjectAddressSet, AlterForeignServerStmt::options, PointerGetDatum(), PointerIsValid, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, AlterForeignServerStmt::servername, SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), transformGenericOptions(), and AlterForeignServerStmt::version.

Referenced by ProcessUtilitySlow().

◆ AlterForeignServerOwner()

ObjectAddress AlterForeignServerOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 415 of file foreigncmds.c.

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 }
static void AlterForeignServerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Definition: foreigncmds.c:338

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

Referenced by ExecAlterOwnerStmt().

◆ AlterForeignServerOwner_oid()

void AlterForeignServerOwner_oid ( Oid  srvId,
Oid  newOwnerId 
)

Definition at line 450 of file foreigncmds.c.

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 }

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

Referenced by shdepReassignOwned().

◆ AlterFunction()

ObjectAddress AlterFunction ( ParseState pstate,
AlterFunctionStmt stmt 
)

Definition at line 1348 of file functioncmds.c.

1349 {
1350  HeapTuple tup;
1351  Oid funcOid;
1352  Form_pg_proc procForm;
1353  bool is_procedure;
1354  Relation rel;
1355  ListCell *l;
1356  DefElem *volatility_item = NULL;
1357  DefElem *strict_item = NULL;
1358  DefElem *security_def_item = NULL;
1359  DefElem *leakproof_item = NULL;
1360  List *set_items = NIL;
1361  DefElem *cost_item = NULL;
1362  DefElem *rows_item = NULL;
1363  DefElem *support_item = NULL;
1364  DefElem *parallel_item = NULL;
1365  ObjectAddress address;
1366 
1367  rel = table_open(ProcedureRelationId, RowExclusiveLock);
1368 
1369  funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
1370 
1371  ObjectAddressSet(address, ProcedureRelationId, funcOid);
1372 
1373  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1374  if (!HeapTupleIsValid(tup)) /* should not happen */
1375  elog(ERROR, "cache lookup failed for function %u", funcOid);
1376 
1377  procForm = (Form_pg_proc) GETSTRUCT(tup);
1378 
1379  /* Permission check: must own function */
1380  if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
1382  NameListToString(stmt->func->objname));
1383 
1384  if (procForm->prokind == PROKIND_AGGREGATE)
1385  ereport(ERROR,
1386  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1387  errmsg("\"%s\" is an aggregate function",
1388  NameListToString(stmt->func->objname))));
1389 
1390  is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
1391 
1392  /* Examine requested actions. */
1393  foreach(l, stmt->actions)
1394  {
1395  DefElem *defel = (DefElem *) lfirst(l);
1396 
1397  if (compute_common_attribute(pstate,
1398  is_procedure,
1399  defel,
1400  &volatility_item,
1401  &strict_item,
1402  &security_def_item,
1403  &leakproof_item,
1404  &set_items,
1405  &cost_item,
1406  &rows_item,
1407  &support_item,
1408  &parallel_item) == false)
1409  elog(ERROR, "option \"%s\" not recognized", defel->defname);
1410  }
1411 
1412  if (volatility_item)
1413  procForm->provolatile = interpret_func_volatility(volatility_item);
1414  if (strict_item)
1415  procForm->proisstrict = boolVal(strict_item->arg);
1416  if (security_def_item)
1417  procForm->prosecdef = boolVal(security_def_item->arg);
1418  if (leakproof_item)
1419  {
1420  procForm->proleakproof = boolVal(leakproof_item->arg);
1421  if (procForm->proleakproof && !superuser())
1422  ereport(ERROR,
1423  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1424  errmsg("only superuser can define a leakproof function")));
1425  }
1426  if (cost_item)
1427  {
1428  procForm->procost = defGetNumeric(cost_item);
1429  if (procForm->procost <= 0)
1430  ereport(ERROR,
1431  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1432  errmsg("COST must be positive")));
1433  }
1434  if (rows_item)
1435  {
1436  procForm->prorows = defGetNumeric(rows_item);
1437  if (procForm->prorows <= 0)
1438  ereport(ERROR,
1439  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1440  errmsg("ROWS must be positive")));
1441  if (!procForm->proretset)
1442  ereport(ERROR,
1443  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1444  errmsg("ROWS is not applicable when function does not return a set")));
1445  }
1446  if (support_item)
1447  {
1448  /* interpret_func_support handles the privilege check */
1449  Oid newsupport = interpret_func_support(support_item);
1450 
1451  /* Add or replace dependency on support function */
1452  if (OidIsValid(procForm->prosupport))
1453  changeDependencyFor(ProcedureRelationId, funcOid,
1454  ProcedureRelationId, procForm->prosupport,
1455  newsupport);
1456  else
1457  {
1458  ObjectAddress referenced;
1459 
1460  referenced.classId = ProcedureRelationId;
1461  referenced.objectId = newsupport;
1462  referenced.objectSubId = 0;
1463  recordDependencyOn(&address, &referenced, DEPENDENCY_NORMAL);
1464  }
1465 
1466  procForm->prosupport = newsupport;
1467  }
1468  if (parallel_item)
1469  procForm->proparallel = interpret_func_parallel(parallel_item);
1470  if (set_items)
1471  {
1472  Datum datum;
1473  bool isnull;
1474  ArrayType *a;
1475  Datum repl_val[Natts_pg_proc];
1476  bool repl_null[Natts_pg_proc];
1477  bool repl_repl[Natts_pg_proc];
1478 
1479  /* extract existing proconfig setting */
1480  datum = SysCacheGetAttr(PROCOID, tup, Anum_pg_proc_proconfig, &isnull);
1481  a = isnull ? NULL : DatumGetArrayTypeP(datum);
1482 
1483  /* update according to each SET or RESET item, left to right */
1484  a = update_proconfig_value(a, set_items);
1485 
1486  /* update the tuple */
1487  memset(repl_repl, false, sizeof(repl_repl));
1488  repl_repl[Anum_pg_proc_proconfig - 1] = true;
1489 
1490  if (a == NULL)
1491  {
1492  repl_val[Anum_pg_proc_proconfig - 1] = (Datum) 0;
1493  repl_null[Anum_pg_proc_proconfig - 1] = true;
1494  }
1495  else
1496  {
1497  repl_val[Anum_pg_proc_proconfig - 1] = PointerGetDatum(a);
1498  repl_null[Anum_pg_proc_proconfig - 1] = false;
1499  }
1500 
1501  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1502  repl_val, repl_null, repl_repl);
1503  }
1504  /* DO NOT put more touches of procForm below here; it's now dangling. */
1505 
1506  /* Do the update */
1507  CatalogTupleUpdate(rel, &tup->t_self, tup);
1508 
1509  InvokeObjectPostAlterHook(ProcedureRelationId, funcOid, 0);
1510 
1511  table_close(rel, NoLock);
1512  heap_freetuple(tup);
1513 
1514  return address;
1515 }
#define DatumGetArrayTypeP(X)
Definition: array.h:254
double defGetNumeric(DefElem *def)
Definition: define.c:82
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:650
static Oid interpret_func_support(DefElem *defel)
Definition: functioncmds.c:675
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:505
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:607
static char interpret_func_parallel(DefElem *defel)
Definition: functioncmds.c:625
int a
Definition: isn.c:69
#define NoLock
Definition: lockdefs.h:34
char * NameListToString(List *names)
Definition: namespace.c:3145
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2208
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:456
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
ObjectWithArgs * func
Definition: parsenodes.h:3184
ObjectType objtype
Definition: parsenodes.h:3183
char * defname
Definition: parsenodes.h:810
Node * arg
Definition: parsenodes.h:811
Definition: pg_list.h:54
@ PROCOID
Definition: syscache.h:79
#define boolVal(v)
Definition: value.h:81

References a, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterFunctionStmt::actions, DefElem::arg, boolVal, 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(), InvokeObjectPostAlterHook, lfirst, LookupFuncWithArgs(), NameListToString(), NIL, NoLock, object_ownercheck(), ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, ObjectWithArgs::objname, AlterFunctionStmt::objtype, OidIsValid, PointerGetDatum(), PROCOID, recordDependencyOn(), RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and update_proconfig_value().

Referenced by ProcessUtilitySlow().

◆ AlterOperator()

ObjectAddress AlterOperator ( AlterOperatorStmt stmt)

Definition at line 411 of file operatorcmds.c.

412 {
413  ObjectAddress address;
414  Oid oprId;
415  Relation catalog;
416  HeapTuple tup;
417  Form_pg_operator oprForm;
418  int i;
419  ListCell *pl;
420  Datum values[Natts_pg_operator];
421  bool nulls[Natts_pg_operator];
422  bool replaces[Natts_pg_operator];
423  List *restrictionName = NIL; /* optional restrict. sel. function */
424  bool updateRestriction = false;
425  Oid restrictionOid;
426  List *joinName = NIL; /* optional join sel. function */
427  bool updateJoin = false;
428  Oid joinOid;
429 
430  /* Look up the operator */
431  oprId = LookupOperWithArgs(stmt->opername, false);
432  catalog = table_open(OperatorRelationId, RowExclusiveLock);
434  if (!HeapTupleIsValid(tup))
435  elog(ERROR, "cache lookup failed for operator %u", oprId);
436  oprForm = (Form_pg_operator) GETSTRUCT(tup);
437 
438  /* Process options */
439  foreach(pl, stmt->options)
440  {
441  DefElem *defel = (DefElem *) lfirst(pl);
442  List *param;
443 
444  if (defel->arg == NULL)
445  param = NIL; /* NONE, removes the function */
446  else
447  param = defGetQualifiedName(defel);
448 
449  if (strcmp(defel->defname, "restrict") == 0)
450  {
451  restrictionName = param;
452  updateRestriction = true;
453  }
454  else if (strcmp(defel->defname, "join") == 0)
455  {
456  joinName = param;
457  updateJoin = true;
458  }
459 
460  /*
461  * The rest of the options that CREATE accepts cannot be changed.
462  * Check for them so that we can give a meaningful error message.
463  */
464  else if (strcmp(defel->defname, "leftarg") == 0 ||
465  strcmp(defel->defname, "rightarg") == 0 ||
466  strcmp(defel->defname, "function") == 0 ||
467  strcmp(defel->defname, "procedure") == 0 ||
468  strcmp(defel->defname, "commutator") == 0 ||
469  strcmp(defel->defname, "negator") == 0 ||
470  strcmp(defel->defname, "hashes") == 0 ||
471  strcmp(defel->defname, "merges") == 0)
472  {
473  ereport(ERROR,
474  (errcode(ERRCODE_SYNTAX_ERROR),
475  errmsg("operator attribute \"%s\" cannot be changed",
476  defel->defname)));
477  }
478  else
479  ereport(ERROR,
480  (errcode(ERRCODE_SYNTAX_ERROR),
481  errmsg("operator attribute \"%s\" not recognized",
482  defel->defname)));
483  }
484 
485  /* Check permissions. Must be owner. */
486  if (!object_ownercheck(OperatorRelationId, oprId, GetUserId()))
488  NameStr(oprForm->oprname));
489 
490  /*
491  * Look up restriction and join estimators if specified
492  */
493  if (restrictionName)
494  restrictionOid = ValidateRestrictionEstimator(restrictionName);
495  else
496  restrictionOid = InvalidOid;
497  if (joinName)
498  joinOid = ValidateJoinEstimator(joinName);
499  else
500  joinOid = InvalidOid;
501 
502  /* Perform additional checks, like OperatorCreate does */
503  if (!(OidIsValid(oprForm->oprleft) && OidIsValid(oprForm->oprright)))
504  {
505  /* If it's not a binary op, these things mustn't be set: */
506  if (OidIsValid(joinOid))
507  ereport(ERROR,
508  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
509  errmsg("only binary operators can have join selectivity")));
510  }
511 
512  if (oprForm->oprresult != BOOLOID)
513  {
514  if (OidIsValid(restrictionOid))
515  ereport(ERROR,
516  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
517  errmsg("only boolean operators can have restriction selectivity")));
518  if (OidIsValid(joinOid))
519  ereport(ERROR,
520  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
521  errmsg("only boolean operators can have join selectivity")));
522  }
523 
524  /* Update the tuple */
525  for (i = 0; i < Natts_pg_operator; ++i)
526  {
527  values[i] = (Datum) 0;
528  replaces[i] = false;
529  nulls[i] = false;
530  }
531  if (updateRestriction)
532  {
533  replaces[Anum_pg_operator_oprrest - 1] = true;
534  values[Anum_pg_operator_oprrest - 1] = restrictionOid;
535  }
536  if (updateJoin)
537  {
538  replaces[Anum_pg_operator_oprjoin - 1] = true;
539  values[Anum_pg_operator_oprjoin - 1] = joinOid;
540  }
541 
542  tup = heap_modify_tuple(tup, RelationGetDescr(catalog),
543  values, nulls, replaces);
544 
545  CatalogTupleUpdate(catalog, &tup->t_self, tup);
546 
547  address = makeOperatorDependencies(tup, false, true);
548 
549  InvokeObjectPostAlterHook(OperatorRelationId, oprId, 0);
550 
551  table_close(catalog, NoLock);
552 
553  return address;
554 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define NameStr(name)
Definition: c.h:730
List * defGetQualifiedName(DefElem *def)
Definition: define.c:253
int i
Definition: isn.c:73
static Oid ValidateJoinEstimator(List *joinName)
Definition: operatorcmds.c:310
static Oid ValidateRestrictionEstimator(List *restrictionName)
Definition: operatorcmds.c:275
Oid LookupOperWithArgs(ObjectWithArgs *oper, bool noError)
Definition: parse_oper.c:145
@ OBJECT_OPERATOR
Definition: parsenodes.h:1994
ObjectAddress makeOperatorDependencies(HeapTuple tuple, bool makeExtensionDep, bool isUpdate)
Definition: pg_operator.c:777
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define InvalidOid
Definition: postgres_ext.h:36
ObjectWithArgs * opername
Definition: parsenodes.h:3302
@ OPEROID
Definition: syscache.h:72

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, object_ownercheck(), ObjectIdGetDatum(), OidIsValid, AlterOperatorStmt::opername, OPEROID, AlterOperatorStmt::options, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), table_open(), ValidateJoinEstimator(), ValidateRestrictionEstimator(), and values.

Referenced by ProcessUtilitySlow().

◆ AlterOpFamily()

Oid AlterOpFamily ( AlterOpFamilyStmt stmt)

Definition at line 817 of file opclasscmds.c.

818 {
819  Oid amoid, /* our AM's oid */
820  opfamilyoid; /* oid of opfamily */
821  int maxOpNumber, /* amstrategies value */
822  optsProcNumber, /* amopclassopts value */
823  maxProcNumber; /* amsupport value */
824  HeapTuple tup;
825  Form_pg_am amform;
826  IndexAmRoutine *amroutine;
827 
828  /* Get necessary info about access method */
830  if (!HeapTupleIsValid(tup))
831  ereport(ERROR,
832  (errcode(ERRCODE_UNDEFINED_OBJECT),
833  errmsg("access method \"%s\" does not exist",
834  stmt->amname)));
835 
836  amform = (Form_pg_am) GETSTRUCT(tup);
837  amoid = amform->oid;
838  amroutine = GetIndexAmRoutineByAmId(amoid, false);
839  ReleaseSysCache(tup);
840 
841  maxOpNumber = amroutine->amstrategies;
842  /* if amstrategies is zero, just enforce that op numbers fit in int16 */
843  if (maxOpNumber <= 0)
844  maxOpNumber = SHRT_MAX;
845  maxProcNumber = amroutine->amsupport;
846  optsProcNumber = amroutine->amoptsprocnum;
847 
848  /* XXX Should we make any privilege check against the AM? */
849 
850  /* Look up the opfamily */
851  opfamilyoid = get_opfamily_oid(amoid, stmt->opfamilyname, false);
852 
853  /*
854  * Currently, we require superuser privileges to alter an opfamily.
855  *
856  * XXX re-enable NOT_USED code sections below if you remove this test.
857  */
858  if (!superuser())
859  ereport(ERROR,
860  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
861  errmsg("must be superuser to alter an operator family")));
862 
863  /*
864  * ADD and DROP cases need separate code from here on down.
865  */
866  if (stmt->isDrop)
867  AlterOpFamilyDrop(stmt, amoid, opfamilyoid,
868  maxOpNumber, maxProcNumber, stmt->items);
869  else
870  AlterOpFamilyAdd(stmt, amoid, opfamilyoid,
871  maxOpNumber, maxProcNumber, optsProcNumber,
872  stmt->items);
873 
874  return opfamilyoid;
875 }
IndexAmRoutine * GetIndexAmRoutineByAmId(Oid amoid, bool noerror)
Definition: amapi.c:56
static void AlterOpFamilyDrop(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, List *items)
Definition: opclasscmds.c:1030
Oid get_opfamily_oid(Oid amID, List *opfamilyname, bool missing_ok)
Definition: opclasscmds.c:139
static void AlterOpFamilyAdd(AlterOpFamilyStmt *stmt, Oid amoid, Oid opfamilyoid, int maxOpNumber, int maxProcNumber, int optsProcNumber, List *items)
Definition: opclasscmds.c:881
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
uint16 amoptsprocnum
Definition: amapi.h:218
uint16 amsupport
Definition: amapi.h:216
uint16 amstrategies
Definition: amapi.h:214
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:865
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:817
@ AMNAME
Definition: syscache.h:35

References AlterOpFamilyAdd(), AlterOpFamilyDrop(), AlterOpFamilyStmt::amname, 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().

◆ AlterStatistics()

ObjectAddress AlterStatistics ( AlterStatsStmt stmt)

Definition at line 602 of file statscmds.c.

603 {
604  Relation rel;
605  Oid stxoid;
606  HeapTuple oldtup;
607  HeapTuple newtup;
608  Datum repl_val[Natts_pg_statistic_ext];
609  bool repl_null[Natts_pg_statistic_ext];
610  bool repl_repl[Natts_pg_statistic_ext];
611  ObjectAddress address;
612  int newtarget = stmt->stxstattarget;
613 
614  /* Limit statistics target to a sane range */
615  if (newtarget < -1)
616  {
617  ereport(ERROR,
618  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
619  errmsg("statistics target %d is too low",
620  newtarget)));
621  }
622  else if (newtarget > 10000)
623  {
624  newtarget = 10000;
626  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
627  errmsg("lowering statistics target to %d",
628  newtarget)));
629  }
630 
631  /* lookup OID of the statistics object */
632  stxoid = get_statistics_object_oid(stmt->defnames, stmt->missing_ok);
633 
634  /*
635  * If we got here and the OID is not valid, it means the statistics object
636  * does not exist, but the command specified IF EXISTS. So report this as
637  * a simple NOTICE and we're done.
638  */
639  if (!OidIsValid(stxoid))
640  {
641  char *schemaname;
642  char *statname;
643 
644  Assert(stmt->missing_ok);
645 
646  DeconstructQualifiedName(stmt->defnames, &schemaname, &statname);
647 
648  if (schemaname)
649  ereport(NOTICE,
650  (errmsg("statistics object \"%s.%s\" does not exist, skipping",
651  schemaname, statname)));
652  else
653  ereport(NOTICE,
654  (errmsg("statistics object \"%s\" does not exist, skipping",
655  statname)));
656 
657  return InvalidObjectAddress;
658  }
659 
660  /* Search pg_statistic_ext */
661  rel = table_open(StatisticExtRelationId, RowExclusiveLock);
662 
663  oldtup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
664  if (!HeapTupleIsValid(oldtup))
665  elog(ERROR, "cache lookup failed for extended statistics object %u", stxoid);
666 
667  /* Must be owner of the existing statistics object */
668  if (!object_ownercheck(StatisticExtRelationId, stxoid, GetUserId()))
670  NameListToString(stmt->defnames));
671 
672  /* Build new tuple. */
673  memset(repl_val, 0, sizeof(repl_val));
674  memset(repl_null, false, sizeof(repl_null));
675  memset(repl_repl, false, sizeof(repl_repl));
676 
677  /* replace the stxstattarget column */
678  repl_repl[Anum_pg_statistic_ext_stxstattarget - 1] = true;
679  repl_val[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(newtarget);
680 
681  newtup = heap_modify_tuple(oldtup, RelationGetDescr(rel),
682  repl_val, repl_null, repl_repl);
683 
684  /* Update system catalog. */
685  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
686 
687  InvokeObjectPostAlterHook(StatisticExtRelationId, stxoid, 0);
688 
689  ObjectAddressSet(address, StatisticExtRelationId, stxoid);
690 
691  /*
692  * NOTE: because we only support altering the statistics target, not the
693  * other fields, there is no need to update dependencies.
694  */
695 
696  heap_freetuple(newtup);
697  ReleaseSysCache(oldtup);
698 
700 
701  return address;
702 }
#define NOTICE
Definition: elog.h:35
Assert(fmt[strlen(fmt) - 1] !='\n')
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2852
Oid get_statistics_object_oid(List *names, bool missing_ok)
Definition: namespace.c:2221
const ObjectAddress InvalidObjectAddress
@ OBJECT_STATISTIC_EXT
Definition: parsenodes.h:2008
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
@ STATEXTOID
Definition: syscache.h:96

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

Referenced by ProcessUtilitySlow().

◆ AlterTSConfiguration()

ObjectAddress AlterTSConfiguration ( AlterTSConfigurationStmt stmt)

Definition at line 1150 of file tsearchcmds.c.

1151 {
1152  HeapTuple tup;
1153  Oid cfgId;
1154  Relation relMap;
1155  ObjectAddress address;
1156 
1157  /* Find the configuration */
1158  tup = GetTSConfigTuple(stmt->cfgname);
1159  if (!HeapTupleIsValid(tup))
1160  ereport(ERROR,
1161  (errcode(ERRCODE_UNDEFINED_OBJECT),
1162  errmsg("text search configuration \"%s\" does not exist",
1163  NameListToString(stmt->cfgname))));
1164 
1165  cfgId = ((Form_pg_ts_config) GETSTRUCT(tup))->oid;
1166 
1167  /* must be owner */
1168  if (!object_ownercheck(TSConfigRelationId, cfgId, GetUserId()))
1170  NameListToString(stmt->cfgname));
1171 
1172  relMap = table_open(TSConfigMapRelationId, RowExclusiveLock);
1173 
1174  /* Add or drop mappings */
1175  if (stmt->dicts)
1176  MakeConfigurationMapping(stmt, tup, relMap);
1177  else if (stmt->tokentype)
1178  DropConfigurationMapping(stmt, tup, relMap);
1179 
1180  /* Update dependencies */
1181  makeConfigurationDependencies(tup, true, relMap);
1182 
1183  InvokeObjectPostAlterHook(TSConfigRelationId, cfgId, 0);
1184 
1185  ObjectAddressSet(address, TSConfigRelationId, cfgId);
1186 
1187  table_close(relMap, RowExclusiveLock);
1188 
1189  ReleaseSysCache(tup);
1190 
1191  return address;
1192 }
@ OBJECT_TSCONFIGURATION
Definition: parsenodes.h:2014
FormData_pg_ts_config * Form_pg_ts_config
Definition: pg_ts_config.h:48
static ObjectAddress makeConfigurationDependencies(HeapTuple tuple, bool removeOld, Relation mapRel)
Definition: tsearchcmds.c:806
static HeapTuple GetTSConfigTuple(List *names)
Definition: tsearchcmds.c:781
static void DropConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1450
static void MakeConfigurationMapping(AlterTSConfigurationStmt *stmt, HeapTuple tup, Relation relMap)
Definition: tsearchcmds.c:1253

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

Referenced by ProcessUtilitySlow().

◆ AlterTSDictionary()

ObjectAddress AlterTSDictionary ( AlterTSDictionaryStmt stmt)

Definition at line 487 of file tsearchcmds.c.

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 (!object_ownercheck(TSDictionaryRelationId, 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 }
List * lappend(List *list, void *datum)
Definition: list.c:338
Oid get_ts_dict_oid(List *names, bool missing_ok)
Definition: namespace.c:2469
@ OBJECT_TSDICTIONARY
Definition: parsenodes.h:2015
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:390
FormData_pg_ts_dict * Form_pg_ts_dict
Definition: pg_ts_dict.h:52
@ TSDICTOID
Definition: syscache.h:108
List * deserialize_deflist(Datum txt)
Definition: tsearchcmds.c:1584
static void verify_dictoptions(Oid tmplId, List *dictoptions)
Definition: tsearchcmds.c:336
text * serialize_deflist(List *deflist)
Definition: tsearchcmds.c:1528

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_ownercheck(), OBJECT_TSDICTIONARY, ObjectAddressSet, ObjectIdGetDatum(), AlterTSDictionaryStmt::options, PointerGetDatum(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), serialize_deflist(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), TSDICTOID, and verify_dictoptions().

Referenced by ProcessUtilitySlow().

◆ AlterUserMapping()

ObjectAddress AlterUserMapping ( AlterUserMappingStmt stmt)

Definition at line 1226 of file foreigncmds.c.

1227 {
1228  Relation rel;
1229  HeapTuple tp;
1230  Datum repl_val[Natts_pg_user_mapping];
1231  bool repl_null[Natts_pg_user_mapping];
1232  bool repl_repl[Natts_pg_user_mapping];
1233  Oid useId;
1234  Oid umId;
1235  ForeignServer *srv;
1236  ObjectAddress address;
1237  RoleSpec *role = (RoleSpec *) stmt->user;
1238 
1239  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1240 
1241  if (role->roletype == ROLESPEC_PUBLIC)
1242  useId = ACL_ID_PUBLIC;
1243  else
1244  useId = get_rolespec_oid(stmt->user, false);
1245 
1246  srv = GetForeignServerByName(stmt->servername, false);
1247 
1248  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1249  ObjectIdGetDatum(useId),
1250  ObjectIdGetDatum(srv->serverid));
1251  if (!OidIsValid(umId))
1252  ereport(ERROR,
1253  (errcode(ERRCODE_UNDEFINED_OBJECT),
1254  errmsg("user mapping for \"%s\" does not exist for server \"%s\"",
1255  MappingUserName(useId), stmt->servername)));
1256 
1257  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1258 
1260 
1261  if (!HeapTupleIsValid(tp))
1262  elog(ERROR, "cache lookup failed for user mapping %u", umId);
1263 
1264  memset(repl_val, 0, sizeof(repl_val));
1265  memset(repl_null, false, sizeof(repl_null));
1266  memset(repl_repl, false, sizeof(repl_repl));
1267 
1268  if (stmt->options)
1269  {
1270  ForeignDataWrapper *fdw;
1271  Datum datum;
1272  bool isnull;
1273 
1274  /*
1275  * Process the options.
1276  */
1277 
1278  fdw = GetForeignDataWrapper(srv->fdwid);
1279 
1280  datum = SysCacheGetAttr(USERMAPPINGUSERSERVER,
1281  tp,
1282  Anum_pg_user_mapping_umoptions,
1283  &isnull);
1284  if (isnull)
1285  datum = PointerGetDatum(NULL);
1286 
1287  /* Prepare the options array */
1288  datum = transformGenericOptions(UserMappingRelationId,
1289  datum,
1290  stmt->options,
1291  fdw->fdwvalidator);
1292 
1293  if (PointerIsValid(DatumGetPointer(datum)))
1294  repl_val[Anum_pg_user_mapping_umoptions - 1] = datum;
1295  else
1296  repl_null[Anum_pg_user_mapping_umoptions - 1] = true;
1297 
1298  repl_repl[Anum_pg_user_mapping_umoptions - 1] = true;
1299  }
1300 
1301  /* Everything looks good - update the tuple */
1302  tp = heap_modify_tuple(tp, RelationGetDescr(rel),
1303  repl_val, repl_null, repl_repl);
1304 
1305  CatalogTupleUpdate(rel, &tp->t_self, tp);
1306 
1307  InvokeObjectPostAlterHook(UserMappingRelationId,
1308  umId, 0);
1309 
1310  ObjectAddressSet(address, UserMappingRelationId, umId);
1311 
1312  heap_freetuple(tp);
1313 
1315 
1316  return address;
1317 }
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5289
#define ACL_ID_PUBLIC
Definition: acl.h:46
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:182
#define MappingUserName(userid)
Definition: foreign.h:20
static void user_mapping_ddl_aclcheck(Oid umuserid, Oid serverid, const char *servername)
Definition: foreigncmds.c:1075
@ ROLESPEC_PUBLIC
Definition: parsenodes.h:396
Oid serverid
Definition: foreign.h:36
RoleSpecType roletype
Definition: parsenodes.h:402
@ USERMAPPINGOID
Definition: syscache.h:115
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:199

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().

◆ CallStmtResultDesc()

TupleDesc CallStmtResultDesc ( CallStmt stmt)

Definition at line 2353 of file functioncmds.c.

2354 {
2355  FuncExpr *fexpr;
2356  HeapTuple tuple;
2357  TupleDesc tupdesc;
2358 
2359  fexpr = stmt->funcexpr;
2360 
2361  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
2362  if (!HeapTupleIsValid(tuple))
2363  elog(ERROR, "cache lookup failed for procedure %u", fexpr->funcid);
2364 
2365  tupdesc = build_function_result_tupdesc_t(tuple);
2366 
2367  ReleaseSysCache(tuple);
2368 
2369  return tupdesc;
2370 }
TupleDesc build_function_result_tupdesc_t(HeapTuple procTuple)
Definition: funcapi.c:1702
FuncExpr * funcexpr
Definition: parsenodes.h:3224
Oid funcid
Definition: primnodes.h:674

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

Referenced by UtilityTupleDescriptor().

◆ CheckIndexCompatible()

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

Definition at line 171 of file indexcmds.c.

175 {
176  bool isconstraint;
177  Oid *typeObjectId;
178  Oid *collationObjectId;
179  Oid *classObjectId;
180  Oid accessMethodId;
181  Oid relationId;
182  HeapTuple tuple;
183  Form_pg_index indexForm;
184  Form_pg_am accessMethodForm;
185  IndexAmRoutine *amRoutine;
186  bool amcanorder;
187  int16 *coloptions;
188  IndexInfo *indexInfo;
189  int numberOfAttributes;
190  int old_natts;
191  bool isnull;
192  bool ret = true;
193  oidvector *old_indclass;
194  oidvector *old_indcollation;
195  Relation irel;
196  int i;
197  Datum d;
198 
199  /* Caller should already have the relation locked in some way. */
200  relationId = IndexGetRelation(oldId, false);
201 
202  /*
203  * We can pretend isconstraint = false unconditionally. It only serves to
204  * decide the text of an error message that should never happen for us.
205  */
206  isconstraint = false;
207 
208  numberOfAttributes = list_length(attributeList);
209  Assert(numberOfAttributes > 0);
210  Assert(numberOfAttributes <= INDEX_MAX_KEYS);
211 
212  /* look up the access method */
213  tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName));
214  if (!HeapTupleIsValid(tuple))
215  ereport(ERROR,
216  (errcode(ERRCODE_UNDEFINED_OBJECT),
217  errmsg("access method \"%s\" does not exist",
218  accessMethodName)));
219  accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
220  accessMethodId = accessMethodForm->oid;
221  amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler);
222  ReleaseSysCache(tuple);
223 
224  amcanorder = amRoutine->amcanorder;
225 
226  /*
227  * Compute the operator classes, collations, and exclusion operators for
228  * the new index, so we can test whether it's compatible with the existing
229  * one. Note that ComputeIndexAttrs might fail here, but that's OK:
230  * DefineIndex would have failed later. Our attributeList contains only
231  * key attributes, thus we're filling ii_NumIndexAttrs and
232  * ii_NumIndexKeyAttrs with same value.
233  */
234  indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes,
235  accessMethodId, NIL, NIL, false, false, false, false);
236  typeObjectId = palloc_array(Oid, numberOfAttributes);
237  collationObjectId = palloc_array(Oid, numberOfAttributes);
238  classObjectId = palloc_array(Oid, numberOfAttributes);
239  coloptions = palloc_array(int16, numberOfAttributes);
240  ComputeIndexAttrs(indexInfo,
241  typeObjectId, collationObjectId, classObjectId,
242  coloptions, attributeList,
243  exclusionOpNames, relationId,
244  accessMethodName, accessMethodId,
245  amcanorder, isconstraint, InvalidOid, 0, NULL);
246 
247 
248  /* Get the soon-obsolete pg_index tuple. */
250  if (!HeapTupleIsValid(tuple))
251  elog(ERROR, "cache lookup failed for index %u", oldId);
252  indexForm = (Form_pg_index) GETSTRUCT(tuple);
253 
254  /*
255  * We don't assess expressions or predicates; assume incompatibility.
256  * Also, if the index is invalid for any reason, treat it as incompatible.
257  */
258  if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) &&
259  heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) &&
260  indexForm->indisvalid))
261  {
262  ReleaseSysCache(tuple);
263  return false;
264  }
265 
266  /* Any change in operator class or collation breaks compatibility. */
267  old_natts = indexForm->indnkeyatts;
268  Assert(old_natts == numberOfAttributes);
269 
270  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indcollation, &isnull);
271  Assert(!isnull);
272  old_indcollation = (oidvector *) DatumGetPointer(d);
273 
274  d = SysCacheGetAttr(INDEXRELID, tuple, Anum_pg_index_indclass, &isnull);
275  Assert(!isnull);
276  old_indclass = (oidvector *) DatumGetPointer(d);
277 
278  ret = (memcmp(old_indclass->values, classObjectId,
279  old_natts * sizeof(Oid)) == 0 &&
280  memcmp(old_indcollation->values, collationObjectId,
281  old_natts * sizeof(Oid)) == 0);
282 
283  ReleaseSysCache(tuple);
284 
285  if (!ret)
286  return false;
287 
288  /* For polymorphic opcintype, column type changes break compatibility. */
289  irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */
290  for (i = 0; i < old_natts; i++)
291  {
292  if (IsPolymorphicType(get_opclass_input_type(classObjectId[i])) &&
293  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
294  {
295  ret = false;
296  break;
297  }
298  }
299 
300  /* Any change in opclass options break compatibility. */
301  if (ret)
302  {
303  Datum *opclassOptions = RelationGetIndexRawAttOptions(irel);
304 
305  ret = CompareOpclassOptions(opclassOptions,
306  indexInfo->ii_OpclassOptions, old_natts);
307 
308  if (opclassOptions)
309  pfree(opclassOptions);
310  }
311 
312  /* Any change in exclusion operator selections breaks compatibility. */
313  if (ret && indexInfo->ii_ExclusionOps != NULL)
314  {
315  Oid *old_operators,
316  *old_procs;
317  uint16 *old_strats;
318 
319  RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats);
320  ret = memcmp(old_operators, indexInfo->ii_ExclusionOps,
321  old_natts * sizeof(Oid)) == 0;
322 
323  /* Require an exact input type match for polymorphic operators. */
324  if (ret)
325  {
326  for (i = 0; i < old_natts && ret; i++)
327  {
328  Oid left,
329  right;
330 
331  op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right);
332  if ((IsPolymorphicType(left) || IsPolymorphicType(right)) &&
333  TupleDescAttr(irel->rd_att, i)->atttypid != typeObjectId[i])
334  {
335  ret = false;
336  break;
337  }
338  }
339  }
340  }
341 
342  index_close(irel, NoLock);
343  return ret;
344 }
IndexAmRoutine * GetIndexAmRoutine(Oid amhandler)
Definition: amapi.c:33
unsigned short uint16
Definition: c.h:489
signed short int16
Definition: c.h:477
#define palloc_array(type, count)
Definition: fe_memutils.h:64
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3521
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
static bool CompareOpclassOptions(Datum *opts1, Datum *opts2, int natts)
Definition: indexcmds.c:353
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, Oid ddl_userid, int ddl_sec_context, int *ddl_save_nestlevel)
Definition: indexcmds.c:1767
#define AccessShareLock
Definition: lockdefs.h:36
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1216
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1340
IndexInfo * makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions, List *predicates, bool unique, bool nulls_not_distinct, bool isready, bool concurrent)
Definition: makefuncs.c:745
void pfree(void *pointer)
Definition: mcxt.c:1436
#define INDEX_MAX_KEYS
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static int list_length(const List *l)
Definition: pg_list.h:152
Datum * RelationGetIndexRawAttOptions(Relation indexrel)
Definition: relcache.c:5769
void RelationGetExclusionInfo(Relation indexRelation, Oid **operators, Oid **procs, uint16 **strategies)
Definition: relcache.c:5486
bool amcanorder
Definition: amapi.h:220
Datum * ii_OpclassOptions
Definition: execnodes.h:189
Oid * ii_ExclusionOps
Definition: execnodes.h:183
TupleDesc rd_att
Definition: rel.h:111
Definition: c.h:710
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:717
@ INDEXRELID
Definition: syscache.h:66
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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, InvalidOid, list_length(), makeIndexInfo(), NIL, NoLock, ObjectIdGetDatum(), op_input_types(), palloc_array, pfree(), PointerGetDatum(), RelationData::rd_att, RelationGetExclusionInfo(), RelationGetIndexRawAttOptions(), ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttr(), TupleDescAttr, and oidvector::values.

Referenced by TryReuseIndex().

◆ ChooseRelationName()

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

Definition at line 2418 of file indexcmds.c.

2421 {
2422  int pass = 0;
2423  char *relname = NULL;
2424  char modlabel[NAMEDATALEN];
2425 
2426  /* try the unmodified label first */
2427  strlcpy(modlabel, label, sizeof(modlabel));
2428 
2429  for (;;)
2430  {
2431  relname = makeObjectName(name1, name2, modlabel);
2432 
2433  if (!OidIsValid(get_relname_relid(relname, namespaceid)))
2434  {
2435  if (!isconstraint ||
2436  !ConstraintNameExists(relname, namespaceid))
2437  break;
2438  }
2439 
2440  /* found a conflict, so try a new name component */
2441  pfree(relname);
2442  snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
2443  }
2444 
2445  return relname;
2446 }
char * makeObjectName(const char *name1, const char *name2, const char *label)
Definition: indexcmds.c:2332
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1867
static char * label
NameData relname
Definition: pg_class.h:38
#define NAMEDATALEN
bool ConstraintNameExists(const char *conname, Oid namespaceid)
#define snprintf
Definition: port.h:238
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

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

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

◆ CreateAccessMethod()

ObjectAddress CreateAccessMethod ( CreateAmStmt stmt)

Definition at line 43 of file amcmds.c.

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 superuser */
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 }
static Oid lookup_am_handler_func(List *handler_name, char amtype)
Definition: amcmds.c:234
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:192
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
List * handler_name
Definition: parsenodes.h:2713
char * amname
Definition: parsenodes.h:2712
#define GetSysCacheOid1(cacheId, oidcol, key1)
Definition: syscache.h:197

References CreateAmStmt::amname, AMNAME, 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().

◆ CreateCast()

ObjectAddress CreateCast ( CreateCastStmt stmt)

Definition at line 1522 of file functioncmds.c.

1523 {
1524  Oid sourcetypeid;
1525  Oid targettypeid;
1526  char sourcetyptype;
1527  char targettyptype;
1528  Oid funcid;
1529  Oid incastid = InvalidOid;
1530  Oid outcastid = InvalidOid;
1531  int nargs;
1532  char castcontext;
1533  char castmethod;
1534  HeapTuple tuple;
1535  AclResult aclresult;
1536  ObjectAddress myself;
1537 
1538  sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1539  targettypeid = typenameTypeId(NULL, stmt->targettype);
1540  sourcetyptype = get_typtype(sourcetypeid);
1541  targettyptype = get_typtype(targettypeid);
1542 
1543  /* No pseudo-types allowed */
1544  if (sourcetyptype == TYPTYPE_PSEUDO)
1545  ereport(ERROR,
1546  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1547  errmsg("source data type %s is a pseudo-type",
1548  TypeNameToString(stmt->sourcetype))));
1549 
1550  if (targettyptype == TYPTYPE_PSEUDO)
1551  ereport(ERROR,
1552  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1553  errmsg("target data type %s is a pseudo-type",
1554  TypeNameToString(stmt->targettype))));
1555 
1556  /* Permission check */
1557  if (!object_ownercheck(TypeRelationId, sourcetypeid, GetUserId())
1558  && !object_ownercheck(TypeRelationId, targettypeid, GetUserId()))
1559  ereport(ERROR,
1560  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1561  errmsg("must be owner of type %s or type %s",
1562  format_type_be(sourcetypeid),
1563  format_type_be(targettypeid))));
1564 
1565  aclresult = object_aclcheck(TypeRelationId, sourcetypeid, GetUserId(), ACL_USAGE);
1566  if (aclresult != ACLCHECK_OK)
1567  aclcheck_error_type(aclresult, sourcetypeid);
1568 
1569  aclresult = object_aclcheck(TypeRelationId, targettypeid, GetUserId(), ACL_USAGE);
1570  if (aclresult != ACLCHECK_OK)
1571  aclcheck_error_type(aclresult, targettypeid);
1572 
1573  /* Domains are allowed for historical reasons, but we warn */
1574  if (sourcetyptype == TYPTYPE_DOMAIN)
1575  ereport(WARNING,
1576  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1577  errmsg("cast will be ignored because the source data type is a domain")));
1578 
1579  else if (targettyptype == TYPTYPE_DOMAIN)
1580  ereport(WARNING,
1581  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1582  errmsg("cast will be ignored because the target data type is a domain")));
1583 
1584  /* Determine the cast method */
1585  if (stmt->func != NULL)
1586  castmethod = COERCION_METHOD_FUNCTION;
1587  else if (stmt->inout)
1588  castmethod = COERCION_METHOD_INOUT;
1589  else
1590  castmethod = COERCION_METHOD_BINARY;
1591 
1592  if (castmethod == COERCION_METHOD_FUNCTION)
1593  {
1594  Form_pg_proc procstruct;
1595 
1596  funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
1597 
1598  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1599  if (!HeapTupleIsValid(tuple))
1600  elog(ERROR, "cache lookup failed for function %u", funcid);
1601 
1602  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1603  nargs = procstruct->pronargs;
1604  if (nargs < 1 || nargs > 3)
1605  ereport(ERROR,
1606  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1607  errmsg("cast function must take one to three arguments")));
1608  if (!IsBinaryCoercibleWithCast(sourcetypeid,
1609  procstruct->proargtypes.values[0],
1610  &incastid))
1611  ereport(ERROR,
1612  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1613  errmsg("argument of cast function must match or be binary-coercible from source data type")));
1614  if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1615  ereport(ERROR,
1616  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1617  errmsg("second argument of cast function must be type %s",
1618  "integer")));
1619  if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1620  ereport(ERROR,
1621  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1622  errmsg("third argument of cast function must be type %s",
1623  "boolean")));
1624  if (!IsBinaryCoercibleWithCast(procstruct->prorettype,
1625  targettypeid,
1626  &outcastid))
1627  ereport(ERROR,
1628  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1629  errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1630 
1631  /*
1632  * Restricting the volatility of a cast function may or may not be a
1633  * good idea in the abstract, but it definitely breaks many old
1634  * user-defined types. Disable this check --- tgl 2/1/03
1635  */
1636 #ifdef NOT_USED
1637  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1638  ereport(ERROR,
1639  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1640  errmsg("cast function must not be volatile")));
1641 #endif
1642  if (procstruct->prokind != PROKIND_FUNCTION)
1643  ereport(ERROR,
1644  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1645  errmsg("cast function must be a normal function")));
1646  if (procstruct->proretset)
1647  ereport(ERROR,
1648  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1649  errmsg("cast function must not return a set")));
1650 
1651  ReleaseSysCache(tuple);
1652  }
1653  else
1654  {
1655  funcid = InvalidOid;
1656  nargs = 0;
1657  }
1658 
1659  if (castmethod == COERCION_METHOD_BINARY)
1660  {
1661  int16 typ1len;
1662  int16 typ2len;
1663  bool typ1byval;
1664  bool typ2byval;
1665  char typ1align;
1666  char typ2align;
1667 
1668  /*
1669  * Must be superuser to create binary-compatible casts, since
1670  * erroneous casts can easily crash the backend.
1671  */
1672  if (!superuser())
1673  ereport(ERROR,
1674  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1675  errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1676 
1677  /*
1678  * Also, insist that the types match as to size, alignment, and
1679  * pass-by-value attributes; this provides at least a crude check that
1680  * they have similar representations. A pair of types that fail this
1681  * test should certainly not be equated.
1682  */
1683  get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1684  get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1685  if (typ1len != typ2len ||
1686  typ1byval != typ2byval ||
1687  typ1align != typ2align)
1688  ereport(ERROR,
1689  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1690  errmsg("source and target data types are not physically compatible")));
1691 
1692  /*
1693  * We know that composite, enum and array types are never binary-
1694  * compatible with each other. They all have OIDs embedded in them.
1695  *
1696  * Theoretically you could build a user-defined base type that is
1697  * binary-compatible with a composite, enum, or array type. But we
1698  * disallow that too, as in practice such a cast is surely a mistake.
1699  * You can always work around that by writing a cast function.
1700  */
1701  if (sourcetyptype == TYPTYPE_COMPOSITE ||
1702  targettyptype == TYPTYPE_COMPOSITE)
1703  ereport(ERROR,
1704  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1705  errmsg("composite data types are not binary-compatible")));
1706 
1707  if (sourcetyptype == TYPTYPE_ENUM ||
1708  targettyptype == TYPTYPE_ENUM)
1709  ereport(ERROR,
1710  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1711  errmsg("enum data types are not binary-compatible")));
1712 
1713  if (OidIsValid(get_element_type(sourcetypeid)) ||
1714  OidIsValid(get_element_type(targettypeid)))
1715  ereport(ERROR,
1716  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1717  errmsg("array data types are not binary-compatible")));
1718 
1719  /*
1720  * We also disallow creating binary-compatibility casts involving
1721  * domains. Casting from a domain to its base type is already
1722  * allowed, and casting the other way ought to go through domain
1723  * coercion to permit constraint checking. Again, if you're intent on
1724  * having your own semantics for that, create a no-op cast function.
1725  *
1726  * NOTE: if we were to relax this, the above checks for composites
1727  * etc. would have to be modified to look through domains to their
1728  * base types.
1729  */
1730  if (sourcetyptype == TYPTYPE_DOMAIN ||
1731  targettyptype == TYPTYPE_DOMAIN)
1732  ereport(ERROR,
1733  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1734  errmsg("domain data types must not be marked binary-compatible")));
1735  }
1736 
1737  /*
1738  * Allow source and target types to be same only for length coercion
1739  * functions. We assume a multi-arg function does length coercion.
1740  */
1741  if (sourcetypeid == targettypeid && nargs < 2)
1742  ereport(ERROR,
1743  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1744  errmsg("source data type and target data type are the same")));
1745 
1746  /* convert CoercionContext enum to char value for castcontext */
1747  switch (stmt->context)
1748  {
1749  case COERCION_IMPLICIT:
1750  castcontext = COERCION_CODE_IMPLICIT;
1751  break;
1752  case COERCION_ASSIGNMENT:
1753  castcontext = COERCION_CODE_ASSIGNMENT;
1754  break;
1755  /* COERCION_PLPGSQL is intentionally not covered here */
1756  case COERCION_EXPLICIT:
1757  castcontext = COERCION_CODE_EXPLICIT;
1758  break;
1759  default:
1760  elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1761  castcontext = 0; /* keep compiler quiet */
1762  break;
1763  }
1764 
1765  myself = CastCreate(sourcetypeid, targettypeid, funcid, incastid, outcastid,
1766  castcontext, castmethod, DEPENDENCY_NORMAL);
1767  return myself;
1768 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3783
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:2998
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2717
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2229
char get_typtype(Oid typid)
Definition: lsyscache.c:2587
bool IsBinaryCoercibleWithCast(Oid srctype, Oid targettype, Oid *castoid)
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:478
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
#define ACL_USAGE
Definition: parsenodes.h:91
@ OBJECT_FUNCTION
Definition: parsenodes.h:1988
ObjectAddress CastCreate(Oid sourcetypeid, Oid targettypeid, Oid funcid, Oid incastid, Oid outcastid, char castcontext, char castmethod, DependencyType behavior)
Definition: pg_cast.c:49
@ COERCION_ASSIGNMENT
Definition: primnodes.h:639
@ COERCION_EXPLICIT
Definition: primnodes.h:641
@ COERCION_IMPLICIT
Definition: primnodes.h:638
TypeName * sourcetype
Definition: parsenodes.h:3716
TypeName * targettype
Definition: parsenodes.h:3717
CoercionContext context
Definition: parsenodes.h:3719
ObjectWithArgs * func
Definition: parsenodes.h:3718

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, IsBinaryCoercibleWithCast(), LookupFuncWithArgs(), object_aclcheck(), OBJECT_FUNCTION, object_ownercheck(), ObjectIdGetDatum(), OidIsValid, PROCOID, ReleaseSysCache(), SearchSysCache1(), CreateCastStmt::sourcetype, superuser(), CreateCastStmt::targettype, TypeNameToString(), typenameTypeId(), and WARNING.

Referenced by ProcessUtilitySlow().

◆ CreateForeignDataWrapper()

ObjectAddress CreateForeignDataWrapper ( ParseState pstate,
CreateFdwStmt stmt 
)

Definition at line 558 of file foreigncmds.c.

559 {
560  Relation rel;
561  Datum values[Natts_pg_foreign_data_wrapper];
562  bool nulls[Natts_pg_foreign_data_wrapper];
563  HeapTuple tuple;
564  Oid fdwId;
565  bool handler_given;
566  bool validator_given;
567  Oid fdwhandler;
568  Oid fdwvalidator;
569  Datum fdwoptions;
570  Oid ownerId;
571  ObjectAddress myself;
572  ObjectAddress referenced;
573 
574  rel = table_open(ForeignDataWrapperRelationId, RowExclusiveLock);
575 
576  /* Must be superuser */
577  if (!superuser())
578  ereport(ERROR,
579  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
580  errmsg("permission denied to create foreign-data wrapper \"%s\"",
581  stmt->fdwname),
582  errhint("Must be superuser to create a foreign-data wrapper.")));
583 
584  /* For now the owner cannot be specified on create. Use effective user ID. */
585  ownerId = GetUserId();
586 
587  /*
588  * Check that there is no other foreign-data wrapper by this name.
589  */
590  if (GetForeignDataWrapperByName(stmt->fdwname, true) != NULL)
591  ereport(ERROR,
593  errmsg("foreign-data wrapper \"%s\" already exists",
594  stmt->fdwname)));
595 
596  /*
597  * Insert tuple into pg_foreign_data_wrapper.
598  */
599  memset(values, 0, sizeof(values));
600  memset(nulls, false, sizeof(nulls));
601 
602  fdwId = GetNewOidWithIndex(rel, ForeignDataWrapperOidIndexId,
603  Anum_pg_foreign_data_wrapper_oid);
604  values[Anum_pg_foreign_data_wrapper_oid - 1] = ObjectIdGetDatum(fdwId);
605  values[Anum_pg_foreign_data_wrapper_fdwname - 1] =
607  values[Anum_pg_foreign_data_wrapper_fdwowner - 1] = ObjectIdGetDatum(ownerId);
608 
609  /* Lookup handler and validator functions, if given */
610  parse_func_options(pstate, stmt->func_options,
611  &handler_given, &fdwhandler,
612  &validator_given, &fdwvalidator);
613 
614  values[Anum_pg_foreign_data_wrapper_fdwhandler - 1] = ObjectIdGetDatum(fdwhandler);
615  values[Anum_pg_foreign_data_wrapper_fdwvalidator - 1] = ObjectIdGetDatum(fdwvalidator);
616 
617  nulls[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
618 
619  fdwoptions = transformGenericOptions(ForeignDataWrapperRelationId,
620  PointerGetDatum(NULL),
621  stmt->options,
622  fdwvalidator);
623 
624  if (PointerIsValid(DatumGetPointer(fdwoptions)))
625  values[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = fdwoptions;
626  else
627  nulls[Anum_pg_foreign_data_wrapper_fdwoptions - 1] = true;
628 
629  tuple = heap_form_tuple(rel->rd_att, values, nulls);
630 
631  CatalogTupleInsert(rel, tuple);
632 
633  heap_freetuple(tuple);
634 
635  /* record dependencies */
636  myself.classId = ForeignDataWrapperRelationId;
637  myself.objectId = fdwId;
638  myself.objectSubId = 0;
639 
640  if (OidIsValid(fdwhandler))
641  {
642  referenced.classId = ProcedureRelationId;
643  referenced.objectId = fdwhandler;
644  referenced.objectSubId = 0;
645  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
646  }
647 
648  if (OidIsValid(fdwvalidator))
649  {
650  referenced.classId = ProcedureRelationId;
651  referenced.objectId = fdwvalidator;
652  referenced.objectSubId = 0;
653  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
654  }
655 
656  recordDependencyOnOwner(ForeignDataWrapperRelationId, fdwId, ownerId);
657 
658  /* dependency on extension */
659  recordDependencyOnCurrentExtension(&myself, false);
660 
661  /* Post creation hook for new foreign data wrapper */
662  InvokeObjectPostCreateHook(ForeignDataWrapperRelationId, fdwId, 0);
663 
665 
666  return myself;
667 }
ForeignDataWrapper * GetForeignDataWrapperByName(const char *fdwname, bool missing_ok)
Definition: foreign.c:96
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
List * func_options
Definition: parsenodes.h:2573
char * fdwname
Definition: parsenodes.h:2572
List * options
Definition: parsenodes.h:2574

References CatalogTupleInsert(), ObjectAddress::classId, CStringGetDatum(), DatumGetPointer(), DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, CreateFdwStmt::fdwname, 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().

◆ CreateForeignServer()

ObjectAddress CreateForeignServer ( CreateForeignServerStmt stmt)

Definition at line 838 of file foreigncmds.c.

839 {
840  Relation rel;
841  Datum srvoptions;
842  Datum values[Natts_pg_foreign_server];
843  bool nulls[Natts_pg_foreign_server];
844  HeapTuple tuple;
845  Oid srvId;
846  Oid ownerId;
847  AclResult aclresult;
848  ObjectAddress myself;
849  ObjectAddress referenced;
850  ForeignDataWrapper *fdw;
851 
852  rel = table_open(ForeignServerRelationId, RowExclusiveLock);
853 
854  /* For now the owner cannot be specified on create. Use effective user ID. */
855  ownerId = GetUserId();
856 
857  /*
858  * Check that there is no other foreign server by this name. If there is
859  * one, do nothing if IF NOT EXISTS was specified.
860  */
861  srvId = get_foreign_server_oid(stmt->servername, true);
862  if (OidIsValid(srvId))
863  {
864  if (stmt->if_not_exists)
865  {
866  /*
867  * If we are in an extension script, insist that the pre-existing
868  * object be a member of the extension, to avoid security risks.
869  */
870  ObjectAddressSet(myself, ForeignServerRelationId, srvId);
872 
873  /* OK to skip */
874  ereport(NOTICE,
876  errmsg("server \"%s\" already exists, skipping",
877  stmt->servername)));
879  return InvalidObjectAddress;
880  }
881  else
882  ereport(ERROR,
884  errmsg("server \"%s\" already exists",
885  stmt->servername)));
886  }
887 
888  /*
889  * Check that the FDW exists and that we have USAGE on it. Also get the
890  * actual FDW for option validation etc.
891  */
892  fdw = GetForeignDataWrapperByName(stmt->fdwname, false);
893 
894  aclresult = object_aclcheck(ForeignDataWrapperRelationId, fdw->fdwid, ownerId, ACL_USAGE);
895  if (aclresult != ACLCHECK_OK)
896  aclcheck_error(aclresult, OBJECT_FDW, fdw->fdwname);
897 
898  /*
899  * Insert tuple into pg_foreign_server.
900  */
901  memset(values, 0, sizeof(values));
902  memset(nulls, false, sizeof(nulls));
903 
904  srvId = GetNewOidWithIndex(rel, ForeignServerOidIndexId,
905  Anum_pg_foreign_server_oid);
906  values[Anum_pg_foreign_server_oid - 1] = ObjectIdGetDatum(srvId);
907  values[Anum_pg_foreign_server_srvname - 1] =
909  values[Anum_pg_foreign_server_srvowner - 1] = ObjectIdGetDatum(ownerId);
910  values[Anum_pg_foreign_server_srvfdw - 1] = ObjectIdGetDatum(fdw->fdwid);
911 
912  /* Add server type if supplied */
913  if (stmt->servertype)
914  values[Anum_pg_foreign_server_srvtype - 1] =
916  else
917  nulls[Anum_pg_foreign_server_srvtype - 1] = true;
918 
919  /* Add server version if supplied */
920  if (stmt->version)
921  values[Anum_pg_foreign_server_srvversion - 1] =
923  else
924  nulls[Anum_pg_foreign_server_srvversion - 1] = true;
925 
926  /* Start with a blank acl */
927  nulls[Anum_pg_foreign_server_srvacl - 1] = true;
928 
929  /* Add server options */
930  srvoptions = transformGenericOptions(ForeignServerRelationId,
931  PointerGetDatum(NULL),
932  stmt->options,
933  fdw->fdwvalidator);
934 
935  if (PointerIsValid(DatumGetPointer(srvoptions)))
936  values[Anum_pg_foreign_server_srvoptions - 1] = srvoptions;
937  else
938  nulls[Anum_pg_foreign_server_srvoptions - 1] = true;
939 
940  tuple = heap_form_tuple(rel->rd_att, values, nulls);
941 
942  CatalogTupleInsert(rel, tuple);
943 
944  heap_freetuple(tuple);
945 
946  /* record dependencies */
947  myself.classId = ForeignServerRelationId;
948  myself.objectId = srvId;
949  myself.objectSubId = 0;
950 
951  referenced.classId = ForeignDataWrapperRelationId;
952  referenced.objectId = fdw->fdwid;
953  referenced.objectSubId = 0;
954  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
955 
956  recordDependencyOnOwner(ForeignServerRelationId, srvId, ownerId);
957 
958  /* dependency on extension */
959  recordDependencyOnCurrentExtension(&myself, false);
960 
961  /* Post creation hook for new foreign server */
962  InvokeObjectPostCreateHook(ForeignServerRelationId, srvId, 0);
963 
965 
966  return myself;
967 }
Oid get_foreign_server_oid(const char *servername, bool missing_ok)
Definition: foreign.c:690
@ OBJECT_FDW
Definition: parsenodes.h:1985
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition: pg_depend.c:257
char * fdwname
Definition: foreign.h:28

References ACL_USAGE, aclcheck_error(), ACLCHECK_OK, CatalogTupleInsert(), checkMembershipInCurrentExtension(), ObjectAddress::classId, CStringGetDatum(), CStringGetTextDatum, DatumGetPointer(), DEPENDENCY_NORMAL, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, ForeignDataWrapper::fdwid, ForeignDataWrapper::fdwname, CreateForeignServerStmt::fdwname, ForeignDataWrapper::fdwvalidator, get_foreign_server_oid(), GetForeignDataWrapperByName(), GetNewOidWithIndex(), GetUserId(), heap_form_tuple(), heap_freetuple(), CreateForeignServerStmt::if_not_exists, InvalidObjectAddress, InvokeObjectPostCreateHook, namein(), NOTICE, object_aclcheck(), OBJECT_FDW, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, OidIsValid, CreateForeignServerStmt::options, 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().

◆ CreateForeignTable()

void CreateForeignTable ( CreateForeignTableStmt stmt,
Oid  relid 
)

Definition at line 1404 of file foreigncmds.c.

1405 {
1406  Relation ftrel;
1407  Datum ftoptions;
1408  Datum values[Natts_pg_foreign_table];
1409  bool nulls[Natts_pg_foreign_table];
1410  HeapTuple tuple;
1411  AclResult aclresult;
1412  ObjectAddress myself;
1413  ObjectAddress referenced;
1414  Oid ownerId;
1415  ForeignDataWrapper *fdw;
1416  ForeignServer *server;
1417 
1418  /*
1419  * Advance command counter to ensure the pg_attribute tuple is visible;
1420  * the tuple might be updated to add constraints in previous step.
1421  */
1423 
1424  ftrel = table_open(ForeignTableRelationId, RowExclusiveLock);
1425 
1426  /*
1427  * For now the owner cannot be specified on create. Use effective user ID.
1428  */
1429  ownerId = GetUserId();
1430 
1431  /*
1432  * Check that the foreign server exists and that we have USAGE on it. Also
1433  * get the actual FDW for option validation etc.
1434  */
1435  server = GetForeignServerByName(stmt->servername, false);
1436  aclresult = object_aclcheck(ForeignServerRelationId, server->serverid, ownerId, ACL_USAGE);
1437  if (aclresult != ACLCHECK_OK)
1438  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
1439 
1440  fdw = GetForeignDataWrapper(server->fdwid);
1441 
1442  /*
1443  * Insert tuple into pg_foreign_table.
1444  */
1445  memset(values, 0, sizeof(values));
1446  memset(nulls, false, sizeof(nulls));
1447 
1448  values[Anum_pg_foreign_table_ftrelid - 1] = ObjectIdGetDatum(relid);
1449  values[Anum_pg_foreign_table_ftserver - 1] = ObjectIdGetDatum(server->serverid);
1450  /* Add table generic options */
1451  ftoptions = transformGenericOptions(ForeignTableRelationId,
1452  PointerGetDatum(NULL),
1453  stmt->options,
1454  fdw->fdwvalidator);
1455 
1456  if (PointerIsValid(DatumGetPointer(ftoptions)))
1457  values[Anum_pg_foreign_table_ftoptions - 1] = ftoptions;
1458  else
1459  nulls[Anum_pg_foreign_table_ftoptions - 1] = true;
1460 
1461  tuple = heap_form_tuple(ftrel->rd_att, values, nulls);
1462 
1463  CatalogTupleInsert(ftrel, tuple);
1464 
1465  heap_freetuple(tuple);
1466 
1467  /* Add pg_class dependency on the server */
1468  myself.classId = RelationRelationId;
1469  myself.objectId = relid;
1470  myself.objectSubId = 0;
1471 
1472  referenced.classId = ForeignServerRelationId;
1473  referenced.objectId = server->serverid;
1474  referenced.objectSubId = 0;
1475  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1476 
1477  table_close(ftrel, RowExclusiveLock);
1478 }
char * servername
Definition: foreign.h:39
void CommandCounterIncrement(void)
Definition: xact.c:1078

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_aclcheck(), OBJECT_FOREIGN_SERVER, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, CreateForeignTableStmt::options, PointerGetDatum(), PointerIsValid, RelationData::rd_att, recordDependencyOn(), RowExclusiveLock, ForeignServer::serverid, ForeignServer::servername, CreateForeignTableStmt::servername, table_close(), table_open(), transformGenericOptions(), and values.

Referenced by ProcessUtilitySlow().

◆ CreateFunction()

ObjectAddress CreateFunction ( ParseState pstate,
CreateFunctionStmt stmt 
)

Definition at line 1016 of file functioncmds.c.

1017 {
1018  char *probin_str;
1019  char *prosrc_str;
1020  Node *prosqlbody;
1021  Oid prorettype;
1022  bool returnsSet;
1023  char *language;
1024  Oid languageOid;
1025  Oid languageValidator;
1026  Node *transformDefElem = NULL;
1027  char *funcname;
1028  Oid namespaceId;
1029  AclResult aclresult;
1030  oidvector *parameterTypes;
1031  List *parameterTypes_list = NIL;
1032  ArrayType *allParameterTypes;
1033  ArrayType *parameterModes;
1034  ArrayType *parameterNames;
1035  List *inParameterNames_list = NIL;
1036  List *parameterDefaults;
1037  Oid variadicArgType;
1038  List *trftypes_list = NIL;
1039  ArrayType *trftypes;
1040  Oid requiredResultType;
1041  bool isWindowFunc,
1042  isStrict,
1043  security,
1044  isLeakProof;
1045  char volatility;
1046  ArrayType *proconfig;
1047  float4 procost;
1048  float4 prorows;
1049  Oid prosupport;
1050  HeapTuple languageTuple;
1051  Form_pg_language languageStruct;
1052  List *as_clause;
1053  char parallel;
1054 
1055  /* Convert list of names to a name and namespace */
1056  namespaceId = QualifiedNameGetCreationNamespace(stmt->funcname,
1057  &funcname);
1058 
1059  /* Check we have creation rights in target namespace */
1060  aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(), ACL_CREATE);
1061  if (aclresult != ACLCHECK_OK)
1062  aclcheck_error(aclresult, OBJECT_SCHEMA,
1063  get_namespace_name(namespaceId));
1064 
1065  /* Set default attributes */
1066  as_clause = NIL;
1067  language = NULL;
1068  isWindowFunc = false;
1069  isStrict = false;
1070  security = false;
1071  isLeakProof = false;
1072  volatility = PROVOLATILE_VOLATILE;
1073  proconfig = NULL;
1074  procost = -1; /* indicates not set */
1075  prorows = -1; /* indicates not set */
1076  prosupport = InvalidOid;
1077  parallel = PROPARALLEL_UNSAFE;
1078 
1079  /* Extract non-default attributes from stmt->options list */
1081  stmt->is_procedure,
1082  stmt->options,
1083  &as_clause, &language, &transformDefElem,
1084  &isWindowFunc, &volatility,
1085  &isStrict, &security, &isLeakProof,
1086  &proconfig, &procost, &prorows,
1087  &prosupport, &parallel);
1088 
1089  if (!language)
1090  {
1091  if (stmt->sql_body)
1092  language = "sql";
1093  else
1094  ereport(ERROR,
1095  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1096  errmsg("no language specified")));
1097  }
1098 
1099  /* Look up the language and validate permissions */
1100  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
1101  if (!HeapTupleIsValid(languageTuple))
1102  ereport(ERROR,
1103  (errcode(ERRCODE_UNDEFINED_OBJECT),
1104  errmsg("language \"%s\" does not exist", language),
1105  (extension_file_exists(language) ?
1106  errhint("Use CREATE EXTENSION to load the language into the database.") : 0)));
1107 
1108  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
1109  languageOid = languageStruct->oid;
1110 
1111  if (languageStruct->lanpltrusted)
1112  {
1113  /* if trusted language, need USAGE privilege */
1114  aclresult = object_aclcheck(LanguageRelationId, languageOid, GetUserId(), ACL_USAGE);
1115  if (aclresult != ACLCHECK_OK)
1116  aclcheck_error(aclresult, OBJECT_LANGUAGE,
1117  NameStr(languageStruct->lanname));
1118  }
1119  else
1120  {
1121  /* if untrusted language, must be superuser */
1122  if (!superuser())
1124  NameStr(languageStruct->lanname));
1125  }
1126 
1127  languageValidator = languageStruct->lanvalidator;
1128 
1129  ReleaseSysCache(languageTuple);
1130 
1131  /*
1132  * Only superuser is allowed to create leakproof functions because
1133  * leakproof functions can see tuples which have not yet been filtered out
1134  * by security barrier views or row-level security policies.
1135  */
1136  if (isLeakProof && !superuser())
1137  ereport(ERROR,
1138  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1139  errmsg("only superuser can define a leakproof function")));
1140 
1141  if (transformDefElem)
1142  {
1143  ListCell *lc;
1144 
1145  foreach(lc, castNode(List, transformDefElem))
1146  {
1147  Oid typeid = typenameTypeId(NULL,
1148  lfirst_node(TypeName, lc));
1149  Oid elt = get_base_element_type(typeid);
1150 
1151  typeid = elt ? elt : typeid;
1152 
1153  get_transform_oid(typeid, languageOid, false);
1154  trftypes_list = lappend_oid(trftypes_list, typeid);
1155  }
1156  }
1157 
1158  /*
1159  * Convert remaining parameters of CREATE to form wanted by
1160  * ProcedureCreate.
1161  */
1163  stmt->parameters,
1164  languageOid,
1166  &parameterTypes,
1167  &parameterTypes_list,
1168  &allParameterTypes,
1169  &parameterModes,
1170  &parameterNames,
1171  &inParameterNames_list,
1172  &parameterDefaults,
1173  &variadicArgType,
1174  &requiredResultType);
1175 
1176  if (stmt->is_procedure)
1177  {
1178  Assert(!stmt->returnType);
1179  prorettype = requiredResultType ? requiredResultType : VOIDOID;
1180  returnsSet = false;
1181  }
1182  else if (stmt->returnType)
1183  {
1184  /* explicit RETURNS clause */
1185  compute_return_type(stmt->returnType, languageOid,
1186  &prorettype, &returnsSet);
1187  if (OidIsValid(requiredResultType) && prorettype != requiredResultType)
1188  ereport(ERROR,
1189  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1190  errmsg("function result type must be %s because of OUT parameters",
1191  format_type_be(requiredResultType))));
1192  }
1193  else if (OidIsValid(requiredResultType))
1194  {
1195  /* default RETURNS clause from OUT parameters */
1196  prorettype = requiredResultType;
1197  returnsSet = false;
1198  }
1199  else
1200  {
1201  ereport(ERROR,
1202  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1203  errmsg("function result type must be specified")));
1204  /* Alternative possibility: default to RETURNS VOID */
1205  prorettype = VOIDOID;
1206  returnsSet = false;
1207  }
1208 
1209  if (trftypes_list != NIL)
1210  {
1211  ListCell *lc;
1212  Datum *arr;
1213  int i;
1214 
1215  arr = palloc(list_length(trftypes_list) * sizeof(Datum));
1216  i = 0;
1217  foreach(lc, trftypes_list)
1218  arr[i++] = ObjectIdGetDatum(lfirst_oid(lc));
1219  trftypes = construct_array_builtin(arr, list_length(trftypes_list), OIDOID);
1220  }
1221  else
1222  {
1223  /* store SQL NULL instead of empty array */
1224  trftypes = NULL;
1225  }
1226 
1227  interpret_AS_clause(languageOid, language, funcname, as_clause, stmt->sql_body,
1228  parameterTypes_list, inParameterNames_list,
1229  &prosrc_str, &probin_str, &prosqlbody,
1230  pstate->p_sourcetext);
1231 
1232  /*
1233  * Set default values for COST and ROWS depending on other parameters;
1234  * reject ROWS if it's not returnsSet. NB: pg_dump knows these default
1235  * values, keep it in sync if you change them.
1236  */
1237  if (procost < 0)
1238  {
1239  /* SQL and PL-language functions are assumed more expensive */
1240  if (languageOid == INTERNALlanguageId ||
1241  languageOid == ClanguageId)
1242  procost = 1;
1243  else
1244  procost = 100;
1245  }
1246  if (prorows < 0)
1247  {
1248  if (returnsSet)
1249  prorows = 1000;
1250  else
1251  prorows = 0; /* dummy value if not returnsSet */
1252  }
1253  else if (!returnsSet)
1254  ereport(ERROR,
1255  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1256  errmsg("ROWS is not applicable when function does not return a set")));
1257 
1258  /*
1259  * And now that we have all the parameters, and know we're permitted to do
1260  * so, go ahead and create the function.
1261  */
1262  return ProcedureCreate(funcname,
1263  namespaceId,
1264  stmt->replace,
1265  returnsSet,
1266  prorettype,
1267  GetUserId(),
1268  languageOid,
1269  languageValidator,
1270  prosrc_str, /* converted to text later */
1271  probin_str, /* converted to text later */
1272  prosqlbody,
1273  stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
1274  security,
1275  isLeakProof,
1276  isStrict,
1277  volatility,
1278  parallel,
1279  parameterTypes,
1280  PointerGetDatum(allParameterTypes),
1281  PointerGetDatum(parameterModes),
1282  PointerGetDatum(parameterNames),
1283  parameterDefaults,
1284  PointerGetDatum(trftypes),
1285  PointerGetDatum(proconfig),
1286  prosupport,
1287  procost,
1288  prorows);
1289 }
@ ACLCHECK_NO_PRIV
Definition: acl.h:184
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3363
float float4
Definition: c.h:613
bool extension_file_exists(const char *extensionName)
Definition: extension.c:2196
static void compute_return_type(TypeName *returnType, Oid languageOid, Oid *prorettype_p, bool *returnsSet_p)
Definition: functioncmds.c:93
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:719
void interpret_function_parameter_list(ParseState *pstate, List *parameters, Oid languageOid, ObjectType objtype, oidvector **parameterTypes, List **parameterTypes_list, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **inParameterNames_list, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:188
static void interpret_AS_clause(Oid languageOid, const char *languageName, char *funcname, List *as, Node *sql_body_in, List *parameterTypes, List *inParameterNames, char **prosrc_str_p, char **probin_str_p, Node **sql_body_out, const char *queryString)
Definition: functioncmds.c:856
Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2790
void * palloc(Size size)
Definition: mcxt.c:1210
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:3038
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
@ OBJECT_SCHEMA
Definition: parsenodes.h:2005
@ OBJECT_PROCEDURE
Definition: parsenodes.h:1998
@ OBJECT_LANGUAGE
Definition: parsenodes.h:1990
#define ACL_CREATE
Definition: parsenodes.h:92
FormData_pg_language * Form_pg_language
Definition: pg_language.h:65
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define lfirst_oid(lc)
Definition: pg_list.h:174
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, Node *prosqlbody, 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:72
TypeName * returnType
Definition: parsenodes.h:3154
Definition: nodes.h:129
const char * p_sourcetext
Definition: parse_node.h:192
@ LANGNAME
Definition: syscache.h:67

References ACL_CREATE, ACL_USAGE, aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_OK, Assert(), castNode, compute_function_attributes(), compute_return_type(), construct_array_builtin(), 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_aclcheck(), OBJECT_FUNCTION, OBJECT_LANGUAGE, OBJECT_PROCEDURE, OBJECT_SCHEMA, ObjectIdGetDatum(), OidIsValid, CreateFunctionStmt::options, ParseState::p_sourcetext, palloc(), CreateFunctionStmt::parameters, PointerGetDatum(), ProcedureCreate(), QualifiedNameGetCreationNamespace(), ReleaseSysCache(), CreateFunctionStmt::replace, CreateFunctionStmt::returnType, SearchSysCache1(), CreateFunctionStmt::sql_body, superuser(), and typenameTypeId().

Referenced by ProcessUtilitySlow().

◆ CreateStatistics()

ObjectAddress CreateStatistics ( CreateStatsStmt stmt)

Definition at line 65 of file statscmds.c.

66 {
67  int16 attnums[STATS_MAX_DIMENSIONS];
68  int nattnums = 0;
69  int numcols;
70  char *namestr;
71  NameData stxname;
72  Oid statoid;
73  Oid namespaceId;
74  Oid stxowner = GetUserId();
75  HeapTuple htup;
76  Datum values[Natts_pg_statistic_ext];
77  bool nulls[Natts_pg_statistic_ext];
78  int2vector *stxkeys;
79  List *stxexprs = NIL;
80  Datum exprsDatum;
81  Relation statrel;
82  Relation rel = NULL;
83  Oid relid;
84  ObjectAddress parentobject,
85  myself;
86  Datum types[4]; /* one for each possible type of statistic */
87  int ntypes;
88  ArrayType *stxkind;
89  bool build_ndistinct;
90  bool build_dependencies;
91  bool build_mcv;
92  bool build_expressions;
93  bool requested_type = false;
94  int i;
95  ListCell *cell;
96  ListCell *cell2;
97 
98  Assert(IsA(stmt, CreateStatsStmt));
99 
100  /*
101  * Examine the FROM clause. Currently, we only allow it to be a single
102  * simple table, but later we'll probably allow multiple tables and JOIN
103  * syntax. The grammar is already prepared for that, so we have to check
104  * here that what we got is what we can support.
105  */
106  if (list_length(stmt->relations) != 1)
107  ereport(ERROR,
108  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
109  errmsg("only a single relation is allowed in CREATE STATISTICS")));
110 
111  foreach(cell, stmt->relations)
112  {
113  Node *rln = (Node *) lfirst(cell);
114 
115  if (!IsA(rln, RangeVar))
116  ereport(ERROR,
117  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
118  errmsg("only a single relation is allowed in CREATE STATISTICS")));
119 
120  /*
121  * CREATE STATISTICS will influence future execution plans but does
122  * not interfere with currently executing plans. So it should be
123  * enough to take only ShareUpdateExclusiveLock on relation,
124  * conflicting with ANALYZE and other DDL that sets statistical
125  * information, but not with normal queries.
126  */
128 
129  /* Restrict to allowed relation types */
130  if (rel->rd_rel->relkind != RELKIND_RELATION &&
131  rel->rd_rel->relkind != RELKIND_MATVIEW &&
132  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
133  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
134  ereport(ERROR,
135  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
136  errmsg("cannot define statistics for relation \"%s\"",
138  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
139 
140  /* You must own the relation to create stats on it */
141  if (!object_ownercheck(RelationRelationId, RelationGetRelid(rel), stxowner))
144 
145  /* Creating statistics on system catalogs is not allowed */
147  ereport(ERROR,
148  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
149  errmsg("permission denied: \"%s\" is a system catalog",
150  RelationGetRelationName(rel))));
151  }
152 
153  Assert(rel);
154  relid = RelationGetRelid(rel);
155 
156  /*
157  * If the node has a name, split it up and determine creation namespace.
158  * If not, put the object in the same namespace as the relation, and cons
159  * up a name for it. (This can happen either via "CREATE STATISTICS ..."
160  * or via "CREATE TABLE ... (LIKE)".)
161  */
162  if (stmt->defnames)
163  namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,
164  &namestr);
165  else
166  {
167  namespaceId = RelationGetNamespace(rel);
170  "stat",
171  namespaceId);
172  }
173  namestrcpy(&stxname, namestr);
174 
175  /*
176  * Deal with the possibility that the statistics object already exists.
177  */
179  CStringGetDatum(namestr),
180  ObjectIdGetDatum(namespaceId)))
181  {
182  if (stmt->if_not_exists)
183  {
184  /*
185  * Since stats objects aren't members of extensions (see comments
186  * below), no need for checkMembershipInCurrentExtension here.
187  */
188  ereport(NOTICE,
190  errmsg("statistics object \"%s\" already exists, skipping",
191  namestr)));
192  relation_close(rel, NoLock);
193  return InvalidObjectAddress;
194  }
195 
196  ereport(ERROR,
198  errmsg("statistics object \"%s\" already exists", namestr)));
199  }
200 
201  /*
202  * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There
203  * might be duplicates and so on, but we'll deal with those later.
204  */
205  numcols = list_length(stmt->exprs);
206  if (numcols > STATS_MAX_DIMENSIONS)
207  ereport(ERROR,
208  (errcode(ERRCODE_TOO_MANY_COLUMNS),
209  errmsg("cannot have more than %d columns in statistics",
211 
212  /*
213  * Convert the expression list to a simple array of attnums, but also keep
214  * a list of more complex expressions. While at it, enforce some
215  * constraints - we don't allow extended statistics on system attributes,
216  * and we require the data type to have a less-than operator.
217  *
218  * There are many ways to "mask" a simple attribute reference as an
219  * expression, for example "(a+0)" etc. We can't possibly detect all of
220  * them, but we handle at least the simple case with the attribute in
221  * parens. There'll always be a way around this, if the user is determined
222  * (like the "(a+0)" example), but this makes it somewhat consistent with
223  * how indexes treat attributes/expressions.
224  */
225  foreach(cell, stmt->exprs)
226  {
227  StatsElem *selem = lfirst_node(StatsElem, cell);
228 
229  if (selem->name) /* column reference */
230  {
231  char *attname;
232  HeapTuple atttuple;
233  Form_pg_attribute attForm;
235 
236  attname = selem->name;
237 
238  atttuple = SearchSysCacheAttName(relid, attname);
239  if (!HeapTupleIsValid(atttuple))
240  ereport(ERROR,
241  (errcode(ERRCODE_UNDEFINED_COLUMN),
242  errmsg("column \"%s\" does not exist",
243  attname)));
244  attForm = (Form_pg_attribute) GETSTRUCT(atttuple);
245 
246  /* Disallow use of system attributes in extended stats */
247  if (attForm->attnum <= 0)
248  ereport(ERROR,
249  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
250  errmsg("statistics creation on system columns is not supported")));
251 
252  /* Disallow data types without a less-than operator */
253  type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
254  if (type->lt_opr == InvalidOid)
255  ereport(ERROR,
256  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
257  errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
258  attname, format_type_be(attForm->atttypid))));
259 
260  attnums[nattnums] = attForm->attnum;
261  nattnums++;
262  ReleaseSysCache(atttuple);
263  }
264  else if (IsA(selem->expr, Var)) /* column reference in parens */
265  {
266  Var *var = (Var *) selem->expr;
268 
269  /* Disallow use of system attributes in extended stats */
270  if (var->varattno <= 0)
271  ereport(ERROR,
272  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
273  errmsg("statistics creation on system columns is not supported")));
274 
275  /* Disallow data types without a less-than operator */
276  type = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR);
277  if (type->lt_opr == InvalidOid)
278  ereport(ERROR,
279  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
280  errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
281  get_attname(relid, var->varattno, false), format_type_be(var->vartype))));
282 
283  attnums[nattnums] = var->varattno;
284  nattnums++;
285  }
286  else /* expression */
287  {
288  Node *expr = selem->expr;
289  Oid atttype;
291  Bitmapset *attnums = NULL;
292  int k;
293 
294  Assert(expr != NULL);
295 
296  /* Disallow expressions referencing system attributes. */
297  pull_varattnos(expr, 1, &attnums);
298 
299  k = -1;
300  while ((k = bms_next_member(attnums, k)) >= 0)
301  {
303 
304  if (attnum <= 0)
305  ereport(ERROR,
306  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
307  errmsg("statistics creation on system columns is not supported")));
308  }
309 
310  /*
311  * Disallow data types without a less-than operator.
312  *
313  * We ignore this for statistics on a single expression, in which
314  * case we'll build the regular statistics only (and that code can
315  * deal with such data types).
316  */
317  if (list_length(stmt->exprs) > 1)
318  {
319  atttype = exprType(expr);
321  if (type->lt_opr == InvalidOid)
322  ereport(ERROR,
323  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
324  errmsg("expression cannot be used in multivariate statistics because its type %s has no default btree operator class",
325  format_type_be(atttype))));
326  }
327 
328  stxexprs = lappend(stxexprs, expr);
329  }
330  }
331 
332  /*
333  * Parse the statistics kinds.
334  *
335  * First check that if this is the case with a single expression, there
336  * are no statistics kinds specified (we don't allow that for the simple
337  * CREATE STATISTICS form).
338  */
339  if ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1))
340  {
341  /* statistics kinds not specified */
342  if (stmt->stat_types != NIL)
343  ereport(ERROR,
344  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
345  errmsg("when building statistics on a single expression, statistics kinds may not be specified")));
346  }
347 
348  /* OK, let's check that we recognize the statistics kinds. */
349  build_ndistinct = false;
350  build_dependencies = false;
351  build_mcv = false;
352  foreach(cell, stmt->stat_types)
353  {
354  char *type = strVal(lfirst(cell));
355 
356  if (strcmp(type, "ndistinct") == 0)
357  {
358  build_ndistinct = true;
359  requested_type = true;
360  }
361  else if (strcmp(type, "dependencies") == 0)
362  {
363  build_dependencies = true;
364  requested_type = true;
365  }
366  else if (strcmp(type, "mcv") == 0)
367  {
368  build_mcv = true;
369  requested_type = true;
370  }
371  else
372  ereport(ERROR,
373  (errcode(ERRCODE_SYNTAX_ERROR),
374  errmsg("unrecognized statistics kind \"%s\"",
375  type)));
376  }
377 
378  /*
379  * If no statistic type was specified, build them all (but only when the
380  * statistics is defined on more than one column/expression).
381  */
382  if ((!requested_type) && (numcols >= 2))
383  {
384  build_ndistinct = true;
385  build_dependencies = true;
386  build_mcv = true;
387  }
388 
389  /*
390  * When there are non-trivial expressions, build the expression stats
391  * automatically. This allows calculating good estimates for stats that
392  * consider per-clause estimates (e.g. functional dependencies).
393  */
394  build_expressions = (stxexprs != NIL);
395 
396  /*
397  * Check that at least two columns were specified in the statement, or
398  * that we're building statistics on a single expression.
399  */
400  if ((numcols < 2) && (list_length(stxexprs) != 1))
401  ereport(ERROR,
402  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
403  errmsg("extended statistics require at least 2 columns")));
404 
405  /*
406  * Sort the attnums, which makes detecting duplicates somewhat easier, and
407  * it does not hurt (it does not matter for the contents, unlike for
408  * indexes, for example).
409  */
410  qsort(attnums, nattnums, sizeof(int16), compare_int16);
411 
412  /*
413  * Check for duplicates in the list of columns. The attnums are sorted so
414  * just check consecutive elements.
415  */
416  for (i = 1; i < nattnums; i++)
417  {
418  if (attnums[i] == attnums[i - 1])
419  ereport(ERROR,
420  (errcode(ERRCODE_DUPLICATE_COLUMN),
421  errmsg("duplicate column name in statistics definition")));
422  }
423 
424  /*
425  * Check for duplicate expressions. We do two loops, counting the
426  * occurrences of each expression. This is O(N^2) but we only allow small
427  * number of expressions and it's not executed often.
428  *
429  * XXX We don't cross-check attributes and expressions, because it does
430  * not seem worth it. In principle we could check that expressions don't
431  * contain trivial attribute references like "(a)", but the reasoning is
432  * similar to why we don't bother with extracting columns from
433  * expressions. It's either expensive or very easy to defeat for
434  * determined user, and there's no risk if we allow such statistics (the
435  * statistics is useless, but harmless).
436  */
437  foreach(cell, stxexprs)
438  {
439  Node *expr1 = (Node *) lfirst(cell);
440  int cnt = 0;
441 
442  foreach(cell2, stxexprs)
443  {
444  Node *expr2 = (Node *) lfirst(cell2);
445 
446  if (equal(expr1, expr2))
447  cnt += 1;
448  }
449 
450  /* every expression should find at least itself */
451  Assert(cnt >= 1);
452 
453  if (cnt > 1)
454  ereport(ERROR,
455  (errcode(ERRCODE_DUPLICATE_COLUMN),
456  errmsg("duplicate expression in statistics definition")));
457  }
458 
459  /* Form an int2vector representation of the sorted column list */
460  stxkeys = buildint2vector(attnums, nattnums);
461 
462  /* construct the char array of enabled statistic types */
463  ntypes = 0;
464  if (build_ndistinct)
465  types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);
466  if (build_dependencies)
467  types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);
468  if (build_mcv)
469  types[ntypes++] = CharGetDatum(STATS_EXT_MCV);
470  if (build_expressions)
471  types[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS);
472  Assert(ntypes > 0 && ntypes <= lengthof(types));
473  stxkind = construct_array_builtin(types, ntypes, CHAROID);
474 
475  /* convert the expressions (if any) to a text datum */
476  if (stxexprs != NIL)
477  {
478  char *exprsString;
479 
480  exprsString = nodeToString(stxexprs);
481  exprsDatum = CStringGetTextDatum(exprsString);
482  pfree(exprsString);
483  }
484  else
485  exprsDatum = (Datum) 0;
486 
487  statrel = table_open(StatisticExtRelationId, RowExclusiveLock);
488 
489  /*
490  * Everything seems fine, so let's build the pg_statistic_ext tuple.
491  */
492  memset(values, 0, sizeof(values));
493  memset(nulls, false, sizeof(nulls));
494 
495  statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,
496  Anum_pg_statistic_ext_oid);
497  values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);
498  values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);
499  values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);
500  values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
501  values[Anum_pg_statistic_ext_stxstattarget - 1] = Int32GetDatum(-1);
502  values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
503  values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
504  values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);
505 
506  values[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum;
507  if (exprsDatum == (Datum) 0)
508  nulls[Anum_pg_statistic_ext_stxexprs - 1] = true;
509 
510  /* insert it into pg_statistic_ext */
511  htup = heap_form_tuple(statrel->rd_att, values, nulls);
512  CatalogTupleInsert(statrel, htup);
513  heap_freetuple(htup);
514 
516 
517  /*
518  * We used to create the pg_statistic_ext_data tuple too, but it's not
519  * clear what value should the stxdinherit flag have (it depends on
520  * whether the rel is partitioned, contains data, etc.)
521  */
522 
523  InvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0);
524 
525  /*
526  * Invalidate relcache so that others see the new statistics object.
527  */
529 
530  relation_close(rel, NoLock);
531 
532  /*
533  * Add an AUTO dependency on each column used in the stats, so that the
534  * stats object goes away if any or all of them get dropped.
535  */
536  ObjectAddressSet(myself, StatisticExtRelationId, statoid);
537 
538  /* add dependencies for plain column references */
539  for (i = 0; i < nattnums; i++)
540  {
541  ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
542  recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
543  }
544 
545  /*
546  * If there are no dependencies on a column, give the statistics object an
547  * auto dependency on the whole table. In most cases, this will be
548  * redundant, but it might not be if the statistics expressions contain no
549  * Vars (which might seem strange but possible). This is consistent with
550  * what we do for indexes in index_create.
551  *
552  * XXX We intentionally don't consider the expressions before adding this
553  * dependency, because recordDependencyOnSingleRelExpr may not create any
554  * dependencies for whole-row Vars.
555  */
556  if (!nattnums)
557  {
558  ObjectAddressSet(parentobject, RelationRelationId, relid);
559  recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
560  }
561 
562  /*
563  * Store dependencies on anything mentioned in statistics expressions,
564  * just like we do for index expressions.
565  */
566  if (stxexprs)
568  (Node *) stxexprs,
569  relid,
571  DEPENDENCY_AUTO, false);
572 
573  /*
574  * Also add dependencies on namespace and owner. These are required
575  * because the stats object might have a different namespace and/or owner
576  * than the underlying table(s).
577  */
578  ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
579  recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);
580 
581  recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);
582 
583  /*
584  * XXX probably there should be a recordDependencyOnCurrentExtension call
585  * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
586  * STATISTICS, which is more work than it seems worth.
587  */
588 
589  /* Add any requested comment */
590  if (stmt->stxcomment != NULL)
591  CreateComments(statoid, StatisticExtRelationId, 0,
592  stmt->stxcomment);
593 
594  /* Return stats object's address */
595  return myself;
596 }
int16 AttrNumber
Definition: attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
#define lengthof(array)
Definition: c.h:772
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
void CreateComments(Oid oid, Oid classoid, int32 subid, const char *comment)
Definition: comment.c:143
void recordDependencyOnSingleRelExpr(const ObjectAddress *depender, Node *expr, Oid relId, DependencyType behavior, DependencyType self_behavior, bool reverse_self)
Definition: dependency.c:1645
@ DEPENDENCY_AUTO
Definition: dependency.h:34
struct typedefs * types
Definition: ecpg.c:29
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
bool allowSystemTableMods
Definition: globals.c:124
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1363
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:826
void namestrcpy(Name name, const char *str)
Definition: name.c:233
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
ObjectType get_relkind_objtype(char relkind)
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
Definition: objectaddress.h:33
char * nodeToString(const void *obj)
Definition: outfuncs.c:877
NameData attname
Definition: pg_attribute.h:41
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define qsort(a, b, c, d)
Definition: port.h:445
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:373
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RelationGetNamespace(relation)
Definition: rel.h:542
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
static char * ChooseExtendedStatisticNameAddition(List *exprs)
Definition: statscmds.c:831
static char * ChooseExtendedStatisticName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: statscmds.c:789
static int compare_int16(const void *a, const void *b)
Definition: statscmds.c:52
Form_pg_class rd_rel
Definition: rel.h:110
char * name
Definition: parsenodes.h:3126
Node * expr
Definition: parsenodes.h:3127
Definition: primnodes.h:223
AttrNumber varattno
Definition: primnodes.h:235
Definition: c.h:699
Definition: c.h:725
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
Definition: syscache.c:958
@ STATEXTNAMENSP
Definition: syscache.h:95
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:190
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339
#define TYPECACHE_LT_OPR
Definition: typcache.h:137
#define strVal(v)
Definition: value.h:82
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:291

References aclcheck_error(), ACLCHECK_NOT_OWNER, allowSystemTableMods, Assert(), attname, attnum, bms_next_member(), buildint2vector(), CacheInvalidateRelcache(), CatalogTupleInsert(), CharGetDatum(), ChooseExtendedStatisticName(), ChooseExtendedStatisticNameAddition(), compare_int16(), construct_array_builtin(), CreateComments(), CStringGetDatum(), CStringGetTextDatum, CreateStatsStmt::defnames, DEPENDENCY_AUTO, DEPENDENCY_NORMAL, equal(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail_relkind_not_supported(), errmsg(), ERROR, StatsElem::expr, CreateStatsStmt::exprs, exprType(), FirstLowInvalidHeapAttributeNumber, format_type_be(), get_attname(), get_relkind_objtype(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), heap_form_tuple(), heap_freetuple(), HeapTupleIsValid, i, if(), CreateStatsStmt::if_not_exists, Int32GetDatum(), InvalidObjectAddress, InvalidOid, InvokeObjectPostCreateHook, IsA, IsSystemRelation(), lappend(), lengthof, lfirst, lfirst_node, list_length(), lookup_type_cache(), StatsElem::name, NameGetDatum(), namestrcpy(), NIL, nodeToString(), NoLock, NOTICE, object_ownercheck(), ObjectAddressSet, ObjectAddressSubSet, ObjectIdGetDatum(), pfree(), PointerGetDatum(), pull_varattnos(), qsort, QualifiedNameGetCreationNamespace(), RelationData::rd_att, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnOwner(), recordDependencyOnSingleRelExpr(), relation_close(), relation_openrv(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, CreateStatsStmt::relations, ReleaseSysCache(), RowExclusiveLock, SearchSysCacheAttName(), SearchSysCacheExists2, ShareUpdateExclusiveLock, CreateStatsStmt::stat_types, STATEXTNAMENSP, STATS_MAX_DIMENSIONS, strVal, CreateStatsStmt::stxcomment, table_open(), generate_unaccent_rules::type, TYPECACHE_LT_OPR, types, values, and Var::varattno.

Referenced by ATExecAddStatistics(), and ProcessUtilitySlow().

◆ CreateTransform()

ObjectAddress CreateTransform ( CreateTransformStmt stmt)

Definition at line 1802 of file functioncmds.c.

1803 {
1804  Oid typeid;
1805  char typtype;
1806  Oid langid;
1807  Oid fromsqlfuncid;
1808  Oid tosqlfuncid;
1809  AclResult aclresult;
1810  Form_pg_proc procstruct;
1811  Datum values[Natts_pg_transform];
1812  bool nulls[Natts_pg_transform] = {0};
1813  bool replaces[Natts_pg_transform] = {0};
1814  Oid transformid;
1815  HeapTuple tuple;
1816  HeapTuple newtuple;
1817  Relation relation;
1818  ObjectAddress myself,
1819  referenced;
1820  ObjectAddresses *addrs;
1821  bool is_replace;
1822 
1823  /*
1824  * Get the type
1825  */
1826  typeid = typenameTypeId(NULL, stmt->type_name);
1827  typtype = get_typtype(typeid);
1828 
1829  if (typtype == TYPTYPE_PSEUDO)
1830  ereport(ERROR,
1831  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1832  errmsg("data type %s is a pseudo-type",
1833  TypeNameToString(stmt->type_name))));
1834 
1835  if (typtype == TYPTYPE_DOMAIN)
1836  ereport(ERROR,
1837  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1838  errmsg("data type %s is a domain",
1839  TypeNameToString(stmt->type_name))));
1840 
1841  if (!object_ownercheck(TypeRelationId, typeid, GetUserId()))
1843 
1844  aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
1845  if (aclresult != ACLCHECK_OK)
1846  aclcheck_error_type(aclresult, typeid);
1847 
1848  /*
1849  * Get the language
1850  */
1851  langid = get_language_oid(stmt->lang, false);
1852 
1853  aclresult = object_aclcheck(LanguageRelationId, langid, GetUserId(), ACL_USAGE);
1854  if (aclresult != ACLCHECK_OK)
1855  aclcheck_error(aclresult, OBJECT_LANGUAGE, stmt->lang);
1856 
1857  /*
1858  * Get the functions
1859  */
1860  if (stmt->fromsql)
1861  {
1862  fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
1863 
1864  if (!object_ownercheck(ProcedureRelationId, fromsqlfuncid, GetUserId()))
1866 
1867  aclresult = object_aclcheck(ProcedureRelationId, fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1868  if (aclresult != ACLCHECK_OK)
1870 
1871  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1872  if (!HeapTupleIsValid(tuple))
1873  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1874  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1875  if (procstruct->prorettype != INTERNALOID)
1876  ereport(ERROR,
1877  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1878  errmsg("return data type of FROM SQL function must be %s",
1879  "internal")));
1880  check_transform_function(procstruct);
1881  ReleaseSysCache(tuple);
1882  }
1883  else
1884  fromsqlfuncid = InvalidOid;
1885 
1886  if (stmt->tosql)
1887  {
1888  tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
1889 
1890  if (!object_ownercheck(ProcedureRelationId, tosqlfuncid, GetUserId()))
1892 
1893  aclresult = object_aclcheck(ProcedureRelationId, tosqlfuncid, GetUserId(), ACL_EXECUTE);
1894  if (aclresult != ACLCHECK_OK)
1896 
1897  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1898  if (!HeapTupleIsValid(tuple))
1899  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1900  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1901  if (procstruct->prorettype != typeid)
1902  ereport(ERROR,
1903  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1904  errmsg("return data type of TO SQL function must be the transform data type")));
1905  check_transform_function(procstruct);
1906  ReleaseSysCache(tuple);
1907  }
1908  else
1909  tosqlfuncid = InvalidOid;
1910 
1911  /*
1912  * Ready to go
1913  */
1914  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1915  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1916  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1917  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1918 
1919  relation = table_open(TransformRelationId, RowExclusiveLock);
1920 
1921  tuple = SearchSysCache2(TRFTYPELANG,
1922  ObjectIdGetDatum(typeid),
1923  ObjectIdGetDatum(langid));
1924  if (HeapTupleIsValid(tuple))
1925  {
1927 
1928  if (!stmt->replace)
1929  ereport(ERROR,
1931  errmsg("transform for type %s language \"%s\" already exists",
1932  format_type_be(typeid),
1933  stmt->lang)));
1934 
1935  replaces[Anum_pg_transform_trffromsql - 1] = true;
1936  replaces[Anum_pg_transform_trftosql - 1] = true;
1937 
1938  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1939  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
1940 
1941  transformid = form->oid;
1942  ReleaseSysCache(tuple);
1943  is_replace = true;
1944  }
1945  else
1946  {
1947  transformid = GetNewOidWithIndex(relation, TransformOidIndexId,
1948  Anum_pg_transform_oid);
1949  values[Anum_pg_transform_oid - 1] = ObjectIdGetDatum(transformid);
1950  newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1951  CatalogTupleInsert(relation, newtuple);
1952  is_replace = false;
1953  }
1954 
1955  if (is_replace)
1956  deleteDependencyRecordsFor(TransformRelationId, transformid, true);
1957 
1958  addrs = new_object_addresses();
1959 
1960  /* make dependency entries */
1961  ObjectAddressSet(myself, TransformRelationId, transformid);
1962 
1963  /* dependency on language */
1964  ObjectAddressSet(referenced, LanguageRelationId, langid);
1965  add_exact_object_address(&referenced, addrs);
1966 
1967  /* dependency on type */
1968  ObjectAddressSet(referenced, TypeRelationId, typeid);
1969  add_exact_object_address(&referenced, addrs);
1970 
1971  /* dependencies on functions */
1972  if (OidIsValid(fromsqlfuncid))
1973  {
1974  ObjectAddressSet(referenced, ProcedureRelationId, fromsqlfuncid);
1975  add_exact_object_address(&referenced, addrs);
1976  }
1977  if (OidIsValid(tosqlfuncid))
1978  {
1979  ObjectAddressSet(referenced, ProcedureRelationId, tosqlfuncid);
1980  add_exact_object_address(&referenced, addrs);
1981  }
1982 
1984  free_object_addresses(addrs);
1985 
1986  /* dependency on extension */
1987  recordDependencyOnCurrentExtension(&myself, is_replace);
1988 
1989  /* Post creation hook for new transform */
1990  InvokeObjectPostCreateHook(TransformRelationId, transformid, 0);
1991 
1992  heap_freetuple(newtuple);
1993 
1994  table_close(relation, RowExclusiveLock);
1995 
1996  return myself;
1997 }
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2790
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2532
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2581
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2821
static void check_transform_function(Form_pg_proc procstruct)
#define ACL_EXECUTE
Definition: parsenodes.h:90
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:300
FormData_pg_transform * Form_pg_transform
Definition: pg_transform.h:43
Oid get_language_oid(const char *langname, bool missing_ok)
Definition: proclang.c:228
ObjectWithArgs * tosql
Definition: parsenodes.h:3734
TypeName * type_name
Definition: parsenodes.h:3731
ObjectWithArgs * fromsql
Definition: parsenodes.h:3733
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:828
@ TRFTYPELANG
Definition: syscache.h:103

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(), NameListToString(), new_object_addresses(), object_aclcheck(), OBJECT_FUNCTION, OBJECT_LANGUAGE, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), ObjectWithArgs::objname, OidIsValid, PROCOID, record_object_address_dependencies(), recordDependencyOnCurrentExtension(), RelationGetDescr, ReleaseSysCache(), CreateTransformStmt::replace, RowExclusiveLock, SearchSysCache1(), SearchSysCache2(), HeapTupleData::t_self, table_close(), table_open(), CreateTransformStmt::tosql, TRFTYPELANG, CreateTransformStmt::type_name, TypeNameToString(), typenameTypeId(), and values.

Referenced by ProcessUtilitySlow().

◆ CreateUserMapping()

ObjectAddress CreateUserMapping ( CreateUserMappingStmt stmt)

Definition at line 1100 of file foreigncmds.c.

1101 {
1102  Relation rel;
1103  Datum useoptions;
1104  Datum values[Natts_pg_user_mapping];
1105  bool nulls[Natts_pg_user_mapping];
1106  HeapTuple tuple;
1107  Oid useId;
1108  Oid umId;
1109  ObjectAddress myself;
1110  ObjectAddress referenced;
1111  ForeignServer *srv;
1112  ForeignDataWrapper *fdw;
1113  RoleSpec *role = (RoleSpec *) stmt->user;
1114 
1115  rel = table_open(UserMappingRelationId, RowExclusiveLock);
1116 
1117  if (role->roletype == ROLESPEC_PUBLIC)
1118  useId = ACL_ID_PUBLIC;
1119  else
1120  useId = get_rolespec_oid(stmt->user, false);
1121 
1122  /* Check that the server exists. */
1123  srv = GetForeignServerByName(stmt->servername, false);
1124 
1125  user_mapping_ddl_aclcheck(useId, srv->serverid, stmt->servername);
1126 
1127  /*
1128  * Check that the user mapping is unique within server.
1129  */
1130  umId = GetSysCacheOid2(USERMAPPINGUSERSERVER, Anum_pg_user_mapping_oid,
1131  ObjectIdGetDatum(useId),
1132  ObjectIdGetDatum(srv->serverid));
1133 
1134  if (OidIsValid(umId))
1135  {
1136  if (stmt->if_not_exists)
1137  {
1138  /*
1139  * Since user mappings aren't members of extensions (see comments
1140  * below), no need for checkMembershipInCurrentExtension here.
1141  */
1142  ereport(NOTICE,
1144  errmsg("user mapping for \"%s\" already exists for server \"%s\", skipping",
1145  MappingUserName(useId),
1146  stmt->servername)));
1147 
1149  return InvalidObjectAddress;
1150  }
1151  else
1152  ereport(ERROR,
1154  errmsg("user mapping for \"%s\" already exists for server \"%s\"",
1155  MappingUserName(useId),
1156  stmt->servername)));
1157  }
1158 
1159  fdw = GetForeignDataWrapper(srv->fdwid);
1160 
1161  /*
1162  * Insert tuple into pg_user_mapping.
1163  */
1164  memset(values, 0, sizeof(values));
1165  memset(nulls, false, sizeof(nulls));
1166 
1167  umId = GetNewOidWithIndex(rel, UserMappingOidIndexId,
1168  Anum_pg_user_mapping_oid);
1169  values[Anum_pg_user_mapping_oid - 1] = ObjectIdGetDatum(umId);
1170  values[Anum_pg_user_mapping_umuser - 1] = ObjectIdGetDatum(useId);
1171  values[Anum_pg_user_mapping_umserver - 1] = ObjectIdGetDatum(srv->serverid);
1172 
1173  /* Add user options */
1174  useoptions = transformGenericOptions(UserMappingRelationId,
1175  PointerGetDatum(NULL),
1176  stmt->options,
1177  fdw->fdwvalidator);
1178 
1179  if (PointerIsValid(DatumGetPointer(useoptions)))
1180  values[Anum_pg_user_mapping_umoptions - 1] = useoptions;
1181  else
1182  nulls[Anum_pg_user_mapping_umoptions - 1] = true;
1183 
1184  tuple = heap_form_tuple(rel->rd_att, values, nulls);
1185 
1186  CatalogTupleInsert(rel, tuple);
1187 
1188  heap_freetuple(tuple);
1189 
1190  /* Add dependency on the server */
1191  myself.classId = UserMappingRelationId;
1192  myself.objectId = umId;
1193  myself.objectSubId = 0;
1194 
1195  referenced.classId = ForeignServerRelationId;
1196  referenced.objectId = srv->serverid;
1197  referenced.objectSubId = 0;
1198  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1199 
1200  if (OidIsValid(useId))
1201  {
1202  /* Record the mapped user dependency */
1203  recordDependencyOnOwner(UserMappingRelationId, umId, useId);
1204  }
1205 
1206  /*
1207  * Perhaps someday there should be a recordDependencyOnCurrentExtension
1208  * call here; but since roles aren't members of extensions, it seems like
1209  * user mappings shouldn't be either. Note that the grammar and pg_dump
1210  * would need to be extended too if we change this.
1211  */
1212 
1213  /* Post creation hook for new user mapping */
1214  InvokeObjectPostCreateHook(UserMappingRelationId, umId, 0);
1215 
1217 
1218  return myself;
1219 }

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(), and values.

Referenced by ProcessUtilitySlow().

◆ defGetBoolean()

bool defGetBoolean ( DefElem def)

Definition at line 108 of file define.c.

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

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

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

◆ defGetInt32()

int32 defGetInt32 ( DefElem def)

Definition at line 163 of file define.c.

164 {
165  if (def->arg == NULL)
166  ereport(ERROR,
167  (errcode(ERRCODE_SYNTAX_ERROR),
168  errmsg("%s requires an integer value",
169  def->defname)));
170  switch (nodeTag(def->arg))
171  {
172  case T_Integer:
173  return (int32) intVal(def->arg);
174  default:
175  ereport(ERROR,
176  (errcode(ERRCODE_SYNTAX_ERROR),
177  errmsg("%s requires an integer value",
178  def->defname)));
179  }
180  return 0; /* keep compiler quiet */
181 }
signed int int32
Definition: c.h:478

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

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

◆ defGetInt64()

int64 defGetInt64 ( DefElem def)

Definition at line 187 of file define.c.

188 {
189  if (def->arg == NULL)
190  ereport(ERROR,
191  (errcode(ERRCODE_SYNTAX_ERROR),
192  errmsg("%s requires a numeric value",
193  def->defname)));
194  switch (nodeTag(def->arg))
195  {
196  case T_Integer:
197  return (int64) intVal(def->arg);
198  case T_Float:
199 
200  /*
201  * Values too large for int4 will be represented as Float
202  * constants by the lexer. Accept these if they are valid int8
203  * strings.
204  */
206  CStringGetDatum(castNode(Float, def->arg)->fval)));
207  default:
208  ereport(ERROR,
209  (errcode(ERRCODE_SYNTAX_ERROR),
210  errmsg("%s requires a numeric value",
211  def->defname)));
212  }
213  return 0; /* keep compiler quiet */
214 }
Datum int8in(PG_FUNCTION_ARGS)
Definition: int8.c:51
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385
Definition: value.h:48

References DefElem::arg, castNode, CStringGetDatum(), DatumGetInt64(), DefElem::defname, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, int8in(), intVal, and nodeTag.

Referenced by init_params(), and parse_basebackup_options().

◆ defGetNumeric()

double defGetNumeric ( DefElem def)

Definition at line 82 of file define.c.

83 {
84  if (def->arg == NULL)
85  ereport(ERROR,
86  (errcode(ERRCODE_SYNTAX_ERROR),
87  errmsg("%s requires a numeric value",
88  def->defname)));
89  switch (nodeTag(def->arg))
90  {
91  case T_Integer:
92  return (double) intVal(def->arg);
93  case T_Float:
94  return floatVal(def->arg);
95  default:
96  ereport(ERROR,
97  (errcode(ERRCODE_SYNTAX_ERROR),
98  errmsg("%s requires a numeric value",
99  def->defname)));
100  }
101  return 0; /* keep compiler quiet */
102 }
#define floatVal(v)
Definition: value.h:80

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

Referenced by AlterFunction(), and compute_function_attributes().

◆ defGetObjectId()

Oid defGetObjectId ( DefElem def)

Definition at line 220 of file define.c.

221 {
222  if (def->arg == NULL)
223  ereport(ERROR,
224  (errcode(ERRCODE_SYNTAX_ERROR),
225  errmsg("%s requires a numeric value",
226  def->defname)));
227  switch (nodeTag(def->arg))
228  {
229  case T_Integer:
230  return (Oid) intVal(def->arg);
231  case T_Float:
232 
233  /*
234  * Values too large for int4 will be represented as Float
235  * constants by the lexer. Accept these if they are valid OID
236  * strings.
237  */
239  CStringGetDatum(castNode(Float, def->arg)->fval)));
240  default:
241  ereport(ERROR,
242  (errcode(ERRCODE_SYNTAX_ERROR),
243  errmsg("%s requires a numeric value",
244  def->defname)));
245  }
246  return 0; /* keep compiler quiet */
247 }
Datum oidin(PG_FUNCTION_ARGS)
Definition: oid.c:36
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242

References DefElem::arg, castNode, CStringGetDatum(), DatumGetObjectId(), DefElem::defname, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, intVal, nodeTag, and oidin().

Referenced by createdb().

◆ defGetQualifiedName()

List* defGetQualifiedName ( DefElem def)

Definition at line 253 of file define.c.

254 {
255  if (def->arg == NULL)
256  ereport(ERROR,
257  (errcode(ERRCODE_SYNTAX_ERROR),
258  errmsg("%s requires a parameter",
259  def->defname)));
260  switch (nodeTag(def->arg))
261  {
262  case T_TypeName:
263  return ((TypeName *) def->arg)->names;
264  case T_List:
265  return (List *) def->arg;
266  case T_String:
267  /* Allow quoted name for backwards compatibility */
268  return list_make1(def->arg);
269  default:
270  ereport(ERROR,
271  (errcode(ERRCODE_SYNTAX_ERROR),
272  errmsg("argument of %s must be a name",
273  def->defname)));
274  }
275  return NIL; /* keep compiler quiet */
276 }
#define list_make1(x1)
Definition: pg_list.h:212

References DefElem::arg, DefElem::defname, ereport, errcode(), errmsg(), ERROR, list_make1, NIL, and nodeTag.

Referenced by AlterOperator(), AlterType(), DefineAggregate(), DefineCollation(), DefineOperator(), DefineRange(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), get_ts_parser_func(), get_ts_template_func(), init_params(), and interpret_func_support().

◆ defGetString()

char* defGetString ( DefElem def)

Definition at line 49 of file define.c.

50 {
51  if (def->arg == NULL)
52  ereport(ERROR,
53  (errcode(ERRCODE_SYNTAX_ERROR),
54  errmsg("%s requires a parameter",
55  def->defname)));
56  switch (nodeTag(def->arg))
57  {
58  case T_Integer:
59  return psprintf("%ld", (long) intVal(def->arg));
60  case T_Float:
61  return castNode(Float, def->arg)->fval;
62  case T_Boolean:
63  return boolVal(def->arg) ? "true" : "false";
64  case T_String:
65  return strVal(def->arg);
66  case T_TypeName:
67  return TypeNameToString((TypeName *) def->arg);
68  case T_List:
69  return NameListToString((List *) def->arg);
70  case T_A_Star:
71  return pstrdup("*");
72  default:
73  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
74  }
75  return NULL; /* keep compiler quiet */
76 }
char * pstrdup(const char *in)
Definition: mcxt.c:1624
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

References DefElem::arg, boolVal, castNode, DefElem::defname, elog(), ereport, errcode(), errmsg(), ERROR, intVal, NameListToString(), nodeTag, psprintf(), pstrdup(), strVal, and TypeNameToString().

Referenced by AlterDatabase(), AlterType(), apply_server_options(), apply_table_options(), check_selective_binary_conversion(), createdb(), CreateExtension(), defGetBoolean(), defGetCopyHeaderChoice(), defGetStreamingMode(), defGetTypeLength(), DefineAggregate(), DefineCollation(), DefineType(), deparseAnalyzeSql(), deparseColumnRef(), deparseRelation(), dintdict_init(), dispell_init(), dsimple_init(), dsnowball_init(), dsynonym_init(), dxsyn_init(), ExecReindex(), ExecVacuum(), ExplainQuery(), ExplainResultDesc(), ExtractConnectionOptions(), extractModify(), file_fdw_validator(), fileGetOptions(), get_batch_size_option(), GrantRole(), optionListToArray(), parse_basebackup_options(), parse_output_parameters(), parse_publication_options(), parse_subscription_options(), parseCreateReplSlotOptions(), postgres_fdw_validator(), postgresAcquireSampleRowsFunc(), ProcessCopyOptions(), prsd_headline(), serialize_deflist(), thesaurus_init(), transformRelOptions(), and unaccent_init().

◆ defGetStringList()

List* defGetStringList ( DefElem def)

Definition at line 357 of file define.c.

358 {
359  ListCell *cell;
360 
361  if (def->arg == NULL)
362  ereport(ERROR,
363  (errcode(ERRCODE_SYNTAX_ERROR),
364  errmsg("%s requires a parameter",
365  def->defname)));
366  if (nodeTag(def->arg) != T_List)
367  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
368 
369  foreach(cell, (List *) def->arg)
370  {
371  Node *str = (Node *) lfirst(cell);
372 
373  if (!IsA(str, String))
374  elog(ERROR, "unexpected node type in name list: %d",
375  (int) nodeTag(str));
376  }
377 
378  return (List *) def->arg;
379 }
Definition: value.h:64

References DefElem::arg, DefElem::defname, elog(), ereport, errcode(), errmsg(), ERROR, IsA, lfirst, nodeTag, and generate_unaccent_rules::str.

◆ defGetTypeLength()

int defGetTypeLength ( DefElem def)

Definition at line 313 of file define.c.

314 {
315  if (def->arg == NULL)
316  ereport(ERROR,
317  (errcode(ERRCODE_SYNTAX_ERROR),
318  errmsg("%s requires a parameter",
319  def->defname)));
320  switch (nodeTag(def->arg))
321  {
322  case T_Integer:
323  return intVal(def->arg);
324  case T_Float:
325  ereport(ERROR,
326  (errcode(ERRCODE_SYNTAX_ERROR),
327  errmsg("%s requires an integer value",
328  def->defname)));
329  break;
330  case T_String:
331  if (pg_strcasecmp(strVal(def->arg), "variable") == 0)
332  return -1; /* variable length */
333  break;
334  case T_TypeName:
335  /* cope if grammar chooses to believe "variable" is a typename */
337  "variable") == 0)
338  return -1; /* variable length */
339  break;
340  case T_List:
341  /* must be an operator name */
342  break;
343  default:
344  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(def->arg));
345  }
346  ereport(ERROR,
347  (errcode(ERRCODE_SYNTAX_ERROR),
348  errmsg("invalid argument for %s: \"%s\"",
349  def->defname, defGetString(def))));
350  return 0; /* keep compiler quiet */
351 }

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

Referenced by DefineType().

◆ defGetTypeName()

TypeName* defGetTypeName ( DefElem def)

Definition at line 285 of file define.c.

286 {
287  if (def->arg == NULL)
288  ereport(ERROR,
289  (errcode(ERRCODE_SYNTAX_ERROR),
290  errmsg("%s requires a parameter",
291  def->defname)));
292  switch (nodeTag(def->arg))
293  {
294  case T_TypeName:
295  return (TypeName *) def->arg;
296  case T_String:
297  /* Allow quoted typename for backwards compatibility */
299  default:
300  ereport(ERROR,
301  (errcode(ERRCODE_SYNTAX_ERROR),
302  errmsg("argument of %s must be a type name",
303  def->defname)));
304  }
305  return NULL; /* keep compiler quiet */
306 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:458

References DefElem::arg, DefElem::defname, ereport, errcode(), errmsg(), ERROR, list_make1, makeTypeNameFromNameList(), and nodeTag.

Referenced by DefineAggregate(), DefineOperator(), DefineRange(), DefineType(), and init_params().

◆ DefineAggregate()

ObjectAddress DefineAggregate ( ParseState pstate,
List name,
List args,
bool  oldstyle,
List parameters,
bool  replace 
)

Definition at line 57 of file aggregatecmds.c.

63 {
64  char *aggName;
65  Oid aggNamespace;
66  AclResult aclresult;
67  char aggKind = AGGKIND_NORMAL;
68  List *transfuncName = NIL;
69  List *finalfuncName = NIL;
70  List *combinefuncName = NIL;
71  List *serialfuncName = NIL;
72  List *deserialfuncName = NIL;
73  List *mtransfuncName = NIL;
74  List *minvtransfuncName = NIL;
75  List *mfinalfuncName = NIL;
76  bool finalfuncExtraArgs = false;
77  bool mfinalfuncExtraArgs = false;
78  char finalfuncModify = 0;
79  char mfinalfuncModify = 0;
80  List *sortoperatorName = NIL;
81  TypeName *baseType = NULL;
82  TypeName *transType = NULL;
83  TypeName *mtransType = NULL;
84  int32 transSpace = 0;
85  int32 mtransSpace = 0;
86  char *initval = NULL;
87  char *minitval = NULL;
88  char *parallel = NULL;
89  int numArgs;
90  int numDirectArgs = 0;
91  oidvector *parameterTypes;
92  ArrayType *allParameterTypes;
93  ArrayType *parameterModes;
94  ArrayType *parameterNames;
95  List *parameterDefaults;
96  Oid variadicArgType;
97  Oid transTypeId;
98  Oid mtransTypeId = InvalidOid;
99  char transTypeType;
100  char mtransTypeType = 0;
101  char proparallel = PROPARALLEL_UNSAFE;
102  ListCell *pl;
103 
104  /* Convert list of names to a name and namespace */
105  aggNamespace = QualifiedNameGetCreationNamespace(name, &aggName);
106 
107  /* Check we have creation rights in target namespace */
108  aclresult = object_aclcheck(NamespaceRelationId, aggNamespace, GetUserId(), ACL_CREATE);
109  if (aclresult != ACLCHECK_OK)
110  aclcheck_error(aclresult, OBJECT_SCHEMA,
111  get_namespace_name(aggNamespace));
112 
113  /* Deconstruct the output of the aggr_args grammar production */
114  if (!oldstyle)
115  {
116  Assert(list_length(args) == 2);
117  numDirectArgs = intVal(lsecond(args));
118  if (numDirectArgs >= 0)
119  aggKind = AGGKIND_ORDERED_SET;
120  else
121  numDirectArgs = 0;
123  }
124 
125  /* Examine aggregate's definition clauses */
126  foreach(pl, parameters)
127  {
128  DefElem *defel = lfirst_node(DefElem, pl);
129 
130  /*
131  * sfunc1, stype1, and initcond1 are accepted as obsolete spellings
132  * for sfunc, stype, initcond.
133  */
134  if (strcmp(defel->defname, "sfunc") == 0)
135  transfuncName = defGetQualifiedName(defel);
136  else if (strcmp(defel->defname, "sfunc1") == 0)
137  transfuncName = defGetQualifiedName(defel);
138  else if (strcmp(defel->defname, "finalfunc") == 0)
139  finalfuncName = defGetQualifiedName(defel);
140  else if (strcmp(defel->defname, "combinefunc") == 0)
141  combinefuncName = defGetQualifiedName(defel);
142  else if (strcmp(defel->defname, "serialfunc") == 0)
143  serialfuncName = defGetQualifiedName(defel);
144  else if (strcmp(defel->defname, "deserialfunc") == 0)
145  deserialfuncName = defGetQualifiedName(defel);
146  else if (strcmp(defel->defname, "msfunc") == 0)
147  mtransfuncName = defGetQualifiedName(defel);
148  else if (strcmp(defel->defname, "minvfunc") == 0)
149  minvtransfuncName = defGetQualifiedName(defel);
150  else if (strcmp(defel->defname, "mfinalfunc") == 0)
151  mfinalfuncName = defGetQualifiedName(defel);
152  else if (strcmp(defel->defname, "finalfunc_extra") == 0)
153  finalfuncExtraArgs = defGetBoolean(defel);
154  else if (strcmp(defel->defname, "mfinalfunc_extra") == 0)
155  mfinalfuncExtraArgs = defGetBoolean(defel);
156  else if (strcmp(defel->defname, "finalfunc_modify") == 0)
157  finalfuncModify = extractModify(defel);
158  else if (strcmp(defel->defname, "mfinalfunc_modify") == 0)
159  mfinalfuncModify = extractModify(defel);
160  else if (strcmp(defel->defname, "sortop") == 0)
161  sortoperatorName = defGetQualifiedName(defel);
162  else if (strcmp(defel->defname, "basetype") == 0)
163  baseType = defGetTypeName(defel);
164  else if (strcmp(defel->defname, "hypothetical") == 0)
165  {
166  if (defGetBoolean(defel))
167  {
168  if (aggKind == AGGKIND_NORMAL)
169  ereport(ERROR,
170  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
171  errmsg("only ordered-set aggregates can be hypothetical")));
172  aggKind = AGGKIND_HYPOTHETICAL;
173  }
174  }
175  else if (strcmp(defel->defname, "stype") == 0)
176  transType = defGetTypeName(defel);
177  else if (strcmp(defel->defname, "stype1") == 0)
178  transType = defGetTypeName(defel);
179  else if (strcmp(defel->defname, "sspace") == 0)
180  transSpace = defGetInt32(defel);
181  else if (strcmp(defel->defname, "mstype") == 0)
182  mtransType = defGetTypeName(defel);
183  else if (strcmp(defel->defname, "msspace") == 0)
184  mtransSpace = defGetInt32(defel);
185  else if (strcmp(defel->defname, "initcond") == 0)
186  initval = defGetString(defel);
187  else if (strcmp(defel->defname, "initcond1") == 0)
188  initval = defGetString(defel);
189  else if (strcmp(defel->defname, "minitcond") == 0)
190  minitval = defGetString(defel);
191  else if (strcmp(defel->defname, "parallel") == 0)
192  parallel = defGetString(defel);
193  else
195  (errcode(ERRCODE_SYNTAX_ERROR),
196  errmsg("aggregate attribute \"%s\" not recognized",
197  defel->defname)));
198  }
199 
200  /*
201  * make sure we have our required definitions
202  */
203  if (transType == NULL)
204  ereport(ERROR,
205  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
206  errmsg("aggregate stype must be specified")));
207  if (transfuncName == NIL)
208  ereport(ERROR,
209  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
210  errmsg("aggregate sfunc must be specified")));
211 
212  /*
213  * if mtransType is given, mtransfuncName and minvtransfuncName must be as
214  * well; if not, then none of the moving-aggregate options should have
215  * been given.
216  */
217  if (mtransType != NULL)
218  {
219  if (mtransfuncName == NIL)
220  ereport(ERROR,
221  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
222  errmsg("aggregate msfunc must be specified when mstype is specified")));
223  if (minvtransfuncName == NIL)
224  ereport(ERROR,
225  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
226  errmsg("aggregate minvfunc must be specified when mstype is specified")));
227  }
228  else
229  {
230  if (mtransfuncName != NIL)
231  ereport(ERROR,
232  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
233  errmsg("aggregate msfunc must not be specified without mstype")));
234  if (minvtransfuncName != NIL)
235  ereport(ERROR,
236  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
237  errmsg("aggregate minvfunc must not be specified without mstype")));
238  if (mfinalfuncName != NIL)
239  ereport(ERROR,
240  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
241  errmsg("aggregate mfinalfunc must not be specified without mstype")));
242  if (mtransSpace != 0)
243  ereport(ERROR,
244  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
245  errmsg("aggregate msspace must not be specified without mstype")));
246  if (minitval != NULL)
247  ereport(ERROR,
248  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
249  errmsg("aggregate minitcond must not be specified without mstype")));
250  }
251 
252  /*
253  * Default values for modify flags can only be determined once we know the
254  * aggKind.
255  */
256  if (finalfuncModify == 0)
257  finalfuncModify = (aggKind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
258  if (mfinalfuncModify == 0)
259  mfinalfuncModify = (aggKind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
260 
261  /*
262  * look up the aggregate's input datatype(s).
263  */
264  if (oldstyle)
265  {
266  /*
267  * Old style: use basetype parameter. This supports aggregates of
268  * zero or one input, with input type ANY meaning zero inputs.
269  *
270  * Historically we allowed the command to look like basetype = 'ANY'
271  * so we must do a case-insensitive comparison for the name ANY. Ugh.
272  */
273  Oid aggArgTypes[1];
274 
275  if (baseType == NULL)
276  ereport(ERROR,
277  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
278  errmsg("aggregate input type must be specified")));
279 
280  if (pg_strcasecmp(TypeNameToString(baseType), "ANY") == 0)
281  {
282  numArgs = 0;
283  aggArgTypes[0] = InvalidOid;
284  }
285  else
286  {
287  numArgs = 1;
288  aggArgTypes[0] = typenameTypeId(NULL, baseType);
289  }
290  parameterTypes = buildoidvector(aggArgTypes, numArgs);
291  allParameterTypes = NULL;
292  parameterModes = NULL;
293  parameterNames = NULL;
294  parameterDefaults = NIL;
295  variadicArgType = InvalidOid;
296  }
297  else
298  {
299  /*
300  * New style: args is a list of FunctionParameters (possibly zero of
301  * 'em). We share functioncmds.c's code for processing them.
302  */
303  Oid requiredResultType;
304 
305  if (baseType != NULL)
306  ereport(ERROR,
307  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
308  errmsg("basetype is redundant with aggregate input type specification")));
309 
310  numArgs = list_length(args);
312  args,
313  InvalidOid,
315  &parameterTypes,
316  NULL,
317  &allParameterTypes,
318  &parameterModes,
319  &parameterNames,
320  NULL,
321  &parameterDefaults,
322  &variadicArgType,
323  &requiredResultType);
324  /* Parameter defaults are not currently allowed by the grammar */
325  Assert(parameterDefaults == NIL);
326  /* There shouldn't have been any OUT parameters, either */
327  Assert(requiredResultType == InvalidOid);
328  }
329 
330  /*
331  * look up the aggregate's transtype.
332  *
333  * transtype can't be a pseudo-type, since we need to be able to store
334  * values of the transtype. However, we can allow polymorphic transtype
335  * in some cases (AggregateCreate will check). Also, we allow "internal"
336  * for functions that want to pass pointers to private data structures;
337  * but allow that only to superusers, since you could crash the system (or
338  * worse) by connecting up incompatible internal-using functions in an
339  * aggregate.
340  */
341  transTypeId = typenameTypeId(NULL, transType);
342  transTypeType = get_typtype(transTypeId);
343  if (transTypeType == TYPTYPE_PSEUDO &&
344  !IsPolymorphicType(transTypeId))
345  {
346  if (transTypeId == INTERNALOID && superuser())
347  /* okay */ ;
348  else
349  ereport(ERROR,
350  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
351  errmsg("aggregate transition data type cannot be %s",
352  format_type_be(transTypeId))));
353  }
354 
355  if (serialfuncName && deserialfuncName)
356  {
357  /*
358  * Serialization is only needed/allowed for transtype INTERNAL.
359  */
360  if (transTypeId != INTERNALOID)
361  ereport(ERROR,
362  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
363  errmsg("serialization functions may be specified only when the aggregate transition data type is %s",
364  format_type_be(INTERNALOID))));
365  }
366  else if (serialfuncName || deserialfuncName)
367  {
368  /*
369  * Cannot specify one function without the other.
370  */
371  ereport(ERROR,
372  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
373  errmsg("must specify both or neither of serialization and deserialization functions")));
374  }
375 
376  /*
377  * If a moving-aggregate transtype is specified, look that up. Same
378  * restrictions as for transtype.
379  */
380  if (mtransType)
381  {
382  mtransTypeId = typenameTypeId(NULL, mtransType);
383  mtransTypeType = get_typtype(mtransTypeId);
384  if (mtransTypeType == TYPTYPE_PSEUDO &&
385  !IsPolymorphicType(mtransTypeId))
386  {
387  if (mtransTypeId == INTERNALOID && superuser())
388  /* okay */ ;
389  else
390  ereport(ERROR,
391  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
392  errmsg("aggregate transition data type cannot be %s",
393  format_type_be(mtransTypeId))));
394  }
395  }
396 
397  /*
398  * If we have an initval, and it's not for a pseudotype (particularly a
399  * polymorphic type), make sure it's acceptable to the type's input
400  * function. We will store the initval as text, because the input
401  * function isn't necessarily immutable (consider "now" for timestamp),
402  * and we want to use the runtime not creation-time interpretation of the
403  * value. However, if it's an incorrect value it seems much more
404  * user-friendly to complain at CREATE AGGREGATE time.
405  */
406  if (initval && transTypeType != TYPTYPE_PSEUDO)
407  {
408  Oid typinput,
409  typioparam;
410 
411  getTypeInputInfo(transTypeId, &typinput, &typioparam);
412  (void) OidInputFunctionCall(typinput, initval, typioparam, -1);
413  }
414 
415  /*
416  * Likewise for moving-aggregate initval.
417  */
418  if (minitval && mtransTypeType != TYPTYPE_PSEUDO)
419  {
420  Oid typinput,
421  typioparam;
422 
423  getTypeInputInfo(mtransTypeId, &typinput, &typioparam);
424  (void) OidInputFunctionCall(typinput, minitval, typioparam, -1);
425  }
426 
427  if (parallel)
428  {
429  if (strcmp(parallel, "safe") == 0)
430  proparallel = PROPARALLEL_SAFE;
431  else if (strcmp(parallel, "restricted") == 0)
432  proparallel = PROPARALLEL_RESTRICTED;
433  else if (strcmp(parallel, "unsafe") == 0)
434  proparallel = PROPARALLEL_UNSAFE;
435  else
436  ereport(ERROR,
437  (errcode(ERRCODE_SYNTAX_ERROR),
438  errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
439  }
440 
441  /*
442  * Most of the argument-checking is done inside of AggregateCreate
443  */
444  return AggregateCreate(aggName, /* aggregate name */
445  aggNamespace, /* namespace */
446  replace,
447  aggKind,
448  numArgs,
449  numDirectArgs,
450  parameterTypes,
451  PointerGetDatum(allParameterTypes),
452  PointerGetDatum(parameterModes),
453  PointerGetDatum(parameterNames),
454  parameterDefaults,
455  variadicArgType,
456  transfuncName, /* step function name */
457  finalfuncName, /* final function name */
458  combinefuncName, /* combine function name */
459  serialfuncName, /* serial function name */
460  deserialfuncName, /* deserial function name */
461  mtransfuncName, /* fwd trans function name */
462  minvtransfuncName, /* inv trans function name */
463  mfinalfuncName, /* final function name */
464  finalfuncExtraArgs,
465  mfinalfuncExtraArgs,
466  finalfuncModify,
467  mfinalfuncModify,
468  sortoperatorName, /* sort operator name */
469  transTypeId, /* transition data type */
470  transSpace, /* transition space */
471  mtransTypeId, /* transition data type */
472  mtransSpace, /* transition space */
473  initval, /* initial condition */
474  minitval, /* initial condition */
475  proparallel); /* parallel safe? */
476 }
static char extractModify(DefElem *defel)
int32 defGetInt32(DefElem *def)
Definition: define.c:163
bool defGetBoolean(DefElem *def)
Definition: define.c:108
TypeName * defGetTypeName(DefElem *def)
Definition: define.c:285
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1741
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2832
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:86
@ OBJECT_AGGREGATE
Definition: parsenodes.h:1970
ObjectAddress AggregateCreate(const char *aggName, Oid aggNamespace, bool replace, char aggKind, int numArgs, int numDirectArgs, oidvector *parameterTypes, Datum allParameterTypes, Datum parameterModes, Datum parameterNames, List *parameterDefaults, Oid variadicArgType, List *aggtransfnName, List *aggfinalfnName, List *aggcombinefnName, List *aggserialfnName, List *aggdeserialfnName, List *aggmtransfnName, List *aggminvtransfnName, List *aggmfinalfnName, bool finalfnExtraArgs, bool mfinalfnExtraArgs, char finalfnModify, char mfinalfnModify, List *aggsortopName, Oid aggTransType, int32 aggTransSpace, Oid aggmTransType, int32 aggmTransSpace, const char *agginitval, const char *aggminitval, char proparallel)
Definition: pg_aggregate.c:46
#define linitial_node(type, l)
Definition: pg_list.h:181
#define lsecond(l)
Definition: pg_list.h:183

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, AggregateCreate(), generate_unaccent_rules::args, Assert(), buildoidvector(), defGetBoolean(), defGetInt32(), defGetQualifiedName(), defGetString(), defGetTypeName(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, extractModify(), format_type_be(), get_namespace_name(), get_typtype(), getTypeInputInfo(), GetUserId(), interpret_function_parameter_list(), intVal, InvalidOid, lfirst_node, linitial_node, list_length(), lsecond, name, NIL, object_aclcheck(), OBJECT_AGGREGATE, OBJECT_SCHEMA, OidInputFunctionCall(), pg_strcasecmp(), PointerGetDatum(), QualifiedNameGetCreationNamespace(), superuser(), TypeNameToString(), typenameTypeId(), and WARNING.

Referenced by ProcessUtilitySlow().

◆ DefineIndex()

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 
)

Definition at line 525 of file indexcmds.c.

535 {
536  bool concurrent;
537  char *indexRelationName;
538  char *accessMethodName;
539  Oid *typeObjectId;
540  Oid *collationObjectId;
541  Oid *classObjectId;
542  Oid accessMethodId;
543  Oid namespaceId;
544  Oid tablespaceId;
545  Oid createdConstraintId = InvalidOid;
546  List *indexColNames;
547  List *allIndexParams;
548  Relation rel;
549  HeapTuple tuple;
550  Form_pg_am accessMethodForm;
551  IndexAmRoutine *amRoutine;
552  bool amcanorder;
553  amoptions_function amoptions;
554  bool partitioned;
555  bool safe_index;
556  Datum reloptions;
557  int16 *coloptions;
558  IndexInfo *indexInfo;
559  bits16 flags;
560  bits16 constr_flags;
561  int numberOfAttributes;
562  int numberOfKeyAttributes;
563  TransactionId limitXmin;
564  ObjectAddress address;
565  LockRelId heaprelid;
566  LOCKTAG heaplocktag;
567  LOCKMODE lockmode;
568  Snapshot snapshot;
569  Oid root_save_userid;
570  int root_save_sec_context;
571  int root_save_nestlevel;
572 
573  root_save_nestlevel = NewGUCNestLevel();
574 
575  /*
576  * Some callers need us to run with an empty default_tablespace; this is a
577  * necessary hack to be able to reproduce catalog state accurately when
578  * recreating indexes after table-rewriting ALTER TABLE.
579  */
580  if (stmt->reset_default_tblspc)
581  (void) set_config_option("default_tablespace", "",
583  GUC_ACTION_SAVE, true, 0, false);
584 
585  /*
586  * Force non-concurrent build on temporary relations, even if CONCURRENTLY
587  * was requested. Other backends can't access a temporary relation, so
588  * there's no harm in grabbing a stronger lock, and a non-concurrent DROP
589  * is more efficient. Do this before any use of the concurrent option is
590  * done.
591  */
592  if (stmt->concurrent && get_rel_persistence(relationId) != RELPERSISTENCE_TEMP)
593  concurrent = true;
594  else
595  concurrent = false;
596 
597  /*
598  * Start progress report. If we're building a partition, this was already
599  * done.
600  */
601  if (!OidIsValid(parentIndexId))
602  {
604  relationId);
606  concurrent ?
609  }
610 
611  /*
612  * No index OID to report yet
613  */
615  InvalidOid);
616 
617  /*
618  * count key attributes in index
619  */
620  numberOfKeyAttributes = list_length(stmt->indexParams);
621 
622  /*
623  * Calculate the new list of index columns including both key columns and
624  * INCLUDE columns. Later we can determine which of these are key
625  * columns, and which are just part of the INCLUDE list by checking the
626  * list position. A list item in a position less than ii_NumIndexKeyAttrs
627  * is part of the key columns, and anything equal to and over is part of
628  * the INCLUDE columns.
629  */
630  allIndexParams = list_concat_copy(stmt->indexParams,
631  stmt->indexIncludingParams);
632  numberOfAttributes = list_length(allIndexParams);
633 
634  if (numberOfKeyAttributes <= 0)
635  ereport(ERROR,
636  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
637  errmsg("must specify at least one column")));
638  if (numberOfAttributes > INDEX_MAX_KEYS)
639  ereport(