PostgreSQL Source Code  git master
functioncmds.c File Reference
#include "postgres.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_language.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_transform.h"
#include "catalog/pg_type.h"
#include "commands/alter.h"
#include "commands/defrem.h"
#include "commands/extension.h"
#include "commands/proclang.h"
#include "executor/execdesc.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_type.h"
#include "pgstat.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for functioncmds.c:

Go to the source code of this file.

Functions

static void compute_return_type (TypeName *returnType, Oid languageOid, Oid *prorettype_p, bool *returnsSet_p)
 
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)
 
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)
 
static char interpret_func_volatility (DefElem *defel)
 
static char interpret_func_parallel (DefElem *defel)
 
static ArrayTypeupdate_proconfig_value (ArrayType *a, List *set_items)
 
static Oid interpret_func_support (DefElem *defel)
 
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)
 
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)
 
ObjectAddress CreateFunction (ParseState *pstate, CreateFunctionStmt *stmt)
 
void RemoveFunctionById (Oid funcOid)
 
ObjectAddress AlterFunction (ParseState *pstate, AlterFunctionStmt *stmt)
 
ObjectAddress CreateCast (CreateCastStmt *stmt)
 
static void check_transform_function (Form_pg_proc procstruct)
 
ObjectAddress CreateTransform (CreateTransformStmt *stmt)
 
Oid get_transform_oid (Oid type_id, Oid lang_id, bool missing_ok)
 
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)
 

Function Documentation

◆ AlterFunction()

ObjectAddress AlterFunction ( ParseState pstate,
AlterFunctionStmt stmt 
)

Definition at line 1352 of file functioncmds.c.

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

Referenced by ProcessUtilitySlow().

1353 {
1354  HeapTuple tup;
1355  Oid funcOid;
1356  Form_pg_proc procForm;
1357  bool is_procedure;
1358  Relation rel;
1359  ListCell *l;
1360  DefElem *volatility_item = NULL;
1361  DefElem *strict_item = NULL;
1362  DefElem *security_def_item = NULL;
1363  DefElem *leakproof_item = NULL;
1364  List *set_items = NIL;
1365  DefElem *cost_item = NULL;
1366  DefElem *rows_item = NULL;
1367  DefElem *support_item = NULL;
1368  DefElem *parallel_item = NULL;
1369  ObjectAddress address;
1370 
1371  rel = table_open(ProcedureRelationId, RowExclusiveLock);
1372 
1373  funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
1374 
1375  ObjectAddressSet(address, ProcedureRelationId, funcOid);
1376 
1377  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1378  if (!HeapTupleIsValid(tup)) /* should not happen */
1379  elog(ERROR, "cache lookup failed for function %u", funcOid);
1380 
1381  procForm = (Form_pg_proc) GETSTRUCT(tup);
1382 
1383  /* Permission check: must own function */
1384  if (!pg_proc_ownercheck(funcOid, GetUserId()))
1386  NameListToString(stmt->func->objname));
1387 
1388  if (procForm->prokind == PROKIND_AGGREGATE)
1389  ereport(ERROR,
1390  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1391  errmsg("\"%s\" is an aggregate function",
1392  NameListToString(stmt->func->objname))));
1393 
1394  is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
1395 
1396  /* Examine requested actions. */
1397  foreach(l, stmt->actions)
1398  {
1399  DefElem *defel = (DefElem *) lfirst(l);
1400 
1401  if (compute_common_attribute(pstate,
1402  is_procedure,
1403  defel,
1404  &volatility_item,
1405  &strict_item,
1406  &security_def_item,
1407  &leakproof_item,
1408  &set_items,
1409  &cost_item,
1410  &rows_item,
1411  &support_item,
1412  &parallel_item) == false)
1413  elog(ERROR, "option \"%s\" not recognized", defel->defname);
1414  }
1415 
1416  if (volatility_item)
1417  procForm->provolatile = interpret_func_volatility(volatility_item);
1418  if (strict_item)
1419  procForm->proisstrict = intVal(strict_item->arg);
1420  if (security_def_item)
1421  procForm->prosecdef = intVal(security_def_item->arg);
1422  if (leakproof_item)
1423  {
1424  procForm->proleakproof = intVal(leakproof_item->arg);
1425  if (procForm->proleakproof && !superuser())
1426  ereport(ERROR,
1427  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1428  errmsg("only superuser can define a leakproof function")));
1429  }
1430  if (cost_item)
1431  {
1432  procForm->procost = defGetNumeric(cost_item);
1433  if (procForm->procost <= 0)
1434  ereport(ERROR,
1435  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1436  errmsg("COST must be positive")));
1437  }
1438  if (rows_item)
1439  {
1440  procForm->prorows = defGetNumeric(rows_item);
1441  if (procForm->prorows <= 0)
1442  ereport(ERROR,
1443  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1444  errmsg("ROWS must be positive")));
1445  if (!procForm->proretset)
1446  ereport(ERROR,
1447  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1448  errmsg("ROWS is not applicable when function does not return a set")));
1449  }
1450  if (support_item)
1451  {
1452  /* interpret_func_support handles the privilege check */
1453  Oid newsupport = interpret_func_support(support_item);
1454 
1455  /* Add or replace dependency on support function */
1456  if (OidIsValid(procForm->prosupport))
1457  changeDependencyFor(ProcedureRelationId, funcOid,
1458  ProcedureRelationId, procForm->prosupport,
1459  newsupport);
1460  else
1461  {
1462  ObjectAddress referenced;
1463 
1464  referenced.classId = ProcedureRelationId;
1465  referenced.objectId = newsupport;
1466  referenced.objectSubId = 0;
1467  recordDependencyOn(&address, &referenced, DEPENDENCY_NORMAL);
1468  }
1469 
1470  procForm->prosupport = newsupport;
1471  }
1472  if (set_items)
1473  {
1474  Datum datum;
1475  bool isnull;
1476  ArrayType *a;
1477  Datum repl_val[Natts_pg_proc];
1478  bool repl_null[Natts_pg_proc];
1479  bool repl_repl[Natts_pg_proc];
1480 
1481  /* extract existing proconfig setting */
1482  datum = SysCacheGetAttr(PROCOID, tup, Anum_pg_proc_proconfig, &isnull);
1483  a = isnull ? NULL : DatumGetArrayTypeP(datum);
1484 
1485  /* update according to each SET or RESET item, left to right */
1486  a = update_proconfig_value(a, set_items);
1487 
1488  /* update the tuple */
1489  memset(repl_repl, false, sizeof(repl_repl));
1490  repl_repl[Anum_pg_proc_proconfig - 1] = true;
1491 
1492  if (a == NULL)
1493  {
1494  repl_val[Anum_pg_proc_proconfig - 1] = (Datum) 0;
1495  repl_null[Anum_pg_proc_proconfig - 1] = true;
1496  }
1497  else
1498  {
1499  repl_val[Anum_pg_proc_proconfig - 1] = PointerGetDatum(a);
1500  repl_null[Anum_pg_proc_proconfig - 1] = false;
1501  }
1502 
1503  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1504  repl_val, repl_null, repl_repl);
1505  }
1506  if (parallel_item)
1507  procForm->proparallel = interpret_func_parallel(parallel_item);
1508 
1509  /* Do the update */
1510  CatalogTupleUpdate(rel, &tup->t_self, tup);
1511 
1512  InvokeObjectPostAlterHook(ProcedureRelationId, funcOid, 0);
1513 
1514  table_close(rel, NoLock);
1515  heap_freetuple(tup);
1516 
1517  return address;
1518 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
#define PointerGetDatum(X)
Definition: postgres.h:600
double defGetNumeric(DefElem *def)
Definition: define.c:85
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
static Oid interpret_func_support(DefElem *defel)
Definition: functioncmds.c:678
ItemPointerData t_self
Definition: htup.h:65
ObjectType objtype
Definition: parsenodes.h:2987
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:610
Node * arg
Definition: parsenodes.h:747
char * NameListToString(List *names)
Definition: namespace.c:3147
uintptr_t Datum
Definition: postgres.h:411
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:653
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define ereport(elevel,...)
Definition: elog.h:157
ObjectWithArgs * func
Definition: parsenodes.h:2988
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:169
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:909
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition: pg_depend.c:392
#define elog(elevel,...)
Definition: elog.h:232
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2207
char * defname
Definition: parsenodes.h:746
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
static bool compute_common_attribute(ParseState *pstate, bool is_procedure, DefElem *defel, DefElem **volatility_item, DefElem **strict_item, DefElem **security_item, DefElem **leakproof_item, List **set_items, DefElem **cost_item, DefElem **rows_item, DefElem **support_item, DefElem **parallel_item)
Definition: functioncmds.c:508
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4896
static char interpret_func_parallel(DefElem *defel)
Definition: functioncmds.c:628
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ CallStmtResultDesc()

TupleDesc CallStmtResultDesc ( CallStmt stmt)

