OSDN Git Service

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