PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
pg_proc.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_language.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_proc_fn.h"
#include "catalog/pg_transform.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_type.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for pg_proc.c:

Go to the source code of this file.

Data Structures

struct  parse_error_callback_arg
 

Functions

static void sql_function_parse_error_callback (void *arg)
 
static int match_prosrc_to_query (const char *prosrc, const char *queryText, int cursorpos)
 
static bool match_prosrc_to_literal (const char *prosrc, const char *literal, int cursorpos, int *newcursorpos)
 
ObjectAddress ProcedureCreate (const char *procedureName, Oid procNamespace, bool replace, bool returnsSet, Oid returnType, Oid proowner, Oid languageObjectId, Oid languageValidator, const char *prosrc, const char *probin, bool isAgg, bool isWindowFunc, bool security_definer, bool isLeakProof, bool isStrict, char volatility, char parallel, oidvector *parameterTypes, Datum allParameterTypes, Datum parameterModes, Datum parameterNames, List *parameterDefaults, Datum trftypes, Datum proconfig, float4 procost, float4 prorows)
 
Datum fmgr_internal_validator (PG_FUNCTION_ARGS)
 
Datum fmgr_c_validator (PG_FUNCTION_ARGS)
 
Datum fmgr_sql_validator (PG_FUNCTION_ARGS)
 
bool function_parse_error_transpose (const char *prosrc)
 
Listoid_array_to_list (Datum datum)
 

Function Documentation

Datum fmgr_c_validator ( PG_FUNCTION_ARGS  )

Definition at line 786 of file pg_proc.c.

References Anum_pg_proc_probin, Anum_pg_proc_prosrc, CheckFunctionValidatorAccess(), elog, ERROR, fetch_finfo_record(), HeapTupleIsValid, load_external_function(), ObjectIdGetDatum, PG_GETARG_OID, PG_RETURN_VOID, PROCOID, ReleaseSysCache(), SearchSysCache1, SysCacheGetAttr(), and TextDatumGetCString.