Definition at line 2340 of file functioncmds.c.

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

Referenced by UtilityTupleDescriptor().

2341 {
2342  FuncExpr *fexpr;
2343  HeapTuple tuple;
2344  TupleDesc tupdesc;
2345 
2346  fexpr = stmt->funcexpr;
2347 
2348  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
2349  if (!HeapTupleIsValid(tuple))
2350  elog(ERROR, "cache lookup failed for procedure %u", fexpr->funcid);
2351 
2352  tupdesc = build_function_result_tupdesc_t(tuple);
2353 
2354  ReleaseSysCache(tuple);
2355 
2356  return tupdesc;
2357 }
FuncExpr * funcexpr
Definition: parsenodes.h:3026
TupleDesc build_function_result_tupdesc_t(HeapTuple procTuple)
Definition: funcapi.c:1602
Oid funcid
Definition: primnodes.h:495
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:232

◆ check_transform_function()

static void check_transform_function ( Form_pg_proc  procstruct)
static

Definition at line 1769 of file functioncmds.c.

References ereport, errcode(), errmsg(), and ERROR.

Referenced by CreateTransform().

1770 {
1771  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1772  ereport(ERROR,
1773  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1774  errmsg("transform function must not be volatile")));
1775  if (procstruct->prokind != PROKIND_FUNCTION)
1776  ereport(ERROR,
1777  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1778  errmsg("transform function must be a normal function")));
1779  if (procstruct->proretset)
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1782  errmsg("transform function must not return a set")));
1783  if (procstruct->pronargs != 1)
1784  ereport(ERROR,
1785  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1786  errmsg("transform function must take one argument")));
1787  if (procstruct->proargtypes.values[0] != INTERNALOID)
1788  ereport(ERROR,
1789  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1790  errmsg("first argument of transform function must be type %s",
1791  "internal")));
1792 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ compute_common_attribute()

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 
)
static

Definition at line 508 of file functioncmds.c.

References DefElem::arg, DefElem::defname, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), lappend(), DefElem::location, and parser_errposition().

Referenced by AlterFunction(), and compute_function_attributes().

520 {
521  if (strcmp(defel->defname, "volatility") == 0)
522  {
523  if (is_procedure)
524  goto procedure_error;
525  if (*volatility_item)
526  errorConflictingDefElem(defel, pstate);
527 
528  *volatility_item = defel;
529  }
530  else if (strcmp(defel->defname, "strict") == 0)
531  {
532  if (is_procedure)
533  goto procedure_error;
534  if (*strict_item)
535  errorConflictingDefElem(defel, pstate);
536 
537  *strict_item = defel;
538  }
539  else if (strcmp(defel->defname, "security") == 0)
540  {
541  if (*security_item)
542  errorConflictingDefElem(defel, pstate);
543 
544  *security_item = defel;
545  }
546  else if (strcmp(defel->defname, "leakproof") == 0)
547  {
548  if (is_procedure)
549  goto procedure_error;
550  if (*leakproof_item)
551  errorConflictingDefElem(defel, pstate);
552 
553  *leakproof_item = defel;
554  }
555  else if (strcmp(defel->defname, "set") == 0)
556  {
557  *set_items = lappend(*set_items, defel->arg);
558  }
559  else if (strcmp(defel->defname, "cost") == 0)
560  {
561  if (is_procedure)
562  goto procedure_error;
563  if (*cost_item)
564  errorConflictingDefElem(defel, pstate);
565 
566  *cost_item = defel;
567  }
568  else if (strcmp(defel->defname, "rows") == 0)
569  {
570  if (is_procedure)
571  goto procedure_error;
572  if (*rows_item)
573  errorConflictingDefElem(defel, pstate);
574 
575  *rows_item = defel;
576  }
577  else if (strcmp(defel->defname, "support") == 0)
578  {
579  if (is_procedure)
580  goto procedure_error;
581  if (*support_item)
582  errorConflictingDefElem(defel, pstate);
583 
584  *support_item = defel;
585  }
586  else if (strcmp(defel->defname, "parallel") == 0)
587  {
588  if (is_procedure)
589  goto procedure_error;
590  if (*parallel_item)
591  errorConflictingDefElem(defel, pstate);
592 
593  *parallel_item = defel;
594  }
595  else
596  return false;
597 
598  /* Recognized an option */
599  return true;
600 
601 procedure_error:
602  ereport(ERROR,
603  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
604  errmsg("invalid attribute in procedure definition"),
605  parser_errposition(pstate, defel->location)));
606  return false;
607 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int location
Definition: parsenodes.h:749
Node * arg
Definition: parsenodes.h:747
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * defname
Definition: parsenodes.h:746

◆ compute_function_attributes()

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 
)
static

Definition at line 722 of file functioncmds.c.

References DefElem::arg, compute_common_attribute(), defGetNumeric(), DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), interpret_func_parallel(), interpret_func_support(), interpret_func_volatility(), intVal, lfirst, DefElem::location, NIL, parser_errposition(), strVal, and update_proconfig_value().

Referenced by CreateFunction().

738 {
739  ListCell *option;
740  DefElem *as_item = NULL;
741  DefElem *language_item = NULL;
742  DefElem *transform_item = NULL;
743  DefElem *windowfunc_item = NULL;
744  DefElem *volatility_item = NULL;
745  DefElem *strict_item = NULL;
746  DefElem *security_item = NULL;
747  DefElem *leakproof_item = NULL;
748  List *set_items = NIL;
749  DefElem *cost_item = NULL;
750  DefElem *rows_item = NULL;
751  DefElem *support_item = NULL;
752  DefElem *parallel_item = NULL;
753 
754  foreach(option, options)
755  {
756  DefElem *defel = (DefElem *) lfirst(option);
757 
758  if (strcmp(defel->defname, "as") == 0)
759  {
760  if (as_item)
761  errorConflictingDefElem(defel, pstate);
762  as_item = defel;
763  }
764  else if (strcmp(defel->defname, "language") == 0)
765  {
766  if (language_item)
767  errorConflictingDefElem(defel, pstate);
768  language_item = defel;
769  }
770  else if (strcmp(defel->defname, "transform") == 0)
771  {
772  if (transform_item)
773  errorConflictingDefElem(defel, pstate);
774  transform_item = defel;
775  }
776  else if (strcmp(defel->defname, "window") == 0)
777  {
778  if (windowfunc_item)
779  errorConflictingDefElem(defel, pstate);
780  if (is_procedure)
781  ereport(ERROR,
782  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
783  errmsg("invalid attribute in procedure definition"),
784  parser_errposition(pstate, defel->location)));
785  windowfunc_item = defel;
786  }
787  else if (compute_common_attribute(pstate,
788  is_procedure,
789  defel,
790  &volatility_item,
791  &strict_item,
792  &security_item,
793  &leakproof_item,
794  &set_items,
795  &cost_item,
796  &rows_item,
797  &support_item,
798  &parallel_item))
799  {
800  /* recognized common option */
801  continue;
802  }
803  else
804  elog(ERROR, "option \"%s\" not recognized",
805  defel->defname);
806  }
807 
808  if (as_item)
809  *as = (List *) as_item->arg;
810  if (language_item)
811  *language = strVal(language_item->arg);
812  if (transform_item)
813  *transform = transform_item->arg;
814  if (windowfunc_item)
815  *windowfunc_p = intVal(windowfunc_item->arg);
816  if (volatility_item)
817  *volatility_p = interpret_func_volatility(volatility_item);
818  if (strict_item)
819  *strict_p = intVal(strict_item->arg);
820  if (security_item)
821  *security_definer = intVal(security_item->arg);
822  if (leakproof_item)
823  *leakproof_p = intVal(leakproof_item->arg);
824  if (set_items)
825  *proconfig = update_proconfig_value(NULL, set_items);
826  if (cost_item)
827  {
828  *procost = defGetNumeric(cost_item);
829  if (*procost <= 0)
830  ereport(ERROR,
831  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
832  errmsg("COST must be positive")));
833  }
834  if (rows_item)
835  {
836  *prorows = defGetNumeric(rows_item);
837  if (*prorows <= 0)
838  ereport(ERROR,
839  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
840  errmsg("ROWS must be positive")));
841  }
842  if (support_item)
843  *prosupport = interpret_func_support(support_item);
844  if (parallel_item)
845  *parallel_p = interpret_func_parallel(parallel_item);
846 }
#define NIL
Definition: pg_list.h:65
double defGetNumeric(DefElem *def)
Definition: define.c:85
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static Oid interpret_func_support(DefElem *defel)
Definition: functioncmds.c:678
int location
Definition: parsenodes.h:749
static char interpret_func_volatility(DefElem *defel)
Definition: functioncmds.c:610
Node * arg
Definition: parsenodes.h:747
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:653
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
char * defname
Definition: parsenodes.h:746
Definition: pg_list.h:50
static bool compute_common_attribute(ParseState *pstate, bool is_procedure, DefElem *defel, DefElem **volatility_item, DefElem **strict_item, DefElem **security_item, DefElem **leakproof_item, List **set_items, DefElem **cost_item, DefElem **rows_item, DefElem **support_item, DefElem **parallel_item)
Definition: functioncmds.c:508
static char interpret_func_parallel(DefElem *defel)
Definition: functioncmds.c:628

