1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/catalog/pg_proc.c,v 1.131 2005/06/28 19:51:21 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/dependency.h"
19 #include "catalog/indexing.h"
20 #include "catalog/pg_language.h"
21 #include "catalog/pg_namespace.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/functions.h"
26 #include "miscadmin.h"
27 #include "mb/pg_wchar.h"
28 #include "parser/parse_type.h"
29 #include "tcop/pquery.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/acl.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/syscache.h"
38 bool check_function_bodies = true;
41 Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
42 Datum fmgr_c_validator(PG_FUNCTION_ARGS);
43 Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
45 static void sql_function_parse_error_callback(void *arg);
46 static int match_prosrc_to_query(const char *prosrc, const char *queryText,
48 static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
49 int cursorpos, int *newcursorpos);
52 /* ----------------------------------------------------------------
55 * Note: allParameterTypes, parameterModes, parameterNames are either arrays
56 * of the proper types or NULL. We declare them Datum, not "ArrayType *",
57 * to avoid importing array.h into pg_proc.h.
58 * ----------------------------------------------------------------
61 ProcedureCreate(const char *procedureName,
67 Oid languageValidator,
71 bool security_definer,
74 oidvector *parameterTypes,
75 Datum allParameterTypes,
83 bool genericInParam = false;
84 bool genericOutParam = false;
85 bool internalInParam = false;
86 bool internalOutParam = false;
90 char nulls[Natts_pg_proc];
91 Datum values[Natts_pg_proc];
92 char replaces[Natts_pg_proc];
104 Assert(PointerIsValid(prosrc));
105 Assert(PointerIsValid(probin));
107 parameterCount = parameterTypes->dim1;
108 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
110 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
111 errmsg("functions cannot have more than %d arguments",
113 /* note: the above is correct, we do NOT count output arguments */
115 if (allParameterTypes != PointerGetDatum(NULL))
118 * We expect the array to be a 1-D OID array; verify that. We
119 * don't need to use deconstruct_array() since the array data is
120 * just going to look like a C array of OID values.
122 allParamCount = ARR_DIMS(DatumGetPointer(allParameterTypes))[0];
123 if (ARR_NDIM(DatumGetPointer(allParameterTypes)) != 1 ||
124 allParamCount <= 0 ||
125 ARR_ELEMTYPE(DatumGetPointer(allParameterTypes)) != OIDOID)
126 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
127 allParams = (Oid *) ARR_DATA_PTR(DatumGetPointer(allParameterTypes));
128 Assert(allParamCount >= parameterCount);
129 /* we assume caller got the contents right */
133 allParamCount = parameterCount;
134 allParams = parameterTypes->values;
138 * Do not allow return type ANYARRAY or ANYELEMENT unless at least one
139 * input argument is ANYARRAY or ANYELEMENT. Also, do not allow
140 * return type INTERNAL unless at least one input argument is INTERNAL.
142 for (i = 0; i < parameterCount; i++)
144 switch (parameterTypes->values[i])
148 genericInParam = true;
151 internalInParam = true;
156 if (allParameterTypes != PointerGetDatum(NULL))
158 for (i = 0; i < allParamCount; i++)
161 * We don't bother to distinguish input and output params here,
162 * so if there is, say, just an input INTERNAL param then we will
163 * still set internalOutParam. This is OK since we don't really
166 switch (allParams[i])
170 genericOutParam = true;
173 internalOutParam = true;
179 if ((returnType == ANYARRAYOID || returnType == ANYELEMENTOID ||
180 genericOutParam) && !genericInParam)
182 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
183 errmsg("cannot determine result data type"),
184 errdetail("A function returning \"anyarray\" or \"anyelement\" must have at least one argument of either type.")));
186 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
188 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
189 errmsg("unsafe use of INTERNAL pseudo-type"),
190 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
193 * don't allow functions of complex types that have the same name as
194 * existing attributes of the type
196 if (parameterCount == 1 &&
197 OidIsValid(parameterTypes->values[0]) &&
198 (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
199 get_attnum(relid, procedureName) != InvalidAttrNumber)
201 (errcode(ERRCODE_DUPLICATE_COLUMN),
202 errmsg("\"%s\" is already an attribute of type %s",
204 format_type_be(parameterTypes->values[0]))));
207 * All seems OK; prepare the data to be inserted into pg_proc.
210 for (i = 0; i < Natts_pg_proc; ++i)
213 values[i] = (Datum) 0;
217 namestrcpy(&procname, procedureName);
218 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
219 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
220 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(GetUserId());
221 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
222 values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
223 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
224 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
225 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
226 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
227 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
228 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
229 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
230 if (allParameterTypes != PointerGetDatum(NULL))
231 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
233 nulls[Anum_pg_proc_proallargtypes - 1] = 'n';
234 if (parameterModes != PointerGetDatum(NULL))
235 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
237 nulls[Anum_pg_proc_proargmodes - 1] = 'n';
238 if (parameterNames != PointerGetDatum(NULL))
239 values[Anum_pg_proc_proargnames - 1] = parameterNames;
241 nulls[Anum_pg_proc_proargnames - 1] = 'n';
242 values[Anum_pg_proc_prosrc - 1] = DirectFunctionCall1(textin,
243 CStringGetDatum(prosrc));
244 values[Anum_pg_proc_probin - 1] = DirectFunctionCall1(textin,
245 CStringGetDatum(probin));
246 /* start out with empty permissions */
247 nulls[Anum_pg_proc_proacl - 1] = 'n';
249 rel = heap_open(ProcedureRelationId, RowExclusiveLock);
250 tupDesc = RelationGetDescr(rel);
252 /* Check for pre-existing definition */
253 oldtup = SearchSysCache(PROCNAMEARGSNSP,
254 PointerGetDatum(procedureName),
255 PointerGetDatum(parameterTypes),
256 ObjectIdGetDatum(procNamespace),
259 if (HeapTupleIsValid(oldtup))
261 /* There is one; okay to replace it? */
262 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
266 (errcode(ERRCODE_DUPLICATE_FUNCTION),
267 errmsg("function \"%s\" already exists with same argument types",
269 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), GetUserId()))
270 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
274 * Not okay to change the return type of the existing proc, since
275 * existing rules, views, etc may depend on the return type.
277 if (returnType != oldproc->prorettype ||
278 returnsSet != oldproc->proretset)
280 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
281 errmsg("cannot change return type of existing function"),
282 errhint("Use DROP FUNCTION first.")));
285 * If it returns RECORD, check for possible change of record type
286 * implied by OUT parameters
288 if (returnType == RECORDOID)
293 olddesc = build_function_result_tupdesc_t(oldtup);
294 newdesc = build_function_result_tupdesc_d(allParameterTypes,
297 if (olddesc == NULL && newdesc == NULL)
298 /* ok, both are runtime-defined RECORDs */ ;
299 else if (olddesc == NULL || newdesc == NULL ||
300 !equalTupleDescs(olddesc, newdesc))
302 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
303 errmsg("cannot change return type of existing function"),
304 errdetail("Row type defined by OUT parameters is different."),
305 errhint("Use DROP FUNCTION first.")));
308 /* Can't change aggregate status, either */
309 if (oldproc->proisagg != isAgg)
311 if (oldproc->proisagg)
313 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
314 errmsg("function \"%s\" is an aggregate",
318 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
319 errmsg("function \"%s\" is not an aggregate",
323 /* do not change existing ownership or permissions, either */
324 replaces[Anum_pg_proc_proowner - 1] = ' ';
325 replaces[Anum_pg_proc_proacl - 1] = ' ';
328 tup = heap_modifytuple(oldtup, tupDesc, values, nulls, replaces);
329 simple_heap_update(rel, &tup->t_self, tup);
331 ReleaseSysCache(oldtup);
336 /* Creating a new procedure */
337 tup = heap_formtuple(tupDesc, values, nulls);
338 simple_heap_insert(rel, tup);
342 /* Need to update indexes for either the insert or update case */
343 CatalogUpdateIndexes(rel, tup);
345 retval = HeapTupleGetOid(tup);
348 * Create dependencies for the new function. If we are updating an
349 * existing function, first delete any existing pg_depend entries.
352 deleteDependencyRecordsFor(ProcedureRelationId, retval);
354 myself.classId = ProcedureRelationId;
355 myself.objectId = retval;
356 myself.objectSubId = 0;
358 /* dependency on namespace */
359 referenced.classId = NamespaceRelationId;
360 referenced.objectId = procNamespace;
361 referenced.objectSubId = 0;
362 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
364 /* dependency on implementation language */
365 referenced.classId = LanguageRelationId;
366 referenced.objectId = languageObjectId;
367 referenced.objectSubId = 0;
368 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
370 /* dependency on return type */
371 referenced.classId = TypeRelationId;
372 referenced.objectId = returnType;
373 referenced.objectSubId = 0;
374 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
376 /* dependency on parameter types */
377 for (i = 0; i < allParamCount; i++)
379 referenced.classId = TypeRelationId;
380 referenced.objectId = allParams[i];
381 referenced.objectSubId = 0;
382 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
387 heap_close(rel, RowExclusiveLock);
389 /* Verify function body */
390 if (OidIsValid(languageValidator))
392 /* Advance command counter so new tuple can be seen by validator */
393 CommandCounterIncrement();
394 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
403 * Validator for internal functions
405 * Check that the given internal function name (the "prosrc" value) is
406 * a known builtin function.
409 fmgr_internal_validator(PG_FUNCTION_ARGS)
411 Oid funcoid = PG_GETARG_OID(0);
419 * We do not honor check_function_bodies since it's unlikely the
420 * function name will be found later if it isn't there now.
423 tuple = SearchSysCache(PROCOID,
424 ObjectIdGetDatum(funcoid),
426 if (!HeapTupleIsValid(tuple))
427 elog(ERROR, "cache lookup failed for function %u", funcoid);
428 proc = (Form_pg_proc) GETSTRUCT(tuple);
430 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
432 elog(ERROR, "null prosrc");
433 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
435 if (fmgr_internal_function(prosrc) == InvalidOid)
437 (errcode(ERRCODE_UNDEFINED_FUNCTION),
438 errmsg("there is no built-in function named \"%s\"",
441 ReleaseSysCache(tuple);
449 * Validator for C language functions
451 * Make sure that the library file exists, is loadable, and contains
452 * the specified link symbol. Also check for a valid function
453 * information record.
456 fmgr_c_validator(PG_FUNCTION_ARGS)
458 Oid funcoid = PG_GETARG_OID(0);
468 * It'd be most consistent to skip the check if
469 * !check_function_bodies, but the purpose of that switch is to be
470 * helpful for pg_dump loading, and for pg_dump loading it's much
471 * better if we *do* check.
474 tuple = SearchSysCache(PROCOID,
475 ObjectIdGetDatum(funcoid),
477 if (!HeapTupleIsValid(tuple))
478 elog(ERROR, "cache lookup failed for function %u", funcoid);
479 proc = (Form_pg_proc) GETSTRUCT(tuple);
481 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
483 elog(ERROR, "null prosrc");
484 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
486 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
488 elog(ERROR, "null probin");
489 probin = DatumGetCString(DirectFunctionCall1(textout, tmp));
491 (void) load_external_function(probin, prosrc, true, &libraryhandle);
492 (void) fetch_finfo_record(libraryhandle, prosrc);
494 ReleaseSysCache(tuple);
501 * Validator for SQL language functions
503 * Parse it here in order to be sure that it contains no syntax errors.
506 fmgr_sql_validator(PG_FUNCTION_ARGS)
508 Oid funcoid = PG_GETARG_OID(0);
511 List *querytree_list;
515 ErrorContextCallback sqlerrcontext;
519 tuple = SearchSysCache(PROCOID,
520 ObjectIdGetDatum(funcoid),
522 if (!HeapTupleIsValid(tuple))
523 elog(ERROR, "cache lookup failed for function %u", funcoid);
524 proc = (Form_pg_proc) GETSTRUCT(tuple);
526 /* Disallow pseudotype result */
527 /* except for RECORD, VOID, ANYARRAY, or ANYELEMENT */
528 if (get_typtype(proc->prorettype) == 'p' &&
529 proc->prorettype != RECORDOID &&
530 proc->prorettype != VOIDOID &&
531 proc->prorettype != ANYARRAYOID &&
532 proc->prorettype != ANYELEMENTOID)
534 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
535 errmsg("SQL functions cannot return type %s",
536 format_type_be(proc->prorettype))));
538 /* Disallow pseudotypes in arguments */
539 /* except for ANYARRAY or ANYELEMENT */
541 for (i = 0; i < proc->pronargs; i++)
543 if (get_typtype(proc->proargtypes.values[i]) == 'p')
545 if (proc->proargtypes.values[i] == ANYARRAYOID ||
546 proc->proargtypes.values[i] == ANYELEMENTOID)
550 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
551 errmsg("SQL functions cannot have arguments of type %s",
552 format_type_be(proc->proargtypes.values[i]))));
556 /* Postpone body checks if !check_function_bodies */
557 if (check_function_bodies)
559 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
561 elog(ERROR, "null prosrc");
563 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
566 * Setup error traceback support for ereport().
568 sqlerrcontext.callback = sql_function_parse_error_callback;
569 sqlerrcontext.arg = tuple;
570 sqlerrcontext.previous = error_context_stack;
571 error_context_stack = &sqlerrcontext;
574 * We can't do full prechecking of the function definition if
575 * there are any polymorphic input types, because actual datatypes
576 * of expression results will be unresolvable. The check will be
577 * done at runtime instead.
579 * We can run the text through the raw parser though; this will at
580 * least catch silly syntactic errors.
584 querytree_list = pg_parse_and_rewrite(prosrc,
585 proc->proargtypes.values,
587 (void) check_sql_fn_retval(funcoid, proc->prorettype,
588 querytree_list, NULL);
591 querytree_list = pg_parse_query(prosrc);
593 error_context_stack = sqlerrcontext.previous;
596 ReleaseSysCache(tuple);
602 * Error context callback for handling errors in SQL function definitions
605 sql_function_parse_error_callback(void *arg)
607 HeapTuple tuple = (HeapTuple) arg;
608 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
613 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
614 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
616 elog(ERROR, "null prosrc");
617 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
619 if (!function_parse_error_transpose(prosrc))
621 /* If it's not a syntax error, push info onto context stack */
622 errcontext("SQL function \"%s\"", NameStr(proc->proname));
629 * Adjust a syntax error occurring inside the function body of a CREATE
630 * FUNCTION command. This can be used by any function validator, not only
631 * for SQL-language functions. It is assumed that the syntax error position
632 * is initially relative to the function body string (as passed in). If
633 * possible, we adjust the position to reference the original CREATE command;
634 * if we can't manage that, we set up an "internal query" syntax error instead.
636 * Returns true if a syntax error was processed, false if not.
639 function_parse_error_transpose(const char *prosrc)
643 const char *queryText;
646 * Nothing to do unless we are dealing with a syntax error that has a
649 * Some PLs may prefer to report the error position as an internal error
650 * to begin with, so check that too.
652 origerrposition = geterrposition();
653 if (origerrposition <= 0)
655 origerrposition = getinternalerrposition();
656 if (origerrposition <= 0)
660 /* We can get the original query text from the active portal (hack...) */
661 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
662 queryText = ActivePortal->sourceText;
664 /* Try to locate the prosrc in the original text */
665 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
667 if (newerrposition > 0)
669 /* Successful, so fix error position to reference original query */
670 errposition(newerrposition);
671 /* Get rid of any report of the error as an "internal query" */
672 internalerrposition(0);
673 internalerrquery(NULL);
678 * If unsuccessful, convert the position to an internal position
679 * marker and give the function text as the internal query.
682 internalerrposition(origerrposition);
683 internalerrquery(prosrc);
690 * Try to locate the string literal containing the function body in the
691 * given text of the CREATE FUNCTION command. If successful, return the
692 * character (not byte) index within the command corresponding to the
693 * given character index within the literal. If not successful, return 0.
696 match_prosrc_to_query(const char *prosrc, const char *queryText,
700 * Rather than fully parsing the CREATE FUNCTION command, we just scan
701 * the command looking for $prosrc$ or 'prosrc'. This could be fooled
702 * (though not in any very probable scenarios), so fail if we find
703 * more than one match.
705 int prosrclen = strlen(prosrc);
706 int querylen = strlen(queryText);
711 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
713 if (queryText[curpos] == '$' &&
714 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
715 queryText[curpos + 1 + prosrclen] == '$')
718 * Found a $foo$ match. Since there are no embedded quoting
719 * characters in a dollar-quoted literal, we don't have to do
720 * any fancy arithmetic; just offset by the starting position.
723 return 0; /* multiple matches, fail */
724 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
727 else if (queryText[curpos] == '\'' &&
728 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
729 cursorpos, &newcursorpos))
732 * Found a 'foo' match. match_prosrc_to_literal() has
733 * adjusted for any quotes or backslashes embedded in the
737 return 0; /* multiple matches, fail */
738 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
747 * Try to match the given source text to a single-quoted literal.
748 * If successful, adjust newcursorpos to correspond to the character
749 * (not byte) index corresponding to cursorpos in the source text.
751 * At entry, literal points just past a ' character. We must check for the
755 match_prosrc_to_literal(const char *prosrc, const char *literal,
756 int cursorpos, int *newcursorpos)
758 int newcp = cursorpos;
762 * This implementation handles backslashes and doubled quotes in the
763 * string literal. It does not handle the SQL syntax for literals
764 * continued across line boundaries.
766 * We do the comparison a character at a time, not a byte at a time, so
767 * that we can do the correct cursorpos math.
771 cursorpos--; /* characters left before cursor */
774 * Check for backslashes and doubled quotes in the literal; adjust
775 * newcp when one is found before the cursor.
777 if (*literal == '\\')
783 else if (*literal == '\'')
785 if (literal[1] != '\'')
791 chlen = pg_mblen(prosrc);
792 if (strncmp(prosrc, literal, chlen) != 0)
798 *newcursorpos = newcp;
800 if (*literal == '\'' && literal[1] != '\'')