787 {
788  Oid funcoid = PG_GETARG_OID(0);
789  void *libraryhandle;
790  HeapTuple tuple;
791  bool isnull;
792  Datum tmp;
793  char *prosrc;
794  char *probin;
795 
796  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
797  PG_RETURN_VOID();
798 
799  /*
800  * It'd be most consistent to skip the check if !check_function_bodies,
801  * but the purpose of that switch is to be helpful for pg_dump loading,
802  * and for pg_dump loading it's much better if we *do* check.
803  */
804 
805  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
806  if (!HeapTupleIsValid(tuple))
807  elog(ERROR, "cache lookup failed for function %u", funcoid);
808 
809  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
810  if (isnull)
811  elog(ERROR, "null prosrc for C function %u", funcoid);
812  prosrc = TextDatumGetCString(tmp);
813 
814  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
815  if (isnull)
816  elog(ERROR, "null probin for C function %u", funcoid);
817  probin = TextDatumGetCString(tmp);
818 
819  (void) load_external_function(probin, prosrc, true, &libraryhandle);
820  (void) fetch_finfo_record(libraryhandle, prosrc);
821 
822  ReleaseSysCache(tuple);
823 
824  PG_RETURN_VOID();
825 }
const Pg_finfo_record * fetch_finfo_record(void *filehandle, char *funcname)
Definition: fmgr.c:444
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
#define Anum_pg_proc_probin
Definition: pg_proc.h:116
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2412
#define PG_GETARG_OID(n)
Definition: fmgr.h:231
PGFunction load_external_function(char *filename, char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:94
#define TextDatumGetCString(d)
Definition: builtins.h:91
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
#define PG_RETURN_VOID()
Definition: fmgr.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define elog
Definition: elog.h:219
Datum fmgr_internal_validator ( PG_FUNCTION_ARGS  )

Definition at line 740 of file pg_proc.c.

References Anum_pg_proc_prosrc, CheckFunctionValidatorAccess(), elog, ereport, errcode(), errmsg(), ERROR, fmgr_internal_function(), HeapTupleIsValid, InvalidOid, ObjectIdGetDatum, PG_GETARG_OID, PG_RETURN_VOID, PROCOID, ReleaseSysCache(), SearchSysCache1, SysCacheGetAttr(), and TextDatumGetCString.

741 {
742  Oid funcoid = PG_GETARG_OID(0);
743  HeapTuple tuple;
744  bool isnull;
745  Datum tmp;
746  char *prosrc;
747 
748  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
749  PG_RETURN_VOID();
750 
751  /*
752  * We do not honor check_function_bodies since it's unlikely the function
753  * name will be found later if it isn't there now.
754  */
755 
756  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
757  if (!HeapTupleIsValid(tuple))
758  elog(ERROR, "cache lookup failed for function %u", funcoid);
759 
760  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
761  if (isnull)
762  elog(ERROR, "null prosrc");
763  prosrc = TextDatumGetCString(tmp);
764 
765  if (fmgr_internal_function(prosrc) == InvalidOid)
766  ereport(ERROR,
767  (errcode(ERRCODE_UNDEFINED_FUNCTION),
768  errmsg("there is no built-in function named \"%s\"",
769  prosrc)));
770 
771  ReleaseSysCache(tuple);
772 
773  PG_RETURN_VOID();
774 }
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
Oid fmgr_internal_function(const char *proname)
Definition: fmgr.c:609
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2412
#define PG_GETARG_OID(n)
Definition: fmgr.h:231
#define ereport(elevel, rest)
Definition: elog.h:122
#define TextDatumGetCString(d)
Definition: builtins.h:91
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
#define InvalidOid
Definition: postgres_ext.h:36
#define PG_RETURN_VOID()
Definition: fmgr.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
Datum fmgr_sql_validator ( PG_FUNCTION_ARGS  )

Definition at line 834 of file pg_proc.c.

References Anum_pg_proc_prosrc, ErrorContextCallback::arg, ErrorContextCallback::callback, castNode, check_function_bodies, check_sql_fn_retval(), CheckFunctionValidatorAccess(), elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, format_type_be(), get_typtype(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, IsPolymorphicType, lfirst, list_concat(), NameStr, NIL, NULL, ObjectIdGetDatum, pg_analyze_and_rewrite_params(), PG_GETARG_OID, pg_parse_query(), PG_RETURN_VOID, prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, parse_error_callback_arg::proname, parse_error_callback_arg::prosrc, RECORDOID, ReleaseSysCache(), SearchSysCache1, sql_fn_parser_setup(), sql_function_parse_error_callback(), SysCacheGetAttr(), TextDatumGetCString, TYPTYPE_PSEUDO, and VOIDOID.

835 {
836  Oid funcoid = PG_GETARG_OID(0);
837  HeapTuple tuple;
838  Form_pg_proc proc;
839  List *raw_parsetree_list;
840  List *querytree_list;
841  ListCell *lc;
842  bool isnull;
843  Datum tmp;
844  char *prosrc;
845  parse_error_callback_arg callback_arg;
846  ErrorContextCallback sqlerrcontext;
847  bool haspolyarg;
848  int i;
849 
850  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
851  PG_RETURN_VOID();
852 
853  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
854  if (!HeapTupleIsValid(tuple))
855  elog(ERROR, "cache lookup failed for function %u", funcoid);
856  proc = (Form_pg_proc) GETSTRUCT(tuple);
857 
858  /* Disallow pseudotype result */
859  /* except for RECORD, VOID, or polymorphic */
860  if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
861  proc->prorettype != RECORDOID &&
862  proc->prorettype != VOIDOID &&
863  !IsPolymorphicType(proc->prorettype))
864  ereport(ERROR,
865  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
866  errmsg("SQL functions cannot return type %s",
867  format_type_be(proc->prorettype))));
868 
869  /* Disallow pseudotypes in arguments */
870  /* except for polymorphic */
871  haspolyarg = false;
872  for (i = 0; i < proc->pronargs; i++)
873  {
874  if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
875  {
876  if (IsPolymorphicType(proc->proargtypes.values[i]))
877  haspolyarg = true;
878  else
879  ereport(ERROR,
880  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
881  errmsg("SQL functions cannot have arguments of type %s",
882  format_type_be(proc->proargtypes.values[i]))));
883  }
884  }
885 
886  /* Postpone body checks if !check_function_bodies */
888  {
889  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
890  if (isnull)
891  elog(ERROR, "null prosrc");
892 
893  prosrc = TextDatumGetCString(tmp);
894 
895  /*
896  * Setup error traceback support for ereport().
897  */
898  callback_arg.proname = NameStr(proc->proname);
899  callback_arg.prosrc = prosrc;
900 
902  sqlerrcontext.arg = (void *) &callback_arg;
903  sqlerrcontext.previous = error_context_stack;
904  error_context_stack = &sqlerrcontext;
905 
906  /*
907  * We can't do full prechecking of the function definition if there
908  * are any polymorphic input types, because actual datatypes of
909  * expression results will be unresolvable. The check will be done at
910  * runtime instead.
911  *
912  * We can run the text through the raw parser though; this will at
913  * least catch silly syntactic errors.
914  */
915  raw_parsetree_list = pg_parse_query(prosrc);
916 
917  if (!haspolyarg)
918  {
919  /*
920  * OK to do full precheck: analyze and rewrite the queries, then
921  * verify the result type.
922  */
924 
925  /* But first, set up parameter information */
926  pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
927 
928  querytree_list = NIL;
929  foreach(lc, raw_parsetree_list)
930  {
931  RawStmt *parsetree = castNode(RawStmt, lfirst(lc));
932  List *querytree_sublist;
933 
934  querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
935  prosrc,
937  pinfo);
938  querytree_list = list_concat(querytree_list,
939  querytree_sublist);
940  }
941 
942  (void) check_sql_fn_retval(funcoid, proc->prorettype,
943  querytree_list,
944  NULL, NULL);
945  }
946 
947  error_context_stack = sqlerrcontext.previous;
948  }
949 
950  ReleaseSysCache(tuple);
951 
952  PG_RETURN_VOID();
953 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1527
char get_typtype(Oid typid)
Definition: lsyscache.c:2347
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
List * list_concat(List *list1, List *list2)
Definition: list.c:321
bool check_function_bodies
Definition: guc.c:449
unsigned int Oid
Definition: postgres_ext.h:31
struct ErrorContextCallback * previous
Definition: elog.h:238
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define VOIDOID
Definition: pg_type.h:678
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:733
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2412
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
#define PG_GETARG_OID(n)
Definition: fmgr.h:231
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:66
#define RECORDOID
Definition: pg_type.h:668
#define ereport(elevel, rest)
Definition: elog.h:122
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg)
Definition: postgres.c:679
#define TextDatumGetCString(d)
Definition: builtins.h:91
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
static void sql_function_parse_error_callback(void *arg)
Definition: pg_proc.c:959
#define PG_RETURN_VOID()
Definition: fmgr.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
#define TYPTYPE_PSEUDO
Definition: pg_type.h:712
void(* callback)(void *arg)
Definition: elog.h:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:494
#define elog
Definition: elog.h:219
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
Definition: pg_list.h:45
bool function_parse_error_transpose ( const char *  prosrc)

Definition at line 983 of file pg_proc.c.

References ActivePortal, Assert, errposition(), geterrposition(), getinternalerrposition(), internalerrposition(), internalerrquery(), match_prosrc_to_query(), NULL, PORTAL_ACTIVE, PortalData::sourceText, and PortalData::status.

Referenced by plpgsql_compile_error_callback(), and sql_function_parse_error_callback().

