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