1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2009, 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.164 2009/06/11 14:48:55 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "access/xact.h"
19 #include "catalog/dependency.h"
20 #include "catalog/indexing.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/syscache.h"
40 Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
41 Datum fmgr_c_validator(PG_FUNCTION_ARGS);
42 Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
44 static void sql_function_parse_error_callback(void *arg);
45 static int match_prosrc_to_query(const char *prosrc, const char *queryText,
47 static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
48 int cursorpos, int *newcursorpos);
51 /* ----------------------------------------------------------------
54 * Note: allParameterTypes, parameterModes, parameterNames, and proconfig
55 * are either arrays of the proper types or NULL. We declare them Datum,
56 * not "ArrayType *", to avoid importing array.h into pg_proc_fn.h.
57 * ----------------------------------------------------------------
60 ProcedureCreate(const char *procedureName,
66 Oid languageValidator,
71 bool security_definer,
74 oidvector *parameterTypes,
75 Datum allParameterTypes,
78 List *parameterDefaults,
87 bool genericInParam = false;
88 bool genericOutParam = false;
89 bool internalInParam = false;
90 bool internalOutParam = false;
91 Oid variadicType = InvalidOid;
95 bool nulls[Natts_pg_proc];
96 Datum values[Natts_pg_proc];
97 bool replaces[Natts_pg_proc];
102 ObjectAddress myself,
109 Assert(PointerIsValid(prosrc));
111 parameterCount = parameterTypes->dim1;
112 if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
114 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
115 errmsg_plural("functions cannot have more than %d argument",
116 "functions cannot have more than %d arguments",
119 /* note: the above is correct, we do NOT count output arguments */
121 if (allParameterTypes != PointerGetDatum(NULL))
124 * We expect the array to be a 1-D OID array; verify that. We don't
125 * need to use deconstruct_array() since the array data is just going
126 * to look like a C array of OID values.
128 ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
130 allParamCount = ARR_DIMS(allParamArray)[0];
131 if (ARR_NDIM(allParamArray) != 1 ||
132 allParamCount <= 0 ||
133 ARR_HASNULL(allParamArray) ||
134 ARR_ELEMTYPE(allParamArray) != OIDOID)
135 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
136 allParams = (Oid *) ARR_DATA_PTR(allParamArray);
137 Assert(allParamCount >= parameterCount);
138 /* we assume caller got the contents right */
142 allParamCount = parameterCount;
143 allParams = parameterTypes->values;
147 * Do not allow polymorphic return type unless at least one input argument
148 * is polymorphic. Also, do not allow return type INTERNAL unless at
149 * least one input argument is INTERNAL.
151 for (i = 0; i < parameterCount; i++)
153 switch (parameterTypes->values[i])
159 genericInParam = true;
162 internalInParam = true;
167 if (allParameterTypes != PointerGetDatum(NULL))
169 for (i = 0; i < allParamCount; i++)
172 * We don't bother to distinguish input and output params here, so
173 * if there is, say, just an input INTERNAL param then we will
174 * still set internalOutParam. This is OK since we don't really
177 switch (allParams[i])
183 genericOutParam = true;
186 internalOutParam = true;
192 if ((IsPolymorphicType(returnType) || genericOutParam)
195 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
196 errmsg("cannot determine result data type"),
197 errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
199 if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
201 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
202 errmsg("unsafe use of pseudo-type \"internal\""),
203 errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
206 * don't allow functions of complex types that have the same name as
207 * existing attributes of the type
209 if (parameterCount == 1 &&
210 OidIsValid(parameterTypes->values[0]) &&
211 (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
212 get_attnum(relid, procedureName) != InvalidAttrNumber)
214 (errcode(ERRCODE_DUPLICATE_COLUMN),
215 errmsg("\"%s\" is already an attribute of type %s",
217 format_type_be(parameterTypes->values[0]))));
219 if (parameterModes != PointerGetDatum(NULL))
222 * We expect the array to be a 1-D CHAR array; verify that. We don't
223 * need to use deconstruct_array() since the array data is just going
224 * to look like a C array of char values.
226 ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
229 if (ARR_NDIM(modesArray) != 1 ||
230 ARR_DIMS(modesArray)[0] != allParamCount ||
231 ARR_HASNULL(modesArray) ||
232 ARR_ELEMTYPE(modesArray) != CHAROID)
233 elog(ERROR, "parameterModes is not a 1-D char array");
234 modes = (char *) ARR_DATA_PTR(modesArray);
237 * Only the last input parameter can be variadic; if it is, save its
238 * element type. Errors here are just elog since caller should have
239 * checked this already.
241 for (i = 0; i < allParamCount; i++)
246 case PROARGMODE_INOUT:
247 if (OidIsValid(variadicType))
248 elog(ERROR, "variadic parameter must be last");
251 case PROARGMODE_TABLE:
254 case PROARGMODE_VARIADIC:
255 if (OidIsValid(variadicType))
256 elog(ERROR, "variadic parameter must be last");
257 switch (allParams[i])
260 variadicType = ANYOID;
263 variadicType = ANYELEMENTOID;
266 variadicType = get_element_type(allParams[i]);
267 if (!OidIsValid(variadicType))
268 elog(ERROR, "variadic parameter is not an array");
273 elog(ERROR, "invalid parameter mode '%c'", modes[i]);
280 * All seems OK; prepare the data to be inserted into pg_proc.
283 for (i = 0; i < Natts_pg_proc; ++i)
286 values[i] = (Datum) 0;
290 namestrcpy(&procname, procedureName);
291 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
292 values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
293 values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(GetUserId());
294 values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
295 values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
296 values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
297 values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
298 values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
299 values[Anum_pg_proc_proiswindow - 1] = BoolGetDatum(isWindowFunc);
300 values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
301 values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
302 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
303 values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
304 values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
305 values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
306 values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
307 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
308 if (allParameterTypes != PointerGetDatum(NULL))
309 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
311 nulls[Anum_pg_proc_proallargtypes - 1] = true;
312 if (parameterModes != PointerGetDatum(NULL))
313 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
315 nulls[Anum_pg_proc_proargmodes - 1] = true;
316 if (parameterNames != PointerGetDatum(NULL))
317 values[Anum_pg_proc_proargnames - 1] = parameterNames;
319 nulls[Anum_pg_proc_proargnames - 1] = true;
320 if (parameterDefaults != NIL)
321 values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
323 nulls[Anum_pg_proc_proargdefaults - 1] = true;
324 values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
326 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
328 nulls[Anum_pg_proc_probin - 1] = true;
329 if (proconfig != PointerGetDatum(NULL))
330 values[Anum_pg_proc_proconfig - 1] = proconfig;
332 nulls[Anum_pg_proc_proconfig - 1] = true;
333 /* start out with empty permissions */
334 nulls[Anum_pg_proc_proacl - 1] = true;
336 rel = heap_open(ProcedureRelationId, RowExclusiveLock);
337 tupDesc = RelationGetDescr(rel);
339 /* Check for pre-existing definition */
340 oldtup = SearchSysCache(PROCNAMEARGSNSP,
341 PointerGetDatum(procedureName),
342 PointerGetDatum(parameterTypes),
343 ObjectIdGetDatum(procNamespace),
346 if (HeapTupleIsValid(oldtup))
348 /* There is one; okay to replace it? */
349 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
353 (errcode(ERRCODE_DUPLICATE_FUNCTION),
354 errmsg("function \"%s\" already exists with same argument types",
356 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), GetUserId()))
357 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
361 * Not okay to change the return type of the existing proc, since
362 * existing rules, views, etc may depend on the return type.
364 if (returnType != oldproc->prorettype ||
365 returnsSet != oldproc->proretset)
367 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
368 errmsg("cannot change return type of existing function"),
369 errhint("Use DROP FUNCTION first.")));
372 * If it returns RECORD, check for possible change of record type
373 * implied by OUT parameters
375 if (returnType == RECORDOID)
380 olddesc = build_function_result_tupdesc_t(oldtup);
381 newdesc = build_function_result_tupdesc_d(allParameterTypes,
384 if (olddesc == NULL && newdesc == NULL)
385 /* ok, both are runtime-defined RECORDs */ ;
386 else if (olddesc == NULL || newdesc == NULL ||
387 !equalTupleDescs(olddesc, newdesc))
389 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
390 errmsg("cannot change return type of existing function"),
391 errdetail("Row type defined by OUT parameters is different."),
392 errhint("Use DROP FUNCTION first.")));
396 * If there are existing defaults, check compatibility: redefinition
397 * must not remove any defaults nor change their types. (Removing a
398 * default might cause a function to fail to satisfy an existing call.
399 * Changing type would only be possible if the associated parameter is
400 * polymorphic, and in such cases a change of default type might alter
401 * the resolved output type of existing calls.)
403 if (oldproc->pronargdefaults != 0)
405 Datum proargdefaults;
411 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
413 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
414 errmsg("cannot remove parameter defaults from existing function"),
415 errhint("Use DROP FUNCTION first.")));
417 proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
418 Anum_pg_proc_proargdefaults,
421 oldDefaults = (List *) stringToNode(TextDatumGetCString(proargdefaults));
422 Assert(IsA(oldDefaults, List));
423 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
425 /* new list can have more defaults than old, advance over 'em */
426 newlc = list_head(parameterDefaults);
427 for (i = list_length(parameterDefaults) - oldproc->pronargdefaults;
430 newlc = lnext(newlc);
432 foreach(oldlc, oldDefaults)
434 Node *oldDef = (Node *) lfirst(oldlc);
435 Node *newDef = (Node *) lfirst(newlc);
437 if (exprType(oldDef) != exprType(newDef))
439 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
440 errmsg("cannot change data type of existing parameter default value"),
441 errhint("Use DROP FUNCTION first.")));
442 newlc = lnext(newlc);
446 /* Can't change aggregate or window-function status, either */
447 if (oldproc->proisagg != isAgg)
449 if (oldproc->proisagg)
451 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
452 errmsg("function \"%s\" is an aggregate function",
456 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
457 errmsg("function \"%s\" is not an aggregate function",
460 if (oldproc->proiswindow != isWindowFunc)
462 if (oldproc->proiswindow)
464 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
465 errmsg("function \"%s\" is a window function",
469 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
470 errmsg("function \"%s\" is not a window function",
474 /* do not change existing ownership or permissions, either */
475 replaces[Anum_pg_proc_proowner - 1] = false;
476 replaces[Anum_pg_proc_proacl - 1] = false;
479 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
480 simple_heap_update(rel, &tup->t_self, tup);
482 ReleaseSysCache(oldtup);
487 /* Creating a new procedure */
488 tup = heap_form_tuple(tupDesc, values, nulls);
489 simple_heap_insert(rel, tup);
493 /* Need to update indexes for either the insert or update case */
494 CatalogUpdateIndexes(rel, tup);
496 retval = HeapTupleGetOid(tup);
499 * Create dependencies for the new function. If we are updating an
500 * existing function, first delete any existing pg_depend entries.
504 deleteDependencyRecordsFor(ProcedureRelationId, retval);
505 deleteSharedDependencyRecordsFor(ProcedureRelationId, retval, 0);
508 myself.classId = ProcedureRelationId;
509 myself.objectId = retval;
510 myself.objectSubId = 0;
512 /* dependency on namespace */
513 referenced.classId = NamespaceRelationId;
514 referenced.objectId = procNamespace;
515 referenced.objectSubId = 0;
516 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
518 /* dependency on implementation language */
519 referenced.classId = LanguageRelationId;
520 referenced.objectId = languageObjectId;
521 referenced.objectSubId = 0;
522 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
524 /* dependency on return type */
525 referenced.classId = TypeRelationId;
526 referenced.objectId = returnType;
527 referenced.objectSubId = 0;
528 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
530 /* dependency on parameter types */
531 for (i = 0; i < allParamCount; i++)
533 referenced.classId = TypeRelationId;
534 referenced.objectId = allParams[i];
535 referenced.objectSubId = 0;
536 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
539 /* dependency on owner */
540 recordDependencyOnOwner(ProcedureRelationId, retval, GetUserId());
544 heap_close(rel, RowExclusiveLock);
546 /* Verify function body */
547 if (OidIsValid(languageValidator))
549 /* Advance command counter so new tuple can be seen by validator */
550 CommandCounterIncrement();
551 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
560 * Validator for internal functions
562 * Check that the given internal function name (the "prosrc" value) is
563 * a known builtin function.
566 fmgr_internal_validator(PG_FUNCTION_ARGS)
568 Oid funcoid = PG_GETARG_OID(0);
576 * We do not honor check_function_bodies since it's unlikely the function
577 * name will be found later if it isn't there now.
580 tuple = SearchSysCache(PROCOID,
581 ObjectIdGetDatum(funcoid),
583 if (!HeapTupleIsValid(tuple))
584 elog(ERROR, "cache lookup failed for function %u", funcoid);
585 proc = (Form_pg_proc) GETSTRUCT(tuple);
587 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
589 elog(ERROR, "null prosrc");
590 prosrc = TextDatumGetCString(tmp);
592 if (fmgr_internal_function(prosrc) == InvalidOid)
594 (errcode(ERRCODE_UNDEFINED_FUNCTION),
595 errmsg("there is no built-in function named \"%s\"",
598 ReleaseSysCache(tuple);
606 * Validator for C language functions
608 * Make sure that the library file exists, is loadable, and contains
609 * the specified link symbol. Also check for a valid function
610 * information record.
613 fmgr_c_validator(PG_FUNCTION_ARGS)
615 Oid funcoid = PG_GETARG_OID(0);
625 * It'd be most consistent to skip the check if !check_function_bodies,
626 * but the purpose of that switch is to be helpful for pg_dump loading,
627 * and for pg_dump loading it's much better if we *do* check.
630 tuple = SearchSysCache(PROCOID,
631 ObjectIdGetDatum(funcoid),
633 if (!HeapTupleIsValid(tuple))
634 elog(ERROR, "cache lookup failed for function %u", funcoid);
635 proc = (Form_pg_proc) GETSTRUCT(tuple);
637 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
639 elog(ERROR, "null prosrc for C function %u", funcoid);
640 prosrc = TextDatumGetCString(tmp);
642 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
644 elog(ERROR, "null probin for C function %u", funcoid);
645 probin = TextDatumGetCString(tmp);
647 (void) load_external_function(probin, prosrc, true, &libraryhandle);
648 (void) fetch_finfo_record(libraryhandle, prosrc);
650 ReleaseSysCache(tuple);
657 * Validator for SQL language functions
659 * Parse it here in order to be sure that it contains no syntax errors.
662 fmgr_sql_validator(PG_FUNCTION_ARGS)
664 Oid funcoid = PG_GETARG_OID(0);
667 List *querytree_list;
671 ErrorContextCallback sqlerrcontext;
675 tuple = SearchSysCache(PROCOID,
676 ObjectIdGetDatum(funcoid),
678 if (!HeapTupleIsValid(tuple))
679 elog(ERROR, "cache lookup failed for function %u", funcoid);
680 proc = (Form_pg_proc) GETSTRUCT(tuple);
682 /* Disallow pseudotype result */
683 /* except for RECORD, VOID, or polymorphic */
684 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
685 proc->prorettype != RECORDOID &&
686 proc->prorettype != VOIDOID &&
687 !IsPolymorphicType(proc->prorettype))
689 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
690 errmsg("SQL functions cannot return type %s",
691 format_type_be(proc->prorettype))));
693 /* Disallow pseudotypes in arguments */
694 /* except for polymorphic */
696 for (i = 0; i < proc->pronargs; i++)
698 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
700 if (IsPolymorphicType(proc->proargtypes.values[i]))
704 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
705 errmsg("SQL functions cannot have arguments of type %s",
706 format_type_be(proc->proargtypes.values[i]))));
710 /* Postpone body checks if !check_function_bodies */
711 if (check_function_bodies)
713 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
715 elog(ERROR, "null prosrc");
717 prosrc = TextDatumGetCString(tmp);
720 * Setup error traceback support for ereport().
722 sqlerrcontext.callback = sql_function_parse_error_callback;
723 sqlerrcontext.arg = tuple;
724 sqlerrcontext.previous = error_context_stack;
725 error_context_stack = &sqlerrcontext;
728 * We can't do full prechecking of the function definition if there
729 * are any polymorphic input types, because actual datatypes of
730 * expression results will be unresolvable. The check will be done at
733 * We can run the text through the raw parser though; this will at
734 * least catch silly syntactic errors.
738 querytree_list = pg_parse_and_rewrite(prosrc,
739 proc->proargtypes.values,
741 (void) check_sql_fn_retval(funcoid, proc->prorettype,
746 querytree_list = pg_parse_query(prosrc);
748 error_context_stack = sqlerrcontext.previous;
751 ReleaseSysCache(tuple);
757 * Error context callback for handling errors in SQL function definitions
760 sql_function_parse_error_callback(void *arg)
762 HeapTuple tuple = (HeapTuple) arg;
763 Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
768 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
769 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
771 elog(ERROR, "null prosrc");
772 prosrc = TextDatumGetCString(tmp);
774 if (!function_parse_error_transpose(prosrc))
776 /* If it's not a syntax error, push info onto context stack */
777 errcontext("SQL function \"%s\"", NameStr(proc->proname));
784 * Adjust a syntax error occurring inside the function body of a CREATE
785 * FUNCTION command. This can be used by any function validator, not only
786 * for SQL-language functions. It is assumed that the syntax error position
787 * is initially relative to the function body string (as passed in). If
788 * possible, we adjust the position to reference the original CREATE command;
789 * if we can't manage that, we set up an "internal query" syntax error instead.
791 * Returns true if a syntax error was processed, false if not.
794 function_parse_error_transpose(const char *prosrc)
798 const char *queryText;
801 * Nothing to do unless we are dealing with a syntax error that has a
804 * Some PLs may prefer to report the error position as an internal error
805 * to begin with, so check that too.
807 origerrposition = geterrposition();
808 if (origerrposition <= 0)
810 origerrposition = getinternalerrposition();
811 if (origerrposition <= 0)
815 /* We can get the original query text from the active portal (hack...) */
816 Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
817 queryText = ActivePortal->sourceText;
819 /* Try to locate the prosrc in the original text */
820 newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
822 if (newerrposition > 0)
824 /* Successful, so fix error position to reference original query */
825 errposition(newerrposition);
826 /* Get rid of any report of the error as an "internal query" */
827 internalerrposition(0);
828 internalerrquery(NULL);
833 * If unsuccessful, convert the position to an internal position
834 * marker and give the function text as the internal query.
837 internalerrposition(origerrposition);
838 internalerrquery(prosrc);
845 * Try to locate the string literal containing the function body in the
846 * given text of the CREATE FUNCTION command. If successful, return the
847 * character (not byte) index within the command corresponding to the
848 * given character index within the literal. If not successful, return 0.
851 match_prosrc_to_query(const char *prosrc, const char *queryText,
855 * Rather than fully parsing the CREATE FUNCTION command, we just scan the
856 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
857 * not in any very probable scenarios), so fail if we find more than one
860 int prosrclen = strlen(prosrc);
861 int querylen = strlen(queryText);
866 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
868 if (queryText[curpos] == '$' &&
869 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
870 queryText[curpos + 1 + prosrclen] == '$')
873 * Found a $foo$ match. Since there are no embedded quoting
874 * characters in a dollar-quoted literal, we don't have to do any
875 * fancy arithmetic; just offset by the starting position.
878 return 0; /* multiple matches, fail */
879 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
882 else if (queryText[curpos] == '\'' &&
883 match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
884 cursorpos, &newcursorpos))
887 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
888 * for any quotes or backslashes embedded in the literal.
891 return 0; /* multiple matches, fail */
892 matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
901 * Try to match the given source text to a single-quoted literal.
902 * If successful, adjust newcursorpos to correspond to the character
903 * (not byte) index corresponding to cursorpos in the source text.
905 * At entry, literal points just past a ' character. We must check for the
909 match_prosrc_to_literal(const char *prosrc, const char *literal,
910 int cursorpos, int *newcursorpos)
912 int newcp = cursorpos;
916 * This implementation handles backslashes and doubled quotes in the
917 * string literal. It does not handle the SQL syntax for literals
918 * continued across line boundaries.
920 * We do the comparison a character at a time, not a byte at a time, so
921 * that we can do the correct cursorpos math.
925 cursorpos--; /* characters left before cursor */
928 * Check for backslashes and doubled quotes in the literal; adjust
929 * newcp when one is found before the cursor.
931 if (*literal == '\\')
937 else if (*literal == '\'')
939 if (literal[1] != '\'')
945 chlen = pg_mblen(prosrc);
946 if (strncmp(prosrc, literal, chlen) != 0)
952 if (*literal == '\'' && literal[1] != '\'')
955 *newcursorpos = newcp;
960 /* Must set *newcursorpos to suppress compiler warning */
961 *newcursorpos = newcp;