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