OSDN Git Service

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