OSDN Git Service

Simplify and standardize conversions between TEXT datums and ordinary C
[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.150 2008/03/25 22:42:42 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] = CStringGetTextDatum(prosrc);
252         values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
253         if (proconfig != PointerGetDatum(NULL))
254                 values[Anum_pg_proc_proconfig - 1] = proconfig;
255         else
256                 nulls[Anum_pg_proc_proconfig - 1] = 'n';
257         /* start out with empty permissions */
258         nulls[Anum_pg_proc_proacl - 1] = 'n';
259
260         rel = heap_open(ProcedureRelationId, RowExclusiveLock);
261         tupDesc = RelationGetDescr(rel);
262
263         /* Check for pre-existing definition */
264         oldtup = SearchSysCache(PROCNAMEARGSNSP,
265                                                         PointerGetDatum(procedureName),
266                                                         PointerGetDatum(parameterTypes),
267                                                         ObjectIdGetDatum(procNamespace),
268                                                         0);
269
270         if (HeapTupleIsValid(oldtup))
271         {
272                 /* There is one; okay to replace it? */
273                 Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
274
275                 if (!replace)
276                         ereport(ERROR,
277                                         (errcode(ERRCODE_DUPLICATE_FUNCTION),
278                         errmsg("function \"%s\" already exists with same argument types",
279                                    procedureName)));
280                 if (!pg_proc_ownercheck(HeapTupleGetOid(oldtup), GetUserId()))
281                         aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_PROC,
282                                                    procedureName);
283
284                 /*
285                  * Not okay to change the return type of the existing proc, since
286                  * existing rules, views, etc may depend on the return type.
287                  */
288                 if (returnType != oldproc->prorettype ||
289                         returnsSet != oldproc->proretset)
290                         ereport(ERROR,
291                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
292                                          errmsg("cannot change return type of existing function"),
293                                          errhint("Use DROP FUNCTION first.")));
294
295                 /*
296                  * If it returns RECORD, check for possible change of record type
297                  * implied by OUT parameters
298                  */
299                 if (returnType == RECORDOID)
300                 {
301                         TupleDesc       olddesc;
302                         TupleDesc       newdesc;
303
304                         olddesc = build_function_result_tupdesc_t(oldtup);
305                         newdesc = build_function_result_tupdesc_d(allParameterTypes,
306                                                                                                           parameterModes,
307                                                                                                           parameterNames);
308                         if (olddesc == NULL && newdesc == NULL)
309                                  /* ok, both are runtime-defined RECORDs */ ;
310                         else if (olddesc == NULL || newdesc == NULL ||
311                                          !equalTupleDescs(olddesc, newdesc))
312                                 ereport(ERROR,
313                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
314                                         errmsg("cannot change return type of existing function"),
315                                 errdetail("Row type defined by OUT parameters is different."),
316                                                  errhint("Use DROP FUNCTION first.")));
317                 }
318
319                 /* Can't change aggregate status, either */
320                 if (oldproc->proisagg != isAgg)
321                 {
322                         if (oldproc->proisagg)
323                                 ereport(ERROR,
324                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
325                                                  errmsg("function \"%s\" is an aggregate",
326                                                                 procedureName)));
327                         else
328                                 ereport(ERROR,
329                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
330                                                  errmsg("function \"%s\" is not an aggregate",
331                                                                 procedureName)));
332                 }
333
334                 /* do not change existing ownership or permissions, either */
335                 replaces[Anum_pg_proc_proowner - 1] = ' ';
336                 replaces[Anum_pg_proc_proacl - 1] = ' ';
337
338                 /* Okay, do it... */
339                 tup = heap_modifytuple(oldtup, tupDesc, values, nulls, replaces);
340                 simple_heap_update(rel, &tup->t_self, tup);
341
342                 ReleaseSysCache(oldtup);
343                 is_update = true;
344         }
345         else
346         {
347                 /* Creating a new procedure */
348                 tup = heap_formtuple(tupDesc, values, nulls);
349                 simple_heap_insert(rel, tup);
350                 is_update = false;
351         }
352
353         /* Need to update indexes for either the insert or update case */
354         CatalogUpdateIndexes(rel, tup);
355
356         retval = HeapTupleGetOid(tup);
357
358         /*
359          * Create dependencies for the new function.  If we are updating an
360          * existing function, first delete any existing pg_depend entries.
361          */
362         if (is_update)
363         {
364                 deleteDependencyRecordsFor(ProcedureRelationId, retval);
365                 deleteSharedDependencyRecordsFor(ProcedureRelationId, retval);
366         }
367
368         myself.classId = ProcedureRelationId;
369         myself.objectId = retval;
370         myself.objectSubId = 0;
371
372         /* dependency on namespace */
373         referenced.classId = NamespaceRelationId;
374         referenced.objectId = procNamespace;
375         referenced.objectSubId = 0;
376         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
377
378         /* dependency on implementation language */
379         referenced.classId = LanguageRelationId;
380         referenced.objectId = languageObjectId;
381         referenced.objectSubId = 0;
382         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
383
384         /* dependency on return type */
385         referenced.classId = TypeRelationId;
386         referenced.objectId = returnType;
387         referenced.objectSubId = 0;
388         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
389
390         /* dependency on parameter types */
391         for (i = 0; i < allParamCount; i++)
392         {
393                 referenced.classId = TypeRelationId;
394                 referenced.objectId = allParams[i];
395                 referenced.objectSubId = 0;
396                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
397         }
398
399         /* dependency on owner */
400         recordDependencyOnOwner(ProcedureRelationId, retval, GetUserId());
401
402         heap_freetuple(tup);
403
404         heap_close(rel, RowExclusiveLock);
405
406         /* Verify function body */
407         if (OidIsValid(languageValidator))
408         {
409                 /* Advance command counter so new tuple can be seen by validator */
410                 CommandCounterIncrement();
411                 OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
412         }
413
414         return retval;
415 }
416
417
418
419 /*
420  * Validator for internal functions
421  *
422  * Check that the given internal function name (the "prosrc" value) is
423  * a known builtin function.
424  */
425 Datum
426 fmgr_internal_validator(PG_FUNCTION_ARGS)
427 {
428         Oid                     funcoid = PG_GETARG_OID(0);
429         HeapTuple       tuple;
430         Form_pg_proc proc;
431         bool            isnull;
432         Datum           tmp;
433         char       *prosrc;
434
435         /*
436          * We do not honor check_function_bodies since it's unlikely the function
437          * name will be found later if it isn't there now.
438          */
439
440         tuple = SearchSysCache(PROCOID,
441                                                    ObjectIdGetDatum(funcoid),
442                                                    0, 0, 0);
443         if (!HeapTupleIsValid(tuple))
444                 elog(ERROR, "cache lookup failed for function %u", funcoid);
445         proc = (Form_pg_proc) GETSTRUCT(tuple);
446
447         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
448         if (isnull)
449                 elog(ERROR, "null prosrc");
450         prosrc = TextDatumGetCString(tmp);
451
452         if (fmgr_internal_function(prosrc) == InvalidOid)
453                 ereport(ERROR,
454                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
455                                  errmsg("there is no built-in function named \"%s\"",
456                                                 prosrc)));
457
458         ReleaseSysCache(tuple);
459
460         PG_RETURN_VOID();
461 }
462
463
464
465 /*
466  * Validator for C language functions
467  *
468  * Make sure that the library file exists, is loadable, and contains
469  * the specified link symbol. Also check for a valid function
470  * information record.
471  */
472 Datum
473 fmgr_c_validator(PG_FUNCTION_ARGS)
474 {
475         Oid                     funcoid = PG_GETARG_OID(0);
476         void       *libraryhandle;
477         HeapTuple       tuple;
478         Form_pg_proc proc;
479         bool            isnull;
480         Datum           tmp;
481         char       *prosrc;
482         char       *probin;
483
484         /*
485          * It'd be most consistent to skip the check if !check_function_bodies,
486          * but the purpose of that switch is to be helpful for pg_dump loading,
487          * and for pg_dump loading it's much better if we *do* check.
488          */
489
490         tuple = SearchSysCache(PROCOID,
491                                                    ObjectIdGetDatum(funcoid),
492                                                    0, 0, 0);
493         if (!HeapTupleIsValid(tuple))
494                 elog(ERROR, "cache lookup failed for function %u", funcoid);
495         proc = (Form_pg_proc) GETSTRUCT(tuple);
496
497         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
498         if (isnull)
499                 elog(ERROR, "null prosrc");
500         prosrc = TextDatumGetCString(tmp);
501
502         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
503         if (isnull)
504                 elog(ERROR, "null probin");
505         probin = TextDatumGetCString(tmp);
506
507         (void) load_external_function(probin, prosrc, true, &libraryhandle);
508         (void) fetch_finfo_record(libraryhandle, prosrc);
509
510         ReleaseSysCache(tuple);
511
512         PG_RETURN_VOID();
513 }
514
515
516 /*
517  * Validator for SQL language functions
518  *
519  * Parse it here in order to be sure that it contains no syntax errors.
520  */
521 Datum
522 fmgr_sql_validator(PG_FUNCTION_ARGS)
523 {
524         Oid                     funcoid = PG_GETARG_OID(0);
525         HeapTuple       tuple;
526         Form_pg_proc proc;
527         List       *querytree_list;
528         bool            isnull;
529         Datum           tmp;
530         char       *prosrc;
531         ErrorContextCallback sqlerrcontext;
532         bool            haspolyarg;
533         int                     i;
534
535         tuple = SearchSysCache(PROCOID,
536                                                    ObjectIdGetDatum(funcoid),
537                                                    0, 0, 0);
538         if (!HeapTupleIsValid(tuple))
539                 elog(ERROR, "cache lookup failed for function %u", funcoid);
540         proc = (Form_pg_proc) GETSTRUCT(tuple);
541
542         /* Disallow pseudotype result */
543         /* except for RECORD, VOID, or polymorphic */
544         if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
545                 proc->prorettype != RECORDOID &&
546                 proc->prorettype != VOIDOID &&
547                 !IsPolymorphicType(proc->prorettype))
548                 ereport(ERROR,
549                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
550                                  errmsg("SQL functions cannot return type %s",
551                                                 format_type_be(proc->prorettype))));
552
553         /* Disallow pseudotypes in arguments */
554         /* except for polymorphic */
555         haspolyarg = false;
556         for (i = 0; i < proc->pronargs; i++)
557         {
558                 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
559                 {
560                         if (IsPolymorphicType(proc->proargtypes.values[i]))
561                                 haspolyarg = true;
562                         else
563                                 ereport(ERROR,
564                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
565                                          errmsg("SQL functions cannot have arguments of type %s",
566                                                         format_type_be(proc->proargtypes.values[i]))));
567                 }
568         }
569
570         /* Postpone body checks if !check_function_bodies */
571         if (check_function_bodies)
572         {
573                 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
574                 if (isnull)
575                         elog(ERROR, "null prosrc");
576
577                 prosrc = TextDatumGetCString(tmp);
578
579                 /*
580                  * Setup error traceback support for ereport().
581                  */
582                 sqlerrcontext.callback = sql_function_parse_error_callback;
583                 sqlerrcontext.arg = tuple;
584                 sqlerrcontext.previous = error_context_stack;
585                 error_context_stack = &sqlerrcontext;
586
587                 /*
588                  * We can't do full prechecking of the function definition if there
589                  * are any polymorphic input types, because actual datatypes of
590                  * expression results will be unresolvable.  The check will be done at
591                  * runtime instead.
592                  *
593                  * We can run the text through the raw parser though; this will at
594                  * least catch silly syntactic errors.
595                  */
596                 if (!haspolyarg)
597                 {
598                         querytree_list = pg_parse_and_rewrite(prosrc,
599                                                                                                   proc->proargtypes.values,
600                                                                                                   proc->pronargs);
601                         (void) check_sql_fn_retval(funcoid, proc->prorettype,
602                                                                            querytree_list,
603                                                                            false, NULL);
604                 }
605                 else
606                         querytree_list = pg_parse_query(prosrc);
607
608                 error_context_stack = sqlerrcontext.previous;
609         }
610
611         ReleaseSysCache(tuple);
612
613         PG_RETURN_VOID();
614 }
615
616 /*
617  * Error context callback for handling errors in SQL function definitions
618  */
619 static void
620 sql_function_parse_error_callback(void *arg)
621 {
622         HeapTuple       tuple = (HeapTuple) arg;
623         Form_pg_proc proc = (Form_pg_proc) GETSTRUCT(tuple);
624         bool            isnull;
625         Datum           tmp;
626         char       *prosrc;
627
628         /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
629         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
630         if (isnull)
631                 elog(ERROR, "null prosrc");
632         prosrc = TextDatumGetCString(tmp);
633
634         if (!function_parse_error_transpose(prosrc))
635         {
636                 /* If it's not a syntax error, push info onto context stack */
637                 errcontext("SQL function \"%s\"", NameStr(proc->proname));
638         }
639
640         pfree(prosrc);
641 }
642
643 /*
644  * Adjust a syntax error occurring inside the function body of a CREATE
645  * FUNCTION command.  This can be used by any function validator, not only
646  * for SQL-language functions.  It is assumed that the syntax error position
647  * is initially relative to the function body string (as passed in).  If
648  * possible, we adjust the position to reference the original CREATE command;
649  * if we can't manage that, we set up an "internal query" syntax error instead.
650  *
651  * Returns true if a syntax error was processed, false if not.
652  */
653 bool
654 function_parse_error_transpose(const char *prosrc)
655 {
656         int                     origerrposition;
657         int                     newerrposition;
658         const char *queryText;
659
660         /*
661          * Nothing to do unless we are dealing with a syntax error that has a
662          * cursor position.
663          *
664          * Some PLs may prefer to report the error position as an internal error
665          * to begin with, so check that too.
666          */
667         origerrposition = geterrposition();
668         if (origerrposition <= 0)
669         {
670                 origerrposition = getinternalerrposition();
671                 if (origerrposition <= 0)
672                         return false;
673         }
674
675         /* We can get the original query text from the active portal (hack...) */
676         Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
677         queryText = ActivePortal->sourceText;
678
679         /* Try to locate the prosrc in the original text */
680         newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
681
682         if (newerrposition > 0)
683         {
684                 /* Successful, so fix error position to reference original query */
685                 errposition(newerrposition);
686                 /* Get rid of any report of the error as an "internal query" */
687                 internalerrposition(0);
688                 internalerrquery(NULL);
689         }
690         else
691         {
692                 /*
693                  * If unsuccessful, convert the position to an internal position
694                  * marker and give the function text as the internal query.
695                  */
696                 errposition(0);
697                 internalerrposition(origerrposition);
698                 internalerrquery(prosrc);
699         }
700
701         return true;
702 }
703
704 /*
705  * Try to locate the string literal containing the function body in the
706  * given text of the CREATE FUNCTION command.  If successful, return the
707  * character (not byte) index within the command corresponding to the
708  * given character index within the literal.  If not successful, return 0.
709  */
710 static int
711 match_prosrc_to_query(const char *prosrc, const char *queryText,
712                                           int cursorpos)
713 {
714         /*
715          * Rather than fully parsing the CREATE FUNCTION command, we just scan the
716          * command looking for $prosrc$ or 'prosrc'.  This could be fooled (though
717          * not in any very probable scenarios), so fail if we find more than one
718          * match.
719          */
720         int                     prosrclen = strlen(prosrc);
721         int                     querylen = strlen(queryText);
722         int                     matchpos = 0;
723         int                     curpos;
724         int                     newcursorpos;
725
726         for (curpos = 0; curpos < querylen - prosrclen; curpos++)
727         {
728                 if (queryText[curpos] == '$' &&
729                         strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
730                         queryText[curpos + 1 + prosrclen] == '$')
731                 {
732                         /*
733                          * Found a $foo$ match.  Since there are no embedded quoting
734                          * characters in a dollar-quoted literal, we don't have to do any
735                          * fancy arithmetic; just offset by the starting position.
736                          */
737                         if (matchpos)
738                                 return 0;               /* multiple matches, fail */
739                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
740                                 + cursorpos;
741                 }
742                 else if (queryText[curpos] == '\'' &&
743                                  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
744                                                                                  cursorpos, &newcursorpos))
745                 {
746                         /*
747                          * Found a 'foo' match.  match_prosrc_to_literal() has adjusted
748                          * for any quotes or backslashes embedded in the literal.
749                          */
750                         if (matchpos)
751                                 return 0;               /* multiple matches, fail */
752                         matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
753                                 + newcursorpos;
754                 }
755         }
756
757         return matchpos;
758 }
759
760 /*
761  * Try to match the given source text to a single-quoted literal.
762  * If successful, adjust newcursorpos to correspond to the character
763  * (not byte) index corresponding to cursorpos in the source text.
764  *
765  * At entry, literal points just past a ' character.  We must check for the
766  * trailing quote.
767  */
768 static bool
769 match_prosrc_to_literal(const char *prosrc, const char *literal,
770                                                 int cursorpos, int *newcursorpos)
771 {
772         int                     newcp = cursorpos;
773         int                     chlen;
774
775         /*
776          * This implementation handles backslashes and doubled quotes in the
777          * string literal.      It does not handle the SQL syntax for literals
778          * continued across line boundaries.
779          *
780          * We do the comparison a character at a time, not a byte at a time, so
781          * that we can do the correct cursorpos math.
782          */
783         while (*prosrc)
784         {
785                 cursorpos--;                    /* characters left before cursor */
786
787                 /*
788                  * Check for backslashes and doubled quotes in the literal; adjust
789                  * newcp when one is found before the cursor.
790                  */
791                 if (*literal == '\\')
792                 {
793                         literal++;
794                         if (cursorpos > 0)
795                                 newcp++;
796                 }
797                 else if (*literal == '\'')
798                 {
799                         if (literal[1] != '\'')
800                                 goto fail;
801                         literal++;
802                         if (cursorpos > 0)
803                                 newcp++;
804                 }
805                 chlen = pg_mblen(prosrc);
806                 if (strncmp(prosrc, literal, chlen) != 0)
807                         goto fail;
808                 prosrc += chlen;
809                 literal += chlen;
810         }
811
812         if (*literal == '\'' && literal[1] != '\'')
813         {
814                 /* success */
815                 *newcursorpos = newcp;
816                 return true;
817         }
818
819 fail:
820         /* Must set *newcursorpos to suppress compiler warning */
821         *newcursorpos = newcp;
822         return false;
823 }