PostgreSQL Source Code  git master
pg_proc.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/catalog.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_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/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_type.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.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, 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)
 
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

◆ fmgr_c_validator()

Datum fmgr_c_validator ( PG_FUNCTION_ARGS  )

Definition at line 770 of file pg_proc.c.

771 {
772  Oid funcoid = PG_GETARG_OID(0);
773  void *libraryhandle;
774  HeapTuple tuple;
775  Datum tmp;
776  char *prosrc;
777  char *probin;
778 
779  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
780  PG_RETURN_VOID();
781 
782  /*
783  * It'd be most consistent to skip the check if !check_function_bodies,
784  * but the purpose of that switch is to be helpful for pg_dump loading,
785  * and for pg_dump loading it's much better if we *do* check.
786  */
787 
788  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
789  if (!HeapTupleIsValid(tuple))
790  elog(ERROR, "cache lookup failed for function %u", funcoid);
791 
792  tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
793  prosrc = TextDatumGetCString(tmp);
794 
795  tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_probin);
796  probin = TextDatumGetCString(tmp);
797 
798  (void) load_external_function(probin, prosrc, true, &libraryhandle);
799  (void) fetch_finfo_record(libraryhandle, prosrc);
800 
801  ReleaseSysCache(tuple);
802 
803  PG_RETURN_VOID();
804 }
#define TextDatumGetCString(d)
Definition: builtins.h:95
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
#define ERROR
Definition: elog.h:39
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2128
const Pg_finfo_record * fetch_finfo_record(void *filehandle, const char *funcname)
Definition: fmgr.c:455
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:1112
@ PROCOID
Definition: syscache.h:79

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

◆ fmgr_internal_validator()

Datum fmgr_internal_validator ( PG_FUNCTION_ARGS  )

Definition at line 727 of file pg_proc.c.

