OSDN Git Service

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