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 "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 771 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.

772 {
773  Oid funcoid = PG_GETARG_OID(0);
774  void *libraryhandle;
775  HeapTuple tuple;
776  bool isnull;
777  Datum tmp;
778  char *prosrc;
779  char *probin;
780 
781  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
782  PG_RETURN_VOID();
783 
784  /*
785  * It'd be most consistent to skip the check if !check_function_bodies,
786  * but the purpose of that switch is to be helpful for pg_dump loading,
787  * and for pg_dump loading it's much better if we *do* check.
788  */
789 
790  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
791  if (!HeapTupleIsValid(tuple))
792  elog(ERROR, "cache lookup failed for function %u", funcoid);
793 
794  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
795  if (isnull)
796  elog(ERROR, "null prosrc for C function %u", funcoid);
797  prosrc = TextDatumGetCString(tmp);
798 
799  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
800  if (isnull)
801  elog(ERROR, "null probin for C function %u", funcoid);
802  probin = TextDatumGetCString(tmp);
803 
804  (void) load_external_function(probin, prosrc, true, &libraryhandle);
805  (void) fetch_finfo_record(libraryhandle, prosrc);
806 
807  ReleaseSysCache(tuple);
808 
809  PG_RETURN_VOID();
810 }
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2035
#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:1127
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const Pg_finfo_record * fetch_finfo_record(void *filehandle, const char *funcname)
Definition: fmgr.c:469
#define elog(elevel,...)
Definition: elog.h:232

◆ fmgr_internal_validator()

Datum fmgr_internal_validator ( PG_FUNCTION_ARGS  )

Definition at line 725 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.

726 {
727  Oid funcoid = PG_GETARG_OID(0);
728  HeapTuple tuple;
729  bool isnull;
730  Datum tmp;
731  char *prosrc;
732 
733  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
734  PG_RETURN_VOID();
735 
736  /*
737  * We do not honor check_function_bodies since it's unlikely the function
738  * name will be found later if it isn't there now.
739  */
740 
741  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
742  if (!HeapTupleIsValid(tuple))
743  elog(ERROR, "cache lookup failed for function %u", funcoid);
744 
745  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
746  if (isnull)
747  elog(ERROR, "null prosrc");
748  prosrc = TextDatumGetCString(tmp);
749 
750  if (fmgr_internal_function(prosrc) == InvalidOid)
751  ereport(ERROR,
752  (errcode(ERRCODE_UNDEFINED_FUNCTION),
753  errmsg("there is no built-in function named \"%s\"",
754  prosrc)));
755 
756  ReleaseSysCache(tuple);
757 
758  PG_RETURN_VOID();
759 }
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
Oid fmgr_internal_function(const char *proname)
Definition: fmgr.c:623
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2035
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232

◆ fmgr_sql_validator()

Datum fmgr_sql_validator ( PG_FUNCTION_ARGS  )

Definition at line 819 of file pg_proc.c.

References 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, list_make1, 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(), stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

820 {
821  Oid funcoid = PG_GETARG_OID(0);
822  HeapTuple tuple;
823  Form_pg_proc proc;
824  List *raw_parsetree_list;
825  List *querytree_list;
826  ListCell *lc;
827  bool isnull;
828  Datum tmp;
829  char *prosrc;
830  parse_error_callback_arg callback_arg;
831  ErrorContextCallback sqlerrcontext;
832  bool haspolyarg;
833  int i;
834 
835  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
836  PG_RETURN_VOID();
837 
838  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
839  if (!HeapTupleIsValid(tuple))
840  elog(ERROR, "cache lookup failed for function %u", funcoid);
841  proc = (Form_pg_proc) GETSTRUCT(tuple);
842 
843  /* Disallow pseudotype result */
844  /* except for RECORD, VOID, or polymorphic */
845  if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
846  proc->prorettype != RECORDOID &&
847  proc->prorettype != VOIDOID &&
848  !IsPolymorphicType(proc->prorettype))
849  ereport(ERROR,
850  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
851  errmsg("SQL functions cannot return type %s",
852  format_type_be(proc->prorettype))));
853 
854  /* Disallow pseudotypes in arguments */
855  /* except for polymorphic */
856  haspolyarg = false;
857  for (i = 0; i < proc->pronargs; i++)
858  {
859  if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
860  {
861  if (IsPolymorphicType(proc->proargtypes.values[i]))
862  haspolyarg = true;
863  else
864  ereport(ERROR,
865  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
866  errmsg("SQL functions cannot have arguments of type %s",
867  format_type_be(proc->proargtypes.values[i]))));
868  }
869  }
870 
871  /* Postpone body checks if !check_function_bodies */
873  {
874  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
875  if (isnull)
876  elog(ERROR, "null prosrc");
877 
878  prosrc = TextDatumGetCString(tmp);
879 
880  /*
881  * Setup error traceback support for ereport().
882  */
883  callback_arg.proname = NameStr(proc->proname);
884  callback_arg.prosrc = prosrc;
885 
887  sqlerrcontext.arg = (void *) &callback_arg;
888  sqlerrcontext.previous = error_context_stack;
889  error_context_stack = &sqlerrcontext;
890 
891  /* If we have prosqlbody, pay attention to that not prosrc */
892  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
893  if (!isnull)
894  {
895  Node *n;
896 
898  if (IsA(n, List))
899  querytree_list = castNode(List, n);
900  else
901  querytree_list = list_make1(list_make1(n));
902  }
903  else
904  {
905  /*
906  * We can't do full prechecking of the function definition if there
907  * are any polymorphic input types, because actual datatypes of
908  * expression results will be unresolvable. The check will be done at
909  * runtime instead.
910  *
911  * We can run the text through the raw parser though; this will at
912  * least catch silly syntactic errors.
913  */
914  raw_parsetree_list = pg_parse_query(prosrc);
915  querytree_list = NIL;
916 
917  if (!haspolyarg)
918  {
919  /*
920  * OK to do full precheck: analyze and rewrite the queries, then
921  * verify the result type.
922  */
924 
925  /* But first, set up parameter information */
926  pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
927 
928  foreach(lc, raw_parsetree_list)
929  {
930  RawStmt *parsetree = lfirst_node(RawStmt, lc);
931  List *querytree_sublist;
932 
933  querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
934  prosrc,
936  pinfo,
937  NULL);
938  querytree_list = lappend(querytree_list,
939  querytree_sublist);
940  }
941  }
942  }
943 
944  if (!haspolyarg)
945  {
946  Oid rettype;
947  TupleDesc rettupdesc;
948 
949  check_sql_fn_statements(querytree_list);
950 
951  (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
952 
953  (void) check_sql_fn_retval(querytree_list,
954  rettype, rettupdesc,
955  false, NULL);
956  }
957 
958  error_context_stack = sqlerrcontext.previous;
959  }
960 
961  ReleaseSysCache(tuple);
962 
963  PG_RETURN_VOID();
964 }
#define NIL
Definition: pg_list.h:65
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1618
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:266
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
void * stringToNode(const char *str)
Definition: read.c:89
char get_typtype(Oid typid)
Definition: lsyscache.c:2576
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
bool check_function_bodies
Definition: guc.c:555
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define list_make1(x1)
Definition: pg_list.h:206
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2035
List * pg_parse_query(const char *query_string)
Definition: postgres.c:594
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
List * lappend(List *list, void *datum)
Definition: list.c:336
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:300
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define InvalidOid
Definition: postgres_ext.h:36
static void sql_function_parse_error_callback(void *arg)
Definition: pg_proc.c:970
#define ereport(elevel,...)
Definition: elog.h:157
void check_sql_fn_statements(List *queryTreeLists)
Definition: functions.c:1524
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#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:679
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
Definition: pg_list.h:50