728 {
729  Oid funcoid = PG_GETARG_OID(0);
730  HeapTuple tuple;
731  Datum tmp;
732  char *prosrc;
733 
734  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
735  PG_RETURN_VOID();
736 
737  /*
738  * We do not honor check_function_bodies since it's unlikely the function
739  * name will be found later if it isn't there now.
740  */
741 
742  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
743  if (!HeapTupleIsValid(tuple))
744  elog(ERROR, "cache lookup failed for function %u", funcoid);
745 
746  tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
747  prosrc = TextDatumGetCString(tmp);
748 
749  if (fmgr_internal_function(prosrc) == InvalidOid)
750  ereport(ERROR,
751  (errcode(ERRCODE_UNDEFINED_FUNCTION),
752  errmsg("there is no built-in function named \"%s\"",
753  prosrc)));
754 
755  ReleaseSysCache(tuple);
756 
757  PG_RETURN_VOID();
758 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ereport(elevel,...)
Definition: elog.h:149
Oid fmgr_internal_function(const char *proname)
Definition: fmgr.c:595
#define InvalidOid
Definition: postgres_ext.h:36

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

◆ fmgr_sql_validator()

Datum fmgr_sql_validator ( PG_FUNCTION_ARGS  )

Definition at line 813 of file pg_proc.c.

814 {
815  Oid funcoid = PG_GETARG_OID(0);
816  HeapTuple tuple;
817  Form_pg_proc proc;
818  List *raw_parsetree_list;
819  List *querytree_list;
820  ListCell *lc;
821  bool isnull;
822  Datum tmp;
823  char *prosrc;
824  parse_error_callback_arg callback_arg;
825  ErrorContextCallback sqlerrcontext;
826  bool haspolyarg;
827  int i;
828 
829  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
830  PG_RETURN_VOID();
831 
832  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
833  if (!HeapTupleIsValid(tuple))
834  elog(ERROR, "cache lookup failed for function %u", funcoid);
835  proc = (Form_pg_proc) GETSTRUCT(tuple);
836 
837  /* Disallow pseudotype result */
838  /* except for RECORD, VOID, or polymorphic */
839  if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
840  proc->prorettype != RECORDOID &&
841  proc->prorettype != VOIDOID &&
842  !IsPolymorphicType(proc->prorettype))
843  ereport(ERROR,
844  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
845  errmsg("SQL functions cannot return type %s",
846  format_type_be(proc->prorettype))));
847 
848  /* Disallow pseudotypes in arguments */
849  /* except for polymorphic */
850  haspolyarg = false;
851  for (i = 0; i < proc->pronargs; i++)
852  {
853  if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
854  {
855  if (IsPolymorphicType(proc->proargtypes.values[i]))
856  haspolyarg = true;
857  else
858  ereport(ERROR,
859  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
860  errmsg("SQL functions cannot have arguments of type %s",
861  format_type_be(proc->proargtypes.values[i]))));
862  }
863  }
864 
865  /* Postpone body checks if !check_function_bodies */
867  {
868  tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
869  prosrc = TextDatumGetCString(tmp);
870 
871  /*
872  * Setup error traceback support for ereport().
873  */
874  callback_arg.proname = NameStr(proc->proname);
875  callback_arg.prosrc = prosrc;
876 
878  sqlerrcontext.arg = (void *) &callback_arg;
879  sqlerrcontext.previous = error_context_stack;
880  error_context_stack = &sqlerrcontext;
881 
882  /* If we have prosqlbody, pay attention to that not prosrc */
883  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
884  if (!isnull)
885  {
886  Node *n;
887  List *stored_query_list;
888 
890  if (IsA(n, List))
891  stored_query_list = linitial(castNode(List, n));
892  else
893  stored_query_list = list_make1(n);
894 
895  querytree_list = NIL;
896  foreach(lc, stored_query_list)
897  {
898  Query *parsetree = lfirst_node(Query, lc);
899  List *querytree_sublist;
900 
901  /*
902  * Typically, we'd have acquired locks already while parsing
903  * the body of the CREATE FUNCTION command. However, a
904  * validator function cannot assume that it's only called in
905  * that context.
906  */
907  AcquireRewriteLocks(parsetree, true, false);
908  querytree_sublist = pg_rewrite_query(parsetree);
909  querytree_list = lappend(querytree_list, querytree_sublist);
910  }
911  }
912  else
913  {
914  /*
915  * We can't do full prechecking of the function definition if
916  * there are any polymorphic input types, because actual datatypes
917  * of expression results will be unresolvable. The check will be
918  * done at runtime instead.
919  *
920  * We can run the text through the raw parser though; this will at
921  * least catch silly syntactic errors.
922  */
923  raw_parsetree_list = pg_parse_query(prosrc);
924  querytree_list = NIL;
925 
926  if (!haspolyarg)
927  {
928  /*
929  * OK to do full precheck: analyze and rewrite the queries,
930  * then verify the result type.
931  */
933 
934  /* But first, set up parameter information */
935  pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
936 
937  foreach(lc, raw_parsetree_list)
938  {
939  RawStmt *parsetree = lfirst_node(RawStmt, lc);
940  List *querytree_sublist;
941 
942  querytree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
943  prosrc,
945  pinfo,
946  NULL);
947  querytree_list = lappend(querytree_list,
948  querytree_sublist);
949  }
950  }
951  }
952 
953  if (!haspolyarg)
954  {
955  Oid rettype;
956  TupleDesc rettupdesc;
957 
958  check_sql_fn_statements(querytree_list);
959 
960  (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
961 
962  (void) check_sql_fn_retval(querytree_list,
963  rettype, rettupdesc,
964  false, NULL);
965  }
966 
967  error_context_stack = sqlerrcontext.previous;
968  }
969 
970  ReleaseSysCache(tuple);
971 
972  PG_RETURN_VOID();
973 }
#define NameStr(name)
Definition: c.h:735
ErrorContextCallback * error_context_stack
Definition: elog.c:95
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:403
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1607
void check_sql_fn_statements(List *queryTreeLists)
Definition: functions.c:1532
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
bool check_function_bodies
Definition: guc_tables.c:509
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
char get_typtype(Oid typid)
Definition: lsyscache.c:2611
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
#define linitial(l)
Definition: pg_list.h:178
static void sql_function_parse_error_callback(void *arg)
Definition: pg_proc.c:979
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
List * pg_parse_query(const char *query_string)
Definition: postgres.c:610
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:763
List * pg_rewrite_query(Query *query)
Definition: postgres.c:803
void * stringToNode(const char *str)
Definition: read.c:90
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
Definition: pg_list.h:54
Definition: nodes.h:129
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1081