◆ compute_return_type()

static void compute_return_type ( TypeName returnType,
Oid  languageOid,
Oid prorettype_p,
bool returnsSet_p 
)
static

Definition at line 92 of file functioncmds.c.

References ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, Assert, ereport, errcode(), errdetail(), errmsg(), ERROR, get_namespace_name(), GETSTRUCT, GetUserId(), LookupTypeName(), TypeName::names, NIL, NOTICE, OBJECT_SCHEMA, ObjectAddress::objectId, OidIsValid, pg_namespace_aclcheck(), pg_type_aclcheck(), QualifiedNameGetCreationNamespace(), ReleaseSysCache(), TypeName::setof, TypeNameToString(), TypeShellMake(), typeTypeId(), TypeName::typmods, and typname.

Referenced by CreateFunction().

94 {
95  Oid rettype;
96  Type typtup;
97  AclResult aclresult;
98 
99  typtup = LookupTypeName(NULL, returnType, NULL, false);
100 
101  if (typtup)
102  {
103  if (!((Form_pg_type) GETSTRUCT(typtup))->typisdefined)
104  {
105  if (languageOid == SQLlanguageId)
106  ereport(ERROR,
107  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
108  errmsg("SQL function cannot return shell type %s",
109  TypeNameToString(returnType))));
110  else
111  ereport(NOTICE,
112  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
113  errmsg("return type %s is only a shell",
114  TypeNameToString(returnType))));
115  }
116  rettype = typeTypeId(typtup);
117  ReleaseSysCache(typtup);
118  }
119  else
120  {
121  char *typnam = TypeNameToString(returnType);
122  Oid namespaceId;
123  AclResult aclresult;
124  char *typname;
125  ObjectAddress address;
126 
127  /*
128  * Only C-coded functions can be I/O functions. We enforce this
129  * restriction here mainly to prevent littering the catalogs with
130  * shell types due to simple typos in user-defined function
131  * definitions.
132  */
133  if (languageOid != INTERNALlanguageId &&
134  languageOid != ClanguageId)
135  ereport(ERROR,
136  (errcode(ERRCODE_UNDEFINED_OBJECT),
137  errmsg("type \"%s\" does not exist", typnam)));
138 
139  /* Reject if there's typmod decoration, too */
140  if (returnType->typmods != NIL)
141  ereport(ERROR,
142  (errcode(ERRCODE_SYNTAX_ERROR),
143  errmsg("type modifier cannot be specified for shell type \"%s\"",
144  typnam)));
145 
146  /* Otherwise, go ahead and make a shell type */
147  ereport(NOTICE,
148  (errcode(ERRCODE_UNDEFINED_OBJECT),
149  errmsg("type \"%s\" is not yet defined", typnam),
150  errdetail("Creating a shell type definition.")));
151  namespaceId = QualifiedNameGetCreationNamespace(returnType->names,
152  &typname);
153  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
154  ACL_CREATE);
155  if (aclresult != ACLCHECK_OK)
156  aclcheck_error(aclresult, OBJECT_SCHEMA,
157  get_namespace_name(namespaceId));
158  address = TypeShellMake(typname, namespaceId, GetUserId());
159  rettype = address.objectId;
160  Assert(OidIsValid(rettype));
161  }
162 
163  aclresult = pg_type_aclcheck(rettype, GetUserId(), ACL_USAGE);
164  if (aclresult != ACLCHECK_OK)
165  aclcheck_error_type(aclresult, rettype);
166 
167  *prorettype_p = rettype;
168  *returnsSet_p = returnType->setof;
169 }
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:38
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * names
Definition: parsenodes.h:221
Oid GetUserId(void)
Definition: miscinit.c:478
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:3040
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
ObjectAddress TypeShellMake(const char *typeName, Oid typeNamespace, Oid ownerId)
Definition: pg_type.c:60
#define OidIsValid(objectId)
Definition: c.h:710
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4756
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3621
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
bool setof
Definition: parsenodes.h:223
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ACL_USAGE
Definition: parsenodes.h:90
NameData typname
Definition: pg_type.h:41
AclResult
Definition: acl.h:177
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
List * typmods
Definition: parsenodes.h:225
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define Assert(condition)
Definition: c.h:804
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
int errmsg(const char *fmt,...)
Definition: elog.c:909
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4806
Oid typeTypeId(Type tp)
Definition: parse_type.c:588

◆ CreateCast()

ObjectAddress CreateCast ( CreateCastStmt stmt)

Definition at line 1525 of file functioncmds.c.

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

Referenced by ProcessUtilitySlow().

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

◆ CreateFunction()

ObjectAddress CreateFunction ( ParseState pstate,
CreateFunctionStmt stmt 
)

Definition at line 1019 of file functioncmds.c.

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

Referenced by ProcessUtilitySlow().

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

◆ CreateTransform()

ObjectAddress CreateTransform ( CreateTransformStmt stmt)

Definition at line 1799 of file functioncmds.c.

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

Referenced by ProcessUtilitySlow().

1800 {
1801  Oid typeid;
1802  char typtype;
1803  Oid langid;
1804  Oid fromsqlfuncid;
1805  Oid tosqlfuncid;
1806  AclResult aclresult;
1807  Form_pg_proc procstruct;
1808  Datum values[Natts_pg_transform];
1809  bool nulls[Natts_pg_transform];
1810  bool replaces[Natts_pg_transform];
1811  Oid transformid;
1812  HeapTuple tuple;
1813  HeapTuple newtuple;
1814  Relation relation;
1815  ObjectAddress myself,
1816  referenced;
1817  ObjectAddresses *addrs;
1818  bool is_replace;
1819 
1820  /*
1821  * Get the type
1822  */
1823  typeid = typenameTypeId(NULL, stmt->type_name);
1824  typtype = get_typtype(typeid);
1825 
1826  if (typtype == TYPTYPE_PSEUDO)
1827  ereport(ERROR,
1828  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1829  errmsg("data type %s is a pseudo-type",
1830  TypeNameToString(stmt->type_name))));
1831 
1832  if (typtype == TYPTYPE_DOMAIN)
1833  ereport(ERROR,
1834  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1835  errmsg("data type %s is a domain",
1836  TypeNameToString(stmt->type_name))));
1837 
1838  if (!pg_type_ownercheck(typeid, GetUserId()))
1840 
1841  aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
1842  if (aclresult != ACLCHECK_OK)
1843  aclcheck_error_type(aclresult, typeid);
1844 
1845  /*
1846  * Get the language
1847  */
1848  langid = get_language_oid(stmt->lang, false);
1849 
1850  aclresult = pg_language_aclcheck(langid, GetUserId(), ACL_USAGE);
1851  if (aclresult != ACLCHECK_OK)
1852  aclcheck_error(aclresult, OBJECT_LANGUAGE, stmt->lang);
1853 
1854  /*
1855  * Get the functions
1856  */
1857  if (stmt->fromsql)
1858  {
1859  fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
1860 
1861  if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
1863 
1864  aclresult = pg_proc_aclcheck(fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1865  if (aclresult != ACLCHECK_OK)
1867 
1868  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1869  if (!HeapTupleIsValid(tuple))
1870  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1871  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1872  if (procstruct->prorettype != INTERNALOID)
1873  ereport(ERROR,
1874  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1875  errmsg("return data type of FROM SQL function must be %s",
1876  "internal")));
1877  check_transform_function(procstruct);
1878  ReleaseSysCache(tuple);
1879  }
1880  else
1881  fromsqlfuncid = InvalidOid;
1882 
1883  if (stmt->tosql)
1884  {
1885  tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
1886 
1887  if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
1889 
1890  aclresult = pg_proc_aclcheck(tosqlfuncid, GetUserId(), ACL_EXECUTE);
1891  if (aclresult != ACLCHECK_OK)
1893 
1894  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1895  if (!HeapTupleIsValid(tuple))
1896  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1897  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1898  if (procstruct->prorettype != typeid)
1899  ereport(ERROR,
1900  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1901  errmsg("return data type of TO SQL function must be the transform data type")));
1902  check_transform_function(procstruct);
1903  ReleaseSysCache(tuple);
1904  }
1905  else
1906  tosqlfuncid = InvalidOid;
1907 
1908  /*
1909  * Ready to go
1910  */
1911  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1912  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1913  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1914  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1915 
1916  MemSet(nulls, false, sizeof(nulls));
1917 
1918  relation = table_open(TransformRelationId, RowExclusiveLock);
1919 
1920  tuple = SearchSysCache2(TRFTYPELANG,
1921  ObjectIdGetDatum(typeid),
1922  ObjectIdGetDatum(langid));
1923  if (HeapTupleIsValid(tuple))
1924  {
1926 
1927  if (!stmt->replace)
1928  ereport(ERROR,
1930  errmsg("transform for type %s language \"%s\" already exists",
1931  format_type_be(typeid),
1932  stmt->lang)));
1933 
1934  MemSet(replaces, false, sizeof(replaces));
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 }
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
ObjectWithArgs * tosql
Definition: parsenodes.h:3528
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static void check_transform_function(Form_pg_proc procstruct)
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
Definition: dependency.c:2691
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:236
Oid get_language_oid(const char *langname, bool missing_ok)
Definition: proclang.c:228
int errcode(int sqlerrcode)
Definition: elog.c:698
char get_typtype(Oid typid)
Definition: lsyscache.c:2576
#define MemSet(start, val, len)
Definition: c.h:1008
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
Definition: dependency.c:2482
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
ObjectAddresses * new_object_addresses(void)
Definition: dependency.c:2427
void free_object_addresses(ObjectAddresses *addrs)
Definition: dependency.c:2722
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
bool pg_type_ownercheck(Oid type_oid, Oid roleid)
Definition: aclchk.c:4844
#define OidIsValid(objectId)
Definition: c.h:710
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4730
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3621
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
FormData_pg_transform * Form_pg_transform
Definition: pg_transform.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ACL_USAGE
Definition: parsenodes.h:90
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
char * NameListToString(List *names)
Definition: namespace.c:3147
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define InvalidOid
Definition: postgres_ext.h:36
ObjectWithArgs * fromsql
Definition: parsenodes.h:3527
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:184
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
TypeName * type_name
Definition: parsenodes.h:3525
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ACL_EXECUTE
Definition: parsenodes.h:89
#define elog(elevel,...)
Definition: elog.h:232
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4718
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
Definition: parse_func.c:2207
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4806
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4896
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ ExecuteCallStmt()

