OSDN Git Service

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