References AcquireRewriteLocks(), ErrorContextCallback::arg, ErrorContextCallback::callback, castNode, check_function_bodies, check_sql_fn_retval(), check_sql_fn_statements(), CheckFunctionValidatorAccess(), elog(), ereport, errcode(), errmsg(), ERROR, error_context_stack, format_type_be(), get_func_result_type(), get_typtype(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, IsA, lappend(), lfirst_node, linitial, list_make1, NameStr, NIL, ObjectIdGetDatum(), pg_analyze_and_rewrite_withcb(), PG_GETARG_OID, pg_parse_query(), PG_RETURN_VOID, pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, parse_error_callback_arg::proname, parse_error_callback_arg::prosrc, ReleaseSysCache(), SearchSysCache1(), sql_fn_parser_setup(), sql_function_parse_error_callback(), stringToNode(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

◆ function_parse_error_transpose()

bool function_parse_error_transpose ( const char *  prosrc)

Definition at line 1003 of file pg_proc.c.

1004 {
1005  int origerrposition;
1006  int newerrposition;
1007 
1008  /*
1009  * Nothing to do unless we are dealing with a syntax error that has a
1010  * cursor position.
1011  *
1012  * Some PLs may prefer to report the error position as an internal error
1013  * to begin with, so check that too.
1014  */
1015  origerrposition = geterrposition();
1016  if (origerrposition <= 0)
1017  {
1018  origerrposition = getinternalerrposition();
1019  if (origerrposition <= 0)
1020  return false;
1021  }
1022 
1023  /* We can get the original query text from the active portal (hack...) */
1025  {
1026  const char *queryText = ActivePortal->sourceText;
1027 
1028  /* Try to locate the prosrc in the original text */
1029  newerrposition = match_prosrc_to_query(prosrc, queryText,
1030  origerrposition);
1031  }
1032  else
1033  {
1034  /*
1035  * Quietly give up if no ActivePortal. This is an unusual situation
1036  * but it can happen in, e.g., logical replication workers.
1037  */
1038  newerrposition = -1;
1039  }
1040 
1041  if (newerrposition > 0)
1042  {
1043  /* Successful, so fix error position to reference original query */
1044  errposition(newerrposition);
1045  /* Get rid of any report of the error as an "internal query" */
1047  internalerrquery(NULL);
1048  }
1049  else
1050  {
1051  /*
1052  * If unsuccessful, convert the position to an internal position
1053  * marker and give the function text as the internal query.
1054  */
1055  errposition(0);
1056  internalerrposition(origerrposition);
1057  internalerrquery(prosrc);
1058  }
1059 
1060  return true;
1061 }
int getinternalerrposition(void)
Definition: elog.c:1594
int internalerrquery(const char *query)
Definition: elog.c:1481
int internalerrposition(int cursorpos)
Definition: elog.c:1461
int geterrposition(void)
Definition: elog.c:1577
int errposition(int cursorpos)
Definition: elog.c:1445
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1070
@ PORTAL_ACTIVE
Definition: portal.h:108
Portal ActivePortal
Definition: pquery.c:35
const char * sourceText
Definition: portal.h:136
PortalStatus status
Definition: portal.h:151

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

Referenced by plpgsql_compile_error_callback(), and sql_function_parse_error_callback().

◆ match_prosrc_to_literal()

static bool match_prosrc_to_literal ( const char *  prosrc,
const char *  literal,
int  cursorpos,
int *  newcursorpos 
)
static

Definition at line 1128 of file pg_proc.c.

1130 {
1131  int newcp = cursorpos;
1132  int chlen;
1133 
1134  /*
1135  * This implementation handles backslashes and doubled quotes in the
1136  * string literal. It does not handle the SQL syntax for literals
1137  * continued across line boundaries.
1138  *
1139  * We do the comparison a character at a time, not a byte at a time, so
1140  * that we can do the correct cursorpos math.
1141  */
1142  while (*prosrc)
1143  {
1144  cursorpos--; /* characters left before cursor */
1145 
1146  /*
1147  * Check for backslashes and doubled quotes in the literal; adjust
1148  * newcp when one is found before the cursor.
1149  */
1150  if (*literal == '\\')
1151  {
1152  literal++;
1153  if (cursorpos > 0)
1154  newcp++;
1155  }
1156  else if (*literal == '\'')
1157  {
1158  if (literal[1] != '\'')
1159  goto fail;
1160  literal++;
1161  if (cursorpos > 0)
1162  newcp++;
1163  }
1164  chlen = pg_mblen(prosrc);
1165  if (strncmp(prosrc, literal, chlen) != 0)
1166  goto fail;
1167  prosrc += chlen;
1168  literal += chlen;
1169  }
1170 
1171  if (*literal == '\'' && literal[1] != '\'')
1172  {
1173  /* success */
1174  *newcursorpos = newcp;
1175  return true;
1176  }
1177 
1178 fail:
1179  /* Must set *newcursorpos to suppress compiler warning */
1180  *newcursorpos = newcp;
1181  return false;
1182 }
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1024

References pg_mblen().

Referenced by match_prosrc_to_query().

◆ match_prosrc_to_query()

static int match_prosrc_to_query ( const char *  prosrc,
const char *  queryText,
int  cursorpos 
)
static

Definition at line 1070 of file pg_proc.c.

1072 {
1073  /*
1074  * Rather than fully parsing the original command, we just scan the
1075  * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1076  * not in any very probable scenarios), so fail if we find more than one
1077  * match.
1078  */
1079  int prosrclen = strlen(prosrc);
1080  int querylen = strlen(queryText);
1081  int matchpos = 0;
1082  int curpos;
1083  int newcursorpos;
1084 
1085  for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1086  {
1087  if (queryText[curpos] == '$' &&
1088  strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1089  queryText[curpos + 1 + prosrclen] == '$')
1090  {
1091  /*
1092  * Found a $foo$ match. Since there are no embedded quoting
1093  * characters in a dollar-quoted literal, we don't have to do any
1094  * fancy arithmetic; just offset by the starting position.
1095  */
1096  if (matchpos)
1097  return 0; /* multiple matches, fail */
1098  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1099  + cursorpos;
1100  }
1101  else if (queryText[curpos] == '\'' &&
1102  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1103  cursorpos, &newcursorpos))
1104  {
1105  /*
1106  * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1107  * for any quotes or backslashes embedded in the literal.
1108  */
1109  if (matchpos)
1110  return 0; /* multiple matches, fail */
1111  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1112  + newcursorpos;
1113  }
1114  }
1115 
1116  return matchpos;
1117 }
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1058
static bool match_prosrc_to_literal(const char *prosrc, const char *literal, int cursorpos, int *newcursorpos)
Definition: pg_proc.c:1128

References match_prosrc_to_literal(), and pg_mbstrlen_with_len().

Referenced by function_parse_error_transpose().

◆ oid_array_to_list()

List* oid_array_to_list ( Datum  datum)

Definition at line 1185 of file pg_proc.c.

1186 {
1187  ArrayType *array = DatumGetArrayTypeP(datum);
1188  Datum *values;
1189  int nelems;
1190  int i;
1191  List *result = NIL;
1192 
1193  deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems);
1194  for (i = 0; i < nelems; i++)
1195  result = lappend_oid(result, values[i]);
1196  return result;
1197 }
#define DatumGetArrayTypeP(X)
Definition: array.h:261
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3679
static Datum values[MAXATTR]
Definition: bootstrap.c:156
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374