984 {
985  int origerrposition;
986  int newerrposition;
987  const char *queryText;
988 
989  /*
990  * Nothing to do unless we are dealing with a syntax error that has a
991  * cursor position.
992  *
993  * Some PLs may prefer to report the error position as an internal error
994  * to begin with, so check that too.
995  */
996  origerrposition = geterrposition();
997  if (origerrposition <= 0)
998  {
999  origerrposition = getinternalerrposition();
1000  if (origerrposition <= 0)
1001  return false;
1002  }
1003 
1004  /* We can get the original query text from the active portal (hack...) */
1006  queryText = ActivePortal->sourceText;
1007 
1008  /* Try to locate the prosrc in the original text */
1009  newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
1010 
1011  if (newerrposition > 0)
1012  {
1013  /* Successful, so fix error position to reference original query */
1014  errposition(newerrposition);
1015  /* Get rid of any report of the error as an "internal query" */
1018  }
1019  else
1020  {
1021  /*
1022  * If unsuccessful, convert the position to an internal position
1023  * marker and give the function text as the internal query.
1024  */
1025  errposition(0);
1026  internalerrposition(origerrposition);
1027  internalerrquery(prosrc);
1028  }
1029 
1030  return true;
1031 }
Portal ActivePortal
Definition: pquery.c:33
int geterrposition(void)
Definition: elog.c:1257
int getinternalerrposition(void)
Definition: elog.c:1274
const char * sourceText
Definition: portal.h:134
int internalerrquery(const char *query)
Definition: elog.c:1161
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
PortalStatus status
Definition: portal.h:146
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1040
int errposition(int cursorpos)
Definition: elog.c:1125
int internalerrposition(int cursorpos)
Definition: elog.c:1141
static bool match_prosrc_to_literal ( const char *  prosrc,
const char *  literal,
int  cursorpos,
int *  newcursorpos 
)
static

Definition at line 1098 of file pg_proc.c.

References pg_mblen().

Referenced by match_prosrc_to_query().

1100 {
1101  int newcp = cursorpos;
1102  int chlen;
1103 
1104  /*
1105  * This implementation handles backslashes and doubled quotes in the
1106  * string literal. It does not handle the SQL syntax for literals
1107  * continued across line boundaries.
1108  *
1109  * We do the comparison a character at a time, not a byte at a time, so
1110  * that we can do the correct cursorpos math.
1111  */
1112  while (*prosrc)
1113  {
1114  cursorpos--; /* characters left before cursor */
1115 
1116  /*
1117  * Check for backslashes and doubled quotes in the literal; adjust
1118  * newcp when one is found before the cursor.
1119  */
1120  if (*literal == '\\')
1121  {
1122  literal++;
1123  if (cursorpos > 0)
1124  newcp++;
1125  }
1126  else if (*literal == '\'')
1127  {
1128  if (literal[1] != '\'')
1129  goto fail;
1130  literal++;
1131  if (cursorpos > 0)
1132  newcp++;
1133  }
1134  chlen = pg_mblen(prosrc);
1135  if (strncmp(prosrc, literal, chlen) != 0)
1136  goto fail;
1137  prosrc += chlen;
1138  literal += chlen;
1139  }
1140 
1141  if (*literal == '\'' && literal[1] != '\'')
1142  {
1143  /* success */
1144  *newcursorpos = newcp;
1145  return true;
1146  }
1147 
1148 fail:
1149  /* Must set *newcursorpos to suppress compiler warning */
1150  *newcursorpos = newcp;
1151  return false;
1152 }
int pg_mblen(const char *mbstr)
Definition: mbutils.c:771
static int match_prosrc_to_query ( const char *  prosrc,
const char *  queryText,
int  cursorpos 
)
static

Definition at line 1040 of file pg_proc.c.

References match_prosrc_to_literal(), and pg_mbstrlen_with_len().

Referenced by function_parse_error_transpose().

1042 {
1043  /*
1044  * Rather than fully parsing the original command, we just scan the
1045  * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1046  * not in any very probable scenarios), so fail if we find more than one
1047  * match.
1048  */
1049  int prosrclen = strlen(prosrc);
1050  int querylen = strlen(queryText);
1051  int matchpos = 0;
1052  int curpos;
1053  int newcursorpos;
1054 
1055  for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1056  {
1057  if (queryText[curpos] == '$' &&
1058  strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1059  queryText[curpos + 1 + prosrclen] == '$')
1060  {
1061  /*
1062  * Found a $foo$ match. Since there are no embedded quoting
1063  * characters in a dollar-quoted literal, we don't have to do any
1064  * fancy arithmetic; just offset by the starting position.
1065  */
1066  if (matchpos)
1067  return 0; /* multiple matches, fail */
1068  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1069  + cursorpos;
1070  }
1071  else if (queryText[curpos] == '\'' &&
1072  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1073  cursorpos, &newcursorpos))
1074  {
1075  /*
1076  * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1077  * for any quotes or backslashes embedded in the literal.
1078  */
1079  if (matchpos)
1080  return 0; /* multiple matches, fail */
1081  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1082  + newcursorpos;
1083  }
1084  }
1085 
1086  return matchpos;
1087 }
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:805
static bool match_prosrc_to_literal(const char *prosrc, const char *literal, int cursorpos, int *newcursorpos)
Definition: pg_proc.c:1098
List* oid_array_to_list ( Datum  datum)

Definition at line 1155 of file pg_proc.c.

References DatumGetArrayTypeP, deconstruct_array(), i, lappend_oid(), NIL, NULL, OIDOID, and values.

Referenced by compile_plperl_function(), and PLy_procedure_create().

1156 {
1157  ArrayType *array = DatumGetArrayTypeP(datum);
1158  Datum *values;
1159  int nelems;
1160  int i;
1161  List *result = NIL;
1162 
1163  deconstruct_array(array,
1164  OIDOID,
1165  sizeof(Oid), true, 'i',
1166  &values, NULL, &nelems);
1167  for (i = 0; i < nelems; i++)
1168  result = lappend_oid(result, values[i]);
1169  return result;
1170 }
#define NIL
Definition: pg_list.h:69
#define OIDOID
Definition: pg_type.h:328
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
uintptr_t Datum
Definition: postgres.h:374
#define NULL
Definition: c.h:226
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int i
Definition: pg_list.h:45
#define DatumGetArrayTypeP(X)
Definition: array.h:242
ObjectAddress ProcedureCreate ( const char *  procedureName,
Oid  procNamespace,
bool  replace,
bool  returnsSet,
Oid  returnType,
Oid  proowner,
Oid  languageObjectId,
Oid  languageValidator,
const char *  prosrc,
const char *  probin,
bool  isAgg,
bool  isWindowFunc,
bool  security_definer,
bool  isLeakProof,
bool  isStrict,
char  volatility,
char  parallel,
oidvector parameterTypes,
Datum  allParameterTypes,
Datum  parameterModes,
Datum  parameterNames,
List parameterDefaults,
Datum  trftypes,
Datum  proconfig,
float4  procost,
float4  prorows 
)

