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/parse_coerce.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, 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 756 of file pg_proc.c.

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

757 {
758  Oid funcoid = PG_GETARG_OID(0);
759  void *libraryhandle;
760  HeapTuple tuple;
761  bool isnull;
762  Datum tmp;
763  char *prosrc;
764  char *probin;
765 
766  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
767  PG_RETURN_VOID();
768 
769  /*
770  * It'd be most consistent to skip the check if !check_function_bodies,
771  * but the purpose of that switch is to be helpful for pg_dump loading,
772  * and for pg_dump loading it's much better if we *do* check.
773  */
774 
775  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
776  if (!HeapTupleIsValid(tuple))
777  elog(ERROR, "cache lookup failed for function %u", funcoid);
778 
779  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
780  if (isnull)
781  elog(ERROR, "null prosrc for C function %u", funcoid);
782  prosrc = TextDatumGetCString(tmp);
783 
784  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
785  if (isnull)
786  elog(ERROR, "null probin for C function %u", funcoid);
787  probin = TextDatumGetCString(tmp);
788 
789  (void) load_external_function(probin, prosrc, true, &libraryhandle);
790  (void) fetch_finfo_record(libraryhandle, prosrc);
791 
792  ReleaseSysCache(tuple);
793 
794  PG_RETURN_VOID();
795 }
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2039
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:107
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:87
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define PG_RETURN_VOID()
Definition: fmgr.h:348
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const Pg_finfo_record * fetch_finfo_record(void *filehandle, const char *funcname)
Definition: fmgr.c:472
#define elog(elevel,...)
Definition: elog.h:214

◆ fmgr_internal_validator()

Datum fmgr_internal_validator ( PG_FUNCTION_ARGS  )

Definition at line 710 of file pg_proc.c.

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

711 {
712  Oid funcoid = PG_GETARG_OID(0);
713  HeapTuple tuple;
714  bool isnull;
715  Datum tmp;
716  char *prosrc;
717 
718  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
719  PG_RETURN_VOID();
720 
721  /*
722  * We do not honor check_function_bodies since it's unlikely the function
723  * name will be found later if it isn't there now.
724  */
725 
726  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
727  if (!HeapTupleIsValid(tuple))
728  elog(ERROR, "cache lookup failed for function %u", funcoid);
729 
730  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
731  if (isnull)
732  elog(ERROR, "null prosrc");
733  prosrc = TextDatumGetCString(tmp);
734 
735  if (fmgr_internal_function(prosrc) == InvalidOid)
736  ereport(ERROR,
737  (errcode(ERRCODE_UNDEFINED_FUNCTION),
738  errmsg("there is no built-in function named \"%s\"",
739  prosrc)));
740 
741  ReleaseSysCache(tuple);
742 
743  PG_RETURN_VOID();
744 }
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
Oid fmgr_internal_function(const char *proname)
Definition: fmgr.c:627
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2039
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:87
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_VOID()
Definition: fmgr.h:348
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214

◆ fmgr_sql_validator()

Datum fmgr_sql_validator ( PG_FUNCTION_ARGS  )

Definition at line 804 of file pg_proc.c.

References ErrorContextCallback::arg, ErrorContextCallback::callback, 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, lfirst_node, list_concat(), NameStr, NIL, 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, ReleaseSysCache(), SearchSysCache1(), sql_fn_parser_setup(), sql_function_parse_error_callback(), SysCacheGetAttr(), and TextDatumGetCString.