◆ function_parse_error_transpose()

bool function_parse_error_transpose ( const char *  prosrc)

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

995 {
996  int origerrposition;
997  int newerrposition;
998  const char *queryText;
999 
1000  /*
1001  * Nothing to do unless we are dealing with a syntax error that has a
1002  * cursor position.
1003  *
1004  * Some PLs may prefer to report the error position as an internal error
1005  * to begin with, so check that too.
1006  */
1007  origerrposition = geterrposition();
1008  if (origerrposition <= 0)
1009  {
1010  origerrposition = getinternalerrposition();
1011  if (origerrposition <= 0)
1012  return false;
1013  }
1014 
1015  /* We can get the original query text from the active portal (hack...) */
1017  queryText = ActivePortal->sourceText;
1018 
1019  /* Try to locate the prosrc in the original text */
1020  newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
1021 
1022  if (newerrposition > 0)
1023  {
1024  /* Successful, so fix error position to reference original query */
1025  errposition(newerrposition);
1026  /* Get rid of any report of the error as an "internal query" */
1028  internalerrquery(NULL);
1029  }
1030  else
1031  {
1032  /*
1033  * If unsuccessful, convert the position to an internal position
1034  * marker and give the function text as the internal query.
1035  */
1036  errposition(0);
1037  internalerrposition(origerrposition);
1038  internalerrquery(prosrc);
1039  }
1040 
1041  return true;
1042 }
Portal ActivePortal
Definition: pquery.c:35
int geterrposition(void)
Definition: elog.c:1417
int getinternalerrposition(void)
Definition: elog.c:1434
const char * sourceText
Definition: portal.h:135
int internalerrquery(const char *query)
Definition: elog.c:1321
#define Assert(condition)
Definition: c.h:804
PortalStatus status
Definition: portal.h:150
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1051
int errposition(int cursorpos)
Definition: elog.c:1285
int internalerrposition(int cursorpos)
Definition: elog.c:1301

◆ match_prosrc_to_literal()

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

Definition at line 1109 of file pg_proc.c.

References pg_mblen().

Referenced by match_prosrc_to_query().

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

◆ match_prosrc_to_query()

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

Definition at line 1051 of file pg_proc.c.

References match_prosrc_to_literal(), and pg_mbstrlen_with_len().

Referenced by function_parse_error_transpose().

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

◆ oid_array_to_list()

List* oid_array_to_list ( Datum  datum)

Definition at line 1166 of file pg_proc.c.

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

Referenced by compile_plperl_function(), and PLy_procedure_create().

1167 {
1168  ArrayType *array = DatumGetArrayTypeP(datum);
1169  Datum *values;
1170  int nelems;
1171  int i;
1172  List *result = NIL;
1173 
1174  deconstruct_array(array,
1175  OIDOID,
1176  sizeof(Oid), true, TYPALIGN_INT,
1177  &values, NULL, &nelems);
1178  for (i = 0; i < nelems; i++)
1179  result = lappend_oid(result, values[i]);
1180  return result;
1181 }
#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:372
uintptr_t Datum
Definition: postgres.h:411
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3488
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int i
Definition: pg_list.h:50
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ 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 70 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(), makeMultirangeConstructors(), and makeRangeConstructors().

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

◆ sql_function_parse_error_callback()

static void sql_function_parse_error_callback ( void *  arg)
static

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

971 {
973 
974  /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
975  if (!function_parse_error_transpose(callback_arg->prosrc))
976  {
977  /* If it's not a syntax error, push info onto context stack */
978  errcontext("SQL function \"%s\"", callback_arg->proname);
979  }
980 }
bool function_parse_error_transpose(const char *prosrc)
Definition: pg_proc.c:994
#define errcontext
Definition: elog.h:204
void * arg