PostgreSQL Source Code git master
pg_proc.h File Reference
#include "catalog/genbki.h"
#include "catalog/objectaddress.h"
#include "catalog/pg_proc_d.h"
#include "nodes/pg_list.h"
Include dependency graph for pg_proc.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef FormData_pg_procForm_pg_proc
 

Functions

 CATALOG (pg_proc, 1255, ProcedureRelationId) BKI_BOOTSTRAP BKI_ROWTYPE_OID(81
 
Oid pronamespace BKI_DEFAULT (pg_catalog) BKI_LOOKUP(pg_namespace)
 
Oid proowner BKI_DEFAULT (POSTGRES) BKI_LOOKUP(pg_authid)
 
Oid prolang BKI_DEFAULT (internal) BKI_LOOKUP(pg_language)
 
float4 procost BKI_DEFAULT (1)
 
float4 prorows BKI_DEFAULT (0)
 
char prokind BKI_DEFAULT (f)
 
bool proisstrict BKI_DEFAULT (t)
 
char provolatile BKI_DEFAULT (i)
 
char proparallel BKI_DEFAULT (s)
 
Oid prorettype BKI_LOOKUP (pg_type)
 
 DECLARE_TOAST (pg_proc, 2836, 2837)
 
 DECLARE_UNIQUE_INDEX_PKEY (pg_proc_oid_index, 2690, ProcedureOidIndexId, pg_proc, btree(oid oid_ops))
 
 DECLARE_UNIQUE_INDEX (pg_proc_proname_args_nsp_index, 2691, ProcedureNameArgsNspIndexId, pg_proc, btree(proname name_ops, proargtypes oidvector_ops, pronamespace oid_ops))
 
 MAKE_SYSCACHE (PROCOID, pg_proc_oid_index, 128)
 
 MAKE_SYSCACHE (PROCNAMEARGSNSP, pg_proc_proname_args_nsp_index, 128)
 
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, List *trfoids, Datum proconfig, Oid prosupport, float4 procost, float4 prorows)
 
bool function_parse_error_transpose (const char *prosrc)
 
Listoid_array_to_list (Datum datum)
 

Variables

ProcedureRelation_Rowtype_Id BKI_SCHEMA_MACRO
 
NameData proname
 
int16 pronargs
 
 FormData_pg_proc
 

Typedef Documentation

◆ Form_pg_proc

Definition at line 136 of file pg_proc.h.

Function Documentation

◆ BKI_DEFAULT() [1/9]

float4 prorows BKI_DEFAULT ( )

◆ BKI_DEFAULT() [2/9]

float4 procost BKI_DEFAULT ( )

◆ BKI_DEFAULT() [3/9]

char prokind BKI_DEFAULT ( )

◆ BKI_DEFAULT() [4/9]

char provolatile BKI_DEFAULT ( i  )

◆ BKI_DEFAULT() [5/9]

Oid prolang BKI_DEFAULT ( internal  )

◆ BKI_DEFAULT() [6/9]

Oid pronamespace BKI_DEFAULT ( pg_catalog  )

◆ BKI_DEFAULT() [7/9]

Oid proowner BKI_DEFAULT ( POSTGRES  )

◆ BKI_DEFAULT() [8/9]

char proparallel BKI_DEFAULT ( )

◆ BKI_DEFAULT() [9/9]

bool proisstrict BKI_DEFAULT ( )

◆ BKI_LOOKUP()

oidvector proargtypes BKI_LOOKUP ( pg_type  )

◆ CATALOG()

CATALOG ( pg_proc  ,
1255  ,
ProcedureRelationId   
)

◆ DECLARE_TOAST()

DECLARE_TOAST ( pg_proc  ,
2836  ,
2837   
)

◆ DECLARE_UNIQUE_INDEX()

DECLARE_UNIQUE_INDEX ( pg_proc_proname_args_nsp_index  ,
2691  ,
ProcedureNameArgsNspIndexId  ,
pg_proc  ,
btree(proname name_ops, proargtypes oidvector_ops, pronamespace oid_ops)   
)

◆ DECLARE_UNIQUE_INDEX_PKEY()

DECLARE_UNIQUE_INDEX_PKEY ( pg_proc_oid_index  ,
2690  ,
ProcedureOidIndexId  ,
pg_proc  ,
btree(oid oid_ops)   
)

◆ function_parse_error_transpose()

bool function_parse_error_transpose ( const char *  prosrc)

Definition at line 1048 of file pg_proc.c.

