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