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 "rewrite/rewriteHandler.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for pg_proc.c:

Go to the source code of this file.

Data Structures

struct  parse_error_callback_arg
 

Functions

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

Function Documentation

◆ fmgr_c_validator()

Datum fmgr_c_validator ( PG_FUNCTION_ARGS  )

Definition at line 770 of file pg_proc.c.

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

771 {
772  Oid funcoid = PG_GETARG_OID(0);
773  void *libraryhandle;
774  HeapTuple tuple;
775  bool isnull;
776  Datum tmp;
777  char *prosrc;
778  char *probin;
779 
780  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
781  PG_RETURN_VOID();
782 
783  /*
784  * It'd be most consistent to skip the check if !check_function_bodies,
785  * but the purpose of that switch is to be helpful for pg_dump loading,
786  * and for pg_dump loading it's much better if we *do* check.
787  */
788 
789  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
790  if (!HeapTupleIsValid(tuple))
791  elog(ERROR, "cache lookup failed for function %u", funcoid);
792 
793  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
794  if (isnull)
795  elog(ERROR, "null prosrc for C function %u", funcoid);
796  prosrc = TextDatumGetCString(tmp);
797 
798  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
799  if (isnull)
800  elog(ERROR, "null probin for C function %u", funcoid);
801  probin = TextDatumGetCString(tmp);
802 
803  (void) load_external_function(probin, prosrc, true, &libraryhandle);
804  (void) fetch_finfo_record(libraryhandle, prosrc);
805 
806  ReleaseSysCache(tuple);
807 
808  PG_RETURN_VOID();
809 }
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:87
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 724 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.

725 {
726  Oid funcoid = PG_GETARG_OID(0);
727  HeapTuple tuple;
728  bool isnull;
729  Datum tmp;
730  char *prosrc;
731 
732  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
733  PG_RETURN_VOID();
734 
735  /*
736  * We do not honor check_function_bodies since it's unlikely the function
737  * name will be found later if it isn't there now.
738  */
739 
740  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
741  if (!HeapTupleIsValid(tuple))
742  elog(ERROR, "cache lookup failed for function %u", funcoid);
743 
744  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
745  if (isnull)
746  elog(ERROR, "null prosrc");
747  prosrc = TextDatumGetCString(tmp);
748 
749  if (fmgr_internal_function(prosrc) == InvalidOid)
750  ereport(ERROR,
751  (errcode(ERRCODE_UNDEFINED_FUNCTION),
752  errmsg("there is no built-in function named \"%s\"",
753  prosrc)));
754 
755  ReleaseSysCache(tuple);
756 
757  PG_RETURN_VOID();
758 }
int errcode(int sqlerrcode)
Definition: elog.c: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:87
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 818 of file pg_proc.c.

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

819 {
820  Oid funcoid = PG_GETARG_OID(0);
821  HeapTuple tuple;
822  Form_pg_proc proc;
823  List *raw_parsetree_list;
824  List *querytree_list;
825  ListCell *lc;
826  bool isnull;
827  Datum tmp;
828  char *prosrc;
829  parse_error_callback_arg callback_arg;
830  ErrorContextCallback sqlerrcontext;
831  bool haspolyarg;
832  int i;
833 
834  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
835  PG_RETURN_VOID();
836 
837  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
838  if (!HeapTupleIsValid(tuple))
839  elog(ERROR, "cache lookup failed for function %u", funcoid);
840  proc = (Form_pg_proc) GETSTRUCT(tuple);
841 
842  /* Disallow pseudotype result */
843  /* except for RECORD, VOID, or polymorphic */
844  if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
845  proc->prorettype != RECORDOID &&
846  proc->prorettype != VOIDOID &&
847  !IsPolymorphicType(proc->prorettype))
848  ereport(ERROR,
849  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
850  errmsg("SQL functions cannot return type %s",
851  format_type_be(proc->prorettype))));
852 
853  /* Disallow pseudotypes in arguments */
854  /* except for polymorphic */
855  haspolyarg = false;
856  for (i = 0; i < proc->pronargs; i++)
857  {
858  if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
859  {
860  if (IsPolymorphicType(proc->proargtypes.values[i]))
861  haspolyarg = true;
862  else
863  ereport(ERROR,
864  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
865  errmsg("SQL functions cannot have arguments of type %s",
866  format_type_be(proc->proargtypes.values[i]))));
867  }
868  }
869 
870  /* Postpone body checks if !check_function_bodies */
872  {
873  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
874  if (isnull)
875  elog(ERROR, "null prosrc");
876 
877  prosrc = TextDatumGetCString(tmp);
878 
879  /*
880  * Setup error traceback support for ereport().
881  */
882  callback_arg.proname = NameStr(proc->proname);
883  callback_arg.prosrc = prosrc;
884 
886  sqlerrcontext.arg = (void *) &callback_arg;
887  sqlerrcontext.previous = error_context_stack;
888  error_context_stack = &sqlerrcontext;
889 
890  /* If we have prosqlbody, pay attention to that not prosrc */
891  tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
892  if (!isnull)
893  {
894  Node *n;
895  List *stored_query_list;
896 
898  if (IsA(n, List))
899  stored_query_list = linitial(castNode(List, n));
900  else
901  stored_query_list = list_make1(n);
902 
903  querytree_list = NIL;
904  foreach(lc, stored_query_list)
905  {
906  Query *parsetree = lfirst_node(Query, lc);
907  List *querytree_sublist;
908 
909  /*
910  * Typically, we'd have acquired locks already while parsing
911  * the body of the CREATE FUNCTION command. However, a
912  * validator function cannot assume that it's only called in
913  * that context.
914  */
915  AcquireRewriteLocks(parsetree, true, false);
916  querytree_sublist = pg_rewrite_query(parsetree);
917  querytree_list = lappend(querytree_list, querytree_sublist);
918  }
919  }
920  else
921  {
922  /*
923  * We can't do full prechecking of the function definition if
924  * there are any polymorphic input types, because actual datatypes
925  * of expression results will be unresolvable. The check will be
926  * done at runtime instead.
927  *
928  * We can run the text through the raw parser though; this will at
929  * least catch silly syntactic errors.
930  */
931  raw_parsetree_list = pg_parse_query(prosrc);
932  querytree_list = NIL;
933 
934  if (!haspolyarg)
935  {
936  /*
937  * OK to do full precheck: analyze and rewrite the queries,
938  * then verify the result type.
939  */
941 
942  /* But first, set up parameter information */
943  pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
944 
945  foreach(lc, raw_parsetree_list)
946  {
947  RawStmt *parsetree = lfirst_node(RawStmt, lc);
948  List *querytree_sublist;
949 
950  querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
951  prosrc,
953  pinfo,
954  NULL);
955  querytree_list = lappend(querytree_list,
956  querytree_sublist);
957  }
958  }
959  }
960 
961  if (!haspolyarg)
962  {
963  Oid rettype;
964  TupleDesc rettupdesc;
965 
966  check_sql_fn_statements(querytree_list);
967 
968  (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
969 
970  (void) check_sql_fn_retval(querytree_list,
971  rettype, rettupdesc,
972  false, NULL);
973  }
974 
975  error_context_stack = sqlerrcontext.previous;
976  }
977 
978  ReleaseSysCache(tuple);
979 
980  PG_RETURN_VOID();
981 }
#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:1599
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define castNode(_type_, nodeptr)
Definition: nodes.h:605
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
Definition: nodes.h:536
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:586
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 linitial(l)
Definition: pg_list.h:174
#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
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
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:87
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:987
#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_rewrite_query(Query *query)
Definition: postgres.c:737
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 1011 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().

