OSDN Git Service

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