void ExecuteCallStmt ( CallStmt stmt,
ParamListInfo  params,
bool  atomic,
DestReceiver dest 
)

Definition at line 2176 of file functioncmds.c.

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, FuncExpr::args, Assert, CallContext::atomic, begin_tup_output_tupdesc(), CreateExecutorState(), CreateExprContext(), DatumGetHeapTupleHeader, TupOutputState::dest, elog, end_tup_output(), EnsurePortalSnapshotExists(), ereport, errcode(), errmsg_plural(), ERROR, EState::es_param_list_info, ExecEvalExprSwitchContext(), ExecPrepareExpr(), ExecStoreHeapTuple(), fmgr_info(), fmgr_info_set_expr, FreeExecutorState(), FUNC_MAX_ARGS, CallStmt::funcexpr, FuncExpr::funcid, FunctionCallInvoke, get_func_name(), GETSTRUCT, GetUserId(), heap_attisnull(), HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, InvokeFunctionExecuteHook, IsA, ItemPointerSetInvalid, lfirst, list_length(), LOCAL_FCINFO, lookup_rowtype_tupdesc(), makeNode, OBJECT_PROCEDURE, ObjectIdGetDatum, pg_proc_aclcheck(), pgstat_end_function_usage(), pgstat_init_function_usage(), PROCOID, _DestReceiver::receiveSlot, ReleaseSysCache(), ReleaseTupleDesc, SearchSysCache1(), TupOutputState::slot, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TTSOpsHeapTuple, and val.

Referenced by standard_ProcessUtility().

2177 {
2178  LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
2179  ListCell *lc;
2180  FuncExpr *fexpr;
2181  int nargs;
2182  int i;
2183  AclResult aclresult;
2184  FmgrInfo flinfo;
2185  CallContext *callcontext;
2186  EState *estate;
2187  ExprContext *econtext;
2188  HeapTuple tp;
2189  PgStat_FunctionCallUsage fcusage;
2190  Datum retval;
2191 
2192  fexpr = stmt->funcexpr;
2193  Assert(fexpr);
2194  Assert(IsA(fexpr, FuncExpr));
2195 
2196  aclresult = pg_proc_aclcheck(fexpr->funcid, GetUserId(), ACL_EXECUTE);
2197  if (aclresult != ACLCHECK_OK)
2198  aclcheck_error(aclresult, OBJECT_PROCEDURE, get_func_name(fexpr->funcid));
2199 
2200  /* Prep the context object we'll pass to the procedure */
2201  callcontext = makeNode(CallContext);
2202  callcontext->atomic = atomic;
2203 
2205  if (!HeapTupleIsValid(tp))
2206  elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
2207 
2208  /*
2209  * If proconfig is set we can't allow transaction commands because of the
2210  * way the GUC stacking works: The transaction boundary would have to pop
2211  * the proconfig setting off the stack. That restriction could be lifted
2212  * by redesigning the GUC nesting mechanism a bit.
2213  */
2214  if (!heap_attisnull(tp, Anum_pg_proc_proconfig, NULL))
2215  callcontext->atomic = true;
2216 
2217  /*
2218  * In security definer procedures, we can't allow transaction commands.
2219  * StartTransaction() insists that the security context stack is empty,
2220  * and AbortTransaction() resets the security context. This could be
2221  * reorganized, but right now it doesn't work.
2222  */
2223  if (((Form_pg_proc) GETSTRUCT(tp))->prosecdef)
2224  callcontext->atomic = true;
2225 
2226  ReleaseSysCache(tp);
2227 
2228  /* safety check; see ExecInitFunc() */
2229  nargs = list_length(fexpr->args);
2230  if (nargs > FUNC_MAX_ARGS)
2231  ereport(ERROR,
2232  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2233  errmsg_plural("cannot pass more than %d argument to a procedure",
2234  "cannot pass more than %d arguments to a procedure",
2235  FUNC_MAX_ARGS,
2236  FUNC_MAX_ARGS)));
2237 
2238  /* Initialize function call structure */
2240  fmgr_info(fexpr->funcid, &flinfo);
2241  fmgr_info_set_expr((Node *) fexpr, &flinfo);
2242  InitFunctionCallInfoData(*fcinfo, &flinfo, nargs, fexpr->inputcollid,
2243  (Node *) callcontext, NULL);
2244 
2245  /*
2246  * Evaluate procedure arguments inside a suitable execution context. Note
2247  * we can't free this context till the procedure returns.
2248  */
2249  estate = CreateExecutorState();
2250  estate->es_param_list_info = params;
2251  econtext = CreateExprContext(estate);
2252 
2253  i = 0;
2254  foreach(lc, fexpr->args)
2255  {
2256  ExprState *exprstate;
2257  Datum val;
2258  bool isnull;
2259 
2260  exprstate = ExecPrepareExpr(lfirst(lc), estate);
2261 
2262  val = ExecEvalExprSwitchContext(exprstate, econtext, &isnull);
2263 
2264  fcinfo->args[i].value = val;
2265  fcinfo->args[i].isnull = isnull;
2266 
2267  i++;
2268  }
2269 
2270  pgstat_init_function_usage(fcinfo, &fcusage);
2271  retval = FunctionCallInvoke(fcinfo);
2272  pgstat_end_function_usage(&fcusage, true);
2273 
2274  if (fexpr->funcresulttype == VOIDOID)
2275  {
2276  /* do nothing */
2277  }
2278  else if (fexpr->funcresulttype == RECORDOID)
2279  {
2280  /*
2281  * send tuple to client
2282  */
2283 
2284  HeapTupleHeader td;
2285  Oid tupType;
2286  int32 tupTypmod;
2287  TupleDesc retdesc;
2288  HeapTupleData rettupdata;
2289  TupOutputState *tstate;
2290  TupleTableSlot *slot;
2291 
2292  if (fcinfo->isnull)
2293  elog(ERROR, "procedure returned null record");
2294 
2295  /*
2296  * Ensure there's an active snapshot whilst we execute whatever's
2297  * involved here. Note that this is *not* sufficient to make the
2298  * world safe for TOAST pointers to be included in the returned data:
2299  * the referenced data could have gone away while we didn't hold a
2300  * snapshot. Hence, it's incumbent on PLs that can do COMMIT/ROLLBACK
2301  * to not return TOAST pointers, unless those pointers were fetched
2302  * after the last COMMIT/ROLLBACK in the procedure.
2303  *
2304  * XXX that is a really nasty, hard-to-test requirement. Is there a
2305  * way to remove it?
2306  */
2308 
2309  td = DatumGetHeapTupleHeader(retval);
2310  tupType = HeapTupleHeaderGetTypeId(td);
2311  tupTypmod = HeapTupleHeaderGetTypMod(td);
2312  retdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2313 
2314  tstate = begin_tup_output_tupdesc(dest, retdesc,
2315  &TTSOpsHeapTuple);
2316 
2317  rettupdata.t_len = HeapTupleHeaderGetDatumLength(td);
2318  ItemPointerSetInvalid(&(rettupdata.t_self));
2319  rettupdata.t_tableOid = InvalidOid;
2320  rettupdata.t_data = td;
2321 
2322  slot = ExecStoreHeapTuple(&rettupdata, tstate->slot, false);
2323  tstate->dest->receiveSlot(slot, tstate->dest);
2324 
2325  end_tup_output(tstate);
2326 
2327  ReleaseTupleDesc(retdesc);
2328  }
2329  else
2330  elog(ERROR, "unexpected result type for procedure: %u",
2331  fexpr->funcresulttype);
2332 
2333  FreeExecutorState(estate);
2334 }
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
Oid funcresulttype
Definition: primnodes.h:496
Definition: fmgr.h:56
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * args
Definition: primnodes.h:503
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1824
FuncExpr * funcexpr
Definition: parsenodes.h:3026
Oid GetUserId(void)
Definition: miscinit.c:478
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
void EnsurePortalSnapshotExists(void)
Definition: pquery.c:1747
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
TupleTableSlot * slot
Definition: executor.h:489
unsigned int Oid
Definition: postgres_ext.h:31
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:746
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
signed int int32
Definition: c.h:429
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:467
#define FUNC_MAX_ARGS
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
void end_tup_output(TupOutputState *tstate)
Definition: execTuples.c:2344
Oid funcid
Definition: primnodes.h:495
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
void pgstat_init_function_usage(FunctionCallInfo fcinfo, PgStat_FunctionCallUsage *fcu)
Definition: pgstat.c:1908
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1579
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
TupOutputState * begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2266
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
Oid t_tableOid
Definition: htup.h:66
EState * CreateExecutorState(void)
Definition: execUtils.c:90
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:191
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:457
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid inputcollid
Definition: primnodes.h:502
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
static int list_length(const List *l)
Definition: pg_list.h:149
void pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
Definition: pgstat.c:1979
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
#define ACL_EXECUTE
Definition: parsenodes.h:89
#define elog(elevel,...)
Definition: elog.h:232
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4718
int i
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
ExprContext * CreateExprContext(EState *estate)
Definition: execUtils.c:301
ParamListInfo es_param_list_info
Definition: execnodes.h:594
DestReceiver * dest
Definition: executor.h:490
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
long val
Definition: informix.c:664
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:451