1012 {
1013  int origerrposition;
1014  int newerrposition;
1015  const char *queryText;
1016 
1017  /*
1018  * Nothing to do unless we are dealing with a syntax error that has a
1019  * cursor position.
1020  *
1021  * Some PLs may prefer to report the error position as an internal error
1022  * to begin with, so check that too.
1023  */
1024  origerrposition = geterrposition();
1025  if (origerrposition <= 0)
1026  {
1027  origerrposition = getinternalerrposition();
1028  if (origerrposition <= 0)
1029  return false;
1030  }
1031 
1032  /* We can get the original query text from the active portal (hack...) */
1034  queryText = ActivePortal->sourceText;
1035 
1036  /* Try to locate the prosrc in the original text */
1037  newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
1038 
1039  if (newerrposition > 0)
1040  {
1041  /* Successful, so fix error position to reference original query */
1042  errposition(newerrposition);
1043  /* Get rid of any report of the error as an "internal query" */
1045  internalerrquery(NULL);
1046  }
1047  else
1048  {
1049  /*
1050  * If unsuccessful, convert the position to an internal position
1051  * marker and give the function text as the internal query.
1052  */
1053  errposition(0);
1054  internalerrposition(origerrposition);
1055  internalerrquery(prosrc);
1056  }
1057 
1058  return true;
1059 }
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:136
int internalerrquery(const char *query)
Definition: elog.c:1321
#define Assert(condition)
Definition: c.h:804
PortalStatus status
Definition: portal.h:151
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1068
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 1126 of file pg_proc.c.

References pg_mblen().

Referenced by match_prosrc_to_query().

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

References match_prosrc_to_literal(), and pg_mbstrlen_with_len().

Referenced by function_parse_error_transpose().

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

◆ oid_array_to_list()

List* oid_array_to_list ( Datum  datum)

Definition at line 1183 of file pg_proc.c.

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

Referenced by compile_plperl_function(), and PLy_procedure_create().

1184 {
1185  ArrayType *array = DatumGetArrayTypeP(datum);
1186  Datum *values;
1187  int nelems;
1188  int i;
1189  List *result = NIL;
1190 
1191  deconstruct_array(array,
1192  OIDOID,
1193  sizeof(Oid), true, TYPALIGN_INT,
1194  &values, NULL, &nelems);
1195  for (i = 0; i < nelems; i++)
1196  result = lappend_oid(result, values[i]);
1197  return result;
1198 }
#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:3491
static Datum values[MAXATTR]
Definition: bootstrap.c:156
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 71 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, 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().

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

◆ sql_function_parse_error_callback()

static void sql_function_parse_error_callback ( void *  arg)
static

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

988 {
990 
991  /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
992  if (!function_parse_error_transpose(callback_arg->prosrc))
993  {
994  /* If it's not a syntax error, push info onto context stack */
995  errcontext("SQL function \"%s\"", callback_arg->proname);
996  }
997 }
bool function_parse_error_transpose(const char *prosrc)
Definition: pg_proc.c:1011
#define errcontext
Definition: elog.h:204
void * arg