OSDN Git Service

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