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.125 2005/03/29 19:44:23 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/catname.h"
19 #include "catalog/dependency.h"
20 #include "catalog/indexing.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "executor/functions.h"
24 #include "miscadmin.h"
25 #include "mb/pg_wchar.h"
26 #include "parser/parse_type.h"
27 #include "tcop/pquery.h"
28 #include "tcop/tcopprot.h"
29 #include "utils/acl.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/syscache.h"
36 bool check_function_bodies = true;
39 Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
40 Datum fmgr_c_validator(PG_FUNCTION_ARGS);
41 Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
43 static Datum create_parameternames_array(int parameterCount,
44 const char *parameterNames[]);
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 /* ----------------------------------------------------------------
54 * ----------------------------------------------------------------
57 ProcedureCreate(const char *procedureName,
63 Oid languageValidator,
67 bool security_definer,
71 const Oid *parameterTypes,
72 const char *parameterNames[])
78 char nulls[Natts_pg_proc];
79 Datum values[Natts_pg_proc];
80 char replaces[Natts_pg_proc];
81 oidvector *proargtypes;
94 Assert(PointerIsValid(prosrc));
95 Assert(PointerIsValid(probin));
97 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
99 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
100 errmsg("functions cannot have more than %d arguments",
104 * Do not allow return type ANYARRAY or ANYELEMENT unless at least one
105 * argument is also ANYARRAY or ANYELEMENT
107 if (returnType == ANYARRAYOID || returnType == ANYELEMENTOID)
109 bool genericParam = false;
111 for (i = 0; i < parameterCount; i++)
113 if (parameterTypes[i] == ANYARRAYOID ||
114 parameterTypes[i] == ANYELEMENTOID)
123 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
124 errmsg("cannot determine result data type"),
125 errdetail("A function returning \"anyarray\" or \"anyelement\" must have at least one argument of either type.")));
128 /* Convert param types to oidvector */
129 /* (Probably we should make caller pass it this way to start with) */
130 proargtypes = buildoidvector(parameterTypes, parameterCount);
132 /* Process param names, if given */
133 namesarray = create_parameternames_array(parameterCount, parameterNames);
136 * don't allow functions of complex types that have the same name as
137 * existing attributes of the type
139 if (parameterCount == 1 && OidIsValid(parameterTypes[0]) &&
140 (relid = typeidTypeRelid(parameterTypes[0])) != InvalidOid &&
141 get_attnum(relid, procedureName) != InvalidAttrNumber)
143 (errcode(ERRCODE_DUPLICATE_COLUMN),
144 errmsg("\"%s\" is already an attribute of type %s",
145 procedureName, format_type_be(parameterTypes[0]))));
148 * All seems OK; prepare the data to be inserted into pg_proc.
151 for (i = 0; i < Natts_pg_proc; ++i)
154 values[i] = (Datum) 0;
158 namestrcpy(&procname, procedureName);
159 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
160 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
161 values[Anum_pg_proc_proowner - 1] = Int32GetDatum(GetUserId());
162 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
163 values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
164 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
165 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
166 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
167 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
168 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
169 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
170 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(proargtypes);
171 /* XXX for now, just null out the new columns */
172 nulls[Anum_pg_proc_proallargtypes - 1] = 'n';
173 nulls[Anum_pg_proc_proargmodes - 1] = 'n';
174 if (namesarray != PointerGetDatum(NULL))
175 values[Anum_pg_proc_proargnames - 1] = namesarray;
177 nulls[Anum_pg_proc_proargnames - 1] = 'n';
178 values[Anum_pg_proc_prosrc - 1] = DirectFunctionCall1(textin,
179 CStringGetDatum(prosrc));
180 values[Anum_pg_proc_probin - 1] = DirectFunctionCall1(textin,
181 CStringGetDatum(probin));
182 /* start out with empty permissions */
183 nulls[Anum_pg_proc_proacl - 1] = 'n';
185 rel = heap_openr(ProcedureRelationName, RowExclusiveLock);
186 tupDesc = RelationGetDescr(rel);
188 /* Check for pre-existing definition */
189 oldtup = SearchSysCache(PROCNAMEARGSNSP,
190 PointerGetDatum(procedureName),
191 PointerGetDatum(proargtypes),
192 ObjectIdGetDatum(procNamespace),
195 if (HeapTupleIsValid(oldtup))
197 /* There is one; okay to replace it? */
198 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
202 (errcode(ERRCODE_DUPLICATE_FUNCTION),
203 errmsg("function \"%s\" already exists with same argument types",
205 if (GetUserId() != oldproc->proowner && !superuser())
206 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
210 * Not okay to change the return type of the existing proc, since
211 * existing rules, views, etc may depend on the return type.
213 if (returnType != oldproc->prorettype ||
214 returnsSet != oldproc->proretset)
216 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
217 errmsg("cannot change return type of existing function"),
218 errhint("Use DROP FUNCTION first.")));
220 /* Can't change aggregate status, either */
221 if (oldproc->proisagg != isAgg)
223 if (oldproc->proisagg)
225 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
226 errmsg("function \"%s\" is an aggregate",
230 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
231 errmsg("function \"%s\" is not an aggregate",
235 /* do not change existing ownership or permissions, either */
236 replaces[Anum_pg_proc_proowner - 1] = ' ';
237 replaces[Anum_pg_proc_proacl - 1] = ' ';
240 tup = heap_modifytuple(oldtup, tupDesc, values, nulls, replaces);
241 simple_heap_update(rel, &tup->t_self, tup);
243 ReleaseSysCache(oldtup);
248 /* Creating a new procedure */
249 tup = heap_formtuple(tupDesc, values, nulls);
250 simple_heap_insert(rel, tup);
254 /* Need to update indexes for either the insert or update case */
255 CatalogUpdateIndexes(rel, tup);
257 retval = HeapTupleGetOid(tup);
260 * Create dependencies for the new function. If we are updating an
261 * existing function, first delete any existing pg_depend entries.
264 deleteDependencyRecordsFor(RelOid_pg_proc, retval);
266 myself.classId = RelOid_pg_proc;
267 myself.objectId = retval;
268 myself.objectSubId = 0;
270 /* dependency on namespace */
271 referenced.classId = get_system_catalog_relid(NamespaceRelationName);
272 referenced.objectId = procNamespace;
273 referenced.objectSubId = 0;
274 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
276 /* dependency on implementation language */
277 referenced.classId = get_system_catalog_relid(LanguageRelationName);
278 referenced.objectId = languageObjectId;
279 referenced.objectSubId = 0;
280 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
282 /* dependency on return type */
283 referenced.classId = RelOid_pg_type;
284 referenced.objectId = returnType;
285 referenced.objectSubId = 0;
286 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
288 /* dependency on input types */
289 for (i = 0; i < parameterCount; i++)
291 referenced.classId = RelOid_pg_type;
292 referenced.objectId = parameterTypes[i];
293 referenced.objectSubId = 0;
294 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
299 heap_close(rel, RowExclusiveLock);
301 /* Verify function body */
302 if (OidIsValid(languageValidator))
304 /* Advance command counter so new tuple can be seen by validator */
305 CommandCounterIncrement();
306 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
314 * create_parameternames_array - build proargnames value from an array
315 * of C strings. Returns a NULL pointer if no names provided.
318 create_parameternames_array(int parameterCount, const char *parameterNames[])
320 Datum elems[FUNC_MAX_ARGS];
326 return PointerGetDatum(NULL);
328 for (i = 0; i < parameterCount; i++)
330 const char *s = parameterNames[i];
337 elems[i] = DirectFunctionCall1(textin, CStringGetDatum(s));
341 return PointerGetDatum(NULL);
343 names = construct_array(elems, parameterCount, TEXTOID, -1, false, 'i');
345 return PointerGetDatum(names);
351 * Validator for internal functions
353 * Check that the given internal function name (the "prosrc" value) is
354 * a known builtin function.
357 fmgr_internal_validator(PG_FUNCTION_ARGS)
359 Oid funcoid = PG_GETARG_OID(0);
367 * We do not honor check_function_bodies since it's unlikely the
368 * function name will be found later if it isn't there now.
371 tuple = SearchSysCache(PROCOID,
372 ObjectIdGetDatum(funcoid),
374 if (!HeapTupleIsValid(tuple))
375 elog(ERROR, "cache lookup failed for function %u", funcoid);
376 proc = (Form_pg_proc) GETSTRUCT(tuple);
378 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
380 elog(ERROR, "null prosrc");
381 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
383 if (fmgr_internal_function(prosrc) == InvalidOid)
385 (errcode(ERRCODE_UNDEFINED_FUNCTION),
386 errmsg("there is no built-in function named \"%s\"",
389 ReleaseSysCache(tuple);
397 * Validator for C language functions
399 * Make sure that the library file exists, is loadable, and contains
400 * the specified link symbol. Also check for a valid function
401 * information record.
404 fmgr_c_validator(PG_FUNCTION_ARGS)
406 Oid funcoid = PG_GETARG_OID(0);
416 * It'd be most consistent to skip the check if
417 * !check_function_bodies, but the purpose of that switch is to be
418 * helpful for pg_dump loading, and for pg_dump loading it's much
419 * better if we *do* check.
422 tuple = SearchSysCache(PROCOID,
423 ObjectIdGetDatum(funcoid),
425 if (!HeapTupleIsValid(tuple))
426 elog(ERROR, "cache lookup failed for function %u", funcoid);
427 proc = (Form_pg_proc) GETSTRUCT(tuple);
429 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
431 elog(ERROR, "null prosrc");
432 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
434 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
436 elog(ERROR, "null probin");
437 probin = DatumGetCString(DirectFunctionCall1(textout, tmp));
439 (void) load_external_function(probin, prosrc, true, &libraryhandle);
440 (void) fetch_finfo_record(libraryhandle, prosrc);
442 ReleaseSysCache(tuple);
449 * Validator for SQL language functions
451 * Parse it here in order to be sure that it contains no syntax errors.
454 fmgr_sql_validator(PG_FUNCTION_ARGS)
456 Oid funcoid = PG_GETARG_OID(0);
459 List *querytree_list;
463 ErrorContextCallback sqlerrcontext;
468 tuple = SearchSysCache(PROCOID,
469 ObjectIdGetDatum(funcoid),
471 if (!HeapTupleIsValid(tuple))
472 elog(ERROR, "cache lookup failed for function %u", funcoid);
473 proc = (Form_pg_proc) GETSTRUCT(tuple);
475 functyptype = get_typtype(proc->prorettype);
477 /* Disallow pseudotype result */
478 /* except for RECORD, VOID, ANYARRAY, or ANYELEMENT */
479 if (functyptype == 'p' &&
480 proc->prorettype != RECORDOID &&
481 proc->prorettype != VOIDOID &&
482 proc->prorettype != ANYARRAYOID &&
483 proc->prorettype != ANYELEMENTOID)
485 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
486 errmsg("SQL functions cannot return type %s",
487 format_type_be(proc->prorettype))));
489 /* Disallow pseudotypes in arguments */
490 /* except for ANYARRAY or ANYELEMENT */
492 for (i = 0; i < proc->pronargs; i++)
494 if (get_typtype(proc->proargtypes.values[i]) == 'p')
496 if (proc->proargtypes.values[i] == ANYARRAYOID ||
497 proc->proargtypes.values[i] == ANYELEMENTOID)
501 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
502 errmsg("SQL functions cannot have arguments of type %s",
503 format_type_be(proc->proargtypes.values[i]))));
507 /* Postpone body checks if !check_function_bodies */
508 if (check_function_bodies)
510 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
512 elog(ERROR, "null prosrc");
514 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
517 * Setup error traceback support for ereport().
519 sqlerrcontext.callback = sql_function_parse_error_callback;
520 sqlerrcontext.arg = tuple;
521 sqlerrcontext.previous = error_context_stack;
522 error_context_stack = &sqlerrcontext;
525 * We can't do full prechecking of the function definition if
526 * there are any polymorphic input types, because actual datatypes
527 * of expression results will be unresolvable. The check will be
528 * done at runtime instead.
530 * We can run the text through the raw parser though; this will at
531 * least catch silly syntactic errors.
535 querytree_list = pg_parse_and_rewrite(prosrc,
536 proc->proargtypes.values,
538 (void) check_sql_fn_retval(proc->prorettype, functyptype,
539 querytree_list, NULL);
542 querytree_list = pg_parse_query(prosrc);
544 error_context_stack = sqlerrcontext.previous;
547 ReleaseSysCache(tuple);
553 * Error context callback for handling errors in SQL function definitions
556 sql_function_parse_error_callback(void *arg)
558 HeapTuple tuple = (HeapTuple) arg;
559 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
564 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
565 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
567 elog(ERROR, "null prosrc");
568 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
570 if (!function_parse_error_transpose(prosrc))
572 /* If it's not a syntax error, push info onto context stack */
573 errcontext("SQL function \"%s\"", NameStr(proc->proname));
580 * Adjust a syntax error occurring inside the function body of a CREATE
581 * FUNCTION command. This can be used by any function validator, not only
582 * for SQL-language functions. It is assumed that the syntax error position
583 * is initially relative to the function body string (as passed in). If
584 * possible, we adjust the position to reference the original CREATE command;
585 * if we can't manage that, we set up an "internal query" syntax error instead.
587 * Returns true if a syntax error was processed, false if not.
590 function_parse_error_transpose(const char *prosrc)
594 const char *queryText;
597 * Nothing to do unless we are dealing with a syntax error that has a
600 * Some PLs may prefer to report the error position as an internal error
601 * to begin with, so check that too.
603 origerrposition = geterrposition();
604 if (origerrposition <= 0)
606 origerrposition = getinternalerrposition();
607 if (origerrposition <= 0)
611 /* We can get the original query text from the active portal (hack...) */
612 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
613 queryText = ActivePortal->sourceText;
615 /* Try to locate the prosrc in the original text */
616 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
618 if (newerrposition > 0)
620 /* Successful, so fix error position to reference original query */
621 errposition(newerrposition);
622 /* Get rid of any report of the error as an "internal query" */
623 internalerrposition(0);
624 internalerrquery(NULL);
629 * If unsuccessful, convert the position to an internal position
630 * marker and give the function text as the internal query.
633 internalerrposition(origerrposition);
634 internalerrquery(prosrc);
641 * Try to locate the string literal containing the function body in the
642 * given text of the CREATE FUNCTION command. If successful, return the
643 * character (not byte) index within the command corresponding to the
644 * given character index within the literal. If not successful, return 0.
647 match_prosrc_to_query(const char *prosrc, const char *queryText,
651 * Rather than fully parsing the CREATE FUNCTION command, we just scan
652 * the command looking for $prosrc$ or 'prosrc'. This could be fooled
653 * (though not in any very probable scenarios), so fail if we find
654 * more than one match.
656 int prosrclen = strlen(prosrc);
657 int querylen = strlen(queryText);
662 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
664 if (queryText[curpos] == '$' &&
665 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
666 queryText[curpos + 1 + prosrclen] == '$')
669 * Found a $foo$ match. Since there are no embedded quoting
670 * characters in a dollar-quoted literal, we don't have to do
671 * any fancy arithmetic; just offset by the starting position.
674 return 0; /* multiple matches, fail */
675 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
678 else if (queryText[curpos] == '\'' &&
679 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
680 cursorpos, &newcursorpos))
683 * Found a 'foo' match. match_prosrc_to_literal() has
684 * adjusted for any quotes or backslashes embedded in the
688 return 0; /* multiple matches, fail */
689 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
698 * Try to match the given source text to a single-quoted literal.
699 * If successful, adjust newcursorpos to correspond to the character
700 * (not byte) index corresponding to cursorpos in the source text.
702 * At entry, literal points just past a ' character. We must check for the
706 match_prosrc_to_literal(const char *prosrc, const char *literal,
707 int cursorpos, int *newcursorpos)
709 int newcp = cursorpos;
713 * This implementation handles backslashes and doubled quotes in the
714 * string literal. It does not handle the SQL syntax for literals
715 * continued across line boundaries.
717 * We do the comparison a character at a time, not a byte at a time, so
718 * that we can do the correct cursorpos math.
722 cursorpos--; /* characters left before cursor */
725 * Check for backslashes and doubled quotes in the literal; adjust
726 * newcp when one is found before the cursor.
728 if (*literal == '\\')
734 else if (*literal == '\'')
736 if (literal[1] != '\'')
742 chlen = pg_mblen(prosrc);
743 if (strncmp(prosrc, literal, chlen) != 0)
749 *newcursorpos = newcp;
751 if (*literal == '\'' && literal[1] != '\'')