]> granicus.if.org Git - postgresql/blob - src/backend/catalog/pg_proc.c
37e7ed4343ef2b1fd429376163267f52c07c4de8
[postgresql] / src / backend / catalog / pg_proc.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_proc.c
4  *        routines to support manipulation of the pg_proc relation
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/catalog/pg_proc.c,v 1.152 2008/07/16 16:55:23 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
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"
27 #include "funcapi.h"
28 #include "mb/pg_wchar.h"
29 #include "miscadmin.h"
30 #include "parser/parse_type.h"
31 #include "tcop/pquery.h"
32 #include "tcop/tcopprot.h"
33 #include "utils/acl.h"
34 #include "utils/builtins.h"
35 #include "utils/lsyscache.h"
36 #include "utils/syscache.h"
37
38
39 Datum           fmgr_internal_validator(PG_FUNCTION_ARGS);
40 Datum           fmgr_c_validator(PG_FUNCTION_ARGS);
41 Datum           fmgr_sql_validator(PG_FUNCTION_ARGS);
42
43 static void sql_function_parse_error_callback(void *arg);
44 static int match_prosrc_to_query(const char *prosrc, const char *queryText,
45                                           int cursorpos);
46 static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
47                                                 int cursorpos, int *newcursorpos);
48
49
50 /* ----------------------------------------------------------------
51  *              ProcedureCreate
52  *
53  * Note: allParameterTypes, parameterModes, parameterNames, and proconfig
54  * are either arrays of the proper types or NULL.  We declare them Datum,
55  * not "ArrayType *", to avoid importing array.h into pg_proc.h.
56  * ----------------------------------------------------------------
57  */
58 Oid
59 ProcedureCreate(const char *procedureName,
60                                 Oid procNamespace,
61                                 bool replace,
62                                 bool returnsSet,
63                                 Oid returnType,
64                                 Oid languageObjectId,
65                                 Oid languageValidator,
66                                 const char *prosrc,
67                                 const char *probin,
68                                 bool isAgg,
69                                 bool security_definer,
70                                 bool isStrict,
71                                 char volatility,
72                                 oidvector *parameterTypes,
73                                 Datum allParameterTypes,
74                                 Datum parameterModes,
75                                 Datum parameterNames,
76                                 Datum proconfig,
77                                 float4 procost,
78                                 float4 prorows)
79 {
80         Oid                     retval;
81         int                     parameterCount;
82         int                     allParamCount;
83         Oid                *allParams;
84         bool            genericInParam = false;
85         bool            genericOutParam = false;
86         bool            internalInParam = false;
87         bool            internalOutParam = false;
88         Oid                     variadicType = InvalidOid;
89         Relation        rel;
90         HeapTuple       tup;
91         HeapTuple       oldtup;
92         char            nulls[Natts_pg_proc];
93         Datum           values[Natts_pg_proc];
94         char            replaces[Natts_pg_proc];
95         Oid                     relid;
96         NameData        procname;
97         TupleDesc       tupDesc;
98         bool            is_update;
99         ObjectAddress myself,
100                                 referenced;
101         int                     i;
102
103         /*
104          * sanity checks
105          */
106         Assert(PointerIsValid(prosrc));
107
108         parameterCount = parameterTypes->dim1;
109         if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
110                 ereport(ERROR,
111                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
112                                  errmsg("functions cannot have more than %d arguments",
113                                                 FUNC_MAX_ARGS)));
114         /* note: the above is correct, we do NOT count output arguments */
115
116         if (allParameterTypes != PointerGetDatum(NULL))
117         {
118                 /*
119                  * We expect the array to be a 1-D OID array; verify that. We don't
120                  * need to use deconstruct_array() since the array data is just going
121                  * to look like a C array of OID values.
122                  */
123                 ArrayType  *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
124
125                 allParamCount = ARR_DIMS(allParamArray)[0];
126                 if (ARR_NDIM(allParamArray) != 1 ||
127                         allParamCount <= 0 ||
128                         ARR_HASNULL(allParamArray) ||
129                         ARR_ELEMTYPE(allParamArray) != OIDOID)
130                         elog(ERROR, "allParameterTypes is not a 1-D Oid array");
131                 allParams = (Oid *) ARR_DATA_PTR(allParamArray);
132                 Assert(allParamCount >= parameterCount);
133                 /* we assume caller got the contents right */
134         }
135         else
136         {
137                 allParamCount = parameterCount;
138                 allParams = parameterTypes->values;
139         }
140
141         /*
142          * Do not allow polymorphic return type unless at least one input argument
143          * is polymorphic.      Also, do not allow return type INTERNAL unless at
144          * least one input argument is INTERNAL.
145          */
146         for (i = 0; i < parameterCount; i++)
147         {
148                 switch (parameterTypes->values[i])
149                 {
150                         case ANYARRAYOID:
151                         case ANYELEMENTOID:
152                         case ANYNONARRAYOID:
153                         case ANYENUMOID:
154                                 genericInParam = true;
155                                 break;
156                         case INTERNALOID:
157                                 internalInParam = true;
158                                 break;
159                 }
160         }
161
162         if (allParameterTypes != PointerGetDatum(NULL))
163         {
164                 for (i = 0; i < allParamCount; i++)
165                 {
166                         /*
167                          * We don't bother to distinguish input and output params here, so
168                          * if there is, say, just an input INTERNAL param then we will
169                          * still set internalOutParam.  This is OK since we don't really
170                          * care.
171                          */
172                         switch (allParams[i])
173                         {
174                                 case ANYARRAYOID:
175                                 case ANYELEMENTOID:
176                                 case ANYNONARRAYOID:
177                                 case ANYENUMOID:
178                                         genericOutParam = true;
179                                         break;
180                                 case INTERNALOID:
181                                         internalOutParam = true;
182                                         break;
183                         }
184                 }
185         }
186
187         if ((IsPolymorphicType(returnType) || genericOutParam)
188                 && !genericInParam)
189                 ereport(ERROR,
190                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
191                                  errmsg("cannot determine result data type"),
192                                  errdetail("A function returning a polymorphic type must have at least one polymorphic argument.")));
193
194         if ((returnType == INTERNALOID || internalOutParam) && !internalInParam)
195                 ereport(ERROR,
196                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
197                                  errmsg("unsafe use of pseudo-type \"internal\""),
198                                  errdetail("A function returning \"internal\" must have at least one \"internal\" argument.")));
199
200         /*
201          * don't allow functions of complex types that have the same name as
202          * existing attributes of the type
203          */
204         if (parameterCount == 1 &&
205                 OidIsValid(parameterTypes->values[0]) &&
206                 (relid = typeidTypeRelid(parameterTypes->values[0])) != InvalidOid &&
207                 get_attnum(relid, procedureName) != InvalidAttrNumber)
208                 ereport(ERROR,
209                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
210                                  errmsg("\"%s\" is already an attribute of type %s",
211                                                 procedureName,
212                                                 format_type_be(parameterTypes->values[0]))));
213
214         if (parameterModes != PointerGetDatum(NULL))
215         {
216                 /*
217                  * We expect the array to be a 1-D CHAR array; verify that. We don't
218                  * need to use deconstruct_array() since the array data is just going
219                  * to look like a C array of char values.
220                  */
221                 ArrayType  *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
222                 char       *modes;
223
224                 if (ARR_NDIM(modesArray) != 1 ||
225                         ARR_DIMS(modesArray)[0] != allParamCount ||
226                         ARR_HASNULL(modesArray) ||
227                         ARR_ELEMTYPE(modesArray) != CHAROID)
228                         elog(ERROR, "parameterModes is not a 1-D char array");
229                 modes = (char *) ARR_DATA_PTR(modesArray);
230                 /*
231                  * Only the last input parameter can be variadic; if it is, save
232                  * its element type.  Errors here are just elog since caller should
233                  * have checked this already.
234                  */
235                 for (i = 0; i < allParamCount; i++)
236                 {
237                         switch (modes[i])
238                         {
239                                 case PROARGMODE_IN:
240                                 case PROARGMODE_INOUT:
241                                         if (OidIsValid(variadicType))
242                                                 elog(ERROR, "variadic parameter must be last");
243                                         break;
244                                 case PROARGMODE_OUT:
245                                         /* okay */
246                                         break;
247                                 case PROARGMODE_VARIADIC:
248                                         if (OidIsValid(variadicType))
249                                                 elog(ERROR, "variadic parameter must be last");
250                                         switch (allParams[i])
251                                         {
252                                                 case ANYOID:
253                                                         variadicType = ANYOID;
254                                                         break;
255                                                 case ANYARRAYOID:
256                                                         variadicType = ANYELEMENTOID;
257                                                         break;
258                                                 default:
259                                                         variadicType = get_element_type(allParams[i]);
260                                                         if (!OidIsValid(variadicType))
261                                                                 elog(ERROR, "variadic parameter is not an array");
262                                                         break;
263                                         }
264                                         break;
265                                 default:
266                                         elog(ERROR, "invalid parameter mode '%c'", modes[i]);
267                                         break;
268                         }
269                 }
270         }
271
272         /*
273          * All seems OK; prepare the data to be inserted into pg_proc.
274          */
275
276         for (i = 0; i < Natts_pg_proc; ++i)
277         {
278                 nulls[i] = ' ';
279                 values[i] = (Datum) 0;
280                 replaces[i] = 'r';
281         }
282
283         namestrcpy(&procname, procedureName);
284         values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
285         values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
286         values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(GetUserId());
287         values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
288         values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
289         values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
290         values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
291         values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
292         values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
293         values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
294         values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
295         values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
296         values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
297         values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
298         values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
299         if (allParameterTypes != PointerGetDatum(NULL))
300                 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
301         else
302                 nulls[Anum_pg_proc_proallargtypes - 1] = 'n';
303         if (parameterModes != PointerGetDatum(NULL))
304                 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
305         else
306                 nulls[Anum_pg_proc_proargmodes - 1] = 'n';
307         if (parameterNames != PointerGetDatum(NULL))
308                 values[Anum_pg_proc_proargnames - 1] = parameterNames;
309         else
310                 nulls[Anum_pg_proc_proargnames - 1] = 'n';
311         values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
312         if (probin)
313                 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
314         else
315                 nulls[Anum_pg_proc_probin - 1] = 'n';
316         if (proconfig != PointerGetDatum(NULL))
317                 values[Anum_pg_proc_proconfig - 1] = proconfig;
318         else
319                 nulls[Anum_pg_proc_proconfig - 1] = 'n';
320         /* start out with empty permissions */
321         nulls[Anum_pg_proc_proacl - 1] = 'n';
322
323         rel = heap_open(ProcedureRelationId, RowExclusiveLock);
324         tupDesc = RelationGetDescr(rel);
325
326         /* Check for pre-existing definition */
327         oldtup = SearchSysCache(PROCNAMEARGSNSP,
328                                                         PointerGetDatum(procedureName),
329                                                         PointerGetDatum(parameterTypes),
330                                                         ObjectIdGetDatum(procNamespace),
331                                                         0);
332
333         if (HeapTupleIsValid(oldtup))
334         {
335                 /* There is one; okay to replace it? */
336                 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
337
338                 if (!replace)
339                         ereport(ERROR,
340                                         (errcode(ERRCODE_DUPLICATE_FUNCTION),
341                         errmsg("function \"%s\" already exists with same argument types",
342                                    procedureName)));
343                 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), GetUserId()))
344                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
345                                                    procedureName);
346
347                 /*
348                  * Not okay to change the return type of the existing proc, since
349                  * existing rules, views, etc may depend on the return type.
350                  */
351                 if (returnType != oldproc->prorettype ||
352                         returnsSet != oldproc->proretset)
353                         ereport(ERROR,
354                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
355                                          errmsg("cannot change return type of existing function"),
356                                          errhint("Use DROP FUNCTION first.")));
357
358                 /*
359                  * If it returns RECORD, check for possible change of record type
360                  * implied by OUT parameters
361                  */
362                 if (returnType == RECORDOID)
363                 {
364                         TupleDesc       olddesc;
365                         TupleDesc       newdesc;
366
367                         olddesc = build_function_result_tupdesc_t(oldtup);
368                         newdesc = build_function_result_tupdesc_d(allParameterTypes,
369                                                                                                           parameterModes,
370                                                                                                           parameterNames);
371                         if (olddesc == NULL && newdesc == NULL)
372                                  /* ok, both are runtime-defined RECORDs */ ;
373                         else if (olddesc == NULL || newdesc == NULL ||
374                                          !equalTupleDescs(olddesc, newdesc))
375                                 ereport(ERROR,
376                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
377                                         errmsg("cannot change return type of existing function"),
378                                 errdetail("Row type defined by OUT parameters is different."),
379                                                  errhint("Use DROP FUNCTION first.")));
380                 }
381
382                 /* Can't change aggregate status, either */
383                 if (oldproc->proisagg != isAgg)
384                 {
385                         if (oldproc->proisagg)
386                                 ereport(ERROR,
387                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
388                                                  errmsg("function \"%s\" is an aggregate",
389                                                                 procedureName)));
390                         else
391                                 ereport(ERROR,
392                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
393                                                  errmsg("function \"%s\" is not an aggregate",
394                                                                 procedureName)));
395                 }
396
397                 /* do not change existing ownership or permissions, either */
398                 replaces[Anum_pg_proc_proowner - 1] = ' ';
399                 replaces[Anum_pg_proc_proacl - 1] = ' ';
400
401                 /* Okay, do it... */
402                 tup = heap_modifytuple(oldtup, tupDesc, values, nulls, replaces);
403                 simple_heap_update(rel, &tup->t_self, tup);
404
405                 ReleaseSysCache(oldtup);
406                 is_update = true;
407         }
408         else
409         {
410                 /* Creating a new procedure */
411                 tup = heap_formtuple(tupDesc, values, nulls);
412                 simple_heap_insert(rel, tup);
413                 is_update = false;
414         }
415
416         /* Need to update indexes for either the insert or update case */
417         CatalogUpdateIndexes(rel, tup);
418
419         retval = HeapTupleGetOid(tup);
420
421         /*
422          * Create dependencies for the new function.  If we are updating an
423          * existing function, first delete any existing pg_depend entries.
424          */
425         if (is_update)
426         {
427                 deleteDependencyRecordsFor(ProcedureRelationId, retval);
428                 deleteSharedDependencyRecordsFor(ProcedureRelationId, retval);
429         }
430
431         myself.classId = ProcedureRelationId;
432         myself.objectId = retval;
433         myself.objectSubId = 0;
434
435         /* dependency on namespace */
436         referenced.classId = NamespaceRelationId;
437         referenced.objectId = procNamespace;
438         referenced.objectSubId = 0;
439         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
440
441         /* dependency on implementation language */
442         referenced.classId = LanguageRelationId;
443         referenced.objectId = languageObjectId;
444         referenced.objectSubId = 0;
445         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
446
447         /* dependency on return type */
448         referenced.classId = TypeRelationId;
449         referenced.objectId = returnType;
450         referenced.objectSubId = 0;
451         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
452
453         /* dependency on parameter types */
454         for (i = 0; i < allParamCount; i++)
455         {
456                 referenced.classId = TypeRelationId;
457                 referenced.objectId = allParams[i];
458                 referenced.objectSubId = 0;
459                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
460         }
461
462         /* dependency on owner */
463         recordDependencyOnOwner(ProcedureRelationId, retval, GetUserId());
464
465         heap_freetuple(tup);
466
467         heap_close(rel, RowExclusiveLock);
468
469         /* Verify function body */
470         if (OidIsValid(languageValidator))
471         {
472                 /* Advance command counter so new tuple can be seen by validator */
473                 CommandCounterIncrement();
474                 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
475         }
476
477         return retval;
478 }
479
480
481
482 /*
483  * Validator for internal functions
484  *
485  * Check that the given internal function name (the "prosrc" value) is
486  * a known builtin function.
487  */
488 Datum
489 fmgr_internal_validator(PG_FUNCTION_ARGS)
490 {
491         Oid                     funcoid = PG_GETARG_OID(0);
492         HeapTuple       tuple;
493         Form_pg_proc proc;
494         bool            isnull;
495         Datum           tmp;
496         char       *prosrc;
497
498         /*
499          * We do not honor check_function_bodies since it's unlikely the function
500          * name will be found later if it isn't there now.
501          */
502
503         tuple = SearchSysCache(PROCOID,
504                                                    ObjectIdGetDatum(funcoid),
505                                                    0, 0, 0);
506         if (!HeapTupleIsValid(tuple))
507                 elog(ERROR, "cache lookup failed for function %u", funcoid);
508         proc = (Form_pg_proc) GETSTRUCT(tuple);
509
510         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
511         if (isnull)
512                 elog(ERROR, "null prosrc");
513         prosrc = TextDatumGetCString(tmp);
514
515         if (fmgr_internal_function(prosrc) == InvalidOid)
516                 ereport(ERROR,
517                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
518                                  errmsg("there is no built-in function named \"%s\"",
519                                                 prosrc)));
520
521         ReleaseSysCache(tuple);
522
523         PG_RETURN_VOID();
524 }
525
526
527
528 /*
529  * Validator for C language functions
530  *
531  * Make sure that the library file exists, is loadable, and contains
532  * the specified link symbol. Also check for a valid function
533  * information record.
534  */
535 Datum
536 fmgr_c_validator(PG_FUNCTION_ARGS)
537 {
538         Oid                     funcoid = PG_GETARG_OID(0);
539         void       *libraryhandle;
540         HeapTuple       tuple;
541         Form_pg_proc proc;
542         bool            isnull;
543         Datum           tmp;
544         char       *prosrc;
545         char       *probin;
546
547         /*
548          * It'd be most consistent to skip the check if !check_function_bodies,
549          * but the purpose of that switch is to be helpful for pg_dump loading,
550          * and for pg_dump loading it's much better if we *do* check.
551          */
552
553         tuple = SearchSysCache(PROCOID,
554                                                    ObjectIdGetDatum(funcoid),
555                                                    0, 0, 0);
556         if (!HeapTupleIsValid(tuple))
557                 elog(ERROR, "cache lookup failed for function %u", funcoid);
558         proc = (Form_pg_proc) GETSTRUCT(tuple);
559
560         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
561         if (isnull)
562                 elog(ERROR, "null prosrc for C function %u", funcoid);
563         prosrc = TextDatumGetCString(tmp);
564
565         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
566         if (isnull)
567                 elog(ERROR, "null probin for C function %u", funcoid);
568         probin = TextDatumGetCString(tmp);
569
570         (void) load_external_function(probin, prosrc, true, &libraryhandle);
571         (void) fetch_finfo_record(libraryhandle, prosrc);
572
573         ReleaseSysCache(tuple);
574
575         PG_RETURN_VOID();
576 }
577
578
579 /*
580  * Validator for SQL language functions
581  *
582  * Parse it here in order to be sure that it contains no syntax errors.
583  */
584 Datum
585 fmgr_sql_validator(PG_FUNCTION_ARGS)
586 {
587         Oid                     funcoid = PG_GETARG_OID(0);
588         HeapTuple       tuple;
589         Form_pg_proc proc;
590         List       *querytree_list;
591         bool            isnull;
592         Datum           tmp;
593         char       *prosrc;
594         ErrorContextCallback sqlerrcontext;
595         bool            haspolyarg;
596         int                     i;
597
598         tuple = SearchSysCache(PROCOID,
599                                                    ObjectIdGetDatum(funcoid),
600                                                    0, 0, 0);
601         if (!HeapTupleIsValid(tuple))
602                 elog(ERROR, "cache lookup failed for function %u", funcoid);
603         proc = (Form_pg_proc) GETSTRUCT(tuple);
604
605         /* Disallow pseudotype result */
606         /* except for RECORD, VOID, or polymorphic */
607         if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
608                 proc->prorettype != RECORDOID &&
609                 proc->prorettype != VOIDOID &&
610                 !IsPolymorphicType(proc->prorettype))
611                 ereport(ERROR,
612                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
613                                  errmsg("SQL functions cannot return type %s",
614                                                 format_type_be(proc->prorettype))));
615
616         /* Disallow pseudotypes in arguments */
617         /* except for polymorphic */
618         haspolyarg = false;
619         for (i = 0; i < proc->pronargs; i++)
620         {
621                 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
622                 {
623                         if (IsPolymorphicType(proc->proargtypes.values[i]))
624                                 haspolyarg = true;
625                         else
626                                 ereport(ERROR,
627                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
628                                          errmsg("SQL functions cannot have arguments of type %s",
629                                                         format_type_be(proc->proargtypes.values[i]))));
630                 }
631         }
632
633         /* Postpone body checks if !check_function_bodies */
634         if (check_function_bodies)
635         {
636                 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
637                 if (isnull)
638                         elog(ERROR, "null prosrc");
639
640                 prosrc = TextDatumGetCString(tmp);
641
642                 /*
643                  * Setup error traceback support for ereport().
644                  */
645                 sqlerrcontext.callback = sql_function_parse_error_callback;
646                 sqlerrcontext.arg = tuple;
647                 sqlerrcontext.previous = error_context_stack;
648                 error_context_stack = &sqlerrcontext;
649
650                 /*
651                  * We can't do full prechecking of the function definition if there
652                  * are any polymorphic input types, because actual datatypes of
653                  * expression results will be unresolvable.  The check will be done at
654                  * runtime instead.
655                  *
656                  * We can run the text through the raw parser though; this will at
657                  * least catch silly syntactic errors.
658                  */
659                 if (!haspolyarg)
660                 {
661                         querytree_list = pg_parse_and_rewrite(prosrc,
662                                                                                                   proc->proargtypes.values,
663                                                                                                   proc->pronargs);
664                         (void) check_sql_fn_retval(funcoid, proc->prorettype,
665                                                                            querytree_list,
666                                                                            false, NULL);
667                 }
668                 else
669                         querytree_list = pg_parse_query(prosrc);
670
671                 error_context_stack = sqlerrcontext.previous;
672         }
673
674         ReleaseSysCache(tuple);
675
676         PG_RETURN_VOID();
677 }
678
679 /*
680  * Error context callback for handling errors in SQL function definitions
681  */
682 static void
683 sql_function_parse_error_callback(void *arg)
684 {
685         HeapTuple       tuple = (HeapTuple) arg;
686         Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
687         bool            isnull;
688         Datum           tmp;
689         char       *prosrc;
690
691         /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
692         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
693         if (isnull)
694                 elog(ERROR, "null prosrc");
695         prosrc = TextDatumGetCString(tmp);
696
697         if (!function_parse_error_transpose(prosrc))
698         {
699                 /* If it's not a syntax error, push info onto context stack */
700                 errcontext("SQL function \"%s\"", NameStr(proc->proname));
701         }
702
703         pfree(prosrc);
704 }
705
706 /*
707  * Adjust a syntax error occurring inside the function body of a CREATE
708  * FUNCTION command.  This can be used by any function validator, not only
709  * for SQL-language functions.  It is assumed that the syntax error position
710  * is initially relative to the function body string (as passed in).  If
711  * possible, we adjust the position to reference the original CREATE command;
712  * if we can't manage that, we set up an "internal query" syntax error instead.
713  *
714  * Returns true if a syntax error was processed, false if not.
715  */
716 bool
717 function_parse_error_transpose(const char *prosrc)
718 {
719         int                     origerrposition;
720         int                     newerrposition;
721         const char *queryText;
722
723         /*
724          * Nothing to do unless we are dealing with a syntax error that has a
725          * cursor position.
726          *
727          * Some PLs may prefer to report the error position as an internal error
728          * to begin with, so check that too.
729          */
730         origerrposition = geterrposition();
731         if (origerrposition <= 0)
732         {
733                 origerrposition = getinternalerrposition();
734                 if (origerrposition <= 0)
735                         return false;
736         }
737
738         /* We can get the original query text from the active portal (hack...) */
739         Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
740         queryText = ActivePortal->sourceText;
741
742         /* Try to locate the prosrc in the original text */
743         newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
744
745         if (newerrposition > 0)
746         {
747                 /* Successful, so fix error position to reference original query */
748                 errposition(newerrposition);
749                 /* Get rid of any report of the error as an "internal query" */
750                 internalerrposition(0);
751                 internalerrquery(NULL);
752         }
753         else
754         {
755                 /*
756                  * If unsuccessful, convert the position to an internal position
757                  * marker and give the function text as the internal query.
758                  */
759                 errposition(0);
760                 internalerrposition(origerrposition);
761                 internalerrquery(prosrc);
762         }
763
764         return true;
765 }
766
767 /*
768  * Try to locate the string literal containing the function body in the
769  * given text of the CREATE FUNCTION command.  If successful, return the
770  * character (not byte) index within the command corresponding to the
771  * given character index within the literal.  If not successful, return 0.
772  */
773 static int
774 match_prosrc_to_query(const char *prosrc, const char *queryText,
775                                           int cursorpos)
776 {
777         /*
778          * Rather than fully parsing the CREATE FUNCTION command, we just scan the
779          * command looking for $prosrc$ or 'prosrc'.  This could be fooled (though
780          * not in any very probable scenarios), so fail if we find more than one
781          * match.
782          */
783         int                     prosrclen = strlen(prosrc);
784         int                     querylen = strlen(queryText);
785         int                     matchpos = 0;
786         int                     curpos;
787         int                     newcursorpos;
788
789         for (curpos = 0; curpos < querylen - prosrclen; curpos++)
790         {
791                 if (queryText[curpos] == '$' &&
792                         strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
793                         queryText[curpos + 1 + prosrclen] == '$')
794                 {
795                         /*
796                          * Found a $foo$ match.  Since there are no embedded quoting
797                          * characters in a dollar-quoted literal, we don't have to do any
798                          * fancy arithmetic; just offset by the starting position.
799                          */
800                         if (matchpos)
801                                 return 0;               /* multiple matches, fail */
802                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
803                                 + cursorpos;
804                 }
805                 else if (queryText[curpos] == '\'' &&
806                                  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
807                                                                                  cursorpos, &newcursorpos))
808                 {
809                         /*
810                          * Found a 'foo' match.  match_prosrc_to_literal() has adjusted
811                          * for any quotes or backslashes embedded in the literal.
812                          */
813                         if (matchpos)
814                                 return 0;               /* multiple matches, fail */
815                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
816                                 + newcursorpos;
817                 }
818         }
819
820         return matchpos;
821 }
822
823 /*
824  * Try to match the given source text to a single-quoted literal.
825  * If successful, adjust newcursorpos to correspond to the character
826  * (not byte) index corresponding to cursorpos in the source text.
827  *
828  * At entry, literal points just past a ' character.  We must check for the
829  * trailing quote.
830  */
831 static bool
832 match_prosrc_to_literal(const char *prosrc, const char *literal,
833                                                 int cursorpos, int *newcursorpos)
834 {
835         int                     newcp = cursorpos;
836         int                     chlen;
837
838         /*
839          * This implementation handles backslashes and doubled quotes in the
840          * string literal.      It does not handle the SQL syntax for literals
841          * continued across line boundaries.
842          *
843          * We do the comparison a character at a time, not a byte at a time, so
844          * that we can do the correct cursorpos math.
845          */
846         while (*prosrc)
847         {
848                 cursorpos--;                    /* characters left before cursor */
849
850                 /*
851                  * Check for backslashes and doubled quotes in the literal; adjust
852                  * newcp when one is found before the cursor.
853                  */
854                 if (*literal == '\\')
855                 {
856                         literal++;
857                         if (cursorpos > 0)
858                                 newcp++;
859                 }
860                 else if (*literal == '\'')
861                 {
862                         if (literal[1] != '\'')
863                                 goto fail;
864                         literal++;
865                         if (cursorpos > 0)
866                                 newcp++;
867                 }
868                 chlen = pg_mblen(prosrc);
869                 if (strncmp(prosrc, literal, chlen) != 0)
870                         goto fail;
871                 prosrc += chlen;
872                 literal += chlen;
873         }
874
875         if (*literal == '\'' && literal[1] != '\'')
876         {
877                 /* success */
878                 *newcursorpos = newcp;
879                 return true;
880         }
881
882 fail:
883         /* Must set *newcursorpos to suppress compiler warning */
884         *newcursorpos = newcp;
885         return false;
886 }