1049{
1050 int origerrposition;
1051 int newerrposition;
1052
1053 /*
1054 * Nothing to do unless we are dealing with a syntax error that has a
1055 * cursor position.
1056 *
1057 * Some PLs may prefer to report the error position as an internal error
1058 * to begin with, so check that too.
1059 */
1060 origerrposition = geterrposition();
1061 if (origerrposition <= 0)
1062 {
1063 origerrposition = getinternalerrposition();
1064 if (origerrposition <= 0)
1065 return false;
1066 }
1067
1068 /* We can get the original query text from the active portal (hack...) */
1070 {
1071 const char *queryText = ActivePortal->sourceText;
1072
1073 /* Try to locate the prosrc in the original text */
1074 newerrposition = match_prosrc_to_query(prosrc, queryText,
1075 origerrposition);
1076 }
1077 else
1078 {
1079 /*
1080 * Quietly give up if no ActivePortal. This is an unusual situation
1081 * but it can happen in, e.g., logical replication workers.
1082 */
1083 newerrposition = -1;
1084 }
1085
1086 if (newerrposition > 0)
1087 {
1088 /* Successful, so fix error position to reference original query */
1089 errposition(newerrposition);
1090 /* Get rid of any report of the error as an "internal query" */
1092 internalerrquery(NULL);
1093 }
1094 else
1095 {
1096 /*
1097 * If unsuccessful, convert the position to an internal position
1098 * marker and give the function text as the internal query.
1099 */
1100 errposition(0);
1101 internalerrposition(origerrposition);
1102 internalerrquery(prosrc);
1103 }
1104
1105 return true;
1106}
int getinternalerrposition(void)
Definition: elog.c:1629
int internalerrquery(const char *query)
Definition: elog.c:1516
int internalerrposition(int cursorpos)
Definition: elog.c:1496
int geterrposition(void)
Definition: elog.c:1612
int errposition(int cursorpos)
Definition: elog.c:1480
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition: pg_proc.c:1115
@ PORTAL_ACTIVE
Definition: portal.h:108
Portal ActivePortal
Definition: pquery.c:36
const char * sourceText
Definition: portal.h:136
PortalStatus status
Definition: portal.h:150

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

Referenced by plpgsql_compile_error_callback(), and sql_function_parse_error_callback().

◆ MAKE_SYSCACHE() [1/2]

MAKE_SYSCACHE ( PROCNAMEARGSNSP  ,
pg_proc_proname_args_nsp_index  ,
128   
)

◆ MAKE_SYSCACHE() [2/2]

MAKE_SYSCACHE ( PROCOID  ,
pg_proc_oid_index  ,
128   
)

◆ oid_array_to_list()

List * oid_array_to_list ( Datum  datum)

Definition at line 1230 of file pg_proc.c.

1231{
1232 ArrayType *array = DatumGetArrayTypeP(datum);
1233 Datum *values;
1234 int nelems;
1235 int i;
1236 List *result = NIL;
1237
1238 deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems);
1239 for (i = 0; i < nelems; i++)
1240 result = lappend_oid(result, DatumGetObjectId(values[i]));
1241 return result;
1242}
#define DatumGetArrayTypeP(X)
Definition: array.h:261
void deconstruct_array_builtin(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3698
static Datum values[MAXATTR]
Definition: bootstrap.c:153
int i
Definition: isn.c:77
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
#define NIL
Definition: pg_list.h:68
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:252
uint64_t Datum
Definition: postgres.h:70
Definition: pg_list.h:54

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

Referenced by compile_plperl_function(), and PLy_procedure_create().

◆ ProcedureCreate()

ObjectAddress ProcedureCreate ( const char *  procedureName,
Oid  procNamespace,
bool  replace,
bool  returnsSet,
Oid  returnType,
Oid  proowner,
Oid  languageObjectId,
Oid  languageValidator,
const char *  prosrc,
const char *  probin,
Node prosqlbody,
char  prokind,
bool  security_definer,
bool  isLeakProof,
bool  isStrict,
char  volatility,
char  parallel,
oidvector parameterTypes,
Datum  allParameterTypes,
Datum  parameterModes,
Datum  parameterNames,
List parameterDefaults,
Datum  trftypes,
List trfoids,
Datum  proconfig,
Oid  prosupport,
float4  procost,
float4  prorows 
)

Definition at line 99 of file pg_proc.c.

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

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

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

Variable Documentation

◆ BKI_SCHEMA_MACRO

ProcedureRelation_Rowtype_Id BKI_SCHEMA_MACRO
Initial value:
{
Oid oid

Definition at line 30 of file pg_proc.h.

◆ FormData_pg_proc

FormData_pg_proc

Definition at line 129 of file pg_proc.h.

◆ proname

◆ pronargs