◆ ExecuteDoStmt()

void ExecuteDoStmt ( ParseState pstate,
DoStmt stmt,
bool  atomic 
)

Definition at line 2054 of file functioncmds.c.

References ACL_USAGE, aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_OK, arg, DefElem::arg, DoStmt::args, InlineCodeBlock::atomic, DefElem::defname, elog, ereport, errcode(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), extension_file_exists(), GETSTRUCT, GetUserId(), HeapTupleIsValid, InlineCodeBlock::langIsTrusted, LANGNAME, InlineCodeBlock::langOid, lfirst, makeNode, NameStr, OBJECT_LANGUAGE, OidFunctionCall1, OidIsValid, pg_language_aclcheck(), PointerGetDatum, ReleaseSysCache(), SearchSysCache1(), InlineCodeBlock::source_text, strVal, and superuser().

Referenced by standard_ProcessUtility().

2055 {
2057  ListCell *arg;
2058  DefElem *as_item = NULL;
2059  DefElem *language_item = NULL;
2060  char *language;
2061  Oid laninline;
2062  HeapTuple languageTuple;
2063  Form_pg_language languageStruct;
2064 
2065  /* Process options we got from gram.y */
2066  foreach(arg, stmt->args)
2067  {
2068  DefElem *defel = (DefElem *) lfirst(arg);
2069 
2070  if (strcmp(defel->defname, "as") == 0)
2071  {
2072  if (as_item)
2073  errorConflictingDefElem(defel, pstate);
2074  as_item = defel;
2075  }
2076  else if (strcmp(defel->defname, "language") == 0)
2077  {
2078  if (language_item)
2079  errorConflictingDefElem(defel, pstate);
2080  language_item = defel;
2081  }
2082  else
2083  elog(ERROR, "option \"%s\" not recognized",
2084  defel->defname);
2085  }
2086 
2087  if (as_item)
2088  codeblock->source_text = strVal(as_item->arg);
2089  else
2090  ereport(ERROR,
2091  (errcode(ERRCODE_SYNTAX_ERROR),
2092  errmsg("no inline code specified")));
2093 
2094  /* if LANGUAGE option wasn't specified, use the default */
2095  if (language_item)
2096  language = strVal(language_item->arg);
2097  else
2098  language = "plpgsql";
2099 
2100  /* Look up the language and validate permissions */
2101  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
2102  if (!HeapTupleIsValid(languageTuple))
2103  ereport(ERROR,
2104  (errcode(ERRCODE_UNDEFINED_OBJECT),
2105  errmsg("language \"%s\" does not exist", language),
2106  (extension_file_exists(language) ?
2107  errhint("Use CREATE EXTENSION to load the language into the database.") : 0)));
2108 
2109  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
2110  codeblock->langOid = languageStruct->oid;
2111  codeblock->langIsTrusted = languageStruct->lanpltrusted;
2112  codeblock->atomic = atomic;
2113 
2114  if (languageStruct->lanpltrusted)
2115  {
2116  /* if trusted language, need USAGE privilege */
2117  AclResult aclresult;
2118 
2119  aclresult = pg_language_aclcheck(codeblock->langOid, GetUserId(),
2120  ACL_USAGE);
2121  if (aclresult != ACLCHECK_OK)
2122  aclcheck_error(aclresult, OBJECT_LANGUAGE,
2123  NameStr(languageStruct->lanname));
2124  }
2125  else
2126  {
2127  /* if untrusted language, must be superuser */
2128  if (!superuser())
2130  NameStr(languageStruct->lanname));
2131  }
2132 
2133  /* get the handler function's OID */
2134  laninline = languageStruct->laninline;
2135  if (!OidIsValid(laninline))
2136  ereport(ERROR,
2137  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2138  errmsg("language \"%s\" does not support inline code execution",
2139  NameStr(languageStruct->lanname))));
2140 
2141  ReleaseSysCache(languageTuple);
2142 
2143  /* execute the inline handler */
2144  OidFunctionCall1(laninline, PointerGetDatum(codeblock));
2145 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
#define PointerGetDatum(X)
Definition: postgres.h:600
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4730
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ERROR
Definition: elog.h:46
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
#define ACL_USAGE
Definition: parsenodes.h:90
Node * arg
Definition: parsenodes.h:747
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
AclResult
Definition: acl.h:177
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:169
List * args
Definition: parsenodes.h:3001
bool extension_file_exists(const char *extensionName)
Definition: extension.c:2229
FormData_pg_language * Form_pg_language
Definition: pg_language.h:65
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
void * arg
char * source_text
Definition: parsenodes.h:3007
char * defname
Definition: parsenodes.h:746

◆ get_transform_oid()

Oid get_transform_oid ( Oid  type_id,
Oid  lang_id,
bool  missing_ok 
)

Definition at line 2007 of file functioncmds.c.

References ereport, errcode(), errmsg(), ERROR, format_type_be(), get_language_name(), GetSysCacheOid2, ObjectIdGetDatum, OidIsValid, and TRFTYPELANG.

Referenced by CreateFunction(), get_object_address(), and ProcedureCreate().

2008 {
2009  Oid oid;
2010 
2011  oid = GetSysCacheOid2(TRFTYPELANG, Anum_pg_transform_oid,
2012  ObjectIdGetDatum(type_id),
2013  ObjectIdGetDatum(lang_id));
2014  if (!OidIsValid(oid) && !missing_ok)
2015  ereport(ERROR,
2016  (errcode(ERRCODE_UNDEFINED_OBJECT),
2017  errmsg("transform for type %s language \"%s\" does not exist",
2018  format_type_be(type_id),
2019  get_language_name(lang_id, false))));
2020  return oid;
2021 }
char * get_language_name(Oid langoid, bool missing_ok)
Definition: lsyscache.c:1154
int errcode(int sqlerrcode)
Definition: elog.c:698
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:195
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ interpret_AS_clause()

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 
)
static

Definition at line 859 of file functioncmds.c.

References SQLFunctionParseInfo::argnames, SQLFunctionParseInfo::argtypes, castNode, CMD_UTILITY, Query::commandType, CreateCommandTag(), ereport, errcode(), errmsg(), ERROR, SQLFunctionParseInfo::fname, free_parsestate(), GetCommandTagName(), i, IsA, lappend(), lfirst, linitial, linitial_node, list_length(), list_make1, list_nth(), list_nth_oid(), lsecond, make_parsestate(), SQLFunctionParseInfo::nargs, NIL, ParseState::p_sourcetext, palloc(), palloc0(), pstrdup(), sql_fn_parser_setup(), strVal, transformStmt(), and Query::utilityStmt.

