OSDN Git Service

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