1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2012, 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/xact.h"
18 #include "catalog/dependency.h"
19 #include "catalog/indexing.h"
20 #include "catalog/objectaccess.h"
21 #include "catalog/pg_language.h"
22 #include "catalog/pg_namespace.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_proc_fn.h"
25 #include "catalog/pg_type.h"
26 #include "executor/functions.h"
28 #include "mb/pg_wchar.h"
29 #include "miscadmin.h"
30 #include "nodes/nodeFuncs.h"
31 #include "parser/parse_type.h"
32 #include "tcop/pquery.h"
33 #include "tcop/tcopprot.h"
34 #include "utils/acl.h"
35 #include "utils/builtins.h"
36 #include "utils/lsyscache.h"
37 #include "utils/rel.h"
38 #include "utils/syscache.h"
41 Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
42 Datum fmgr_c_validator(PG_FUNCTION_ARGS);
43 Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
49 } parse_error_callback_arg;
51 static void sql_function_parse_error_callback(void *arg);
52 static int match_prosrc_to_query(const char *prosrc, const char *queryText,
54 static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
55 int cursorpos, int *newcursorpos);
58 /* ----------------------------------------------------------------
61 * Note: allParameterTypes, parameterModes, parameterNames, and proconfig
62 * are either arrays of the proper types or NULL. We declare them Datum,
63 * not "ArrayType *", to avoid importing array.h into pg_proc_fn.h.
64 * ----------------------------------------------------------------
67 ProcedureCreate(const char *procedureName,
74 Oid languageValidator,
79 bool security_definer,
83 oidvector *parameterTypes,
84 Datum allParameterTypes,
87 List *parameterDefaults,
96 char *paramModes = NULL;
97 bool genericInParam = false;
98 bool genericOutParam = false;
99 bool anyrangeInParam = false;
100 bool anyrangeOutParam = false;
101 bool internalInParam = false;
102 bool internalOutParam = false;
103 Oid variadicType = InvalidOid;
108 bool nulls[Natts_pg_proc];
109 Datum values[Natts_pg_proc];
110 bool replaces[Natts_pg_proc];
115 ObjectAddress myself,
122 Assert(PointerIsValid(prosrc));
124 parameterCount = parameterTypes->dim1;
125 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
127 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
128 errmsg_plural("functions cannot have more than %d argument",
129 "functions cannot have more than %d arguments",
132 /* note: the above is correct, we do NOT count output arguments */
134 /* Deconstruct array inputs */
135 if (allParameterTypes != PointerGetDatum(NULL))
138 * We expect the array to be a 1-D OID array; verify that. We don't
139 * need to use deconstruct_array() since the array data is just going
140 * to look like a C array of OID values.
142 ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
144 allParamCount = ARR_DIMS(allParamArray)[0];
145 if (ARR_NDIM(allParamArray) != 1 ||
146 allParamCount <= 0 ||
147 ARR_HASNULL(allParamArray) ||
148 ARR_ELEMTYPE(allParamArray) != OIDOID)
149 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
150 allParams = (Oid *) ARR_DATA_PTR(allParamArray);
151 Assert(allParamCount >= parameterCount);
152 /* we assume caller got the contents right */
156 allParamCount = parameterCount;
157 allParams = parameterTypes->values;
160 if (parameterModes != PointerGetDatum(NULL))
163 * We expect the array to be a 1-D CHAR array; verify that. We don't
164 * need to use deconstruct_array() since the array data is just going
165 * to look like a C array of char values.
167 ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
169 if (ARR_NDIM(modesArray) != 1 ||
170 ARR_DIMS(modesArray)[0] != allParamCount ||
171 ARR_HASNULL(modesArray) ||
172 ARR_ELEMTYPE(modesArray) != CHAROID)
173 elog(ERROR, "parameterModes is not a 1-D char array");
174 paramModes = (char *) ARR_DATA_PTR(modesArray);
178 * Detect whether we have polymorphic or INTERNAL arguments. The first
179 * loop checks input arguments, the second output arguments.
181 for (i = 0; i < parameterCount; i++)
183 switch (parameterTypes->values[i])
189 genericInParam = true;
192 genericInParam = true;
193 anyrangeInParam = true;
196 internalInParam = true;
201 if (allParameterTypes != PointerGetDatum(NULL))
203 for (i = 0; i < allParamCount; i++)
205 if (paramModes == NULL ||
206 paramModes[i] == PROARGMODE_IN ||
207 paramModes[i] == PROARGMODE_VARIADIC)
208 continue; /* ignore input-only params */
210 switch (allParams[i])
216 genericOutParam = true;
219 genericOutParam = true;
220 anyrangeOutParam = true;
223 internalOutParam = true;
230 * Do not allow polymorphic return type unless at least one input argument
231 * is polymorphic. ANYRANGE return type is even stricter: must have an
232 * ANYRANGE input (since we can't deduce the specific range type from
233 * ANYELEMENT). Also, do not allow return type INTERNAL unless at least
234 * one input argument is INTERNAL.
236 if ((IsPolymorphicType(returnType) || genericOutParam)
239 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
240 errmsg("cannot determine result data type"),
241 errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
243 if ((returnType == ANYRANGEOID || anyrangeOutParam) &&
246 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
247 errmsg("cannot determine result data type"),
248 errdetail("A function returning ANYRANGE must have at least one ANYRANGE argument.")));
250 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
252 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
253 errmsg("unsafe use of pseudo-type \"internal\""),
254 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
257 * don't allow functions of complex types that have the same name as
258 * existing attributes of the type
260 if (parameterCount == 1 &&
261 OidIsValid(parameterTypes->values[0]) &&
262 (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
263 get_attnum(relid, procedureName) != InvalidAttrNumber)
265 (errcode(ERRCODE_DUPLICATE_COLUMN),
266 errmsg("\"%s\" is already an attribute of type %s",
268 format_type_be(parameterTypes->values[0]))));
270 if (paramModes != NULL)
273 * Only the last input parameter can be variadic; if it is, save its
274 * element type. Errors here are just elog since caller should have
275 * checked this already.
277 for (i = 0; i < allParamCount; i++)
279 switch (paramModes[i])
282 case PROARGMODE_INOUT:
283 if (OidIsValid(variadicType))
284 elog(ERROR, "variadic parameter must be last");
287 case PROARGMODE_TABLE:
290 case PROARGMODE_VARIADIC:
291 if (OidIsValid(variadicType))
292 elog(ERROR, "variadic parameter must be last");
293 switch (allParams[i])
296 variadicType = ANYOID;
299 variadicType = ANYELEMENTOID;
302 variadicType = get_element_type(allParams[i]);
303 if (!OidIsValid(variadicType))
304 elog(ERROR, "variadic parameter is not an array");
309 elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
316 * All seems OK; prepare the data to be inserted into pg_proc.
319 for (i = 0; i < Natts_pg_proc; ++i)
322 values[i] = (Datum) 0;
326 namestrcpy(&procname, procedureName);
327 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
328 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
329 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
330 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
331 values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
332 values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
333 values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
334 values[Anum_pg_proc_protransform - 1] = ObjectIdGetDatum(InvalidOid);
335 values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
336 values[Anum_pg_proc_proiswindow - 1] = BoolGetDatum(isWindowFunc);
337 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
338 values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
339 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
340 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
341 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
342 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
343 values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
344 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
345 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
346 if (allParameterTypes != PointerGetDatum(NULL))
347 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
349 nulls[Anum_pg_proc_proallargtypes - 1] = true;
350 if (parameterModes != PointerGetDatum(NULL))
351 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
353 nulls[Anum_pg_proc_proargmodes - 1] = true;
354 if (parameterNames != PointerGetDatum(NULL))
355 values[Anum_pg_proc_proargnames - 1] = parameterNames;
357 nulls[Anum_pg_proc_proargnames - 1] = true;
358 if (parameterDefaults != NIL)
359 values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
361 nulls[Anum_pg_proc_proargdefaults - 1] = true;
362 values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
364 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
366 nulls[Anum_pg_proc_probin - 1] = true;
367 if (proconfig != PointerGetDatum(NULL))
368 values[Anum_pg_proc_proconfig - 1] = proconfig;
370 nulls[Anum_pg_proc_proconfig - 1] = true;
371 /* proacl will be determined later */
373 rel = heap_open(ProcedureRelationId, RowExclusiveLock);
374 tupDesc = RelationGetDescr(rel);
376 /* Check for pre-existing definition */
377 oldtup = SearchSysCache3(PROCNAMEARGSNSP,
378 PointerGetDatum(procedureName),
379 PointerGetDatum(parameterTypes),
380 ObjectIdGetDatum(procNamespace));
382 if (HeapTupleIsValid(oldtup))
384 /* There is one; okay to replace it? */
385 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
391 (errcode(ERRCODE_DUPLICATE_FUNCTION),
392 errmsg("function \"%s\" already exists with same argument types",
394 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), proowner))
395 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
399 * Not okay to change the return type of the existing proc, since
400 * existing rules, views, etc may depend on the return type.
402 if (returnType != oldproc->prorettype ||
403 returnsSet != oldproc->proretset)
405 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
406 errmsg("cannot change return type of existing function"),
407 errhint("Use DROP FUNCTION first.")));
410 * If it returns RECORD, check for possible change of record type
411 * implied by OUT parameters
413 if (returnType == RECORDOID)
418 olddesc = build_function_result_tupdesc_t(oldtup);
419 newdesc = build_function_result_tupdesc_d(allParameterTypes,
422 if (olddesc == NULL && newdesc == NULL)
423 /* ok, both are runtime-defined RECORDs */ ;
424 else if (olddesc == NULL || newdesc == NULL ||
425 !equalTupleDescs(olddesc, newdesc))
427 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
428 errmsg("cannot change return type of existing function"),
429 errdetail("Row type defined by OUT parameters is different."),
430 errhint("Use DROP FUNCTION first.")));
434 * If there were any named input parameters, check to make sure the
435 * names have not been changed, as this could break existing calls. We
436 * allow adding names to formerly unnamed parameters, though.
438 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
439 Anum_pg_proc_proargnames,
444 char **old_arg_names;
445 char **new_arg_names;
450 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
451 Anum_pg_proc_proargmodes,
454 proargmodes = PointerGetDatum(NULL); /* just to be sure */
456 n_old_arg_names = get_func_input_arg_names(proargnames,
459 n_new_arg_names = get_func_input_arg_names(parameterNames,
462 for (j = 0; j < n_old_arg_names; j++)
464 if (old_arg_names[j] == NULL)
466 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
467 strcmp(old_arg_names[j], new_arg_names[j]) != 0)
469 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
470 errmsg("cannot change name of input parameter \"%s\"",
472 errhint("Use DROP FUNCTION first.")));
477 * If there are existing defaults, check compatibility: redefinition
478 * must not remove any defaults nor change their types. (Removing a
479 * default might cause a function to fail to satisfy an existing call.
480 * Changing type would only be possible if the associated parameter is
481 * polymorphic, and in such cases a change of default type might alter
482 * the resolved output type of existing calls.)
484 if (oldproc->pronargdefaults != 0)
486 Datum proargdefaults;
491 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
493 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
494 errmsg("cannot remove parameter defaults from existing function"),
495 errhint("Use DROP FUNCTION first.")));
497 proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
498 Anum_pg_proc_proargdefaults,
501 oldDefaults = (List *) stringToNode(TextDatumGetCString(proargdefaults));
502 Assert(IsA(oldDefaults, List));
503 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
505 /* new list can have more defaults than old, advance over 'em */
506 newlc = list_head(parameterDefaults);
507 for (i = list_length(parameterDefaults) - oldproc->pronargdefaults;
510 newlc = lnext(newlc);
512 foreach(oldlc, oldDefaults)
514 Node *oldDef = (Node *) lfirst(oldlc);
515 Node *newDef = (Node *) lfirst(newlc);
517 if (exprType(oldDef) != exprType(newDef))
519 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
520 errmsg("cannot change data type of existing parameter default value"),
521 errhint("Use DROP FUNCTION first.")));
522 newlc = lnext(newlc);
526 /* Can't change aggregate or window-function status, either */
527 if (oldproc->proisagg != isAgg)
529 if (oldproc->proisagg)
531 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
532 errmsg("function \"%s\" is an aggregate function",
536 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
537 errmsg("function \"%s\" is not an aggregate function",
540 if (oldproc->proiswindow != isWindowFunc)
542 if (oldproc->proiswindow)
544 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
545 errmsg("function \"%s\" is a window function",
549 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
550 errmsg("function \"%s\" is not a window function",
555 * Do not change existing ownership or permissions, either. Note
556 * dependency-update code below has to agree with this decision.
558 replaces[Anum_pg_proc_proowner - 1] = false;
559 replaces[Anum_pg_proc_proacl - 1] = false;
562 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
563 simple_heap_update(rel, &tup->t_self, tup);
565 ReleaseSysCache(oldtup);
570 /* Creating a new procedure */
572 /* First, get default permissions and set up proacl */
573 proacl = get_user_default_acl(ACL_OBJECT_FUNCTION, proowner,
576 values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
578 nulls[Anum_pg_proc_proacl - 1] = true;
580 tup = heap_form_tuple(tupDesc, values, nulls);
581 simple_heap_insert(rel, tup);
585 /* Need to update indexes for either the insert or update case */
586 CatalogUpdateIndexes(rel, tup);
588 retval = HeapTupleGetOid(tup);
591 * Create dependencies for the new function. If we are updating an
592 * existing function, first delete any existing pg_depend entries.
593 * (However, since we are not changing ownership or permissions, the
594 * shared dependencies do *not* need to change, and we leave them alone.)
597 deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
599 myself.classId = ProcedureRelationId;
600 myself.objectId = retval;
601 myself.objectSubId = 0;
603 /* dependency on namespace */
604 referenced.classId = NamespaceRelationId;
605 referenced.objectId = procNamespace;
606 referenced.objectSubId = 0;
607 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
609 /* dependency on implementation language */
610 referenced.classId = LanguageRelationId;
611 referenced.objectId = languageObjectId;
612 referenced.objectSubId = 0;
613 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
615 /* dependency on return type */
616 referenced.classId = TypeRelationId;
617 referenced.objectId = returnType;
618 referenced.objectSubId = 0;
619 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
621 /* dependency on parameter types */
622 for (i = 0; i < allParamCount; i++)
624 referenced.classId = TypeRelationId;
625 referenced.objectId = allParams[i];
626 referenced.objectSubId = 0;
627 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
630 /* dependency on parameter default expressions */
631 if (parameterDefaults)
632 recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
633 NIL, DEPENDENCY_NORMAL);
635 /* dependency on owner */
637 recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
639 /* dependency on any roles mentioned in ACL */
640 if (!is_update && proacl != NULL)
645 nnewmembers = aclmembers(proacl, &newmembers);
646 updateAclDependencies(ProcedureRelationId, retval, 0,
649 nnewmembers, newmembers);
652 /* dependency on extension */
653 recordDependencyOnCurrentExtension(&myself, is_update);
657 /* Post creation hook for new function */
658 InvokeObjectAccessHook(OAT_POST_CREATE,
659 ProcedureRelationId, retval, 0, NULL);
661 heap_close(rel, RowExclusiveLock);
663 /* Verify function body */
664 if (OidIsValid(languageValidator))
666 ArrayType *set_items;
669 /* Advance command counter so new tuple can be seen by validator */
670 CommandCounterIncrement();
672 /* Set per-function configuration parameters */
673 set_items = (ArrayType *) DatumGetPointer(proconfig);
674 if (set_items) /* Need a new GUC nesting level */
676 save_nestlevel = NewGUCNestLevel();
677 ProcessGUCArray(set_items,
678 (superuser() ? PGC_SUSET : PGC_USERSET),
683 save_nestlevel = 0; /* keep compiler quiet */
685 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
688 AtEOXact_GUC(true, save_nestlevel);
697 * Validator for internal functions
699 * Check that the given internal function name (the "prosrc" value) is
700 * a known builtin function.
703 fmgr_internal_validator(PG_FUNCTION_ARGS)
705 Oid funcoid = PG_GETARG_OID(0);
712 * We do not honor check_function_bodies since it's unlikely the function
713 * name will be found later if it isn't there now.
716 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
717 if (!HeapTupleIsValid(tuple))
718 elog(ERROR, "cache lookup failed for function %u", funcoid);
720 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
722 elog(ERROR, "null prosrc");
723 prosrc = TextDatumGetCString(tmp);
725 if (fmgr_internal_function(prosrc) == InvalidOid)
727 (errcode(ERRCODE_UNDEFINED_FUNCTION),
728 errmsg("there is no built-in function named \"%s\"",
731 ReleaseSysCache(tuple);
739 * Validator for C language functions
741 * Make sure that the library file exists, is loadable, and contains
742 * the specified link symbol. Also check for a valid function
743 * information record.
746 fmgr_c_validator(PG_FUNCTION_ARGS)
748 Oid funcoid = PG_GETARG_OID(0);
757 * It'd be most consistent to skip the check if !check_function_bodies,
758 * but the purpose of that switch is to be helpful for pg_dump loading,
759 * and for pg_dump loading it's much better if we *do* check.
762 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
763 if (!HeapTupleIsValid(tuple))
764 elog(ERROR, "cache lookup failed for function %u", funcoid);
766 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
768 elog(ERROR, "null prosrc for C function %u", funcoid);
769 prosrc = TextDatumGetCString(tmp);
771 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
773 elog(ERROR, "null probin for C function %u", funcoid);
774 probin = TextDatumGetCString(tmp);
776 (void) load_external_function(probin, prosrc, true, &libraryhandle);
777 (void) fetch_finfo_record(libraryhandle, prosrc);
779 ReleaseSysCache(tuple);
786 * Validator for SQL language functions
788 * Parse it here in order to be sure that it contains no syntax errors.
791 fmgr_sql_validator(PG_FUNCTION_ARGS)
793 Oid funcoid = PG_GETARG_OID(0);
796 List *raw_parsetree_list;
797 List *querytree_list;
802 parse_error_callback_arg callback_arg;
803 ErrorContextCallback sqlerrcontext;
807 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
808 if (!HeapTupleIsValid(tuple))
809 elog(ERROR, "cache lookup failed for function %u", funcoid);
810 proc = (Form_pg_proc) GETSTRUCT(tuple);
812 /* Disallow pseudotype result */
813 /* except for RECORD, VOID, or polymorphic */
814 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
815 proc->prorettype != RECORDOID &&
816 proc->prorettype != VOIDOID &&
817 !IsPolymorphicType(proc->prorettype))
819 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
820 errmsg("SQL functions cannot return type %s",
821 format_type_be(proc->prorettype))));
823 /* Disallow pseudotypes in arguments */
824 /* except for polymorphic */
826 for (i = 0; i < proc->pronargs; i++)
828 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
830 if (IsPolymorphicType(proc->proargtypes.values[i]))
834 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
835 errmsg("SQL functions cannot have arguments of type %s",
836 format_type_be(proc->proargtypes.values[i]))));
840 /* Postpone body checks if !check_function_bodies */
841 if (check_function_bodies)
843 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
845 elog(ERROR, "null prosrc");
847 prosrc = TextDatumGetCString(tmp);
850 * Setup error traceback support for ereport().
852 callback_arg.proname = NameStr(proc->proname);
853 callback_arg.prosrc = prosrc;
855 sqlerrcontext.callback = sql_function_parse_error_callback;
856 sqlerrcontext.arg = (void *) &callback_arg;
857 sqlerrcontext.previous = error_context_stack;
858 error_context_stack = &sqlerrcontext;
861 * We can't do full prechecking of the function definition if there
862 * are any polymorphic input types, because actual datatypes of
863 * expression results will be unresolvable. The check will be done at
866 * We can run the text through the raw parser though; this will at
867 * least catch silly syntactic errors.
869 raw_parsetree_list = pg_parse_query(prosrc);
874 * OK to do full precheck: analyze and rewrite the queries, then
875 * verify the result type.
877 SQLFunctionParseInfoPtr pinfo;
879 /* But first, set up parameter information */
880 pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
882 querytree_list = NIL;
883 foreach(lc, raw_parsetree_list)
885 Node *parsetree = (Node *) lfirst(lc);
886 List *querytree_sublist;
888 querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
890 (ParserSetupHook) sql_fn_parser_setup,
892 querytree_list = list_concat(querytree_list,
896 (void) check_sql_fn_retval(funcoid, proc->prorettype,
901 error_context_stack = sqlerrcontext.previous;
904 ReleaseSysCache(tuple);
910 * Error context callback for handling errors in SQL function definitions
913 sql_function_parse_error_callback(void *arg)
915 parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
917 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
918 if (!function_parse_error_transpose(callback_arg->prosrc))
920 /* If it's not a syntax error, push info onto context stack */
921 errcontext("SQL function \"%s\"", callback_arg->proname);
926 * Adjust a syntax error occurring inside the function body of a CREATE
927 * FUNCTION or DO command. This can be used by any function validator or
928 * anonymous-block handler, not only for SQL-language functions.
929 * It is assumed that the syntax error position is initially relative to the
930 * function body string (as passed in). If possible, we adjust the position
931 * to reference the original command text; if we can't manage that, we set
932 * up an "internal query" syntax error instead.
934 * Returns true if a syntax error was processed, false if not.
937 function_parse_error_transpose(const char *prosrc)
941 const char *queryText;
944 * Nothing to do unless we are dealing with a syntax error that has a
947 * Some PLs may prefer to report the error position as an internal error
948 * to begin with, so check that too.
950 origerrposition = geterrposition();
951 if (origerrposition <= 0)
953 origerrposition = getinternalerrposition();
954 if (origerrposition <= 0)
958 /* We can get the original query text from the active portal (hack...) */
959 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
960 queryText = ActivePortal->sourceText;
962 /* Try to locate the prosrc in the original text */
963 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
965 if (newerrposition > 0)
967 /* Successful, so fix error position to reference original query */
968 errposition(newerrposition);
969 /* Get rid of any report of the error as an "internal query" */
970 internalerrposition(0);
971 internalerrquery(NULL);
976 * If unsuccessful, convert the position to an internal position
977 * marker and give the function text as the internal query.
980 internalerrposition(origerrposition);
981 internalerrquery(prosrc);
988 * Try to locate the string literal containing the function body in the
989 * given text of the CREATE FUNCTION or DO command. If successful, return
990 * the character (not byte) index within the command corresponding to the
991 * given character index within the literal. If not successful, return 0.
994 match_prosrc_to_query(const char *prosrc, const char *queryText,
998 * Rather than fully parsing the original command, we just scan the
999 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1000 * not in any very probable scenarios), so fail if we find more than one
1003 int prosrclen = strlen(prosrc);
1004 int querylen = strlen(queryText);
1009 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1011 if (queryText[curpos] == '$' &&
1012 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1013 queryText[curpos + 1 + prosrclen] == '$')
1016 * Found a $foo$ match. Since there are no embedded quoting
1017 * characters in a dollar-quoted literal, we don't have to do any
1018 * fancy arithmetic; just offset by the starting position.
1021 return 0; /* multiple matches, fail */
1022 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1025 else if (queryText[curpos] == '\'' &&
1026 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1027 cursorpos, &newcursorpos))
1030 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1031 * for any quotes or backslashes embedded in the literal.
1034 return 0; /* multiple matches, fail */
1035 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1044 * Try to match the given source text to a single-quoted literal.
1045 * If successful, adjust newcursorpos to correspond to the character
1046 * (not byte) index corresponding to cursorpos in the source text.
1048 * At entry, literal points just past a ' character. We must check for the
1052 match_prosrc_to_literal(const char *prosrc, const char *literal,
1053 int cursorpos, int *newcursorpos)
1055 int newcp = cursorpos;
1059 * This implementation handles backslashes and doubled quotes in the
1060 * string literal. It does not handle the SQL syntax for literals
1061 * continued across line boundaries.
1063 * We do the comparison a character at a time, not a byte at a time, so
1064 * that we can do the correct cursorpos math.
1068 cursorpos--; /* characters left before cursor */
1071 * Check for backslashes and doubled quotes in the literal; adjust
1072 * newcp when one is found before the cursor.
1074 if (*literal == '\\')
1080 else if (*literal == '\'')
1082 if (literal[1] != '\'')
1088 chlen = pg_mblen(prosrc);
1089 if (strncmp(prosrc, literal, chlen) != 0)
1095 if (*literal == '\'' && literal[1] != '\'')
1098 *newcursorpos = newcp;
1103 /* Must set *newcursorpos to suppress compiler warning */
1104 *newcursorpos = newcp;