1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/catalog/pg_proc.c
13 *-------------------------------------------------------------------------
17 #include "access/htup_details.h"
18 #include "access/table.h"
19 #include "access/xact.h"
20 #include "catalog/catalog.h"
21 #include "catalog/dependency.h"
22 #include "catalog/indexing.h"
23 #include "catalog/objectaccess.h"
24 #include "catalog/pg_language.h"
25 #include "catalog/pg_namespace.h"
26 #include "catalog/pg_proc.h"
27 #include "catalog/pg_transform.h"
28 #include "catalog/pg_type.h"
29 #include "commands/defrem.h"
30 #include "executor/functions.h"
32 #include "mb/pg_wchar.h"
33 #include "miscadmin.h"
34 #include "nodes/nodeFuncs.h"
35 #include "parser/parse_type.h"
36 #include "tcop/pquery.h"
37 #include "tcop/tcopprot.h"
38 #include "utils/acl.h"
39 #include "utils/builtins.h"
40 #include "utils/lsyscache.h"
41 #include "utils/regproc.h"
42 #include "utils/rel.h"
43 #include "utils/syscache.h"
50 } parse_error_callback_arg;
52 static void sql_function_parse_error_callback(void *arg);
53 static int match_prosrc_to_query(const char *prosrc, const char *queryText,
55 static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
56 int cursorpos, int *newcursorpos);
59 /* ----------------------------------------------------------------
62 * Note: allParameterTypes, parameterModes, parameterNames, trftypes, and proconfig
63 * are either arrays of the proper types or NULL. We declare them Datum,
64 * not "ArrayType *", to avoid importing array.h into pg_proc.h.
65 * ----------------------------------------------------------------
68 ProcedureCreate(const char *procedureName,
75 Oid languageValidator,
79 bool security_definer,
84 oidvector *parameterTypes,
85 Datum allParameterTypes,
88 List *parameterDefaults,
99 char *paramModes = NULL;
100 bool genericInParam = false;
101 bool genericOutParam = false;
102 bool anyrangeInParam = false;
103 bool anyrangeOutParam = false;
104 bool internalInParam = false;
105 bool internalOutParam = false;
106 Oid variadicType = InvalidOid;
111 bool nulls[Natts_pg_proc];
112 Datum values[Natts_pg_proc];
113 bool replaces[Natts_pg_proc];
117 ObjectAddress myself,
125 Assert(PointerIsValid(prosrc));
127 parameterCount = parameterTypes->dim1;
128 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
130 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
131 errmsg_plural("functions cannot have more than %d argument",
132 "functions cannot have more than %d arguments",
135 /* note: the above is correct, we do NOT count output arguments */
137 /* Deconstruct array inputs */
138 if (allParameterTypes != PointerGetDatum(NULL))
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.
145 ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
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 */
159 allParamCount = parameterCount;
160 allParams = parameterTypes->values;
163 if (parameterModes != PointerGetDatum(NULL))
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.
170 ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
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);
181 * Detect whether we have polymorphic or INTERNAL arguments. The first
182 * loop checks input arguments, the second output arguments.
184 for (i = 0; i < parameterCount; i++)
186 switch (parameterTypes->values[i])
192 genericInParam = true;
195 genericInParam = true;
196 anyrangeInParam = true;
199 internalInParam = true;
204 if (allParameterTypes != PointerGetDatum(NULL))
206 for (i = 0; i < allParamCount; i++)
208 if (paramModes == NULL ||
209 paramModes[i] == PROARGMODE_IN ||
210 paramModes[i] == PROARGMODE_VARIADIC)
211 continue; /* ignore input-only params */
213 switch (allParams[i])
219 genericOutParam = true;
222 genericOutParam = true;
223 anyrangeOutParam = true;
226 internalOutParam = true;
233 * Do not allow polymorphic return type unless at least one input argument
234 * is polymorphic. ANYRANGE return type is even stricter: must have an
235 * ANYRANGE input (since we can't deduce the specific range type from
236 * ANYELEMENT). Also, do not allow return type INTERNAL unless at least
237 * one input argument is INTERNAL.
239 if ((IsPolymorphicType(returnType) || genericOutParam)
242 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
243 errmsg("cannot determine result data type"),
244 errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
246 if ((returnType == ANYRANGEOID || anyrangeOutParam) &&
249 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
250 errmsg("cannot determine result data type"),
251 errdetail("A function returning \"anyrange\" must have at least one \"anyrange\" argument.")));
253 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
255 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
256 errmsg("unsafe use of pseudo-type \"internal\""),
257 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
259 if (paramModes != NULL)
262 * Only the last input parameter can be variadic; if it is, save its
263 * element type. Errors here are just elog since caller should have
264 * checked this already.
266 for (i = 0; i < allParamCount; i++)
268 switch (paramModes[i])
271 case PROARGMODE_INOUT:
272 if (OidIsValid(variadicType))
273 elog(ERROR, "variadic parameter must be last");
276 case PROARGMODE_TABLE:
279 case PROARGMODE_VARIADIC:
280 if (OidIsValid(variadicType))
281 elog(ERROR, "variadic parameter must be last");
282 switch (allParams[i])
285 variadicType = ANYOID;
288 variadicType = ANYELEMENTOID;
291 variadicType = get_element_type(allParams[i]);
292 if (!OidIsValid(variadicType))
293 elog(ERROR, "variadic parameter is not an array");
298 elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
305 * All seems OK; prepare the data to be inserted into pg_proc.
308 for (i = 0; i < Natts_pg_proc; ++i)
311 values[i] = (Datum) 0;
315 namestrcpy(&procname, procedureName);
316 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
317 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
318 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
319 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
320 values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
321 values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
322 values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
323 values[Anum_pg_proc_prosupport - 1] = ObjectIdGetDatum(prosupport);
324 values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
325 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
326 values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
327 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
328 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
329 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
330 values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
331 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
332 values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
333 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
334 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
335 if (allParameterTypes != PointerGetDatum(NULL))
336 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
338 nulls[Anum_pg_proc_proallargtypes - 1] = true;
339 if (parameterModes != PointerGetDatum(NULL))
340 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
342 nulls[Anum_pg_proc_proargmodes - 1] = true;
343 if (parameterNames != PointerGetDatum(NULL))
344 values[Anum_pg_proc_proargnames - 1] = parameterNames;
346 nulls[Anum_pg_proc_proargnames - 1] = true;
347 if (parameterDefaults != NIL)
348 values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
350 nulls[Anum_pg_proc_proargdefaults - 1] = true;
351 if (trftypes != PointerGetDatum(NULL))
352 values[Anum_pg_proc_protrftypes - 1] = trftypes;
354 nulls[Anum_pg_proc_protrftypes - 1] = true;
355 values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
357 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
359 nulls[Anum_pg_proc_probin - 1] = true;
360 if (proconfig != PointerGetDatum(NULL))
361 values[Anum_pg_proc_proconfig - 1] = proconfig;
363 nulls[Anum_pg_proc_proconfig - 1] = true;
364 /* proacl will be determined later */
366 rel = table_open(ProcedureRelationId, RowExclusiveLock);
367 tupDesc = RelationGetDescr(rel);
369 /* Check for pre-existing definition */
370 oldtup = SearchSysCache3(PROCNAMEARGSNSP,
371 PointerGetDatum(procedureName),
372 PointerGetDatum(parameterTypes),
373 ObjectIdGetDatum(procNamespace));
375 if (HeapTupleIsValid(oldtup))
377 /* There is one; okay to replace it? */
378 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
385 (errcode(ERRCODE_DUPLICATE_FUNCTION),
386 errmsg("function \"%s\" already exists with same argument types",
388 if (!pg_proc_ownercheck(oldproc->oid, proowner))
389 aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
392 /* Not okay to change routine kind */
393 if (oldproc->prokind != prokind)
395 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
396 errmsg("cannot change routine kind"),
397 (oldproc->prokind == PROKIND_AGGREGATE ?
398 errdetail("\"%s\" is an aggregate function.", procedureName) :
399 oldproc->prokind == PROKIND_FUNCTION ?
400 errdetail("\"%s\" is a function.", procedureName) :
401 oldproc->prokind == PROKIND_PROCEDURE ?
402 errdetail("\"%s\" is a procedure.", procedureName) :
403 oldproc->prokind == PROKIND_WINDOW ?
404 errdetail("\"%s\" is a window function.", procedureName) :
407 dropcmd = (prokind == PROKIND_PROCEDURE ? "DROP PROCEDURE" :
408 prokind == PROKIND_AGGREGATE ? "DROP AGGREGATE" :
412 * Not okay to change the return type of the existing proc, since
413 * existing rules, views, etc may depend on the return type.
415 * In case of a procedure, a changing return type means that whether
416 * the procedure has output parameters was changed. Since there is no
417 * user visible return type, we produce a more specific error message.
419 if (returnType != oldproc->prorettype ||
420 returnsSet != oldproc->proretset)
422 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
423 prokind == PROKIND_PROCEDURE
424 ? errmsg("cannot change whether a procedure has output parameters")
425 : errmsg("cannot change return type of existing function"),
428 * translator: first %s is DROP FUNCTION, DROP PROCEDURE, or DROP
431 errhint("Use %s %s first.",
433 format_procedure(oldproc->oid))));
436 * If it returns RECORD, check for possible change of record type
437 * implied by OUT parameters
439 if (returnType == RECORDOID)
444 olddesc = build_function_result_tupdesc_t(oldtup);
445 newdesc = build_function_result_tupdesc_d(prokind,
449 if (olddesc == NULL && newdesc == NULL)
450 /* ok, both are runtime-defined RECORDs */ ;
451 else if (olddesc == NULL || newdesc == NULL ||
452 !equalTupleDescs(olddesc, newdesc))
454 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
455 errmsg("cannot change return type of existing function"),
456 errdetail("Row type defined by OUT parameters is different."),
457 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
458 errhint("Use %s %s first.",
460 format_procedure(oldproc->oid))));
464 * If there were any named input parameters, check to make sure the
465 * names have not been changed, as this could break existing calls. We
466 * allow adding names to formerly unnamed parameters, though.
468 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
469 Anum_pg_proc_proargnames,
474 char **old_arg_names;
475 char **new_arg_names;
480 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
481 Anum_pg_proc_proargmodes,
484 proargmodes = PointerGetDatum(NULL); /* just to be sure */
486 n_old_arg_names = get_func_input_arg_names(proargnames,
489 n_new_arg_names = get_func_input_arg_names(parameterNames,
492 for (j = 0; j < n_old_arg_names; j++)
494 if (old_arg_names[j] == NULL)
496 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
497 strcmp(old_arg_names[j], new_arg_names[j]) != 0)
499 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
500 errmsg("cannot change name of input parameter \"%s\"",
502 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
503 errhint("Use %s %s first.",
505 format_procedure(oldproc->oid))));
510 * If there are existing defaults, check compatibility: redefinition
511 * must not remove any defaults nor change their types. (Removing a
512 * default might cause a function to fail to satisfy an existing call.
513 * Changing type would only be possible if the associated parameter is
514 * polymorphic, and in such cases a change of default type might alter
515 * the resolved output type of existing calls.)
517 if (oldproc->pronargdefaults != 0)
519 Datum proargdefaults;
524 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
526 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
527 errmsg("cannot remove parameter defaults from existing function"),
528 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
529 errhint("Use %s %s first.",
531 format_procedure(oldproc->oid))));
533 proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
534 Anum_pg_proc_proargdefaults,
537 oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
538 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
540 /* new list can have more defaults than old, advance over 'em */
541 newlc = list_nth_cell(parameterDefaults,
542 list_length(parameterDefaults) -
543 oldproc->pronargdefaults);
545 foreach(oldlc, oldDefaults)
547 Node *oldDef = (Node *) lfirst(oldlc);
548 Node *newDef = (Node *) lfirst(newlc);
550 if (exprType(oldDef) != exprType(newDef))
552 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
553 errmsg("cannot change data type of existing parameter default value"),
554 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
555 errhint("Use %s %s first.",
557 format_procedure(oldproc->oid))));
558 newlc = lnext(parameterDefaults, newlc);
563 * Do not change existing oid, ownership or permissions, either. Note
564 * dependency-update code below has to agree with this decision.
566 replaces[Anum_pg_proc_oid - 1] = false;
567 replaces[Anum_pg_proc_proowner - 1] = false;
568 replaces[Anum_pg_proc_proacl - 1] = false;
571 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
572 CatalogTupleUpdate(rel, &tup->t_self, tup);
574 ReleaseSysCache(oldtup);
579 /* Creating a new procedure */
582 /* First, get default permissions and set up proacl */
583 proacl = get_user_default_acl(OBJECT_FUNCTION, proowner,
586 values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
588 nulls[Anum_pg_proc_proacl - 1] = true;
590 newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId,
592 values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid);
593 tup = heap_form_tuple(tupDesc, values, nulls);
594 CatalogTupleInsert(rel, tup);
599 retval = ((Form_pg_proc) GETSTRUCT(tup))->oid;
602 * Create dependencies for the new function. If we are updating an
603 * existing function, first delete any existing pg_depend entries.
604 * (However, since we are not changing ownership or permissions, the
605 * shared dependencies do *not* need to change, and we leave them alone.)
608 deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
610 myself.classId = ProcedureRelationId;
611 myself.objectId = retval;
612 myself.objectSubId = 0;
614 /* dependency on namespace */
615 referenced.classId = NamespaceRelationId;
616 referenced.objectId = procNamespace;
617 referenced.objectSubId = 0;
618 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
620 /* dependency on implementation language */
621 referenced.classId = LanguageRelationId;
622 referenced.objectId = languageObjectId;
623 referenced.objectSubId = 0;
624 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
626 /* dependency on return type */
627 referenced.classId = TypeRelationId;
628 referenced.objectId = returnType;
629 referenced.objectSubId = 0;
630 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
632 /* dependency on transform used by return type, if any */
633 if ((trfid = get_transform_oid(returnType, languageObjectId, true)))
635 referenced.classId = TransformRelationId;
636 referenced.objectId = trfid;
637 referenced.objectSubId = 0;
638 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
641 /* dependency on parameter types */
642 for (i = 0; i < allParamCount; i++)
644 referenced.classId = TypeRelationId;
645 referenced.objectId = allParams[i];
646 referenced.objectSubId = 0;
647 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
649 /* dependency on transform used by parameter type, if any */
650 if ((trfid = get_transform_oid(allParams[i], languageObjectId, true)))
652 referenced.classId = TransformRelationId;
653 referenced.objectId = trfid;
654 referenced.objectSubId = 0;
655 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
659 /* dependency on parameter default expressions */
660 if (parameterDefaults)
661 recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
662 NIL, DEPENDENCY_NORMAL);
664 /* dependency on support function, if any */
665 if (OidIsValid(prosupport))
667 referenced.classId = ProcedureRelationId;
668 referenced.objectId = prosupport;
669 referenced.objectSubId = 0;
670 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
673 /* dependency on owner */
675 recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
677 /* dependency on any roles mentioned in ACL */
679 recordDependencyOnNewAcl(ProcedureRelationId, retval, 0,
682 /* dependency on extension */
683 recordDependencyOnCurrentExtension(&myself, is_update);
687 /* Post creation hook for new function */
688 InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0);
690 table_close(rel, RowExclusiveLock);
692 /* Verify function body */
693 if (OidIsValid(languageValidator))
695 ArrayType *set_items = NULL;
696 int save_nestlevel = 0;
698 /* Advance command counter so new tuple can be seen by validator */
699 CommandCounterIncrement();
702 * Set per-function configuration parameters so that the validation is
703 * done with the environment the function expects. However, if
704 * check_function_bodies is off, we don't do this, because that would
705 * create dump ordering hazards that pg_dump doesn't know how to deal
706 * with. (For example, a SET clause might refer to a not-yet-created
707 * text search configuration.) This means that the validator
708 * shouldn't complain about anything that might depend on a GUC
709 * parameter when check_function_bodies is off.
711 if (check_function_bodies)
713 set_items = (ArrayType *) DatumGetPointer(proconfig);
714 if (set_items) /* Need a new GUC nesting level */
716 save_nestlevel = NewGUCNestLevel();
717 ProcessGUCArray(set_items,
718 (superuser() ? PGC_SUSET : PGC_USERSET),
724 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
727 AtEOXact_GUC(true, save_nestlevel);
736 * Validator for internal functions
738 * Check that the given internal function name (the "prosrc" value) is
739 * a known builtin function.
742 fmgr_internal_validator(PG_FUNCTION_ARGS)
744 Oid funcoid = PG_GETARG_OID(0);
750 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
754 * We do not honor check_function_bodies since it's unlikely the function
755 * name will be found later if it isn't there now.
758 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
759 if (!HeapTupleIsValid(tuple))
760 elog(ERROR, "cache lookup failed for function %u", funcoid);
762 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
764 elog(ERROR, "null prosrc");
765 prosrc = TextDatumGetCString(tmp);
767 if (fmgr_internal_function(prosrc) == InvalidOid)
769 (errcode(ERRCODE_UNDEFINED_FUNCTION),
770 errmsg("there is no built-in function named \"%s\"",
773 ReleaseSysCache(tuple);
781 * Validator for C language functions
783 * Make sure that the library file exists, is loadable, and contains
784 * the specified link symbol. Also check for a valid function
785 * information record.
788 fmgr_c_validator(PG_FUNCTION_ARGS)
790 Oid funcoid = PG_GETARG_OID(0);
798 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
802 * It'd be most consistent to skip the check if !check_function_bodies,
803 * but the purpose of that switch is to be helpful for pg_dump loading,
804 * and for pg_dump loading it's much better if we *do* check.
807 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
808 if (!HeapTupleIsValid(tuple))
809 elog(ERROR, "cache lookup failed for function %u", funcoid);
811 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
813 elog(ERROR, "null prosrc for C function %u", funcoid);
814 prosrc = TextDatumGetCString(tmp);
816 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
818 elog(ERROR, "null probin for C function %u", funcoid);
819 probin = TextDatumGetCString(tmp);
821 (void) load_external_function(probin, prosrc, true, &libraryhandle);
822 (void) fetch_finfo_record(libraryhandle, prosrc);
824 ReleaseSysCache(tuple);
831 * Validator for SQL language functions
833 * Parse it here in order to be sure that it contains no syntax errors.
836 fmgr_sql_validator(PG_FUNCTION_ARGS)
838 Oid funcoid = PG_GETARG_OID(0);
841 List *raw_parsetree_list;
842 List *querytree_list;
847 parse_error_callback_arg callback_arg;
848 ErrorContextCallback sqlerrcontext;
852 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
855 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
856 if (!HeapTupleIsValid(tuple))
857 elog(ERROR, "cache lookup failed for function %u", funcoid);
858 proc = (Form_pg_proc) GETSTRUCT(tuple);
860 /* Disallow pseudotype result */
861 /* except for RECORD, VOID, or polymorphic */
862 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
863 proc->prorettype != RECORDOID &&
864 proc->prorettype != VOIDOID &&
865 !IsPolymorphicType(proc->prorettype))
867 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
868 errmsg("SQL functions cannot return type %s",
869 format_type_be(proc->prorettype))));
871 /* Disallow pseudotypes in arguments */
872 /* except for polymorphic */
874 for (i = 0; i < proc->pronargs; i++)
876 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
878 if (IsPolymorphicType(proc->proargtypes.values[i]))
882 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
883 errmsg("SQL functions cannot have arguments of type %s",
884 format_type_be(proc->proargtypes.values[i]))));
888 /* Postpone body checks if !check_function_bodies */
889 if (check_function_bodies)
891 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
893 elog(ERROR, "null prosrc");
895 prosrc = TextDatumGetCString(tmp);
898 * Setup error traceback support for ereport().
900 callback_arg.proname = NameStr(proc->proname);
901 callback_arg.prosrc = prosrc;
903 sqlerrcontext.callback = sql_function_parse_error_callback;
904 sqlerrcontext.arg = (void *) &callback_arg;
905 sqlerrcontext.previous = error_context_stack;
906 error_context_stack = &sqlerrcontext;
909 * We can't do full prechecking of the function definition if there
910 * are any polymorphic input types, because actual datatypes of
911 * expression results will be unresolvable. The check will be done at
914 * We can run the text through the raw parser though; this will at
915 * least catch silly syntactic errors.
917 raw_parsetree_list = pg_parse_query(prosrc);
922 * OK to do full precheck: analyze and rewrite the queries, then
923 * verify the result type.
925 SQLFunctionParseInfoPtr pinfo;
927 /* But first, set up parameter information */
928 pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
930 querytree_list = NIL;
931 foreach(lc, raw_parsetree_list)
933 RawStmt *parsetree = lfirst_node(RawStmt, lc);
934 List *querytree_sublist;
936 querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
938 (ParserSetupHook) sql_fn_parser_setup,
941 querytree_list = list_concat(querytree_list,
945 check_sql_fn_statements(querytree_list);
946 (void) check_sql_fn_retval(funcoid, proc->prorettype,
951 error_context_stack = sqlerrcontext.previous;
954 ReleaseSysCache(tuple);
960 * Error context callback for handling errors in SQL function definitions
963 sql_function_parse_error_callback(void *arg)
965 parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
967 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
968 if (!function_parse_error_transpose(callback_arg->prosrc))
970 /* If it's not a syntax error, push info onto context stack */
971 errcontext("SQL function \"%s\"", callback_arg->proname);
976 * Adjust a syntax error occurring inside the function body of a CREATE
977 * FUNCTION or DO command. This can be used by any function validator or
978 * anonymous-block handler, not only for SQL-language functions.
979 * It is assumed that the syntax error position is initially relative to the
980 * function body string (as passed in). If possible, we adjust the position
981 * to reference the original command text; if we can't manage that, we set
982 * up an "internal query" syntax error instead.
984 * Returns true if a syntax error was processed, false if not.
987 function_parse_error_transpose(const char *prosrc)
991 const char *queryText;
994 * Nothing to do unless we are dealing with a syntax error that has a
997 * Some PLs may prefer to report the error position as an internal error
998 * to begin with, so check that too.
1000 origerrposition = geterrposition();
1001 if (origerrposition <= 0)
1003 origerrposition = getinternalerrposition();
1004 if (origerrposition <= 0)
1008 /* We can get the original query text from the active portal (hack...) */
1009 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
1010 queryText = ActivePortal->sourceText;
1012 /* Try to locate the prosrc in the original text */
1013 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
1015 if (newerrposition > 0)
1017 /* Successful, so fix error position to reference original query */
1018 errposition(newerrposition);
1019 /* Get rid of any report of the error as an "internal query" */
1020 internalerrposition(0);
1021 internalerrquery(NULL);
1026 * If unsuccessful, convert the position to an internal position
1027 * marker and give the function text as the internal query.
1030 internalerrposition(origerrposition);
1031 internalerrquery(prosrc);
1038 * Try to locate the string literal containing the function body in the
1039 * given text of the CREATE FUNCTION or DO command. If successful, return
1040 * the character (not byte) index within the command corresponding to the
1041 * given character index within the literal. If not successful, return 0.
1044 match_prosrc_to_query(const char *prosrc, const char *queryText,
1048 * Rather than fully parsing the original command, we just scan the
1049 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1050 * not in any very probable scenarios), so fail if we find more than one
1053 int prosrclen = strlen(prosrc);
1054 int querylen = strlen(queryText);
1059 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1061 if (queryText[curpos] == '$' &&
1062 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1063 queryText[curpos + 1 + prosrclen] == '$')
1066 * Found a $foo$ match. Since there are no embedded quoting
1067 * characters in a dollar-quoted literal, we don't have to do any
1068 * fancy arithmetic; just offset by the starting position.
1071 return 0; /* multiple matches, fail */
1072 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1075 else if (queryText[curpos] == '\'' &&
1076 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1077 cursorpos, &newcursorpos))
1080 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1081 * for any quotes or backslashes embedded in the literal.
1084 return 0; /* multiple matches, fail */
1085 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1094 * Try to match the given source text to a single-quoted literal.
1095 * If successful, adjust newcursorpos to correspond to the character
1096 * (not byte) index corresponding to cursorpos in the source text.
1098 * At entry, literal points just past a ' character. We must check for the
1102 match_prosrc_to_literal(const char *prosrc, const char *literal,
1103 int cursorpos, int *newcursorpos)
1105 int newcp = cursorpos;
1109 * This implementation handles backslashes and doubled quotes in the
1110 * string literal. It does not handle the SQL syntax for literals
1111 * continued across line boundaries.
1113 * We do the comparison a character at a time, not a byte at a time, so
1114 * that we can do the correct cursorpos math.
1118 cursorpos--; /* characters left before cursor */
1121 * Check for backslashes and doubled quotes in the literal; adjust
1122 * newcp when one is found before the cursor.
1124 if (*literal == '\\')
1130 else if (*literal == '\'')
1132 if (literal[1] != '\'')
1138 chlen = pg_mblen(prosrc);
1139 if (strncmp(prosrc, literal, chlen) != 0)
1145 if (*literal == '\'' && literal[1] != '\'')
1148 *newcursorpos = newcp;
1153 /* Must set *newcursorpos to suppress compiler warning */
1154 *newcursorpos = newcp;
1159 oid_array_to_list(Datum datum)
1161 ArrayType *array = DatumGetArrayTypeP(datum);
1167 deconstruct_array(array,
1169 sizeof(Oid), true, 'i',
1170 &values, NULL, &nelems);
1171 for (i = 0; i < nelems; i++)
1172 result = lappend_oid(result, values[i]);