Referenced by CreateFunction().

865 {
866  if (!sql_body_in && !as)
867  ereport(ERROR,
868  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
869  errmsg("no function body specified")));
870 
871  if (sql_body_in && as)
872  ereport(ERROR,
873  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
874  errmsg("duplicate function body specified")));
875 
876  if (sql_body_in && languageOid != SQLlanguageId)
877  ereport(ERROR,
878  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
879  errmsg("inline SQL function body only valid for language SQL")));
880 
881  *sql_body_out = NULL;
882 
883  if (languageOid == ClanguageId)
884  {
885  /*
886  * For "C" language, store the file name in probin and, when given,
887  * the link symbol name in prosrc. If link symbol is omitted,
888  * substitute procedure name. We also allow link symbol to be
889  * specified as "-", since that was the habit in PG versions before
890  * 8.4, and there might be dump files out there that don't translate
891  * that back to "omitted".
892  */
893  *probin_str_p = strVal(linitial(as));
894  if (list_length(as) == 1)
895  *prosrc_str_p = funcname;
896  else
897  {
898  *prosrc_str_p = strVal(lsecond(as));
899  if (strcmp(*prosrc_str_p, "-") == 0)
900  *prosrc_str_p = funcname;
901  }
902  }
903  else if (sql_body_in)
904  {
906 
908 
909  pinfo->fname = funcname;
910  pinfo->nargs = list_length(parameterTypes);
911  pinfo->argtypes = (Oid *) palloc(pinfo->nargs * sizeof(Oid));
912  pinfo->argnames = (char **) palloc(pinfo->nargs * sizeof(char *));
913  for (int i = 0; i < list_length(parameterTypes); i++)
914  {
915  char *s = strVal(list_nth(inParameterNames, i));
916 
917  pinfo->argtypes[i] = list_nth_oid(parameterTypes, i);
918  if (IsPolymorphicType(pinfo->argtypes[i]))
919  ereport(ERROR,
920  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
921  errmsg("SQL function with unquoted function body cannot have polymorphic arguments")));
922 
923  if (s[0] != '\0')
924  pinfo->argnames[i] = s;
925  else
926  pinfo->argnames[i] = NULL;
927  }
928 
929  if (IsA(sql_body_in, List))
930  {
931  List *stmts = linitial_node(List, castNode(List, sql_body_in));
932  ListCell *lc;
933  List *transformed_stmts = NIL;
934 
935  foreach(lc, stmts)
936  {
937  Node *stmt = lfirst(lc);
938  Query *q;
939  ParseState *pstate = make_parsestate(NULL);
940 
941  pstate->p_sourcetext = queryString;
942  sql_fn_parser_setup(pstate, pinfo);
943  q = transformStmt(pstate, stmt);
944  if (q->commandType == CMD_UTILITY)
945  ereport(ERROR,
946  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
947  errmsg("%s is not yet supported in unquoted SQL function body",
949  transformed_stmts = lappend(transformed_stmts, q);
950  free_parsestate(pstate);
951  }
952 
953  *sql_body_out = (Node *) list_make1(transformed_stmts);
954  }
955  else
956  {
957  Query *q;
958  ParseState *pstate = make_parsestate(NULL);
959 
960  pstate->p_sourcetext = queryString;
961  sql_fn_parser_setup(pstate, pinfo);
962  q = transformStmt(pstate, sql_body_in);
963  if (q->commandType == CMD_UTILITY)
964  ereport(ERROR,
965  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
966  errmsg("%s is not yet supported in unquoted SQL function body",
968  free_parsestate(pstate);
969 
970  *sql_body_out = (Node *) q;
971  }
972 
973  /*
974  * We must put something in prosrc. For the moment, just record an
975  * empty string. It might be useful to store the original text of the
976  * CREATE FUNCTION statement --- but to make actual use of that in
977  * error reports, we'd also have to adjust readfuncs.c to not throw
978  * away node location fields when reading prosqlbody.
979  */
980  *prosrc_str_p = pstrdup("");
981 
982  /* But we definitely don't need probin. */
983  *probin_str_p = NULL;
984  }
985  else
986  {
987  /* Everything else wants the given string in prosrc. */
988  *prosrc_str_p = strVal(linitial(as));
989  *probin_str_p = NULL;
990 
991  if (list_length(as) != 1)
992  ereport(ERROR,
993  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
994  errmsg("only one AS item needed for language \"%s\"",
995  languageName)));
996 
997  if (languageOid == INTERNALlanguageId)
998  {
999  /*
1000  * In PostgreSQL versions before 6.5, the SQL name of the created
1001  * function could not be different from the internal name, and
1002  * "prosrc" wasn't used. So there is code out there that does
1003  * CREATE FUNCTION xyz AS '' LANGUAGE internal. To preserve some
1004  * modicum of backwards compatibility, accept an empty "prosrc"
1005  * value as meaning the supplied SQL function name.
1006  */
1007  if (strlen(*prosrc_str_p) == 0)
1008  *prosrc_str_p = funcname;
1009  }
1010  }
1011 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
Definition: nodes.h:539
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:128
#define linitial_node(type, l)
Definition: pg_list.h:177
#define lsecond(l)
Definition: pg_list.h:179
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
static Oid list_nth_oid(const List *list, int n)
Definition: pg_list.h:300
#define list_make1(x1)
Definition: pg_list.h:206
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
const char * p_sourcetext
Definition: parse_node.h:181
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:276
List * lappend(List *list, void *datum)
Definition: list.c:336
void * palloc0(Size size)
Definition: mcxt.c:1093
#define ereport(elevel,...)
Definition: elog.h:157
CmdType commandType
Definition: parsenodes.h:120
#define lfirst(lc)
Definition: pg_list.h:169
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2320
SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:35
static int list_length(const List *l)
Definition: pg_list.h:149
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:50

◆ interpret_func_parallel()

static char interpret_func_parallel ( DefElem defel)
static

Definition at line 628 of file functioncmds.c.

References DefElem::arg, ereport, errcode(), errmsg(), ERROR, generate_unaccent_rules::str, and strVal.

Referenced by AlterFunction(), and compute_function_attributes().

629 {
630  char *str = strVal(defel->arg);
631 
632  if (strcmp(str, "safe") == 0)
633  return PROPARALLEL_SAFE;
634  else if (strcmp(str, "unsafe") == 0)
635  return PROPARALLEL_UNSAFE;
636  else if (strcmp(str, "restricted") == 0)
637  return PROPARALLEL_RESTRICTED;
638  else
639  {
640  ereport(ERROR,
641  (errcode(ERRCODE_SYNTAX_ERROR),
642  errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
643  return PROPARALLEL_UNSAFE; /* keep compiler quiet */
644  }
645 }
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
Node * arg
Definition: parsenodes.h:747
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ interpret_func_support()

static Oid interpret_func_support ( DefElem defel)
static

Definition at line 678 of file functioncmds.c.

References defGetQualifiedName(), ereport, errcode(), errmsg(), ERROR, func_signature_string(), get_func_rettype(), LookupFuncName(), NameListToString(), NIL, OidIsValid, and superuser().

Referenced by AlterFunction(), and compute_function_attributes().

679 {
680  List *procName = defGetQualifiedName(defel);
681  Oid procOid;
682  Oid argList[1];
683 
684  /*
685  * Support functions always take one INTERNAL argument and return
686  * INTERNAL.
687  */
688  argList[0] = INTERNALOID;
689 
690  procOid = LookupFuncName(procName, 1, argList, true);
691  if (!OidIsValid(procOid))
692  ereport(ERROR,
693  (errcode(ERRCODE_UNDEFINED_FUNCTION),
694  errmsg("function %s does not exist",
695  func_signature_string(procName, 1, NIL, argList))));
696 
697  if (get_func_rettype(procOid) != INTERNALOID)
698  ereport(ERROR,
699  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
700  errmsg("support function %s must return type %s",
701  NameListToString(procName), "internal")));
702 
703  /*
704  * Someday we might want an ACL check here; but for now, we insist that
705  * you be superuser to specify a support function, so privilege on the
706  * support function is moot.
707  */
708  if (!superuser())
709  ereport(ERROR,
710  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
711  errmsg("must be superuser to specify a support function")));
712 
713  return procOid;
714 }
#define NIL
Definition: pg_list.h:65
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1626
#define ERROR
Definition: elog.h:46
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2145
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2031
char * NameListToString(List *names)
Definition: namespace.c:3147
#define ereport(elevel,...)
Definition: elog.h:157
List * defGetQualifiedName(DefElem *def)
Definition: define.c:223
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: pg_list.h:50

◆ interpret_func_volatility()

static char interpret_func_volatility ( DefElem defel)
static

Definition at line 610 of file functioncmds.c.

References DefElem::arg, elog, ERROR, generate_unaccent_rules::str, and strVal.

Referenced by AlterFunction(), and compute_function_attributes().

611 {
612  char *str = strVal(defel->arg);
613 
614  if (strcmp(str, "immutable") == 0)
615  return PROVOLATILE_IMMUTABLE;
616  else if (strcmp(str, "stable") == 0)
617  return PROVOLATILE_STABLE;
618  else if (strcmp(str, "volatile") == 0)
619  return PROVOLATILE_VOLATILE;
620  else
621  {
622  elog(ERROR, "invalid volatility \"%s\"", str);
623  return 0; /* keep compiler quiet */
624  }
625 }
#define strVal(v)
Definition: value.h:54
#define ERROR
Definition: elog.h:46
Node * arg
Definition: parsenodes.h:747
#define elog(elevel,...)
Definition: elog.h:232

◆ interpret_function_parameter_list()

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 at line 188 of file functioncmds.c.

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, FunctionParameter::argType, assign_expr_collations(), buildoidvector(), CharGetDatum, coerce_to_specific_type(), construct_array(), contain_var_clause(), CStringGetTextDatum, FunctionParameter::defexpr, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_FUNCTION_DEFAULT, FUNC_PARAM_DEFAULT, FUNC_PARAM_IN, FUNC_PARAM_OUT, FUNC_PARAM_TABLE, FUNC_PARAM_VARIADIC, get_element_type(), GETSTRUCT, GetUserId(), i, InvalidOid, lappend(), lappend_oid(), lfirst, list_length(), LookupTypeName(), makeString(), FunctionParameter::mode, FunctionParameter::name, NIL, NOTICE, OBJECT_AGGREGATE, OBJECT_PROCEDURE, ObjectIdGetDatum, OidIsValid, ParseState::p_rtable, palloc(), palloc0(), pg_type_aclcheck(), PointerGetDatum, pstrdup(), px(), ReleaseSysCache(), TypeName::setof, transformExpr(), TypeNameToString(), and typeTypeId().

Referenced by CreateFunction(), and DefineAggregate().

201 {
202  int parameterCount = list_length(parameters);
203  Oid *inTypes;
204  int inCount = 0;
205  Datum *allTypes;
206  Datum *paramModes;
207  Datum *paramNames;
208  int outCount = 0;
209  int varCount = 0;
210  bool have_names = false;
211  bool have_defaults = false;
212  ListCell *x;
213  int i;
214 
215  *variadicArgType = InvalidOid; /* default result */
216  *requiredResultType = InvalidOid; /* default result */
217 
218  inTypes = (Oid *) palloc(parameterCount * sizeof(Oid));
219  allTypes = (Datum *) palloc(parameterCount * sizeof(Datum));
220  paramModes = (Datum *) palloc(parameterCount * sizeof(Datum));
221  paramNames = (Datum *) palloc0(parameterCount * sizeof(Datum));
222  *parameterDefaults = NIL;
223 
224  /* Scan the list and extract data into work arrays */
225  i = 0;
226  foreach(x, parameters)
227  {
229  TypeName *t = fp->argType;
230  FunctionParameterMode fpmode = fp->mode;
231  bool isinput = false;
232  Oid toid;
233  Type typtup;
234  AclResult aclresult;
235 
236  /* For our purposes here, a defaulted mode spec is identical to IN */
237  if (fpmode == FUNC_PARAM_DEFAULT)
238  fpmode = FUNC_PARAM_IN;
239 
240  typtup = LookupTypeName(NULL, t, NULL, false);
241  if (typtup)
242  {
243  if (!((Form_pg_type) GETSTRUCT(typtup))->typisdefined)
244  {
245  /* As above, hard error if language is SQL */
246  if (languageOid == SQLlanguageId)
247  ereport(ERROR,
248  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
249  errmsg("SQL function cannot accept shell type %s",
250  TypeNameToString(t))));
251  /* We don't allow creating aggregates on shell types either */
252  else if (objtype == OBJECT_AGGREGATE)
253  ereport(ERROR,
254  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
255  errmsg("aggregate cannot accept shell type %s",
256  TypeNameToString(t))));
257  else
258  ereport(NOTICE,
259  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
260  errmsg("argument type %s is only a shell",
261  TypeNameToString(t))));
262  }
263  toid = typeTypeId(typtup);
264  ReleaseSysCache(typtup);
265  }
266  else
267  {
268  ereport(ERROR,
269  (errcode(ERRCODE_UNDEFINED_OBJECT),
270  errmsg("type %s does not exist",
271  TypeNameToString(t))));
272  toid = InvalidOid; /* keep compiler quiet */
273  }
274 
275  aclresult = pg_type_aclcheck(toid, GetUserId(), ACL_USAGE);
276  if (aclresult != ACLCHECK_OK)
277  aclcheck_error_type(aclresult, toid);
278 
279  if (t->setof)
280  {
281  if (objtype == OBJECT_AGGREGATE)
282  ereport(ERROR,
283  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
284  errmsg("aggregates cannot accept set arguments")));
285  else if (objtype == OBJECT_PROCEDURE)
286  ereport(ERROR,
287  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
288  errmsg("procedures cannot accept set arguments")));
289  else
290  ereport(ERROR,
291  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
292  errmsg("functions cannot accept set arguments")));
293  }
294 
295  /* handle input parameters */
296  if (fpmode != FUNC_PARAM_OUT && fpmode != FUNC_PARAM_TABLE)
297  {
298  /* other input parameters can't follow a VARIADIC parameter */
299  if (varCount > 0)
300  ereport(ERROR,
301  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
302  errmsg("VARIADIC parameter must be the last input parameter")));
303  inTypes[inCount++] = toid;
304  isinput = true;
305  if (parameterTypes_list)
306  *parameterTypes_list = lappend_oid(*parameterTypes_list, toid);
307  }
308 
309  /* handle output parameters */
310  if (fpmode != FUNC_PARAM_IN && fpmode != FUNC_PARAM_VARIADIC)
311  {
312  if (objtype == OBJECT_PROCEDURE)
313  {
314  /*
315  * We disallow OUT-after-VARIADIC only for procedures. While
316  * such a case causes no confusion in ordinary function calls,
317  * it would cause confusion in a CALL statement.
318  */
319  if (varCount > 0)
320  ereport(ERROR,
321  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
322  errmsg("VARIADIC parameter must be the last parameter")));
323  /* Procedures with output parameters always return RECORD */
324  *requiredResultType = RECORDOID;
325  }
326  else if (outCount == 0) /* save first output param's type */
327  *requiredResultType = toid;
328  outCount++;
329  }
330 
331  if (fpmode == FUNC_PARAM_VARIADIC)
332  {
333  *variadicArgType = toid;
334  varCount++;
335  /* validate variadic parameter type */
336  switch (toid)
337  {
338  case ANYARRAYOID:
339  case ANYCOMPATIBLEARRAYOID:
340  case ANYOID:
341  /* okay */
342  break;
343  default:
344  if (!OidIsValid(get_element_type(toid)))
345  ereport(ERROR,
346  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
347  errmsg("VARIADIC parameter must be an array")));
348  break;
349  }
350  }
351 
352  allTypes[i] = ObjectIdGetDatum(toid);
353 
354  paramModes[i] = CharGetDatum(fpmode);
355 
356  if (fp->name && fp->name[0])
357  {
358  ListCell *px;
359 
360  /*
361  * As of Postgres 9.0 we disallow using the same name for two
362  * input or two output function parameters. Depending on the
363  * function's language, conflicting input and output names might
364  * be bad too, but we leave it to the PL to complain if so.
365  */
366  foreach(px, parameters)
367  {
368  FunctionParameter *prevfp = (FunctionParameter *) lfirst(px);
369  FunctionParameterMode prevfpmode;
370 
371  if (prevfp == fp)
372  break;
373  /* as above, default mode is IN */
374  prevfpmode = prevfp->mode;
375  if (prevfpmode == FUNC_PARAM_DEFAULT)
376  prevfpmode = FUNC_PARAM_IN;
377  /* pure in doesn't conflict with pure out */
378  if ((fpmode == FUNC_PARAM_IN ||
379  fpmode == FUNC_PARAM_VARIADIC) &&
380  (prevfpmode == FUNC_PARAM_OUT ||
381  prevfpmode == FUNC_PARAM_TABLE))
382  continue;
383  if ((prevfpmode == FUNC_PARAM_IN ||
384  prevfpmode == FUNC_PARAM_VARIADIC) &&
385  (fpmode == FUNC_PARAM_OUT ||
386  fpmode == FUNC_PARAM_TABLE))
387  continue;
388  if (prevfp->name && prevfp->name[0] &&
389  strcmp(prevfp->name, fp->name) == 0)
390  ereport(ERROR,
391  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
392  errmsg("parameter name \"%s\" used more than once",
393  fp->name)));
394  }
395 
396  paramNames[i] = CStringGetTextDatum(fp->name);
397  have_names = true;
398  }
399 
400  if (inParameterNames_list)
401  *inParameterNames_list = lappend(*inParameterNames_list, makeString(fp->name ? fp->name : pstrdup("")));
402 
403  if (fp->defexpr)
404  {
405  Node *def;
406 
407  if (!isinput)
408  ereport(ERROR,
409  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
410  errmsg("only input parameters can have default values")));
411 
412  def = transformExpr(pstate, fp->defexpr,
414  def = coerce_to_specific_type(pstate, def, toid, "DEFAULT");
415  assign_expr_collations(pstate, def);
416 
417  /*
418  * Make sure no variables are referred to (this is probably dead
419  * code now that add_missing_from is history).
420  */
421  if (list_length(pstate->p_rtable) != 0 ||
422  contain_var_clause(def))
423  ereport(ERROR,
424  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
425  errmsg("cannot use table references in parameter default value")));
426 
427  /*
428  * transformExpr() should have already rejected subqueries,
429  * aggregates, and window functions, based on the EXPR_KIND_ for a
430  * default expression.
431  *
432  * It can't return a set either --- but coerce_to_specific_type
433  * already checked that for us.
434  *
435  * Note: the point of these restrictions is to ensure that an
436  * expression that, on its face, hasn't got subplans, aggregates,
437  * etc cannot suddenly have them after function default arguments
438  * are inserted.
439  */
440 
441  *parameterDefaults = lappend(*parameterDefaults, def);
442  have_defaults = true;
443  }
444  else
445  {
446  if (isinput && have_defaults)
447  ereport(ERROR,
448  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
449  errmsg("input parameters after one with a default value must also have defaults")));
450 
451  /*
452  * For procedures, we also can't allow OUT parameters after one
453  * with a default, because the same sort of confusion arises in a
454  * CALL statement.
455  */
456  if (objtype == OBJECT_PROCEDURE && have_defaults)
457  ereport(ERROR,
458  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
459  errmsg("procedure OUT parameters cannot appear after one with a default value")));
460  }
461 
462  i++;
463  }
464 
465  /* Now construct the proper outputs as needed */
466  *parameterTypes = buildoidvector(inTypes, inCount);
467 
468  if (outCount > 0 || varCount > 0)
469  {
470  *allParameterTypes = construct_array(allTypes, parameterCount, OIDOID,
471  sizeof(Oid), true, TYPALIGN_INT);
472  *parameterModes = construct_array(paramModes, parameterCount, CHAROID,
473  1, true, TYPALIGN_CHAR);
474  if (outCount > 1)
475  *requiredResultType = RECORDOID;
476  /* otherwise we set requiredResultType correctly above */
477  }
478  else
479  {
480  *allParameterTypes = NULL;
481  *parameterModes = NULL;
482  }
483 
484  if (have_names)
485  {
486  for (i = 0; i < parameterCount; i++)
487  {
488  if (paramNames[i] == PointerGetDatum(NULL))
489  paramNames[i] = CStringGetTextDatum("");
490  }
491  *parameterNames = construct_array(paramNames, parameterCount, TEXTOID,
492  -1, false, TYPALIGN_INT);
493  }
494  else
495  *parameterNames = NULL;
496 }
Value * makeString(char *str)
Definition: value.c:53
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:38
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2706
#define PointerGetDatum(X)
Definition: postgres.h:600
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
bool contain_var_clause(Node *node)
Definition: var.c:358
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3621
void assign_expr_collations(ParseState *pstate, Node *expr)
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool setof
Definition: parsenodes.h:223
FunctionParameterMode
Definition: parsenodes.h:2963
#define ACL_USAGE
Definition: parsenodes.h:90
TypeName * argType
Definition: parsenodes.h:2979
List * lappend(List *list, void *datum)
Definition: list.c:336
void * palloc0(Size size)
Definition: mcxt.c:1093
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define InvalidOid
Definition: postgres_ext.h:36
void px(PlannerInfo *root, Gene *tour1, Gene *tour2, Gene *offspring, int num_gene, City *city_table)
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
#define lfirst(lc)
Definition: pg_list.h:169
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static int list_length(const List *l)
Definition: pg_list.h:149
#define CharGetDatum(X)
Definition: postgres.h:460
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
#define CStringGetTextDatum(s)
Definition: builtins.h:82
FunctionParameterMode mode
Definition: parsenodes.h:2980
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4806
Oid typeTypeId(Type tp)
Definition: parse_type.c:588
List * p_rtable
Definition: parse_node.h:182

