1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2013, 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/xact.h"
19 #include "catalog/dependency.h"
20 #include "catalog/indexing.h"
21 #include "catalog/objectaccess.h"
22 #include "catalog/pg_language.h"
23 #include "catalog/pg_namespace.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_proc_fn.h"
26 #include "catalog/pg_type.h"
27 #include "executor/functions.h"
29 #include "mb/pg_wchar.h"
30 #include "miscadmin.h"
31 #include "nodes/nodeFuncs.h"
32 #include "parser/parse_type.h"
33 #include "tcop/pquery.h"
34 #include "tcop/tcopprot.h"
35 #include "utils/acl.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/rel.h"
39 #include "utils/syscache.h"
42 Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
43 Datum fmgr_c_validator(PG_FUNCTION_ARGS);
44 Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
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, 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_fn.h.
65 * ----------------------------------------------------------------
68 ProcedureCreate(const char *procedureName,
75 Oid languageValidator,
80 bool security_definer,
84 oidvector *parameterTypes,
85 Datum allParameterTypes,
88 List *parameterDefaults,
97 char *paramModes = NULL;
98 bool genericInParam = false;
99 bool genericOutParam = false;
100 bool anyrangeInParam = false;
101 bool anyrangeOutParam = false;
102 bool internalInParam = false;
103 bool internalOutParam = false;
104 Oid variadicType = InvalidOid;
109 bool nulls[Natts_pg_proc];
110 Datum values[Natts_pg_proc];
111 bool replaces[Natts_pg_proc];
116 ObjectAddress myself,
123 Assert(PointerIsValid(prosrc));
125 parameterCount = parameterTypes->dim1;
126 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
128 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
129 errmsg_plural("functions cannot have more than %d argument",
130 "functions cannot have more than %d arguments",
133 /* note: the above is correct, we do NOT count output arguments */
135 /* Deconstruct array inputs */
136 if (allParameterTypes != PointerGetDatum(NULL))
139 * We expect the array to be a 1-D OID array; verify that. We don't
140 * need to use deconstruct_array() since the array data is just going
141 * to look like a C array of OID values.
143 ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
145 allParamCount = ARR_DIMS(allParamArray)[0];
146 if (ARR_NDIM(allParamArray) != 1 ||
147 allParamCount <= 0 ||
148 ARR_HASNULL(allParamArray) ||
149 ARR_ELEMTYPE(allParamArray) != OIDOID)
150 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
151 allParams = (Oid *) ARR_DATA_PTR(allParamArray);
152 Assert(allParamCount >= parameterCount);
153 /* we assume caller got the contents right */
157 allParamCount = parameterCount;
158 allParams = parameterTypes->values;
161 if (parameterModes != PointerGetDatum(NULL))
164 * We expect the array to be a 1-D CHAR array; verify that. We don't
165 * need to use deconstruct_array() since the array data is just going
166 * to look like a C array of char values.
168 ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
170 if (ARR_NDIM(modesArray) != 1 ||
171 ARR_DIMS(modesArray)[0] != allParamCount ||
172 ARR_HASNULL(modesArray) ||
173 ARR_ELEMTYPE(modesArray) != CHAROID)
174 elog(ERROR, "parameterModes is not a 1-D char array");
175 paramModes = (char *) ARR_DATA_PTR(modesArray);
179 * Detect whether we have polymorphic or INTERNAL arguments. The first
180 * loop checks input arguments, the second output arguments.
182 for (i = 0; i < parameterCount; i++)
184 switch (parameterTypes->values[i])
190 genericInParam = true;
193 genericInParam = true;
194 anyrangeInParam = true;
197 internalInParam = true;
202 if (allParameterTypes != PointerGetDatum(NULL))
204 for (i = 0; i < allParamCount; i++)
206 if (paramModes == NULL ||
207 paramModes[i] == PROARGMODE_IN ||
208 paramModes[i] == PROARGMODE_VARIADIC)
209 continue; /* ignore input-only params */
211 switch (allParams[i])
217 genericOutParam = true;
220 genericOutParam = true;
221 anyrangeOutParam = true;
224 internalOutParam = true;
231 * Do not allow polymorphic return type unless at least one input argument
232 * is polymorphic. ANYRANGE return type is even stricter: must have an
233 * ANYRANGE input (since we can't deduce the specific range type from
234 * ANYELEMENT). Also, do not allow return type INTERNAL unless at least
235 * one input argument is INTERNAL.
237 if ((IsPolymorphicType(returnType) || genericOutParam)
240 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
241 errmsg("cannot determine result data type"),
242 errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
244 if ((returnType == ANYRANGEOID || anyrangeOutParam) &&
247 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
248 errmsg("cannot determine result data type"),
249 errdetail("A function returning \"anyrange\" must have at least one \"anyrange\" argument.")));
251 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
253 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
254 errmsg("unsafe use of pseudo-type \"internal\""),
255 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
258 * don't allow functions of complex types that have the same name as
259 * existing attributes of the type
261 if (parameterCount == 1 &&
262 OidIsValid(parameterTypes->values[0]) &&
263 (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
264 get_attnum(relid, procedureName) != InvalidAttrNumber)
266 (errcode(ERRCODE_DUPLICATE_COLUMN),
267 errmsg("\"%s\" is already an attribute of type %s",
269 format_type_be(parameterTypes->values[0]))));
271 if (paramModes != NULL)
274 * Only the last input parameter can be variadic; if it is, save its
275 * element type. Errors here are just elog since caller should have
276 * checked this already.
278 for (i = 0; i < allParamCount; i++)
280 switch (paramModes[i])
283 case PROARGMODE_INOUT:
284 if (OidIsValid(variadicType))
285 elog(ERROR, "variadic parameter must be last");
288 case PROARGMODE_TABLE:
291 case PROARGMODE_VARIADIC:
292 if (OidIsValid(variadicType))
293 elog(ERROR, "variadic parameter must be last");
294 switch (allParams[i])
297 variadicType = ANYOID;
300 variadicType = ANYELEMENTOID;
303 variadicType = get_element_type(allParams[i]);
304 if (!OidIsValid(variadicType))
305 elog(ERROR, "variadic parameter is not an array");
310 elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
317 * All seems OK; prepare the data to be inserted into pg_proc.
320 for (i = 0; i < Natts_pg_proc; ++i)
323 values[i] = (Datum) 0;
327 namestrcpy(&procname, procedureName);
328 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
329 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
330 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
331 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
332 values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
333 values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
334 values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
335 values[Anum_pg_proc_protransform - 1] = ObjectIdGetDatum(InvalidOid);
336 values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
337 values[Anum_pg_proc_proiswindow - 1] = BoolGetDatum(isWindowFunc);
338 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
339 values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
340 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
341 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
342 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
343 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
344 values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
345 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
346 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
347 if (allParameterTypes != PointerGetDatum(NULL))
348 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
350 nulls[Anum_pg_proc_proallargtypes - 1] = true;
351 if (parameterModes != PointerGetDatum(NULL))
352 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
354 nulls[Anum_pg_proc_proargmodes - 1] = true;
355 if (parameterNames != PointerGetDatum(NULL))
356 values[Anum_pg_proc_proargnames - 1] = parameterNames;
358 nulls[Anum_pg_proc_proargnames - 1] = true;
359 if (parameterDefaults != NIL)
360 values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
362 nulls[Anum_pg_proc_proargdefaults - 1] = true;
363 values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
365 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
367 nulls[Anum_pg_proc_probin - 1] = true;
368 if (proconfig != PointerGetDatum(NULL))
369 values[Anum_pg_proc_proconfig - 1] = proconfig;
371 nulls[Anum_pg_proc_proconfig - 1] = true;
372 /* proacl will be determined later */
374 rel = heap_open(ProcedureRelationId, RowExclusiveLock);
375 tupDesc = RelationGetDescr(rel);
377 /* Check for pre-existing definition */
378 oldtup = SearchSysCache3(PROCNAMEARGSNSP,
379 PointerGetDatum(procedureName),
380 PointerGetDatum(parameterTypes),
381 ObjectIdGetDatum(procNamespace));
383 if (HeapTupleIsValid(oldtup))
385 /* There is one; okay to replace it? */
386 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
392 (errcode(ERRCODE_DUPLICATE_FUNCTION),
393 errmsg("function \"%s\" already exists with same argument types",
395 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), proowner))
396 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
400 * Not okay to change the return type of the existing proc, since
401 * existing rules, views, etc may depend on the return type.
403 if (returnType != oldproc->prorettype ||
404 returnsSet != oldproc->proretset)
406 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
407 errmsg("cannot change return type of existing function"),
408 errhint("Use DROP FUNCTION %s first.",
409 format_procedure(HeapTupleGetOid(oldtup)))));
412 * If it returns RECORD, check for possible change of record type
413 * implied by OUT parameters
415 if (returnType == RECORDOID)
420 olddesc = build_function_result_tupdesc_t(oldtup);
421 newdesc = build_function_result_tupdesc_d(allParameterTypes,
424 if (olddesc == NULL && newdesc == NULL)
425 /* ok, both are runtime-defined RECORDs */ ;
426 else if (olddesc == NULL || newdesc == NULL ||
427 !equalTupleDescs(olddesc, newdesc))
429 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
430 errmsg("cannot change return type of existing function"),
431 errdetail("Row type defined by OUT parameters is different."),
432 errhint("Use DROP FUNCTION %s first.",
433 format_procedure(HeapTupleGetOid(oldtup)))));
437 * If there were any named input parameters, check to make sure the
438 * names have not been changed, as this could break existing calls. We
439 * allow adding names to formerly unnamed parameters, though.
441 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
442 Anum_pg_proc_proargnames,
447 char **old_arg_names;
448 char **new_arg_names;
453 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
454 Anum_pg_proc_proargmodes,
457 proargmodes = PointerGetDatum(NULL); /* just to be sure */
459 n_old_arg_names = get_func_input_arg_names(proargnames,
462 n_new_arg_names = get_func_input_arg_names(parameterNames,
465 for (j = 0; j < n_old_arg_names; j++)
467 if (old_arg_names[j] == NULL)
469 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
470 strcmp(old_arg_names[j], new_arg_names[j]) != 0)
472 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
473 errmsg("cannot change name of input parameter \"%s\"",
475 errhint("Use DROP FUNCTION %s first.",
476 format_procedure(HeapTupleGetOid(oldtup)))));
481 * If there are existing defaults, check compatibility: redefinition
482 * must not remove any defaults nor change their types. (Removing a
483 * default might cause a function to fail to satisfy an existing call.
484 * Changing type would only be possible if the associated parameter is
485 * polymorphic, and in such cases a change of default type might alter
486 * the resolved output type of existing calls.)
488 if (oldproc->pronargdefaults != 0)
490 Datum proargdefaults;
495 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
497 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
498 errmsg("cannot remove parameter defaults from existing function"),
499 errhint("Use DROP FUNCTION %s first.",
500 format_procedure(HeapTupleGetOid(oldtup)))));
502 proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
503 Anum_pg_proc_proargdefaults,
506 oldDefaults = (List *) stringToNode(TextDatumGetCString(proargdefaults));
507 Assert(IsA(oldDefaults, List));
508 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
510 /* new list can have more defaults than old, advance over 'em */
511 newlc = list_head(parameterDefaults);
512 for (i = list_length(parameterDefaults) - oldproc->pronargdefaults;
515 newlc = lnext(newlc);
517 foreach(oldlc, oldDefaults)
519 Node *oldDef = (Node *) lfirst(oldlc);
520 Node *newDef = (Node *) lfirst(newlc);
522 if (exprType(oldDef) != exprType(newDef))
524 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
525 errmsg("cannot change data type of existing parameter default value"),
526 errhint("Use DROP FUNCTION %s first.",
527 format_procedure(HeapTupleGetOid(oldtup)))));
528 newlc = lnext(newlc);
532 /* Can't change aggregate or window-function status, either */
533 if (oldproc->proisagg != isAgg)
535 if (oldproc->proisagg)
537 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
538 errmsg("function \"%s\" is an aggregate function",
542 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
543 errmsg("function \"%s\" is not an aggregate function",
546 if (oldproc->proiswindow != isWindowFunc)
548 if (oldproc->proiswindow)
550 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
551 errmsg("function \"%s\" is a window function",
555 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
556 errmsg("function \"%s\" is not a window function",
561 * Do not change existing ownership or permissions, either. Note
562 * dependency-update code below has to agree with this decision.
564 replaces[Anum_pg_proc_proowner - 1] = false;
565 replaces[Anum_pg_proc_proacl - 1] = false;
568 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
569 simple_heap_update(rel, &tup->t_self, tup);
571 ReleaseSysCache(oldtup);
576 /* Creating a new procedure */
578 /* First, get default permissions and set up proacl */
579 proacl = get_user_default_acl(ACL_OBJECT_FUNCTION, proowner,
582 values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
584 nulls[Anum_pg_proc_proacl - 1] = true;
586 tup = heap_form_tuple(tupDesc, values, nulls);
587 simple_heap_insert(rel, tup);
591 /* Need to update indexes for either the insert or update case */
592 CatalogUpdateIndexes(rel, tup);
594 retval = HeapTupleGetOid(tup);
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 parameter types */
628 for (i = 0; i < allParamCount; i++)
630 referenced.classId = TypeRelationId;
631 referenced.objectId = allParams[i];
632 referenced.objectSubId = 0;
633 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
636 /* dependency on parameter default expressions */
637 if (parameterDefaults)
638 recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
639 NIL, DEPENDENCY_NORMAL);
641 /* dependency on owner */
643 recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
645 /* dependency on any roles mentioned in ACL */
646 if (!is_update && proacl != NULL)
651 nnewmembers = aclmembers(proacl, &newmembers);
652 updateAclDependencies(ProcedureRelationId, retval, 0,
655 nnewmembers, newmembers);
658 /* dependency on extension */
659 recordDependencyOnCurrentExtension(&myself, is_update);
663 /* Post creation hook for new function */
664 InvokeObjectAccessHook(OAT_POST_CREATE,
665 ProcedureRelationId, retval, 0, NULL);
667 heap_close(rel, RowExclusiveLock);
669 /* Verify function body */
670 if (OidIsValid(languageValidator))
672 ArrayType *set_items;
675 /* Advance command counter so new tuple can be seen by validator */
676 CommandCounterIncrement();
678 /* Set per-function configuration parameters */
679 set_items = (ArrayType *) DatumGetPointer(proconfig);
680 if (set_items) /* Need a new GUC nesting level */
682 save_nestlevel = NewGUCNestLevel();
683 ProcessGUCArray(set_items,
684 (superuser() ? PGC_SUSET : PGC_USERSET),
689 save_nestlevel = 0; /* keep compiler quiet */
691 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
694 AtEOXact_GUC(true, save_nestlevel);
703 * Validator for internal functions
705 * Check that the given internal function name (the "prosrc" value) is
706 * a known builtin function.
709 fmgr_internal_validator(PG_FUNCTION_ARGS)
711 Oid funcoid = PG_GETARG_OID(0);
718 * We do not honor check_function_bodies since it's unlikely the function
719 * name will be found later if it isn't there now.
722 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
723 if (!HeapTupleIsValid(tuple))
724 elog(ERROR, "cache lookup failed for function %u", funcoid);
726 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
728 elog(ERROR, "null prosrc");
729 prosrc = TextDatumGetCString(tmp);
731 if (fmgr_internal_function(prosrc) == InvalidOid)
733 (errcode(ERRCODE_UNDEFINED_FUNCTION),
734 errmsg("there is no built-in function named \"%s\"",
737 ReleaseSysCache(tuple);
745 * Validator for C language functions
747 * Make sure that the library file exists, is loadable, and contains
748 * the specified link symbol. Also check for a valid function
749 * information record.
752 fmgr_c_validator(PG_FUNCTION_ARGS)
754 Oid funcoid = PG_GETARG_OID(0);
763 * It'd be most consistent to skip the check if !check_function_bodies,
764 * but the purpose of that switch is to be helpful for pg_dump loading,
765 * and for pg_dump loading it's much better if we *do* check.
768 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
769 if (!HeapTupleIsValid(tuple))
770 elog(ERROR, "cache lookup failed for function %u", funcoid);
772 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
774 elog(ERROR, "null prosrc for C function %u", funcoid);
775 prosrc = TextDatumGetCString(tmp);
777 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
779 elog(ERROR, "null probin for C function %u", funcoid);
780 probin = TextDatumGetCString(tmp);
782 (void) load_external_function(probin, prosrc, true, &libraryhandle);
783 (void) fetch_finfo_record(libraryhandle, prosrc);
785 ReleaseSysCache(tuple);
792 * Validator for SQL language functions
794 * Parse it here in order to be sure that it contains no syntax errors.
797 fmgr_sql_validator(PG_FUNCTION_ARGS)
799 Oid funcoid = PG_GETARG_OID(0);
802 List *raw_parsetree_list;
803 List *querytree_list;
808 parse_error_callback_arg callback_arg;
809 ErrorContextCallback sqlerrcontext;
813 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
814 if (!HeapTupleIsValid(tuple))
815 elog(ERROR, "cache lookup failed for function %u", funcoid);
816 proc = (Form_pg_proc) GETSTRUCT(tuple);
818 /* Disallow pseudotype result */
819 /* except for RECORD, VOID, or polymorphic */
820 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
821 proc->prorettype != RECORDOID &&
822 proc->prorettype != VOIDOID &&
823 !IsPolymorphicType(proc->prorettype))
825 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
826 errmsg("SQL functions cannot return type %s",
827 format_type_be(proc->prorettype))));
829 /* Disallow pseudotypes in arguments */
830 /* except for polymorphic */
832 for (i = 0; i < proc->pronargs; i++)
834 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
836 if (IsPolymorphicType(proc->proargtypes.values[i]))
840 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
841 errmsg("SQL functions cannot have arguments of type %s",
842 format_type_be(proc->proargtypes.values[i]))));
846 /* Postpone body checks if !check_function_bodies */
847 if (check_function_bodies)
849 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
851 elog(ERROR, "null prosrc");
853 prosrc = TextDatumGetCString(tmp);
856 * Setup error traceback support for ereport().
858 callback_arg.proname = NameStr(proc->proname);
859 callback_arg.prosrc = prosrc;
861 sqlerrcontext.callback = sql_function_parse_error_callback;
862 sqlerrcontext.arg = (void *) &callback_arg;
863 sqlerrcontext.previous = error_context_stack;
864 error_context_stack = &sqlerrcontext;
867 * We can't do full prechecking of the function definition if there
868 * are any polymorphic input types, because actual datatypes of
869 * expression results will be unresolvable. The check will be done at
872 * We can run the text through the raw parser though; this will at
873 * least catch silly syntactic errors.
875 raw_parsetree_list = pg_parse_query(prosrc);
880 * OK to do full precheck: analyze and rewrite the queries, then
881 * verify the result type.
883 SQLFunctionParseInfoPtr pinfo;
885 /* But first, set up parameter information */
886 pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
888 querytree_list = NIL;
889 foreach(lc, raw_parsetree_list)
891 Node *parsetree = (Node *) lfirst(lc);
892 List *querytree_sublist;
894 querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
896 (ParserSetupHook) sql_fn_parser_setup,
898 querytree_list = list_concat(querytree_list,
902 (void) check_sql_fn_retval(funcoid, proc->prorettype,
907 error_context_stack = sqlerrcontext.previous;
910 ReleaseSysCache(tuple);
916 * Error context callback for handling errors in SQL function definitions
919 sql_function_parse_error_callback(void *arg)
921 parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
923 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
924 if (!function_parse_error_transpose(callback_arg->prosrc))
926 /* If it's not a syntax error, push info onto context stack */
927 errcontext("SQL function \"%s\"", callback_arg->proname);
932 * Adjust a syntax error occurring inside the function body of a CREATE
933 * FUNCTION or DO command. This can be used by any function validator or
934 * anonymous-block handler, not only for SQL-language functions.
935 * It is assumed that the syntax error position is initially relative to the
936 * function body string (as passed in). If possible, we adjust the position
937 * to reference the original command text; if we can't manage that, we set
938 * up an "internal query" syntax error instead.
940 * Returns true if a syntax error was processed, false if not.
943 function_parse_error_transpose(const char *prosrc)
947 const char *queryText;
950 * Nothing to do unless we are dealing with a syntax error that has a
953 * Some PLs may prefer to report the error position as an internal error
954 * to begin with, so check that too.
956 origerrposition = geterrposition();
957 if (origerrposition <= 0)
959 origerrposition = getinternalerrposition();
960 if (origerrposition <= 0)
964 /* We can get the original query text from the active portal (hack...) */
965 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
966 queryText = ActivePortal->sourceText;
968 /* Try to locate the prosrc in the original text */
969 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
971 if (newerrposition > 0)
973 /* Successful, so fix error position to reference original query */
974 errposition(newerrposition);
975 /* Get rid of any report of the error as an "internal query" */
976 internalerrposition(0);
977 internalerrquery(NULL);
982 * If unsuccessful, convert the position to an internal position
983 * marker and give the function text as the internal query.
986 internalerrposition(origerrposition);
987 internalerrquery(prosrc);
994 * Try to locate the string literal containing the function body in the
995 * given text of the CREATE FUNCTION or DO command. If successful, return
996 * the character (not byte) index within the command corresponding to the
997 * given character index within the literal. If not successful, return 0.
1000 match_prosrc_to_query(const char *prosrc, const char *queryText,
1004 * Rather than fully parsing the original command, we just scan the
1005 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1006 * not in any very probable scenarios), so fail if we find more than one
1009 int prosrclen = strlen(prosrc);
1010 int querylen = strlen(queryText);
1015 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1017 if (queryText[curpos] == '$' &&
1018 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1019 queryText[curpos + 1 + prosrclen] == '$')
1022 * Found a $foo$ match. Since there are no embedded quoting
1023 * characters in a dollar-quoted literal, we don't have to do any
1024 * fancy arithmetic; just offset by the starting position.
1027 return 0; /* multiple matches, fail */
1028 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1031 else if (queryText[curpos] == '\'' &&
1032 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1033 cursorpos, &newcursorpos))
1036 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1037 * for any quotes or backslashes embedded in the literal.
1040 return 0; /* multiple matches, fail */
1041 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1050 * Try to match the given source text to a single-quoted literal.
1051 * If successful, adjust newcursorpos to correspond to the character
1052 * (not byte) index corresponding to cursorpos in the source text.
1054 * At entry, literal points just past a ' character. We must check for the
1058 match_prosrc_to_literal(const char *prosrc, const char *literal,
1059 int cursorpos, int *newcursorpos)
1061 int newcp = cursorpos;
1065 * This implementation handles backslashes and doubled quotes in the
1066 * string literal. It does not handle the SQL syntax for literals
1067 * continued across line boundaries.
1069 * We do the comparison a character at a time, not a byte at a time, so
1070 * that we can do the correct cursorpos math.
1074 cursorpos--; /* characters left before cursor */
1077 * Check for backslashes and doubled quotes in the literal; adjust
1078 * newcp when one is found before the cursor.
1080 if (*literal == '\\')
1086 else if (*literal == '\'')
1088 if (literal[1] != '\'')
1094 chlen = pg_mblen(prosrc);
1095 if (strncmp(prosrc, literal, chlen) != 0)
1101 if (*literal == '\'' && literal[1] != '\'')
1104 *newcursorpos = newcp;
1109 /* Must set *newcursorpos to suppress compiler warning */
1110 *newcursorpos = newcp;