805 {
806  Oid funcoid = PG_GETARG_OID(0);
807  HeapTuple tuple;
808  Form_pg_proc proc;
809  List *raw_parsetree_list;
810  List *querytree_list;
811  ListCell *lc;
812  bool isnull;
813  Datum tmp;
814  char *prosrc;
815  parse_error_callback_arg callback_arg;
816  ErrorContextCallback sqlerrcontext;
817  bool haspolyarg;
818  int i;
819 
820  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
821  PG_RETURN_VOID();
822 
823  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
824  if (!HeapTupleIsValid(tuple))
825  elog(ERROR, "cache lookup failed for function %u", funcoid);
826  proc = (Form_pg_proc) GETSTRUCT(tuple);
827 
828  /* Disallow pseudotype result */
829  /* except for RECORD, VOID, or polymorphic */
830  if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
831  proc->prorettype != RECORDOID &&
832  proc->prorettype != VOIDOID &&
833  !IsPolymorphicType(proc->prorettype))
834  ereport(ERROR,
835  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
836  errmsg("SQL functions cannot return type %s",
837  format_type_be(proc->prorettype))));
838 
839  /* Disallow pseudotypes in arguments */
840  /* except for polymorphic */
841  haspolyarg = false;
842  for (i = 0; i < proc->pronargs; i++)
843  {
844  if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
845  {
846  if (IsPolymorphicType(proc->proargtypes.values[i]))
847  haspolyarg = true;
848  else
849  ereport(ERROR,
850  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
851  errmsg("SQL functions cannot have arguments of type %s",
852  format_type_be(proc->proargtypes.values[i]))));
853  }
854  }
855 
856  /* Postpone body checks if !check_function_bodies */
858  {
859  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
860  if (isnull)
861  elog(ERROR, "null prosrc");
862 
863  prosrc = TextDatumGetCString(tmp);
864 
865  /*
866  * Setup error traceback support for ereport().
867  */
868  callback_arg.proname = NameStr(proc->proname);
869  callback_arg.prosrc = prosrc;
870 
872  sqlerrcontext.arg = (void *) &callback_arg;
873  sqlerrcontext.previous = error_context_stack;
874  error_context_stack = &sqlerrcontext;
875 
876  /*
877  * We can't do full prechecking of the function definition if there
878  * are any polymorphic input types, because actual datatypes of
879  * expression results will be unresolvable. The check will be done at
880  * runtime instead.
881  *
882  * We can run the text through the raw parser though; this will at
883  * least catch silly syntactic errors.
884  */
885  raw_parsetree_list = pg_parse_query(prosrc);
886 
887  if (!haspolyarg)
888  {
889  /*
890  * OK to do full precheck: analyze and rewrite the queries, then
891  * verify the result type.
892  */
894  Oid rettype;
895  TupleDesc rettupdesc;
896 
897  /* But first, set up parameter information */
898  pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
899 
900  querytree_list = NIL;
901  foreach(lc, raw_parsetree_list)
902  {
903  RawStmt *parsetree = lfirst_node(RawStmt, lc);
904  List *querytree_sublist;
905 
906  querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
907  prosrc,
909  pinfo,
910  NULL);
911  querytree_list = list_concat(querytree_list,
912  querytree_sublist);
913  }
914 
915  check_sql_fn_statements(querytree_list);
916 
917  (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
918 
919  (void) check_sql_fn_retval(querytree_list,
920  rettype, rettupdesc,
921  false, NULL);
922  }
923 
924  error_context_stack = sqlerrcontext.previous;
925  }
926 
927  ReleaseSysCache(tuple);
928 
929  PG_RETURN_VOID();
930 }
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void check_sql_fn_statements(List *queryTreeList)
Definition: functions.c:1512
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:279
bool check_sql_fn_retval(List *queryTreeList, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1594
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
char get_typtype(Oid typid)
Definition: lsyscache.c:2517
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
bool check_function_bodies
Definition: guc.c:528
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2039
List * pg_parse_query(const char *query_string)
Definition: postgres.c:628
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:298
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:87
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
static void sql_function_parse_error_callback(void *arg)
Definition: pg_proc.c:936
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_VOID()
Definition: fmgr.h:348
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:713
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:622
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:190
Definition: pg_list.h:50

◆ function_parse_error_transpose()

bool function_parse_error_transpose ( const char *  prosrc)

Definition at line 960 of file pg_proc.c.

References ActivePortal, Assert, 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().

961 {
962  int origerrposition;
963  int newerrposition;
964  const char *queryText;
965 
966  /*
967  * Nothing to do unless we are dealing with a syntax error that has a
968  * cursor position.
969  *
970  * Some PLs may prefer to report the error position as an internal error
971  * to begin with, so check that too.
972  */
973  origerrposition = geterrposition();
974  if (origerrposition <= 0)
975  {
976  origerrposition = getinternalerrposition();
977  if (origerrposition <= 0)
978  return false;
979  }
980 
981  /* We can get the original query text from the active portal (hack...) */
983  queryText = ActivePortal->sourceText;
984 
985  /* Try to locate the prosrc in the original text */
986  newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
987 
988  if (newerrposition > 0)
989  {
990  /* Successful, so fix error position to reference original query */
991  errposition(newerrposition);
992  /* Get rid of any report of the error as an "internal query" */
994  internalerrquery(NULL);
995  }
996  else
997  {
998  /*
999  * If unsuccessful, convert the position to an internal position
1000  * marker and give the function text as the internal query.
1001  */
1002  errposition(0);
1003  internalerrposition(origerrposition);
1004  internalerrquery(prosrc);
1005  }
1006 
1007  return true;
1008 }
Portal ActivePortal
Definition: pquery.c:35
int geterrposition(void)
Definition: elog.c:1331
int getinternalerrposition(void)
Definition: elog.c:1348
const char * sourceText
Definition: portal.h:135
int internalerrquery(const char *query)
Definition: elog.c:1235
#define Assert(condition)
Definition: c.h:745
PortalStatus status
Definition: portal.h:150
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1017
int errposition(int cursorpos)
Definition: elog.c:1199
int internalerrposition(int cursorpos)
Definition: elog.c:1215

◆ match_prosrc_to_literal()

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

Definition at line 1075 of file pg_proc.c.

References pg_mblen().

Referenced by match_prosrc_to_query().

1077 {
1078  int newcp = cursorpos;
1079  int chlen;
1080 
1081  /*
1082  * This implementation handles backslashes and doubled quotes in the
1083  * string literal. It does not handle the SQL syntax for literals
1084  * continued across line boundaries.
1085  *
1086  * We do the comparison a character at a time, not a byte at a time, so
1087  * that we can do the correct cursorpos math.
1088  */
1089  while (*prosrc)
1090  {
1091  cursorpos--; /* characters left before cursor */
1092 
1093  /*
1094  * Check for backslashes and doubled quotes in the literal; adjust
1095  * newcp when one is found before the cursor.
1096  */
1097  if (*literal == '\\')
1098  {
1099  literal++;
1100  if (cursorpos > 0)
1101  newcp++;
1102  }
1103  else if (*literal == '\'')
1104  {
1105  if (literal[1] != '\'')
1106  goto fail;
1107  literal++;
1108  if (cursorpos > 0)
1109  newcp++;
1110  }
1111  chlen = pg_mblen(prosrc);
1112  if (strncmp(prosrc, literal, chlen) != 0)
1113  goto fail;
1114  prosrc += chlen;
1115  literal += chlen;
1116  }
1117 
1118  if (*literal == '\'' && literal[1] != '\'')
1119  {
1120  /* success */
1121  *newcursorpos = newcp;
1122  return true;
1123  }
1124 
1125 fail:
1126  /* Must set *newcursorpos to suppress compiler warning */
1127  *newcursorpos = newcp;
1128  return false;
1129 }
int pg_mblen(const char *mbstr)
Definition: mbutils.c:907

◆ match_prosrc_to_query()

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

Definition at line 1017 of file pg_proc.c.

References match_prosrc_to_literal(), and pg_mbstrlen_with_len().

Referenced by function_parse_error_transpose().

1019 {
1020  /*
1021  * Rather than fully parsing the original command, we just scan the
1022  * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1023  * not in any very probable scenarios), so fail if we find more than one
1024  * match.
1025  */
1026  int prosrclen = strlen(prosrc);
1027  int querylen = strlen(queryText);
1028  int matchpos = 0;
1029  int curpos;
1030  int newcursorpos;
1031 
1032  for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1033  {
1034  if (queryText[curpos] == '$' &&
1035  strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1036  queryText[curpos + 1 + prosrclen] == '$')
1037  {
1038  /*
1039  * Found a $foo$ match. Since there are no embedded quoting
1040  * characters in a dollar-quoted literal, we don't have to do any
1041  * fancy arithmetic; just offset by the starting position.
1042  */
1043  if (matchpos)
1044  return 0; /* multiple matches, fail */
1045  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1046  + cursorpos;
1047  }
1048  else if (queryText[curpos] == '\'' &&
1049  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1050  cursorpos, &newcursorpos))
1051  {
1052  /*
1053  * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1054  * for any quotes or backslashes embedded in the literal.
1055  */
1056  if (matchpos)
1057  return 0; /* multiple matches, fail */
1058  matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1059  + newcursorpos;
1060  }
1061  }
1062 
1063  return matchpos;
1064 }
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:941
static bool match_prosrc_to_literal(const char *prosrc, const char *literal, int cursorpos, int *newcursorpos)
Definition: pg_proc.c:1075