◆ IsThereFunctionInNamespace()

void IsThereFunctionInNamespace ( const char *  proname,
int  pronargs,
oidvector proargtypes,
Oid  nspOid 
)

Definition at line 2031 of file functioncmds.c.

References CStringGetDatum, ereport, errcode(), errmsg(), ERROR, funcname_signature_string(), get_namespace_name(), NIL, ObjectIdGetDatum, PointerGetDatum, PROCNAMEARGSNSP, SearchSysCacheExists3, and oidvector::values.

Referenced by AlterObjectNamespace_internal(), and AlterObjectRename_internal().

2033 {
2034  /* check for duplicate name (more friendly than unique-index failure) */
2037  PointerGetDatum(proargtypes),
2038  ObjectIdGetDatum(nspOid)))
2039  ereport(ERROR,
2040  (errcode(ERRCODE_DUPLICATE_FUNCTION),
2041  errmsg("function %s already exists in schema \"%s\"",
2043  NIL, proargtypes->values),
2044  get_namespace_name(nspOid))));
2045 }
#define NIL
Definition: pg_list.h:65
NameData proname
Definition: pg_proc.h:35
#define PointerGetDatum(X)
Definition: postgres.h:600
int errcode(int sqlerrcode)
Definition: elog.c:698
int16 pronargs
Definition: pg_proc.h:81
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define SearchSysCacheExists3(cacheId, key1, key2, key3)
Definition: syscache.h:188
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:668
#define CStringGetDatum(X)
Definition: postgres.h:622
const char * funcname_signature_string(const char *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1994
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ RemoveFunctionById()

void RemoveFunctionById ( Oid  funcOid)

Definition at line 1304 of file functioncmds.c.

References AGGFNOID, CatalogTupleDelete(), elog, ERROR, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, PROCOID, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by doDeletion().

1305 {
1306  Relation relation;
1307  HeapTuple tup;
1308  char prokind;
1309 
1310  /*
1311  * Delete the pg_proc tuple.
1312  */
1313  relation = table_open(ProcedureRelationId, RowExclusiveLock);
1314 
1315  tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
1316  if (!HeapTupleIsValid(tup)) /* should not happen */
1317  elog(ERROR, "cache lookup failed for function %u", funcOid);
1318 
1319  prokind = ((Form_pg_proc) GETSTRUCT(tup))->prokind;
1320 
1321  CatalogTupleDelete(relation, &tup->t_self);
1322 
1323  ReleaseSysCache(tup);
1324 
1325  table_close(relation, RowExclusiveLock);
1326 
1327  /*
1328  * If there's a pg_aggregate tuple, delete that too.
1329  */
1330  if (prokind == PROKIND_AGGREGATE)
1331  {
1332  relation = table_open(AggregateRelationId, RowExclusiveLock);
1333 
1334  tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcOid));
1335  if (!HeapTupleIsValid(tup)) /* should not happen */
1336  elog(ERROR, "cache lookup failed for pg_aggregate tuple for function %u", funcOid);
1337 
1338  CatalogTupleDelete(relation, &tup->t_self);
1339 
1340  ReleaseSysCache(tup);
1341 
1342  table_close(relation, RowExclusiveLock);
1343  }
1344 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ update_proconfig_value()

