OSDN Git Service

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