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,
98 char *paramModes = NULL;
99 bool genericInParam = false;
100 bool genericOutParam = false;
101 bool anyrangeInParam = false;
102 bool anyrangeOutParam = false;
103 bool internalInParam = false;
104 bool internalOutParam = false;
105 Oid variadicType = InvalidOid;
110 bool nulls[Natts_pg_proc];
111 Datum values[Natts_pg_proc];
112 bool replaces[Natts_pg_proc];
116 ObjectAddress myself,
124 Assert(PointerIsValid(prosrc));
126 parameterCount = parameterTypes->dim1;
127 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
129 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
130 errmsg_plural("functions cannot have more than %d argument",
131 "functions cannot have more than %d arguments",
134 /* note: the above is correct, we do NOT count output arguments */
136 /* Deconstruct array inputs */
137 if (allParameterTypes != PointerGetDatum(NULL))
140 * We expect the array to be a 1-D OID array; verify that. We don't
141 * need to use deconstruct_array() since the array data is just going
142 * to look like a C array of OID values.
144 ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
146 allParamCount = ARR_DIMS(allParamArray)[0];
147 if (ARR_NDIM(allParamArray) != 1 ||
148 allParamCount <= 0 ||
149 ARR_HASNULL(allParamArray) ||
150 ARR_ELEMTYPE(allParamArray) != OIDOID)
151 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
152 allParams = (Oid *) ARR_DATA_PTR(allParamArray);
153 Assert(allParamCount >= parameterCount);
154 /* we assume caller got the contents right */
158 allParamCount = parameterCount;
159 allParams = parameterTypes->values;
162 if (parameterModes != PointerGetDatum(NULL))
165 * We expect the array to be a 1-D CHAR array; verify that. We don't
166 * need to use deconstruct_array() since the array data is just going
167 * to look like a C array of char values.
169 ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
171 if (ARR_NDIM(modesArray) != 1 ||
172 ARR_DIMS(modesArray)[0] != allParamCount ||
173 ARR_HASNULL(modesArray) ||
174 ARR_ELEMTYPE(modesArray) != CHAROID)
175 elog(ERROR, "parameterModes is not a 1-D char array");
176 paramModes = (char *) ARR_DATA_PTR(modesArray);
180 * Detect whether we have polymorphic or INTERNAL arguments. The first
181 * loop checks input arguments, the second output arguments.
183 for (i = 0; i < parameterCount; i++)
185 switch (parameterTypes->values[i])
191 genericInParam = true;
194 genericInParam = true;
195 anyrangeInParam = true;
198 internalInParam = true;
203 if (allParameterTypes != PointerGetDatum(NULL))
205 for (i = 0; i < allParamCount; i++)
207 if (paramModes == NULL ||
208 paramModes[i] == PROARGMODE_IN ||
209 paramModes[i] == PROARGMODE_VARIADIC)
210 continue; /* ignore input-only params */
212 switch (allParams[i])
218 genericOutParam = true;
221 genericOutParam = true;
222 anyrangeOutParam = true;
225 internalOutParam = true;
232 * Do not allow polymorphic return type unless at least one input argument
233 * is polymorphic. ANYRANGE return type is even stricter: must have an
234 * ANYRANGE input (since we can't deduce the specific range type from
235 * ANYELEMENT). Also, do not allow return type INTERNAL unless at least
236 * one input argument is INTERNAL.
238 if ((IsPolymorphicType(returnType) || genericOutParam)
241 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
242 errmsg("cannot determine result data type"),
243 errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
245 if ((returnType == ANYRANGEOID || anyrangeOutParam) &&
248 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
249 errmsg("cannot determine result data type"),
250 errdetail("A function returning \"anyrange\" must have at least one \"anyrange\" argument.")));
252 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
254 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
255 errmsg("unsafe use of pseudo-type \"internal\""),
256 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
258 if (paramModes != NULL)
261 * Only the last input parameter can be variadic; if it is, save its
262 * element type. Errors here are just elog since caller should have
263 * checked this already.
265 for (i = 0; i < allParamCount; i++)
267 switch (paramModes[i])
270 case PROARGMODE_INOUT:
271 if (OidIsValid(variadicType))
272 elog(ERROR, "variadic parameter must be last");
275 case PROARGMODE_TABLE:
278 case PROARGMODE_VARIADIC:
279 if (OidIsValid(variadicType))
280 elog(ERROR, "variadic parameter must be last");
281 switch (allParams[i])
284 variadicType = ANYOID;
287 variadicType = ANYELEMENTOID;
290 variadicType = get_element_type(allParams[i]);
291 if (!OidIsValid(variadicType))
292 elog(ERROR, "variadic parameter is not an array");
297 elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
304 * All seems OK; prepare the data to be inserted into pg_proc.
307 for (i = 0; i < Natts_pg_proc; ++i)
310 values[i] = (Datum) 0;
314 namestrcpy(&procname, procedureName);
315 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
316 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
317 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
318 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
319 values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
320 values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
321 values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
322 values[Anum_pg_proc_protransform - 1] = ObjectIdGetDatum(InvalidOid);
323 values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
324 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
325 values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
326 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
327 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
328 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
329 values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
330 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
331 values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
332 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
333 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
334 if (allParameterTypes != PointerGetDatum(NULL))
335 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
337 nulls[Anum_pg_proc_proallargtypes - 1] = true;
338 if (parameterModes != PointerGetDatum(NULL))
339 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
341 nulls[Anum_pg_proc_proargmodes - 1] = true;
342 if (parameterNames != PointerGetDatum(NULL))
343 values[Anum_pg_proc_proargnames - 1] = parameterNames;
345 nulls[Anum_pg_proc_proargnames - 1] = true;
346 if (parameterDefaults != NIL)
347 values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
349 nulls[Anum_pg_proc_proargdefaults - 1] = true;
350 if (trftypes != PointerGetDatum(NULL))
351 values[Anum_pg_proc_protrftypes - 1] = trftypes;
353 nulls[Anum_pg_proc_protrftypes - 1] = true;
354 values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
356 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
358 nulls[Anum_pg_proc_probin - 1] = true;
359 if (proconfig != PointerGetDatum(NULL))
360 values[Anum_pg_proc_proconfig - 1] = proconfig;
362 nulls[Anum_pg_proc_proconfig - 1] = true;
363 /* proacl will be determined later */
365 rel = heap_open(ProcedureRelationId, RowExclusiveLock);
366 tupDesc = RelationGetDescr(rel);
368 /* Check for pre-existing definition */
369 oldtup = SearchSysCache3(PROCNAMEARGSNSP,
370 PointerGetDatum(procedureName),
371 PointerGetDatum(parameterTypes),
372 ObjectIdGetDatum(procNamespace));
374 if (HeapTupleIsValid(oldtup))
376 /* There is one; okay to replace it? */
377 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
384 (errcode(ERRCODE_DUPLICATE_FUNCTION),
385 errmsg("function \"%s\" already exists with same argument types",
387 if (!pg_proc_ownercheck(oldproc->oid, proowner))
388 aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
391 /* Not okay to change routine kind */
392 if (oldproc->prokind != prokind)
394 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
395 errmsg("cannot change routine kind"),
396 (oldproc->prokind == PROKIND_AGGREGATE ?
397 errdetail("\"%s\" is an aggregate function.", procedureName) :
398 oldproc->prokind == PROKIND_FUNCTION ?
399 errdetail("\"%s\" is a function.", procedureName) :
400 oldproc->prokind == PROKIND_PROCEDURE ?
401 errdetail("\"%s\" is a procedure.", procedureName) :
402 oldproc->prokind == PROKIND_WINDOW ?
403 errdetail("\"%s\" is a window function.", procedureName) :
406 dropcmd = (prokind == PROKIND_PROCEDURE ? "DROP PROCEDURE" : "DROP FUNCTION");
409 * Not okay to change the return type of the existing proc, since
410 * existing rules, views, etc may depend on the return type.
412 * In case of a procedure, a changing return type means that whether
413 * the procedure has output parameters was changed. Since there is no
414 * user visible return type, we produce a more specific error message.
416 if (returnType != oldproc->prorettype ||
417 returnsSet != oldproc->proretset)
419 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
420 prokind == PROKIND_PROCEDURE
421 ? errmsg("cannot change whether a procedure has output parameters")
422 : errmsg("cannot change return type of existing function"),
423 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
424 errhint("Use %s %s first.",
426 format_procedure(oldproc->oid))));
429 * If it returns RECORD, check for possible change of record type
430 * implied by OUT parameters
432 if (returnType == RECORDOID)
437 olddesc = build_function_result_tupdesc_t(oldtup);
438 newdesc = build_function_result_tupdesc_d(prokind,
442 if (olddesc == NULL && newdesc == NULL)
443 /* ok, both are runtime-defined RECORDs */ ;
444 else if (olddesc == NULL || newdesc == NULL ||
445 !equalTupleDescs(olddesc, newdesc))
447 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
448 errmsg("cannot change return type of existing function"),
449 errdetail("Row type defined by OUT parameters is different."),
450 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
451 errhint("Use %s %s first.",
453 format_procedure(oldproc->oid))));
457 * If there were any named input parameters, check to make sure the
458 * names have not been changed, as this could break existing calls. We
459 * allow adding names to formerly unnamed parameters, though.
461 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
462 Anum_pg_proc_proargnames,
467 char **old_arg_names;
468 char **new_arg_names;
473 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
474 Anum_pg_proc_proargmodes,
477 proargmodes = PointerGetDatum(NULL); /* just to be sure */
479 n_old_arg_names = get_func_input_arg_names(proargnames,
482 n_new_arg_names = get_func_input_arg_names(parameterNames,
485 for (j = 0; j < n_old_arg_names; j++)
487 if (old_arg_names[j] == NULL)
489 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
490 strcmp(old_arg_names[j], new_arg_names[j]) != 0)
492 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
493 errmsg("cannot change name of input parameter \"%s\"",
495 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
496 errhint("Use %s %s first.",
498 format_procedure(oldproc->oid))));
503 * If there are existing defaults, check compatibility: redefinition
504 * must not remove any defaults nor change their types. (Removing a
505 * default might cause a function to fail to satisfy an existing call.
506 * Changing type would only be possible if the associated parameter is
507 * polymorphic, and in such cases a change of default type might alter
508 * the resolved output type of existing calls.)
510 if (oldproc->pronargdefaults != 0)
512 Datum proargdefaults;
517 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
519 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
520 errmsg("cannot remove parameter defaults from existing function"),
521 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
522 errhint("Use %s %s first.",
524 format_procedure(oldproc->oid))));
526 proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
527 Anum_pg_proc_proargdefaults,
530 oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
531 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
533 /* new list can have more defaults than old, advance over 'em */
534 newlc = list_head(parameterDefaults);
535 for (i = list_length(parameterDefaults) - oldproc->pronargdefaults;
538 newlc = lnext(newlc);
540 foreach(oldlc, oldDefaults)
542 Node *oldDef = (Node *) lfirst(oldlc);
543 Node *newDef = (Node *) lfirst(newlc);
545 if (exprType(oldDef) != exprType(newDef))
547 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
548 errmsg("cannot change data type of existing parameter default value"),
549 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
550 errhint("Use %s %s first.",
552 format_procedure(oldproc->oid))));
553 newlc = lnext(newlc);
558 * Do not change existing oid, ownership or permissions, either. Note
559 * dependency-update code below has to agree with this decision.
561 replaces[Anum_pg_proc_oid - 1] = false;
562 replaces[Anum_pg_proc_proowner - 1] = false;
563 replaces[Anum_pg_proc_proacl - 1] = false;
566 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
567 CatalogTupleUpdate(rel, &tup->t_self, tup);
569 ReleaseSysCache(oldtup);
574 /* Creating a new procedure */
577 /* First, get default permissions and set up proacl */
578 proacl = get_user_default_acl(OBJECT_FUNCTION, proowner,
581 values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
583 nulls[Anum_pg_proc_proacl - 1] = true;
585 newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId,
587 values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid);
588 tup = heap_form_tuple(tupDesc, values, nulls);
589 CatalogTupleInsert(rel, tup);
594 retval = ((Form_pg_proc) GETSTRUCT(tup))->oid;
597 * Create dependencies for the new function. If we are updating an
598 * existing function, first delete any existing pg_depend entries.
599 * (However, since we are not changing ownership or permissions, the
600 * shared dependencies do *not* need to change, and we leave them alone.)
603 deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
605 myself.classId = ProcedureRelationId;
606 myself.objectId = retval;
607 myself.objectSubId = 0;
609 /* dependency on namespace */
610 referenced.classId = NamespaceRelationId;
611 referenced.objectId = procNamespace;
612 referenced.objectSubId = 0;
613 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
615 /* dependency on implementation language */
616 referenced.classId = LanguageRelationId;
617 referenced.objectId = languageObjectId;
618 referenced.objectSubId = 0;
619 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
621 /* dependency on return type */
622 referenced.classId = TypeRelationId;
623 referenced.objectId = returnType;
624 referenced.objectSubId = 0;
625 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
627 /* dependency on transform used by return type, if any */
628 if ((trfid = get_transform_oid(returnType, languageObjectId, true)))
630 referenced.classId = TransformRelationId;
631 referenced.objectId = trfid;
632 referenced.objectSubId = 0;
633 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
636 /* dependency on parameter types */
637 for (i = 0; i < allParamCount; i++)
639 referenced.classId = TypeRelationId;
640 referenced.objectId = allParams[i];
641 referenced.objectSubId = 0;
642 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
644 /* dependency on transform used by parameter type, if any */
645 if ((trfid = get_transform_oid(allParams[i], languageObjectId, true)))
647 referenced.classId = TransformRelationId;
648 referenced.objectId = trfid;
649 referenced.objectSubId = 0;
650 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
654 /* dependency on parameter default expressions */
655 if (parameterDefaults)
656 recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
657 NIL, DEPENDENCY_NORMAL);
659 /* dependency on owner */
661 recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
663 /* dependency on any roles mentioned in ACL */
665 recordDependencyOnNewAcl(ProcedureRelationId, retval, 0,
668 /* dependency on extension */
669 recordDependencyOnCurrentExtension(&myself, is_update);
673 /* Post creation hook for new function */
674 InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0);
676 heap_close(rel, RowExclusiveLock);
678 /* Verify function body */
679 if (OidIsValid(languageValidator))
681 ArrayType *set_items = NULL;
682 int save_nestlevel = 0;
684 /* Advance command counter so new tuple can be seen by validator */
685 CommandCounterIncrement();
688 * Set per-function configuration parameters so that the validation is
689 * done with the environment the function expects. However, if
690 * check_function_bodies is off, we don't do this, because that would
691 * create dump ordering hazards that pg_dump doesn't know how to deal
692 * with. (For example, a SET clause might refer to a not-yet-created
693 * text search configuration.) This means that the validator
694 * shouldn't complain about anything that might depend on a GUC
695 * parameter when check_function_bodies is off.
697 if (check_function_bodies)
699 set_items = (ArrayType *) DatumGetPointer(proconfig);
700 if (set_items) /* Need a new GUC nesting level */
702 save_nestlevel = NewGUCNestLevel();
703 ProcessGUCArray(set_items,
704 (superuser() ? PGC_SUSET : PGC_USERSET),
710 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
713 AtEOXact_GUC(true, save_nestlevel);
722 * Validator for internal functions
724 * Check that the given internal function name (the "prosrc" value) is
725 * a known builtin function.
728 fmgr_internal_validator(PG_FUNCTION_ARGS)
730 Oid funcoid = PG_GETARG_OID(0);
736 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
740 * We do not honor check_function_bodies since it's unlikely the function
741 * name will be found later if it isn't there now.
744 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
745 if (!HeapTupleIsValid(tuple))
746 elog(ERROR, "cache lookup failed for function %u", funcoid);
748 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
750 elog(ERROR, "null prosrc");
751 prosrc = TextDatumGetCString(tmp);
753 if (fmgr_internal_function(prosrc) == InvalidOid)
755 (errcode(ERRCODE_UNDEFINED_FUNCTION),
756 errmsg("there is no built-in function named \"%s\"",
759 ReleaseSysCache(tuple);
767 * Validator for C language functions
769 * Make sure that the library file exists, is loadable, and contains
770 * the specified link symbol. Also check for a valid function
771 * information record.
774 fmgr_c_validator(PG_FUNCTION_ARGS)
776 Oid funcoid = PG_GETARG_OID(0);
784 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
788 * It'd be most consistent to skip the check if !check_function_bodies,
789 * but the purpose of that switch is to be helpful for pg_dump loading,
790 * and for pg_dump loading it's much better if we *do* check.
793 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
794 if (!HeapTupleIsValid(tuple))
795 elog(ERROR, "cache lookup failed for function %u", funcoid);
797 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
799 elog(ERROR, "null prosrc for C function %u", funcoid);
800 prosrc = TextDatumGetCString(tmp);
802 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
804 elog(ERROR, "null probin for C function %u", funcoid);
805 probin = TextDatumGetCString(tmp);
807 (void) load_external_function(probin, prosrc, true, &libraryhandle);
808 (void) fetch_finfo_record(libraryhandle, prosrc);
810 ReleaseSysCache(tuple);
817 * Validator for SQL language functions
819 * Parse it here in order to be sure that it contains no syntax errors.
822 fmgr_sql_validator(PG_FUNCTION_ARGS)
824 Oid funcoid = PG_GETARG_OID(0);
827 List *raw_parsetree_list;
828 List *querytree_list;
833 parse_error_callback_arg callback_arg;
834 ErrorContextCallback sqlerrcontext;
838 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
841 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
842 if (!HeapTupleIsValid(tuple))
843 elog(ERROR, "cache lookup failed for function %u", funcoid);
844 proc = (Form_pg_proc) GETSTRUCT(tuple);
846 /* Disallow pseudotype result */
847 /* except for RECORD, VOID, or polymorphic */
848 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
849 proc->prorettype != RECORDOID &&
850 proc->prorettype != VOIDOID &&
851 !IsPolymorphicType(proc->prorettype))
853 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
854 errmsg("SQL functions cannot return type %s",
855 format_type_be(proc->prorettype))));
857 /* Disallow pseudotypes in arguments */
858 /* except for polymorphic */
860 for (i = 0; i < proc->pronargs; i++)
862 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
864 if (IsPolymorphicType(proc->proargtypes.values[i]))
868 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
869 errmsg("SQL functions cannot have arguments of type %s",
870 format_type_be(proc->proargtypes.values[i]))));
874 /* Postpone body checks if !check_function_bodies */
875 if (check_function_bodies)
877 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
879 elog(ERROR, "null prosrc");
881 prosrc = TextDatumGetCString(tmp);
884 * Setup error traceback support for ereport().
886 callback_arg.proname = NameStr(proc->proname);
887 callback_arg.prosrc = prosrc;
889 sqlerrcontext.callback = sql_function_parse_error_callback;
890 sqlerrcontext.arg = (void *) &callback_arg;
891 sqlerrcontext.previous = error_context_stack;
892 error_context_stack = &sqlerrcontext;
895 * We can't do full prechecking of the function definition if there
896 * are any polymorphic input types, because actual datatypes of
897 * expression results will be unresolvable. The check will be done at
900 * We can run the text through the raw parser though; this will at
901 * least catch silly syntactic errors.
903 raw_parsetree_list = pg_parse_query(prosrc);
908 * OK to do full precheck: analyze and rewrite the queries, then
909 * verify the result type.
911 SQLFunctionParseInfoPtr pinfo;
913 /* But first, set up parameter information */
914 pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
916 querytree_list = NIL;
917 foreach(lc, raw_parsetree_list)
919 RawStmt *parsetree = lfirst_node(RawStmt, lc);
920 List *querytree_sublist;
922 querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
924 (ParserSetupHook) sql_fn_parser_setup,
927 querytree_list = list_concat(querytree_list,
931 check_sql_fn_statements(querytree_list);
932 (void) check_sql_fn_retval(funcoid, proc->prorettype,
937 error_context_stack = sqlerrcontext.previous;
940 ReleaseSysCache(tuple);
946 * Error context callback for handling errors in SQL function definitions
949 sql_function_parse_error_callback(void *arg)
951 parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
953 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
954 if (!function_parse_error_transpose(callback_arg->prosrc))
956 /* If it's not a syntax error, push info onto context stack */
957 errcontext("SQL function \"%s\"", callback_arg->proname);
962 * Adjust a syntax error occurring inside the function body of a CREATE
963 * FUNCTION or DO command. This can be used by any function validator or
964 * anonymous-block handler, not only for SQL-language functions.
965 * It is assumed that the syntax error position is initially relative to the
966 * function body string (as passed in). If possible, we adjust the position
967 * to reference the original command text; if we can't manage that, we set
968 * up an "internal query" syntax error instead.
970 * Returns true if a syntax error was processed, false if not.
973 function_parse_error_transpose(const char *prosrc)
977 const char *queryText;
980 * Nothing to do unless we are dealing with a syntax error that has a
983 * Some PLs may prefer to report the error position as an internal error
984 * to begin with, so check that too.
986 origerrposition = geterrposition();
987 if (origerrposition <= 0)
989 origerrposition = getinternalerrposition();
990 if (origerrposition <= 0)
994 /* We can get the original query text from the active portal (hack...) */
995 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
996 queryText = ActivePortal->sourceText;
998 /* Try to locate the prosrc in the original text */
999 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
1001 if (newerrposition > 0)
1003 /* Successful, so fix error position to reference original query */
1004 errposition(newerrposition);
1005 /* Get rid of any report of the error as an "internal query" */
1006 internalerrposition(0);
1007 internalerrquery(NULL);
1012 * If unsuccessful, convert the position to an internal position
1013 * marker and give the function text as the internal query.
1016 internalerrposition(origerrposition);
1017 internalerrquery(prosrc);
1024 * Try to locate the string literal containing the function body in the
1025 * given text of the CREATE FUNCTION or DO command. If successful, return
1026 * the character (not byte) index within the command corresponding to the
1027 * given character index within the literal. If not successful, return 0.
1030 match_prosrc_to_query(const char *prosrc, const char *queryText,
1034 * Rather than fully parsing the original command, we just scan the
1035 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1036 * not in any very probable scenarios), so fail if we find more than one
1039 int prosrclen = strlen(prosrc);
1040 int querylen = strlen(queryText);
1045 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1047 if (queryText[curpos] == '$' &&
1048 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1049 queryText[curpos + 1 + prosrclen] == '$')
1052 * Found a $foo$ match. Since there are no embedded quoting
1053 * characters in a dollar-quoted literal, we don't have to do any
1054 * fancy arithmetic; just offset by the starting position.
1057 return 0; /* multiple matches, fail */
1058 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1061 else if (queryText[curpos] == '\'' &&
1062 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1063 cursorpos, &newcursorpos))
1066 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1067 * for any quotes or backslashes embedded in the literal.
1070 return 0; /* multiple matches, fail */
1071 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1080 * Try to match the given source text to a single-quoted literal.
1081 * If successful, adjust newcursorpos to correspond to the character
1082 * (not byte) index corresponding to cursorpos in the source text.
1084 * At entry, literal points just past a ' character. We must check for the
1088 match_prosrc_to_literal(const char *prosrc, const char *literal,
1089 int cursorpos, int *newcursorpos)
1091 int newcp = cursorpos;
1095 * This implementation handles backslashes and doubled quotes in the
1096 * string literal. It does not handle the SQL syntax for literals
1097 * continued across line boundaries.
1099 * We do the comparison a character at a time, not a byte at a time, so
1100 * that we can do the correct cursorpos math.
1104 cursorpos--; /* characters left before cursor */
1107 * Check for backslashes and doubled quotes in the literal; adjust
1108 * newcp when one is found before the cursor.
1110 if (*literal == '\\')
1116 else if (*literal == '\'')
1118 if (literal[1] != '\'')
1124 chlen = pg_mblen(prosrc);
1125 if (strncmp(prosrc, literal, chlen) != 0)
1131 if (*literal == '\'' && literal[1] != '\'')
1134 *newcursorpos = newcp;
1139 /* Must set *newcursorpos to suppress compiler warning */
1140 *newcursorpos = newcp;
1145 oid_array_to_list(Datum datum)
1147 ArrayType *array = DatumGetArrayTypeP(datum);
1153 deconstruct_array(array,
1155 sizeof(Oid), true, 'i',
1156 &values, NULL, &nelems);
1157 for (i = 0; i < nelems; i++)
1158 result = lappend_oid(result, values[i]);