static ArrayType* update_proconfig_value ( ArrayType a,
List set_items 
)
static

Definition at line 653 of file functioncmds.c.

References ExtractSetVariableArgs(), GUCArrayAdd(), GUCArrayDelete(), VariableSetStmt::kind, lfirst_node, VariableSetStmt::name, and VAR_RESET_ALL.

Referenced by AlterFunction(), and compute_function_attributes().

654 {
655  ListCell *l;
656 
657  foreach(l, set_items)
658  {
660 
661  if (sstmt->kind == VAR_RESET_ALL)
662  a = NULL;
663  else
664  {
665  char *valuestr = ExtractSetVariableArgs(sstmt);
666 
667  if (valuestr)
668  a = GUCArrayAdd(a, sstmt->name, valuestr);
669  else /* RESET */
670  a = GUCArrayDelete(a, sstmt->name);
671  }
672  }
673 
674  return a;
675 }
ArrayType * GUCArrayAdd(ArrayType *array, const char *name, const char *value)
Definition: guc.c:11082
VariableSetKind kind
Definition: parsenodes.h:2141
#define lfirst_node(type, lc)
Definition: pg_list.h:172
ArrayType * GUCArrayDelete(ArrayType *array, const char *name)
Definition: guc.c:11162
char * ExtractSetVariableArgs(VariableSetStmt *stmt)
Definition: guc.c:8822