OSDN Git Service

Implement SQL-spec RETURNS TABLE syntax for functions.
[pg-rex/syncrep.git] / 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.153 2008/07/18 03:32:52 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                                 case PROARGMODE_TABLE:
246                                         /* okay */
247                                         break;
248                                 case PROARGMODE_VARIADIC:
249                                         if (OidIsValid(variadicType))
250                                                 elog(ERROR, "variadic parameter must be last");
251                                         switch (allParams[i])
252                                         {
253                                                 case ANYOID:
254                                                         variadicType = ANYOID;
255                                                         break;
256                                                 case ANYARRAYOID:
257                                                         variadicType = ANYELEMENTOID;
258                                                         break;
259                                                 default:
260                                                         variadicType = get_element_type(allParams[i]);
261                                                         if (!OidIsValid(variadicType))
262                                                                 elog(ERROR, "variadic parameter is not an array");
263                                                         break;
264                                         }
265                                         break;
266                                 default:
267                                         elog(ERROR, "invalid parameter mode '%c'", modes[i]);
268                                         break;
269                         }
270                 }
271         }
272
273         /*
274          * All seems OK; prepare the data to be inserted into pg_proc.
275          */
276
277         for (i = 0; i < Natts_pg_proc; ++i)
278         {
279                 nulls[i] = ' ';
280                 values[i] = (Datum) 0;
281                 replaces[i] = 'r';
282         }
283
284         namestrcpy(&procname, procedureName);
285         values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
286         values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
287         values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(GetUserId());
288         values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
289         values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
290         values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
291         values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
292         values[Anum_pg_proc_proisagg - 1] = BoolGetDatum(isAgg);
293         values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
294         values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
295         values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
296         values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
297         values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
298         values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
299         values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
300         if (allParameterTypes != PointerGetDatum(NULL))
301                 values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
302         else
303                 nulls[Anum_pg_proc_proallargtypes - 1] = 'n';
304         if (parameterModes != PointerGetDatum(NULL))
305                 values[Anum_pg_proc_proargmodes - 1] = parameterModes;
306         else
307                 nulls[Anum_pg_proc_proargmodes - 1] = 'n';
308         if (parameterNames != PointerGetDatum(NULL))
309                 values[Anum_pg_proc_proargnames - 1] = parameterNames;
310         else
311                 nulls[Anum_pg_proc_proargnames - 1] = 'n';
312         values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
313         if (probin)
314                 values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
315         else
316                 nulls[Anum_pg_proc_probin - 1] = 'n';
317         if (proconfig != PointerGetDatum(NULL))
318                 values[Anum_pg_proc_proconfig - 1] = proconfig;
319         else
320                 nulls[Anum_pg_proc_proconfig - 1] = 'n';
321         /* start out with empty permissions */
322         nulls[Anum_pg_proc_proacl - 1] = 'n';
323
324         rel = heap_open(ProcedureRelationId, RowExclusiveLock);
325         tupDesc = RelationGetDescr(rel);
326
327         /* Check for pre-existing definition */
328         oldtup = SearchSysCache(PROCNAMEARGSNSP,
329                                                         PointerGetDatum(procedureName),
330                                                         PointerGetDatum(parameterTypes),
331                                                         ObjectIdGetDatum(procNamespace),
332                                                         0);
333
334         if (HeapTupleIsValid(oldtup))
335         {
336                 /* There is one; okay to replace it? */
337                 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
338
339                 if (!replace)
340                         ereport(ERROR,
341                                         (errcode(ERRCODE_DUPLICATE_FUNCTION),
342                         errmsg("function \"%s\" already exists with same argument types",
343                                    procedureName)));
344                 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), GetUserId()))
345                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
346                                                    procedureName);
347
348                 /*
349                  * Not okay to change the return type of the existing proc, since
350                  * existing rules, views, etc may depend on the return type.
351                  */
352                 if (returnType != oldproc->prorettype ||
353                         returnsSet != oldproc->proretset)
354                         ereport(ERROR,
355                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
356                                          errmsg("cannot change return type of existing function"),
357                                          errhint("Use DROP FUNCTION first.")));
358
359                 /*
360                  * If it returns RECORD, check for possible change of record type
361                  * implied by OUT parameters
362                  */
363                 if (returnType == RECORDOID)
364                 {
365                         TupleDesc       olddesc;
366                         TupleDesc       newdesc;
367
368                         olddesc = build_function_result_tupdesc_t(oldtup);
369                         newdesc = build_function_result_tupdesc_d(allParameterTypes,
370                                                                                                           parameterModes,
371                                                                                                           parameterNames);
372                         if (olddesc == NULL && newdesc == NULL)
373                                  /* ok, both are runtime-defined RECORDs */ ;
374                         else if (olddesc == NULL || newdesc == NULL ||
375                                          !equalTupleDescs(olddesc, newdesc))
376                                 ereport(ERROR,
377                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
378                                         errmsg("cannot change return type of existing function"),
379                                 errdetail("Row type defined by OUT parameters is different."),
380                                                  errhint("Use DROP FUNCTION first.")));
381                 }
382
383                 /* Can't change aggregate status, either */
384                 if (oldproc->proisagg != isAgg)
385                 {
386                         if (oldproc->proisagg)
387                                 ereport(ERROR,
388                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
389                                                  errmsg("function \"%s\" is an aggregate",
390                                                                 procedureName)));
391                         else
392                                 ereport(ERROR,
393                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
394                                                  errmsg("function \"%s\" is not an aggregate",
395                                                                 procedureName)));
396                 }
397
398                 /* do not change existing ownership or permissions, either */
399                 replaces[Anum_pg_proc_proowner - 1] = ' ';
400                 replaces[Anum_pg_proc_proacl - 1] = ' ';
401
402                 /* Okay, do it... */
403                 tup = heap_modifytuple(oldtup, tupDesc, values, nulls, replaces);
404                 simple_heap_update(rel, &tup->t_self, tup);
405
406                 ReleaseSysCache(oldtup);
407                 is_update = true;
408         }
409         else
410         {
411                 /* Creating a new procedure */
412                 tup = heap_formtuple(tupDesc, values, nulls);
413                 simple_heap_insert(rel, tup);
414                 is_update = false;
415         }
416
417         /* Need to update indexes for either the insert or update case */
418         CatalogUpdateIndexes(rel, tup);
419
420         retval = HeapTupleGetOid(tup);
421
422         /*
423          * Create dependencies for the new function.  If we are updating an
424          * existing function, first delete any existing pg_depend entries.
425          */
426         if (is_update)
427         {
428                 deleteDependencyRecordsFor(ProcedureRelationId, retval);
429                 deleteSharedDependencyRecordsFor(ProcedureRelationId, retval);
430         }
431
432         myself.classId = ProcedureRelationId;
433         myself.objectId = retval;
434         myself.objectSubId = 0;
435
436         /* dependency on namespace */
437         referenced.classId = NamespaceRelationId;
438         referenced.objectId = procNamespace;
439         referenced.objectSubId = 0;
440         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
441
442         /* dependency on implementation language */
443         referenced.classId = LanguageRelationId;
444         referenced.objectId = languageObjectId;
445         referenced.objectSubId = 0;
446         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
447
448         /* dependency on return type */
449         referenced.classId = TypeRelationId;
450         referenced.objectId = returnType;
451         referenced.objectSubId = 0;
452         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
453
454         /* dependency on parameter types */
455         for (i = 0; i < allParamCount; i++)
456         {
457                 referenced.classId = TypeRelationId;
458                 referenced.objectId = allParams[i];
459                 referenced.objectSubId = 0;
460                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
461         }
462
463         /* dependency on owner */
464         recordDependencyOnOwner(ProcedureRelationId, retval, GetUserId());
465
466         heap_freetuple(tup);
467
468         heap_close(rel, RowExclusiveLock);
469
470         /* Verify function body */
471         if (OidIsValid(languageValidator))
472         {
473                 /* Advance command counter so new tuple can be seen by validator */
474                 CommandCounterIncrement();
475                 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
476         }
477
478         return retval;
479 }
480
481
482
483 /*
484  * Validator for internal functions
485  *
486  * Check that the given internal function name (the "prosrc" value) is
487  * a known builtin function.
488  */
489 Datum
490 fmgr_internal_validator(PG_FUNCTION_ARGS)
491 {
492         Oid                     funcoid = PG_GETARG_OID(0);
493         HeapTuple       tuple;
494         Form_pg_proc proc;
495         bool            isnull;
496         Datum           tmp;
497         char       *prosrc;
498
499         /*
500          * We do not honor check_function_bodies since it's unlikely the function
501          * name will be found later if it isn't there now.
502          */
503
504         tuple = SearchSysCache(PROCOID,
505                                                    ObjectIdGetDatum(funcoid),
506                                                    0, 0, 0);
507         if (!HeapTupleIsValid(tuple))
508                 elog(ERROR, "cache lookup failed for function %u", funcoid);
509         proc = (Form_pg_proc) GETSTRUCT(tuple);
510
511         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
512         if (isnull)
513                 elog(ERROR, "null prosrc");
514         prosrc = TextDatumGetCString(tmp);
515
516         if (fmgr_internal_function(prosrc) == InvalidOid)
517                 ereport(ERROR,
518                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
519                                  errmsg("there is no built-in function named \"%s\"",
520                                                 prosrc)));
521
522         ReleaseSysCache(tuple);
523
524         PG_RETURN_VOID();
525 }
526
527
528
529 /*
530  * Validator for C language functions
531  *
532  * Make sure that the library file exists, is loadable, and contains
533  * the specified link symbol. Also check for a valid function
534  * information record.
535  */
536 Datum
537 fmgr_c_validator(PG_FUNCTION_ARGS)
538 {
539         Oid                     funcoid = PG_GETARG_OID(0);
540         void       *libraryhandle;
541         HeapTuple       tuple;
542         Form_pg_proc proc;
543         bool            isnull;
544         Datum           tmp;
545         char       *prosrc;
546         char       *probin;
547
548         /*
549          * It'd be most consistent to skip the check if !check_function_bodies,
550          * but the purpose of that switch is to be helpful for pg_dump loading,
551          * and for pg_dump loading it's much better if we *do* check.
552          */
553
554         tuple = SearchSysCache(PROCOID,
555                                                    ObjectIdGetDatum(funcoid),
556                                                    0, 0, 0);
557         if (!HeapTupleIsValid(tuple))
558                 elog(ERROR, "cache lookup failed for function %u", funcoid);
559         proc = (Form_pg_proc) GETSTRUCT(tuple);
560
561         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
562         if (isnull)
563                 elog(ERROR, "null prosrc for C function %u", funcoid);
564         prosrc = TextDatumGetCString(tmp);
565
566         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
567         if (isnull)
568                 elog(ERROR, "null probin for C function %u", funcoid);
569         probin = TextDatumGetCString(tmp);
570
571         (void) load_external_function(probin, prosrc, true, &libraryhandle);
572         (void) fetch_finfo_record(libraryhandle, prosrc);
573
574         ReleaseSysCache(tuple);
575
576         PG_RETURN_VOID();
577 }
578
579
580 /*
581  * Validator for SQL language functions
582  *
583  * Parse it here in order to be sure that it contains no syntax errors.
584  */
585 Datum
586 fmgr_sql_validator(PG_FUNCTION_ARGS)
587 {
588         Oid                     funcoid = PG_GETARG_OID(0);
589         HeapTuple       tuple;
590         Form_pg_proc proc;
591         List       *querytree_list;
592         bool            isnull;
593         Datum           tmp;
594         char       *prosrc;
595         ErrorContextCallback sqlerrcontext;
596         bool            haspolyarg;
597         int                     i;
598
599         tuple = SearchSysCache(PROCOID,
600                                                    ObjectIdGetDatum(funcoid),
601                                                    0, 0, 0);
602         if (!HeapTupleIsValid(tuple))
603                 elog(ERROR, "cache lookup failed for function %u", funcoid);
604         proc = (Form_pg_proc) GETSTRUCT(tuple);
605
606         /* Disallow pseudotype result */
607         /* except for RECORD, VOID, or polymorphic */
608         if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
609                 proc->prorettype != RECORDOID &&
610                 proc->prorettype != VOIDOID &&
611                 !IsPolymorphicType(proc->prorettype))
612                 ereport(ERROR,
613                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
614                                  errmsg("SQL functions cannot return type %s",
615                                                 format_type_be(proc->prorettype))));
616
617         /* Disallow pseudotypes in arguments */
618         /* except for polymorphic */
619         haspolyarg = false;
620         for (i = 0; i < proc->pronargs; i++)
621         {
622                 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
623                 {
624                         if (IsPolymorphicType(proc->proargtypes.values[i]))
625                                 haspolyarg = true;
626                         else
627                                 ereport(ERROR,
628                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
629                                          errmsg("SQL functions cannot have arguments of type %s",
630                                                         format_type_be(proc->proargtypes.values[i]))));
631                 }
632         }
633
634         /* Postpone body checks if !check_function_bodies */
635         if (check_function_bodies)
636         {
637                 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
638                 if (isnull)
639                         elog(ERROR, "null prosrc");
640
641                 prosrc = TextDatumGetCString(tmp);
642
643                 /*
644                  * Setup error traceback support for ereport().
645                  */
646                 sqlerrcontext.callback = sql_function_parse_error_callback;
647                 sqlerrcontext.arg = tuple;
648                 sqlerrcontext.previous = error_context_stack;
649                 error_context_stack = &sqlerrcontext;
650
651                 /*
652                  * We can't do full prechecking of the function definition if there
653                  * are any polymorphic input types, because actual datatypes of
654                  * expression results will be unresolvable.  The check will be done at
655                  * runtime instead.
656                  *
657                  * We can run the text through the raw parser though; this will at
658                  * least catch silly syntactic errors.
659                  */
660                 if (!haspolyarg)
661                 {
662                         querytree_list = pg_parse_and_rewrite(prosrc,
663                                                                                                   proc->proargtypes.values,
664                                                                                                   proc->pronargs);
665                         (void) check_sql_fn_retval(funcoid, proc->prorettype,
666                                                                            querytree_list,
667                                                                            false, NULL);
668                 }
669                 else
670                         querytree_list = pg_parse_query(prosrc);
671
672                 error_context_stack = sqlerrcontext.previous;
673         }
674
675         ReleaseSysCache(tuple);
676
677         PG_RETURN_VOID();
678 }
679
680 /*
681  * Error context callback for handling errors in SQL function definitions
682  */
683 static void
684 sql_function_parse_error_callback(void *arg)
685 {
686         HeapTuple       tuple = (HeapTuple) arg;
687         Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
688         bool            isnull;
689         Datum           tmp;
690         char       *prosrc;
691
692         /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
693         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
694         if (isnull)
695                 elog(ERROR, "null prosrc");
696         prosrc = TextDatumGetCString(tmp);
697
698         if (!function_parse_error_transpose(prosrc))
699         {
700                 /* If it's not a syntax error, push info onto context stack */
701                 errcontext("SQL function \"%s\"", NameStr(proc->proname));
702         }
703
704         pfree(prosrc);
705 }
706
707 /*
708  * Adjust a syntax error occurring inside the function body of a CREATE
709  * FUNCTION command.  This can be used by any function validator, not only
710  * for SQL-language functions.  It is assumed that the syntax error position
711  * is initially relative to the function body string (as passed in).  If
712  * possible, we adjust the position to reference the original CREATE command;
713  * if we can't manage that, we set up an "internal query" syntax error instead.
714  *
715  * Returns true if a syntax error was processed, false if not.
716  */
717 bool
718 function_parse_error_transpose(const char *prosrc)
719 {
720         int                     origerrposition;
721         int                     newerrposition;
722         const char *queryText;
723
724         /*
725          * Nothing to do unless we are dealing with a syntax error that has a
726          * cursor position.
727          *
728          * Some PLs may prefer to report the error position as an internal error
729          * to begin with, so check that too.
730          */
731         origerrposition = geterrposition();
732         if (origerrposition <= 0)
733         {
734                 origerrposition = getinternalerrposition();
735                 if (origerrposition <= 0)
736                         return false;
737         }
738
739         /* We can get the original query text from the active portal (hack...) */
740         Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
741         queryText = ActivePortal->sourceText;
742
743         /* Try to locate the prosrc in the original text */
744         newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
745
746         if (newerrposition > 0)
747         {
748                 /* Successful, so fix error position to reference original query */
749                 errposition(newerrposition);
750                 /* Get rid of any report of the error as an "internal query" */
751                 internalerrposition(0);
752                 internalerrquery(NULL);
753         }
754         else
755         {
756                 /*
757                  * If unsuccessful, convert the position to an internal position
758                  * marker and give the function text as the internal query.
759                  */
760                 errposition(0);
761                 internalerrposition(origerrposition);
762                 internalerrquery(prosrc);
763         }
764
765         return true;
766 }
767
768 /*
769  * Try to locate the string literal containing the function body in the
770  * given text of the CREATE FUNCTION command.  If successful, return the
771  * character (not byte) index within the command corresponding to the
772  * given character index within the literal.  If not successful, return 0.
773  */
774 static int
775 match_prosrc_to_query(const char *prosrc, const char *queryText,
776                                           int cursorpos)
777 {
778         /*
779          * Rather than fully parsing the CREATE FUNCTION command, we just scan the
780          * command looking for $prosrc$ or 'prosrc'.  This could be fooled (though
781          * not in any very probable scenarios), so fail if we find more than one
782          * match.
783          */
784         int                     prosrclen = strlen(prosrc);
785         int                     querylen = strlen(queryText);
786         int                     matchpos = 0;
787         int                     curpos;
788         int                     newcursorpos;
789
790         for (curpos = 0; curpos < querylen - prosrclen; curpos++)
791         {
792                 if (queryText[curpos] == '$' &&
793                         strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
794                         queryText[curpos + 1 + prosrclen] == '$')
795                 {
796                         /*
797                          * Found a $foo$ match.  Since there are no embedded quoting
798                          * characters in a dollar-quoted literal, we don't have to do any
799                          * fancy arithmetic; just offset by the starting position.
800                          */
801                         if (matchpos)
802                                 return 0;               /* multiple matches, fail */
803                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
804                                 + cursorpos;
805                 }
806                 else if (queryText[curpos] == '\'' &&
807                                  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
808                                                                                  cursorpos, &newcursorpos))
809                 {
810                         /*
811                          * Found a 'foo' match.  match_prosrc_to_literal() has adjusted
812                          * for any quotes or backslashes embedded in the literal.
813                          */
814                         if (matchpos)
815                                 return 0;               /* multiple matches, fail */
816                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
817                                 + newcursorpos;
818                 }
819         }
820
821         return matchpos;
822 }
823
824 /*
825  * Try to match the given source text to a single-quoted literal.
826  * If successful, adjust newcursorpos to correspond to the character
827  * (not byte) index corresponding to cursorpos in the source text.
828  *
829  * At entry, literal points just past a ' character.  We must check for the
830  * trailing quote.
831  */
832 static bool
833 match_prosrc_to_literal(const char *prosrc, const char *literal,
834                                                 int cursorpos, int *newcursorpos)
835 {
836         int                     newcp = cursorpos;
837         int                     chlen;
838
839         /*
840          * This implementation handles backslashes and doubled quotes in the
841          * string literal.      It does not handle the SQL syntax for literals
842          * continued across line boundaries.
843          *
844          * We do the comparison a character at a time, not a byte at a time, so
845          * that we can do the correct cursorpos math.
846          */
847         while (*prosrc)
848         {
849                 cursorpos--;                    /* characters left before cursor */
850
851                 /*
852                  * Check for backslashes and doubled quotes in the literal; adjust
853                  * newcp when one is found before the cursor.
854                  */
855                 if (*literal == '\\')
856                 {
857                         literal++;
858                         if (cursorpos > 0)
859                                 newcp++;
860                 }
861                 else if (*literal == '\'')
862                 {
863                         if (literal[1] != '\'')
864                                 goto fail;
865                         literal++;
866                         if (cursorpos > 0)
867                                 newcp++;
868                 }
869                 chlen = pg_mblen(prosrc);
870                 if (strncmp(prosrc, literal, chlen) != 0)
871                         goto fail;
872                 prosrc += chlen;
873                 literal += chlen;
874         }
875
876         if (*literal == '\'' && literal[1] != '\'')
877         {
878                 /* success */
879                 *newcursorpos = newcp;
880                 return true;
881         }
882
883 fail:
884         /* Must set *newcursorpos to suppress compiler warning */
885         *newcursorpos = newcp;
886         return false;
887 }