Definition at line 67 of file pg_proc.c.

References ACL_KIND_PROC, ACL_OBJECT_FUNCTION, aclcheck_error(), ACLCHECK_NOT_OWNER, aclmembers(), Anum_pg_proc_proacl, Anum_pg_proc_proallargtypes, Anum_pg_proc_proargdefaults, Anum_pg_proc_proargmodes, Anum_pg_proc_proargnames, Anum_pg_proc_proargtypes, Anum_pg_proc_probin, Anum_pg_proc_proconfig, Anum_pg_proc_procost, Anum_pg_proc_proisagg, Anum_pg_proc_proisstrict, Anum_pg_proc_proiswindow, Anum_pg_proc_prolang, Anum_pg_proc_proleakproof, Anum_pg_proc_proname, Anum_pg_proc_pronamespace, Anum_pg_proc_pronargdefaults, Anum_pg_proc_pronargs, Anum_pg_proc_proowner, Anum_pg_proc_proparallel, Anum_pg_proc_proretset, Anum_pg_proc_prorettype, Anum_pg_proc_prorows, Anum_pg_proc_prosecdef, Anum_pg_proc_prosrc, Anum_pg_proc_protransform, Anum_pg_proc_protrftypes, Anum_pg_proc_provariadic, Anum_pg_proc_provolatile, ANYARRAYOID, ANYELEMENTOID, ANYENUMOID, ANYNONARRAYOID, ANYOID, ANYRANGEOID, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, AtEOXact_GUC(), BoolGetDatum, build_function_result_tupdesc_d(), build_function_result_tupdesc_t(), castNode, CatalogTupleInsert(), CatalogTupleUpdate(), CharGetDatum, CHAROID, check_function_bodies, ObjectAddress::classId, CommandCounterIncrement(), CStringGetTextDatum, DatumGetPointer, deleteDependencyRecordsFor(), DEPENDENCY_NORMAL, oidvector::dim1, elog, equalTupleDescs(), ereport, errcode(), errdetail(), errhint(), errmsg(), errmsg_plural(), ERROR, exprType(), Float4GetDatum(), format_procedure(), format_type_be(), FUNC_MAX_ARGS, get_attnum(), get_element_type(), get_func_input_arg_names(), get_transform_oid(), get_user_default_acl(), GETSTRUCT, GUC_ACTION_SAVE, heap_close, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, i, INTERNALOID, InvalidAttrNumber, InvalidOid, InvokeObjectPostCreateHook, IsPolymorphicType, LanguageRelationId, lfirst, list_head(), list_length(), lnext, NameGetDatum, NamespaceRelationId, namestrcpy(), Natts_pg_proc, NewGUCNestLevel(), NIL, nodeToString(), NULL, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidFunctionCall1, OidIsValid, OIDOID, pg_proc_ownercheck(), PGC_S_SESSION, PGC_SUSET, PGC_USERSET, PointerGetDatum, PointerIsValid, PROARGMODE_IN, PROARGMODE_INOUT, PROARGMODE_OUT, PROARGMODE_TABLE, PROARGMODE_VARIADIC, ProcedureRelationId, ProcessGUCArray(), PROCNAMEARGSNSP, recordDependencyOn(), recordDependencyOnCurrentExtension(), recordDependencyOnExpr(), recordDependencyOnOwner(), RECORDOID, RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3, stringToNode(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, TextDatumGetCString, TransformRelationId, typeidTypeRelid(), TypeRelationId, UInt16GetDatum, updateAclDependencies(), values, and oidvector::values.

Referenced by AggregateCreate(), CreateFunction(), CreateProceduralLanguage(), and makeRangeConstructors().

93 {
94  Oid retval;
95  int parameterCount;
96  int allParamCount;
97  Oid *allParams;
98  char *paramModes = NULL;
99  bool genericInParam = false;
100  bool genericOutParam = false;
101  bool anyrangeInParam = false;
102  bool anyrangeOutParam = false;
103  bool internalInParam = false;
104  bool internalOutParam = false;
105  Oid variadicType = InvalidOid;
106  Acl *proacl = NULL;
107  Relation rel;
108  HeapTuple tup;
109  HeapTuple oldtup;
110  bool nulls[Natts_pg_proc];
112  bool replaces[Natts_pg_proc];
113  Oid relid;
114  NameData procname;
115  TupleDesc tupDesc;
116  bool is_update;
117  ObjectAddress myself,
118  referenced;
119  int i;
120  Oid trfid;
121 
122  /*
123  * sanity checks
124  */
125  Assert(PointerIsValid(prosrc));
126 
127  parameterCount = parameterTypes->dim1;
128  if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
129  ereport(ERROR,
130  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
131  errmsg_plural("functions cannot have more than %d argument",
132  "functions cannot have more than %d arguments",
133  FUNC_MAX_ARGS,
134  FUNC_MAX_ARGS)));
135  /* note: the above is correct, we do NOT count output arguments */
136 
137  /* Deconstruct array inputs */
138  if (allParameterTypes != PointerGetDatum(NULL))
139  {
140  /*
141  * We expect the array to be a 1-D OID array; verify that. We don't
142  * need to use deconstruct_array() since the array data is just going
143  * to look like a C array of OID values.
144  */
145  ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
146 
147  allParamCount = ARR_DIMS(allParamArray)[0];
148  if (ARR_NDIM(allParamArray) != 1 ||
149  allParamCount <= 0 ||
150  ARR_HASNULL(allParamArray) ||
151  ARR_ELEMTYPE(allParamArray) != OIDOID)
152  elog(ERROR, "allParameterTypes is not a 1-D Oid array");
153  allParams = (Oid *) ARR_DATA_PTR(allParamArray);
154  Assert(allParamCount >= parameterCount);
155  /* we assume caller got the contents right */
156  }
157  else
158  {
159  allParamCount = parameterCount;
160  allParams = parameterTypes->values;
161  }
162 
163  if (parameterModes != PointerGetDatum(NULL))
164  {
165  /*
166  * We expect the array to be a 1-D CHAR array; verify that. We don't
167  * need to use deconstruct_array() since the array data is just going
168  * to look like a C array of char values.
169  */
170  ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
171 
172  if (ARR_NDIM(modesArray) != 1 ||
173  ARR_DIMS(modesArray)[0] != allParamCount ||
174  ARR_HASNULL(modesArray) ||
175  ARR_ELEMTYPE(modesArray) != CHAROID)
176  elog(ERROR, "parameterModes is not a 1-D char array");
177  paramModes = (char *) ARR_DATA_PTR(modesArray);
178  }
179 
180  /*
181  * Detect whether we have polymorphic or INTERNAL arguments. The first
182  * loop checks input arguments, the second output arguments.
183  */
184  for (i = 0; i < parameterCount; i++)
185  {
186  switch (parameterTypes->values[i])
187  {
188  case ANYARRAYOID:
189  case ANYELEMENTOID:
190  case ANYNONARRAYOID:
191  case ANYENUMOID:
192  genericInParam = true;
193  break;
194  case ANYRANGEOID:
195  genericInParam = true;
196  anyrangeInParam = true;
197  break;
198  case INTERNALOID:
199  internalInParam = true;
200  break;
201  }
202  }
203 
204  if (allParameterTypes != PointerGetDatum(NULL))
205  {
206  for (i = 0; i < allParamCount; i++)
207  {
208  if (paramModes == NULL ||
209  paramModes[i] == PROARGMODE_IN ||
210  paramModes[i] == PROARGMODE_VARIADIC)
211  continue; /* ignore input-only params */
212 
213  switch (allParams[i])
214  {
215  case ANYARRAYOID:
216  case ANYELEMENTOID:
217  case ANYNONARRAYOID:
218  case ANYENUMOID:
219  genericOutParam = true;
220  break;
221  case ANYRANGEOID:
222  genericOutParam = true;
223  anyrangeOutParam = true;
224  break;
225  case INTERNALOID:
226  internalOutParam = true;
227  break;
228  }
229  }
230  }
231 
232  /*
233  * Do not allow polymorphic return type unless at least one input argument
234  * is polymorphic. ANYRANGE return type is even stricter: must have an
235  * ANYRANGE input (since we can't deduce the specific range type from
236  * ANYELEMENT). Also, do not allow return type INTERNAL unless at least
237  * one input argument is INTERNAL.
238  */
239  if ((IsPolymorphicType(returnType) || genericOutParam)
240  && !genericInParam)
241  ereport(ERROR,
242  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
243  errmsg("cannot determine result data type"),
244  errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
245 
246  if ((returnType == ANYRANGEOID || anyrangeOutParam) &&
247  !anyrangeInParam)
248  ereport(ERROR,
249  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
250  errmsg("cannot determine result data type"),
251  errdetail("A function returning \"anyrange\" must have at least one \"anyrange\" argument.")));
252 
253  if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
254  ereport(ERROR,
255  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
256  errmsg("unsafe use of pseudo-type \"internal\""),
257  errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
258 
259  /*
260  * don't allow functions of complex types that have the same name as
261  * existing attributes of the type
262  */
263  if (parameterCount == 1 &&
264  OidIsValid(parameterTypes->values[0]) &&
265  (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
266  get_attnum(relid, procedureName) != InvalidAttrNumber)
267  ereport(ERROR,
268  (errcode(ERRCODE_DUPLICATE_COLUMN),
269  errmsg("\"%s\" is already an attribute of type %s",
270  procedureName,
271  format_type_be(parameterTypes->values[0]))));
272 
273  if (paramModes != NULL)
274  {
275  /*
276  * Only the last input parameter can be variadic; if it is, save its
277  * element type. Errors here are just elog since caller should have
278  * checked this already.
279  */
280  for (i = 0; i < allParamCount; i++)
281  {
282  switch (paramModes[i])
283  {
284  case PROARGMODE_IN:
285  case PROARGMODE_INOUT:
286  if (OidIsValid(variadicType))
287  elog(ERROR, "variadic parameter must be last");
288  break;
289  case PROARGMODE_OUT:
290  case PROARGMODE_TABLE:
291  /* okay */
292  break;
293  case PROARGMODE_VARIADIC:
294  if (OidIsValid(variadicType))
295  elog(ERROR, "variadic parameter must be last");
296  switch (allParams[i])
297  {
298  case ANYOID:
299  variadicType = ANYOID;
300  break;
301  case ANYARRAYOID:
302  variadicType = ANYELEMENTOID;
303  break;
304  default:
305  variadicType = get_element_type(allParams[i]);
306  if (!OidIsValid(variadicType))
307  elog(ERROR, "variadic parameter is not an array");
308  break;
309  }
310  break;
311  default:
312  elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
313  break;
314  }
315  }
316  }
317 
318  /*
319  * All seems OK; prepare the data to be inserted into pg_proc.
320  */
321 
322  for (i = 0; i < Natts_pg_proc; ++i)
323  {
324  nulls[i] = false;
325  values[i] = (Datum) 0;
326  replaces[i] = true;
327  }
328 
329  namestrcpy(&procname, procedureName);
330  values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
331  values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
332  values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
333  values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
334  values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
335  values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
336  values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
338  values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
339  values[Anum_pg_proc_proiswindow - 1] = BoolGetDatum(isWindowFunc);
340  values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
341  values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
342  values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
343  values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
344  values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
345  values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
346  values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
347  values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
348  values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
349  values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
350  if (allParameterTypes != PointerGetDatum(NULL))
351  values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
352  else
353  nulls[Anum_pg_proc_proallargtypes - 1] = true;
354  if (parameterModes != PointerGetDatum(NULL))
355  values[Anum_pg_proc_proargmodes - 1] = parameterModes;
356  else
357  nulls[Anum_pg_proc_proargmodes - 1] = true;
358  if (parameterNames != PointerGetDatum(NULL))
359  values[Anum_pg_proc_proargnames - 1] = parameterNames;
360  else
361  nulls[Anum_pg_proc_proargnames - 1] = true;
362  if (parameterDefaults != NIL)
363  values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
364  else
365  nulls[Anum_pg_proc_proargdefaults - 1] = true;
366  if (trftypes != PointerGetDatum(NULL))
367  values[Anum_pg_proc_protrftypes - 1] = trftypes;
368  else
369  nulls[Anum_pg_proc_protrftypes - 1] = true;
370  values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
371  if (probin)
372  values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
373  else
374  nulls[Anum_pg_proc_probin - 1] = true;
375  if (proconfig != PointerGetDatum(NULL))
376  values[Anum_pg_proc_proconfig - 1] = proconfig;
377  else
378  nulls[Anum_pg_proc_proconfig - 1] = true;
379  /* proacl will be determined later */
380 
382  tupDesc = RelationGetDescr(rel);
383 
384  /* Check for pre-existing definition */
386  PointerGetDatum(procedureName),
387  PointerGetDatum(parameterTypes),
388  ObjectIdGetDatum(procNamespace));
389 
390  if (HeapTupleIsValid(oldtup))
391  {
392  /* There is one; okay to replace it? */
393  Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
394  Datum proargnames;
395  bool isnull;
396 
397  if (!replace)
398  ereport(ERROR,
399  (errcode(ERRCODE_DUPLICATE_FUNCTION),
400  errmsg("function \"%s\" already exists with same argument types",
401  procedureName)));
402  if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), proowner))
404  procedureName);
405 
406  /*
407  * Not okay to change the return type of the existing proc, since
408  * existing rules, views, etc may depend on the return type.
409  */
410  if (returnType != oldproc->prorettype ||
411  returnsSet != oldproc->proretset)
412  ereport(ERROR,
413  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
414  errmsg("cannot change return type of existing function"),
415  errhint("Use DROP FUNCTION %s first.",
416  format_procedure(HeapTupleGetOid(oldtup)))));
417 
418  /*
419  * If it returns RECORD, check for possible change of record type
420  * implied by OUT parameters
421  */
422  if (returnType == RECORDOID)
423  {
424  TupleDesc olddesc;
425  TupleDesc newdesc;
426 
427  olddesc = build_function_result_tupdesc_t(oldtup);
428  newdesc = build_function_result_tupdesc_d(allParameterTypes,
429  parameterModes,
430  parameterNames);
431  if (olddesc == NULL && newdesc == NULL)
432  /* ok, both are runtime-defined RECORDs */ ;
433  else if (olddesc == NULL || newdesc == NULL ||
434  !equalTupleDescs(olddesc, newdesc))
435  ereport(ERROR,
436  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
437  errmsg("cannot change return type of existing function"),
438  errdetail("Row type defined by OUT parameters is different."),
439  errhint("Use DROP FUNCTION %s first.",
440  format_procedure(HeapTupleGetOid(oldtup)))));
441  }
442 
443  /*
444  * If there were any named input parameters, check to make sure the
445  * names have not been changed, as this could break existing calls. We
446  * allow adding names to formerly unnamed parameters, though.
447  */
448  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
450  &isnull);
451  if (!isnull)
452  {
453  Datum proargmodes;
454  char **old_arg_names;
455  char **new_arg_names;
456  int n_old_arg_names;
457  int n_new_arg_names;
458  int j;
459 
460  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
462  &isnull);
463  if (isnull)
464  proargmodes = PointerGetDatum(NULL); /* just to be sure */
465 
466  n_old_arg_names = get_func_input_arg_names(proargnames,
467  proargmodes,
468  &old_arg_names);
469  n_new_arg_names = get_func_input_arg_names(parameterNames,
470  parameterModes,
471  &new_arg_names);
472  for (j = 0; j < n_old_arg_names; j++)
473  {
474  if (old_arg_names[j] == NULL)
475  continue;
476  if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
477  strcmp(old_arg_names[j], new_arg_names[j]) != 0)
478  ereport(ERROR,
479  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
480  errmsg("cannot change name of input parameter \"%s\"",
481  old_arg_names[j]),
482  errhint("Use DROP FUNCTION %s first.",
483  format_procedure(HeapTupleGetOid(oldtup)))));
484  }
485  }
486 
487  /*
488  * If there are existing defaults, check compatibility: redefinition
489  * must not remove any defaults nor change their types. (Removing a
490  * default might cause a function to fail to satisfy an existing call.
491  * Changing type would only be possible if the associated parameter is
492  * polymorphic, and in such cases a change of default type might alter
493  * the resolved output type of existing calls.)
494  */
495  if (oldproc->pronargdefaults != 0)
496  {
497  Datum proargdefaults;
498  List *oldDefaults;
499  ListCell *oldlc;
500  ListCell *newlc;
501 
502  if (list_length(parameterDefaults) < oldproc->pronargdefaults)
503  ereport(ERROR,
504  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
505  errmsg("cannot remove parameter defaults from existing function"),
506  errhint("Use DROP FUNCTION %s first.",
507  format_procedure(HeapTupleGetOid(oldtup)))));
508 
509  proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
511  &isnull);
512  Assert(!isnull);
513  oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
514  Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
515 
516  /* new list can have more defaults than old, advance over 'em */
517  newlc = list_head(parameterDefaults);
518  for (i = list_length(parameterDefaults) - oldproc->pronargdefaults;
519  i > 0;
520  i--)
521  newlc = lnext(newlc);
522 
523  foreach(oldlc, oldDefaults)
524  {
525  Node *oldDef = (Node *) lfirst(oldlc);
526  Node *newDef = (Node *) lfirst(newlc);
527 
528  if (exprType(oldDef) != exprType(newDef))
529  ereport(ERROR,
530  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
531  errmsg("cannot change data type of existing parameter default value"),
532  errhint("Use DROP FUNCTION %s first.",
533  format_procedure(HeapTupleGetOid(oldtup)))));
534  newlc = lnext(newlc);
535  }
536  }
537 
538  /* Can't change aggregate or window-function status, either */
539  if (oldproc->proisagg != isAgg)
540  {
541  if (oldproc->proisagg)
542  ereport(ERROR,
543  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
544  errmsg("function \"%s\" is an aggregate function",
545  procedureName)));
546  else
547  ereport(ERROR,
548  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
549  errmsg("function \"%s\" is not an aggregate function",
550  procedureName)));
551  }
552  if (oldproc->proiswindow != isWindowFunc)
553  {
554  if (oldproc->proiswindow)
555  ereport(ERROR,
556  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
557  errmsg("function \"%s\" is a window function",
558  procedureName)));
559  else
560  ereport(ERROR,
561  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
562  errmsg("function \"%s\" is not a window function",
563  procedureName)));
564  }
565 
566  /*
567  * Do not change existing ownership or permissions, either. Note
568  * dependency-update code below has to agree with this decision.
569  */
570  replaces[Anum_pg_proc_proowner - 1] = false;
571  replaces[Anum_pg_proc_proacl - 1] = false;
572 
573  /* Okay, do it... */
574  tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
575  CatalogTupleUpdate(rel, &tup->t_self, tup);
576 
577  ReleaseSysCache(oldtup);
578  is_update = true;
579  }
580  else
581  {
582  /* Creating a new procedure */
583 
584  /* First, get default permissions and set up proacl */
585  proacl = get_user_default_acl(ACL_OBJECT_FUNCTION, proowner,
586  procNamespace);
587  if (proacl != NULL)
588  values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
589  else
590  nulls[Anum_pg_proc_proacl - 1] = true;
591 
592  tup = heap_form_tuple(tupDesc, values, nulls);
593  CatalogTupleInsert(rel, tup);
594  is_update = false;
595  }
596 
597 
598  retval = HeapTupleGetOid(tup);
599 
600  /*
601  * Create dependencies for the new function. If we are updating an
602  * existing function, first delete any existing pg_depend entries.
603  * (However, since we are not changing ownership or permissions, the
604  * shared dependencies do *not* need to change, and we leave them alone.)
605  */
606  if (is_update)
608 
609  myself.classId = ProcedureRelationId;
610  myself.objectId = retval;
611  myself.objectSubId = 0;
612 
613  /* dependency on namespace */
614  referenced.classId = NamespaceRelationId;
615  referenced.objectId = procNamespace;
616  referenced.objectSubId = 0;
617  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
618 
619  /* dependency on implementation language */
620  referenced.classId = LanguageRelationId;
621  referenced.objectId = languageObjectId;
622  referenced.objectSubId = 0;
623  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
624 
625  /* dependency on return type */
626  referenced.classId = TypeRelationId;
627  referenced.objectId = returnType;
628  referenced.objectSubId = 0;
629  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
630 
631  /* dependency on transform used by return type, if any */
632  if ((trfid = get_transform_oid(returnType, languageObjectId, true)))
633  {
634  referenced.classId = TransformRelationId;
635  referenced.objectId = trfid;
636  referenced.objectSubId = 0;
637  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
638  }
639 
640  /* dependency on parameter types */
641  for (i = 0; i < allParamCount; i++)
642  {
643  referenced.classId = TypeRelationId;
644  referenced.objectId = allParams[i];
645  referenced.objectSubId = 0;
646  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
647 
648  /* dependency on transform used by parameter type, if any */
649  if ((trfid = get_transform_oid(allParams[i], languageObjectId, true)))
650  {
651  referenced.classId = TransformRelationId;
652  referenced.objectId = trfid;
653  referenced.objectSubId = 0;
654  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
655  }
656  }
657 
658  /* dependency on parameter default expressions */
659  if (parameterDefaults)
660  recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
662 
663  /* dependency on owner */
664  if (!is_update)
665  recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
666 
667  /* dependency on any roles mentioned in ACL */
668  if (!is_update && proacl != NULL)
669  {
670  int nnewmembers;
671  Oid *newmembers;
672 
673  nnewmembers = aclmembers(proacl, &newmembers);
675  proowner,
676  0, NULL,
677  nnewmembers, newmembers);
678  }
679 
680  /* dependency on extension */
681  recordDependencyOnCurrentExtension(&myself, is_update);
682 
683  heap_freetuple(tup);
684 
685  /* Post creation hook for new function */
687 
689 
690  /* Verify function body */
691  if (OidIsValid(languageValidator))
692  {
693  ArrayType *set_items = NULL;
694  int save_nestlevel = 0;
695 
696  /* Advance command counter so new tuple can be seen by validator */
698 
699  /*
700  * Set per-function configuration parameters so that the validation is
701  * done with the environment the function expects. However, if
702  * check_function_bodies is off, we don't do this, because that would
703  * create dump ordering hazards that pg_dump doesn't know how to deal
704  * with. (For example, a SET clause might refer to a not-yet-created
705  * text search configuration.) This means that the validator
706  * shouldn't complain about anything that might depend on a GUC
707  * parameter when check_function_bodies is off.
708  */
710  {
711  set_items = (ArrayType *) DatumGetPointer(proconfig);
712  if (set_items) /* Need a new GUC nesting level */
713  {
714  save_nestlevel = NewGUCNestLevel();
715  ProcessGUCArray(set_items,
719  }
720  }
721 
722  OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
723 
724  if (set_items)
725  AtEOXact_GUC(true, save_nestlevel);
726  }
727 
728  return myself;
729 }
#define Anum_pg_proc_proisstrict
Definition: pg_proc.h:102
#define ANYNONARRAYOID
Definition: pg_type.h:692
#define NIL
Definition: pg_list.h:69
#define Anum_pg_proc_pronargdefaults
Definition: pg_proc.h:107
void updateAclDependencies(Oid classId, Oid objectId, int32 objsubId, Oid ownerId, int noldmembers, Oid *oldmembers, int nnewmembers, Oid *newmembers)
Definition: pg_shdepend.c:420
#define Anum_pg_proc_prorettype
Definition: pg_proc.h:108
#define NamespaceRelationId
Definition: pg_namespace.h:34
void * stringToNode(char *str)
Definition: read.c:38
#define NameGetDatum(X)
Definition: postgres.h:603
#define Anum_pg_proc_prosecdef
Definition: pg_proc.h:100
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define TransformRelationId
Definition: pg_transform.h:25
#define RelationGetDescr(relation)
Definition: rel.h:425
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
#define OIDOID
Definition: pg_type.h:328
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2452
#define PointerGetDatum(X)
Definition: postgres.h:564
#define ProcedureRelationId
Definition: pg_proc.h:33
#define Anum_pg_proc_procost
Definition: pg_proc.h:94
#define ANYELEMENTOID
Definition: pg_type.h:690
#define Anum_pg_proc_prorows
Definition: pg_proc.h:95
TupleDesc build_function_result_tupdesc_d(Datum proallargtypes, Datum proargmodes, Datum proargnames)
Definition: funcapi.c:1169
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:191
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
#define Anum_pg_proc_proacl
Definition: pg_proc.h:118
Definition: nodes.h:508
int errcode(int sqlerrcode)
Definition: elog.c:575
#define Anum_pg_proc_protransform
Definition: pg_proc.h:97
bool superuser(void)
Definition: superuser.c:47
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
#define Anum_pg_proc_protrftypes
Definition: pg_proc.h:114
Oid typeidTypeRelid(Oid type_id)
Definition: parse_type.c:647
#define Anum_pg_proc_prolang
Definition: pg_proc.h:93
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define Anum_pg_proc_proisagg
Definition: pg_proc.h:98
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:158
bool check_function_bodies
Definition: guc.c:449
#define PROARGMODE_VARIADIC
Definition: pg_proc.h:5393
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define TypeRelationId
Definition: pg_type.h:34
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#define OidIsValid(objectId)
Definition: c.h:533
#define PROARGMODE_INOUT
Definition: pg_proc.h:5392
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
#define PROARGMODE_OUT
Definition: pg_proc.h:5391
#define Anum_pg_proc_pronargs
Definition: pg_proc.h:106
#define FUNC_MAX_ARGS
Oid get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
#define Anum_pg_proc_probin
Definition: pg_proc.h:116
TupleDesc build_function_result_tupdesc_t(HeapTuple procTuple)
Definition: funcapi.c:1121
#define Natts_pg_proc
Definition: pg_proc.h:89
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define Anum_pg_proc_proretset
Definition: pg_proc.h:103
#define IsPolymorphicType(typid)
Definition: pg_type.h:733
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define ANYRANGEOID
Definition: pg_type.h:702
#define ARR_DIMS(a)
Definition: array.h:275
Definition: guc.h:75
#define PROARGMODE_TABLE
Definition: pg_proc.h:5394
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:2114
ItemPointerData t_self
Definition: htup.h:65
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:593
Definition: c.h:488
#define ARR_DATA_PTR(a)
Definition: array.h:303
#define ANYENUMOID
Definition: pg_type.h:694
#define Anum_pg_proc_proargdefaults
Definition: pg_proc.h:113
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:821
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:481
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
int dim1
Definition: c.h:479
#define RowExclusiveLock
Definition: lockdefs.h:38
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5040
#define Anum_pg_proc_proowner
Definition: pg_proc.h:92
int errdetail(const char *fmt,...)
Definition: elog.c:873
Acl * get_user_default_acl(GrantObjectType objtype, Oid ownerId, Oid nsp_oid)
Definition: aclchk.c:5194
#define ANYOID
Definition: pg_type.h:674
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1332
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define ARR_HASNULL(a)
Definition: array.h:272
#define Anum_pg_proc_proargmodes
Definition: pg_proc.h:111
#define RECORDOID
Definition: pg_type.h:668
#define Anum_pg_proc_proparallel
Definition: pg_proc.h:105
#define Anum_pg_proc_provariadic
Definition: pg_proc.h:96
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define PROARGMODE_IN
Definition: pg_proc.h:5390
#define Anum_pg_proc_proleakproof
Definition: pg_proc.h:101
#define Anum_pg_proc_proargnames
Definition: pg_proc.h:112
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:933
#define TextDatumGetCString(d)
Definition: builtins.h:91
#define ANYARRAYOID
Definition: pg_type.h:676
uintptr_t Datum
Definition: postgres.h:374
void CommandCounterIncrement(void)
Definition: xact.c:921
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1245
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define CHAROID
Definition: pg_type.h:296
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define BoolGetDatum(X)
Definition: postgres.h:410
#define InvalidOid
Definition: postgres_ext.h:36
void ProcessGUCArray(ArrayType *array, GucContext context, GucSource source, GucAction action)
Definition: guc.c:9370
#define INTERNALOID
Definition: pg_type.h:686
char * format_procedure(Oid procedure_oid)
Definition: regproc.c:367
#define Anum_pg_proc_provolatile
Definition: pg_proc.h:104
#define Anum_pg_proc_proargtypes
Definition: pg_proc.h:109
int aclmembers(const Acl *acl, Oid **roleids)
Definition: acl.c:1457
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
#define Anum_pg_proc_pronamespace
Definition: pg_proc.h:91
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:139
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
#define ARR_NDIM(a)
Definition: array.h:271
#define InvalidAttrNumber
Definition: attnum.h:23
#define CharGetDatum(X)
Definition: postgres.h:424
#define Anum_pg_proc_proiswindow
Definition: pg_proc.h:99
#define DatumGetPointer(X)
Definition: postgres.h:557
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define Anum_pg_proc_proallargtypes
Definition: pg_proc.h:110
int NewGUCNestLevel(void)
Definition: guc.c:5026
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:153
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:90
char * nodeToString(const void *obj)
Definition: outfuncs.c:3981
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:352
#define LanguageRelationId
Definition: pg_language.h:29
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:793
Definition: pg_list.h:45
#define PointerIsValid(pointer)
Definition: c.h:521
#define ARR_ELEMTYPE(a)
Definition: array.h:273
#define UInt16GetDatum(X)
Definition: postgres.h:473
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4599
#define Anum_pg_proc_proname
Definition: pg_proc.h:90
static void sql_function_parse_error_callback ( void *  arg)
static

Definition at line 959 of file pg_proc.c.

References errcontext, function_parse_error_transpose(), parse_error_callback_arg::proname, and parse_error_callback_arg::prosrc.

Referenced by fmgr_sql_validator().

960 {
962 
963  /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
964  if (!function_parse_error_transpose(callback_arg->prosrc))
965  {
966  /* If it's not a syntax error, push info onto context stack */
967  errcontext("SQL function \"%s\"", callback_arg->proname);
968  }
969 }
bool function_parse_error_transpose(const char *prosrc)
Definition: pg_proc.c:983
#define errcontext
Definition: elog.h:164
void * arg