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