References DatumGetArrayTypeP, deconstruct_array_builtin(), i, lappend_oid(), NIL, and values.

Referenced by compile_plperl_function(), and PLy_procedure_create().

◆ ProcedureCreate()

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 at line 72 of file pg_proc.c.

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

References aclcheck_error(), ACLCHECK_NOT_OWNER, add_exact_object_address(), 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(), check_function_bodies, check_valid_internal_signature(), check_valid_polymorphic_signature(), CommandCounterIncrement(), CStringGetTextDatum, DatumGetPointer(), deleteDependencyRecordsFor(), DEPENDENCY_NORMAL, oidvector::dim1, elog(), equalTupleDescs(), ereport, errcode(), errdetail(), errdetail_internal(), errhint(), errmsg(), errmsg_plural(), ERROR, exprType(), Float4GetDatum(), format_procedure(), free_object_addresses(), FUNC_MAX_ARGS, get_element_type(), get_func_input_arg_names(), get_transform_oid(), get_user_default_acl(), GetNewOidWithIndex(), GETSTRUCT, GUC_ACTION_SAVE, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostCreateHook, j, lfirst, list_length(), list_nth_cell(), lnext(), NameGetDatum(), namestrcpy(), new_object_addresses(), NewGUCNestLevel(), NIL, nodeToString(), OBJECT_FUNCTION, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PGC_S_SESSION, PGC_SUSET, PGC_USERSET, pgstat_create_function(), PointerGetDatum(), PointerIsValid, ProcessGUCArray(), PROCNAMEARGSNSP, record_object_address_dependencies(), recordDependencyOnCurrentExtension(), recordDependencyOnExpr(), recordDependencyOnNewAcl(), recordDependencyOnOwner(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), stringToNode(), superuser(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, UInt16GetDatum(), oidvector::values, and values.

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

◆ sql_function_parse_error_callback()

static void sql_function_parse_error_callback ( void *  arg)
static

Definition at line 979 of file pg_proc.c.

980 {
982 
983  /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
984  if (!function_parse_error_transpose(callback_arg->prosrc))
985  {
986  /* If it's not a syntax error, push info onto context stack */
987  errcontext("SQL function \"%s\"", callback_arg->proname);
988  }
989 }
#define errcontext
Definition: elog.h:196
void * arg
bool function_parse_error_transpose(const char *prosrc)
Definition: pg_proc.c:1003

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

Referenced by fmgr_sql_validator().