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