◆ oid_array_to_list()

List* oid_array_to_list ( Datum  datum)

Definition at line 1132 of file pg_proc.c.

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

Referenced by compile_plperl_function(), and PLy_procedure_create().

1133 {
1134  ArrayType *array = DatumGetArrayTypeP(datum);
1135  Datum *values;
1136  int nelems;
1137  int i;
1138  List *result = NIL;
1139 
1140  deconstruct_array(array,
1141  OIDOID,
1142  sizeof(Oid), true, TYPALIGN_INT,
1143  &values, NULL, &nelems);
1144  for (i = 0; i < nelems; i++)
1145  result = lappend_oid(result, values[i]);
1146  return result;
1147 }
#define NIL
Definition: pg_list.h:65
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
uintptr_t Datum
Definition: postgres.h:367
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3483
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int i
Definition: pg_list.h:50
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ 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,
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 69 of file pg_proc.c.

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, lfirst, list_length(), list_nth_cell(), lnext(), NameGetDatum, namestrcpy(), new_object_addresses(), NewGUCNestLevel(), NIL, nodeToString(), OBJECT_FUNCTION, ObjectAddressSet, ObjectIdGetDatum, OidFunctionCall1, OidIsValid, pg_proc_ownercheck(), PGC_S_SESSION, PGC_SUSET, PGC_USERSET, PointerGetDatum, PointerIsValid, ProcedureOidIndexId, ProcessGUCArray(), PROCNAMEARGSNSP, record_object_address_dependencies(), recordDependencyOnCurrentExtension(), recordDependencyOnExpr(), recordDependencyOnNewAcl(), recordDependencyOnOwner(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), stringToNode(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, UInt16GetDatum, values, and oidvector::values.

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

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

◆ sql_function_parse_error_callback()

static void sql_function_parse_error_callback ( void *  arg)
static

Definition at line 936 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().

937 {
939 
940  /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
941  if (!function_parse_error_transpose(callback_arg->prosrc))
942  {
943  /* If it's not a syntax error, push info onto context stack */
944  errcontext("SQL function \"%s\"", callback_arg->proname);
945  }
946 }
bool function_parse_error_transpose(const char *prosrc)
Definition: pg_proc.c:960
#define errcontext
Definition: elog.h:185
void * arg