OSDN Git Service

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