PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pg_proc.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * pg_proc.c
4 * routines to support manipulation of the pg_proc relation
5 *
6 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/catalog/pg_proc.c
12 *
13 *-------------------------------------------------------------------------
14 */
15#include "postgres.h"
16
17#include "access/htup_details.h"
18#include "access/table.h"
19#include "access/xact.h"
20#include "catalog/catalog.h"
21#include "catalog/dependency.h"
22#include "catalog/indexing.h"
23#include "catalog/namespace.h"
25#include "catalog/pg_language.h"
27#include "catalog/pg_proc.h"
29#include "catalog/pg_type.h"
30#include "executor/functions.h"
31#include "funcapi.h"
32#include "mb/pg_wchar.h"
33#include "miscadmin.h"
34#include "nodes/nodeFuncs.h"
35#include "parser/parse_coerce.h"
36#include "pgstat.h"
38#include "tcop/pquery.h"
39#include "tcop/tcopprot.h"
40#include "utils/acl.h"
41#include "utils/builtins.h"
42#include "utils/lsyscache.h"
43#include "utils/regproc.h"
44#include "utils/rel.h"
45#include "utils/syscache.h"
46
47
48typedef struct
49{
50 char *proname;
51 char *prosrc;
53
54static void sql_function_parse_error_callback(void *arg);
55static int match_prosrc_to_query(const char *prosrc, const char *queryText,
56 int cursorpos);
57static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
58 int cursorpos, int *newcursorpos);
59
60
61/* ----------------------------------------------------------------
62 * ProcedureCreate
63 *
64 * procedureName: string name of routine (proname)
65 * procNamespace: OID of namespace (pronamespace)
66 * replace: true to allow replacement of an existing pg_proc entry
67 * returnsSet: returns set? (proretset)
68 * returnType: OID of result type (prorettype)
69 * proowner: OID of owner role (proowner)
70 * languageObjectId: OID of function language (prolang)
71 * languageValidator: OID of validator function to apply, if any
72 * prosrc: string form of function definition (prosrc)
73 * probin: string form of binary reference, or NULL (probin)
74 * prosqlbody: Node tree of pre-parsed SQL body, or NULL (prosqlbody)
75 * prokind: function/aggregate/procedure/etc code (prokind)
76 * security_definer: security definer? (prosecdef)
77 * isLeakProof: leak proof? (proleakproof)
78 * isStrict: strict? (proisstrict)
79 * volatility: volatility code (provolatile)
80 * parallel: parallel safety code (proparallel)
81 * parameterTypes: input parameter types, as an oidvector (proargtypes)
82 * allParameterTypes: all parameter types, as an OID array (proallargtypes)
83 * parameterModes: parameter modes, as a "char" array (proargmodes)
84 * parameterNames: parameter names, as a text array (proargnames)
85 * parameterDefaults: defaults, as a List of Node trees (proargdefaults)
86 * trftypes: transformable type OIDs, as an OID array (protrftypes)
87 * trfoids: List of transform OIDs that routine should depend on
88 * proconfig: GUC set clauses, as a text array (proconfig)
89 * prosupport: OID of support function, if any (prosupport)
90 * procost: cost factor (procost)
91 * prorows: estimated output rows for a SRF (prorows)
92 *
93 * Note: allParameterTypes, parameterModes, parameterNames, trftypes, and proconfig
94 * are either arrays of the proper types or NULL. We declare them Datum,
95 * not "ArrayType *", to avoid importing array.h into pg_proc.h.
96 * ----------------------------------------------------------------
97 */
101 bool replace,
102 bool returnsSet,
103 Oid returnType,
107 const char *prosrc,
108 const char *probin,
110 char prokind,
111 bool security_definer,
112 bool isLeakProof,
113 bool isStrict,
114 char volatility,
115 char parallel,
116 oidvector *parameterTypes,
121 Datum trftypes,
122 List *trfoids,
127{
128 Oid retval;
129 int parameterCount;
130 int allParamCount;
131 Oid *allParams;
132 char *paramModes = NULL;
134 Acl *proacl = NULL;
135 Relation rel;
138 bool nulls[Natts_pg_proc];
141 NameData procname;
142 TupleDesc tupDesc;
143 bool is_update;
147 char *detailmsg;
148 int i;
149 ObjectAddresses *addrs;
150
151 /*
152 * sanity checks
153 */
154 Assert(prosrc);
155
156 parameterCount = parameterTypes->dim1;
160 errmsg_plural("functions cannot have more than %d argument",
161 "functions cannot have more than %d arguments",
163 FUNC_MAX_ARGS)));
164 /* note: the above is correct, we do NOT count output arguments */
165
166 /* Deconstruct array inputs */
168 {
169 /*
170 * We expect the array to be a 1-D OID array; verify that. We don't
171 * need to use deconstruct_array() since the array data is just going
172 * to look like a C array of OID values.
173 */
175
177 if (ARR_NDIM(allParamArray) != 1 ||
178 allParamCount <= 0 ||
181 elog(ERROR, "allParameterTypes is not a 1-D Oid array");
184 /* we assume caller got the contents right */
185 }
186 else
187 {
189 allParams = parameterTypes->values;
190 }
191
193 {
194 /*
195 * We expect the array to be a 1-D CHAR array; verify that. We don't
196 * need to use deconstruct_array() since the array data is just going
197 * to look like a C array of char values.
198 */
200
201 if (ARR_NDIM(modesArray) != 1 ||
205 elog(ERROR, "parameterModes is not a 1-D char array");
207 }
208
209 /*
210 * Do not allow polymorphic return type unless there is a polymorphic
211 * input argument that we can use to deduce the actual return type.
212 */
213 detailmsg = check_valid_polymorphic_signature(returnType,
214 parameterTypes->values,
216 if (detailmsg)
219 errmsg("cannot determine result data type"),
220 errdetail_internal("%s", detailmsg)));
221
222 /*
223 * Also, do not allow return type INTERNAL unless at least one input
224 * argument is INTERNAL.
225 */
226 detailmsg = check_valid_internal_signature(returnType,
227 parameterTypes->values,
229 if (detailmsg)
232 errmsg("unsafe use of pseudo-type \"internal\""),
233 errdetail_internal("%s", detailmsg)));
234
235 /*
236 * Apply the same tests to any OUT arguments.
237 */
239 {
240 for (i = 0; i < allParamCount; i++)
241 {
242 if (paramModes == NULL ||
245 continue; /* ignore input-only params */
246
248 parameterTypes->values,
250 if (detailmsg)
253 errmsg("cannot determine result data type"),
254 errdetail_internal("%s", detailmsg)));
256 parameterTypes->values,
258 if (detailmsg)
261 errmsg("unsafe use of pseudo-type \"internal\""),
262 errdetail_internal("%s", detailmsg)));
263 }
264 }
265
266 /* Identify variadic argument type, if any */
267 if (paramModes != NULL)
268 {
269 /*
270 * Only the last input parameter can be variadic; if it is, save its
271 * element type. Errors here are just elog since caller should have
272 * checked this already.
273 */
274 for (i = 0; i < allParamCount; i++)
275 {
276 switch (paramModes[i])
277 {
278 case PROARGMODE_IN:
279 case PROARGMODE_INOUT:
281 elog(ERROR, "variadic parameter must be last");
282 break;
283 case PROARGMODE_OUT:
284 if (OidIsValid(variadicType) && prokind == PROKIND_PROCEDURE)
285 elog(ERROR, "variadic parameter must be last");
286 break;
287 case PROARGMODE_TABLE:
288 /* okay */
289 break;
292 elog(ERROR, "variadic parameter must be last");
293 switch (allParams[i])
294 {
295 case ANYOID:
297 break;
298 case ANYARRAYOID:
300 break;
303 break;
304 default:
307 elog(ERROR, "variadic parameter is not an array");
308 break;
309 }
310 break;
311 default:
312 elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
313 break;
314 }
315 }
316 }
317
318 /*
319 * All seems OK; prepare the data to be inserted into pg_proc.
320 */
321
322 for (i = 0; i < Natts_pg_proc; ++i)
323 {
324 nulls[i] = false;
325 values[i] = (Datum) 0;
326 replaces[i] = true;
327 }
328
329 namestrcpy(&procname, procedureName);
330 values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
342 values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
348 values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
351 else
352 nulls[Anum_pg_proc_proallargtypes - 1] = true;
355 else
356 nulls[Anum_pg_proc_proargmodes - 1] = true;
359 else
360 nulls[Anum_pg_proc_proargnames - 1] = true;
361 if (parameterDefaults != NIL)
363 else
364 nulls[Anum_pg_proc_proargdefaults - 1] = true;
365 if (trftypes != PointerGetDatum(NULL))
366 values[Anum_pg_proc_protrftypes - 1] = trftypes;
367 else
368 nulls[Anum_pg_proc_protrftypes - 1] = true;
370 if (probin)
372 else
373 nulls[Anum_pg_proc_probin - 1] = true;
374 if (prosqlbody)
376 else
377 nulls[Anum_pg_proc_prosqlbody - 1] = true;
380 else
381 nulls[Anum_pg_proc_proconfig - 1] = true;
382 /* proacl will be determined later */
383
385 tupDesc = RelationGetDescr(rel);
386
387 /* Check for pre-existing definition */
390 PointerGetDatum(parameterTypes),
392
394 {
395 /* There is one; okay to replace it? */
398 bool isnull;
399 const char *dropcmd;
400
401 if (!replace)
404 errmsg("function \"%s\" already exists with same argument types",
405 procedureName)));
409
410 /* Not okay to change routine kind */
411 if (oldproc->prokind != prokind)
414 errmsg("cannot change routine kind"),
415 (oldproc->prokind == PROKIND_AGGREGATE ?
416 errdetail("\"%s\" is an aggregate function.", procedureName) :
417 oldproc->prokind == PROKIND_FUNCTION ?
418 errdetail("\"%s\" is a function.", procedureName) :
419 oldproc->prokind == PROKIND_PROCEDURE ?
420 errdetail("\"%s\" is a procedure.", procedureName) :
421 oldproc->prokind == PROKIND_WINDOW ?
422 errdetail("\"%s\" is a window function.", procedureName) :
423 0)));
424
425 dropcmd = (prokind == PROKIND_PROCEDURE ? "DROP PROCEDURE" :
426 prokind == PROKIND_AGGREGATE ? "DROP AGGREGATE" :
427 "DROP FUNCTION");
428
429 /*
430 * Not okay to change the return type of the existing proc, since
431 * existing rules, views, etc may depend on the return type.
432 *
433 * In case of a procedure, a changing return type means that whether
434 * the procedure has output parameters was changed. Since there is no
435 * user visible return type, we produce a more specific error message.
436 */
437 if (returnType != oldproc->prorettype ||
438 returnsSet != oldproc->proretset)
441 prokind == PROKIND_PROCEDURE
442 ? errmsg("cannot change whether a procedure has output parameters")
443 : errmsg("cannot change return type of existing function"),
444
445 /*
446 * translator: first %s is DROP FUNCTION, DROP PROCEDURE, or DROP
447 * AGGREGATE
448 */
449 errhint("Use %s %s first.",
450 dropcmd,
451 format_procedure(oldproc->oid))));
452
453 /*
454 * If it returns RECORD, check for possible change of record type
455 * implied by OUT parameters
456 */
457 if (returnType == RECORDOID)
458 {
461
467 if (olddesc == NULL && newdesc == NULL)
468 /* ok, both are runtime-defined RECORDs */ ;
469 else if (olddesc == NULL || newdesc == NULL ||
473 errmsg("cannot change return type of existing function"),
474 errdetail("Row type defined by OUT parameters is different."),
475 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
476 errhint("Use %s %s first.",
477 dropcmd,
478 format_procedure(oldproc->oid))));
479 }
480
481 /*
482 * If there were any named input parameters, check to make sure the
483 * names have not been changed, as this could break existing calls. We
484 * allow adding names to formerly unnamed parameters, though.
485 */
488 &isnull);
489 if (!isnull)
490 {
492 char **old_arg_names;
493 char **new_arg_names;
494 int n_old_arg_names;
495 int n_new_arg_names;
496 int j;
497
500 &isnull);
501 if (isnull)
502 proargmodes = PointerGetDatum(NULL); /* just to be sure */
503
510 for (j = 0; j < n_old_arg_names; j++)
511 {
512 if (old_arg_names[j] == NULL)
513 continue;
514 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
518 errmsg("cannot change name of input parameter \"%s\"",
520 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
521 errhint("Use %s %s first.",
522 dropcmd,
523 format_procedure(oldproc->oid))));
524 }
525 }
526
527 /*
528 * If there are existing defaults, check compatibility: redefinition
529 * must not remove any defaults nor change their types. (Removing a
530 * default might cause a function to fail to satisfy an existing call.
531 * Changing type would only be possible if the associated parameter is
532 * polymorphic, and in such cases a change of default type might alter
533 * the resolved output type of existing calls.)
534 */
535 if (oldproc->pronargdefaults != 0)
536 {
541
542 if (list_length(parameterDefaults) < oldproc->pronargdefaults)
545 errmsg("cannot remove parameter defaults from existing function"),
546 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
547 errhint("Use %s %s first.",
548 dropcmd,
549 format_procedure(oldproc->oid))));
550
554 Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
555
556 /* new list can have more defaults than old, advance over 'em */
559 oldproc->pronargdefaults);
560
561 foreach(oldlc, oldDefaults)
562 {
563 Node *oldDef = (Node *) lfirst(oldlc);
564 Node *newDef = (Node *) lfirst(newlc);
565
569 errmsg("cannot change data type of existing parameter default value"),
570 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
571 errhint("Use %s %s first.",
572 dropcmd,
573 format_procedure(oldproc->oid))));
575 }
576 }
577
578 /*
579 * Do not change existing oid, ownership or permissions, either. Note
580 * dependency-update code below has to agree with this decision.
581 */
582 replaces[Anum_pg_proc_oid - 1] = false;
583 replaces[Anum_pg_proc_proowner - 1] = false;
584 replaces[Anum_pg_proc_proacl - 1] = false;
585
586 /* Okay, do it... */
587 tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
588 CatalogTupleUpdate(rel, &tup->t_self, tup);
589
591 is_update = true;
592 }
593 else
594 {
595 /* Creating a new procedure */
596 Oid newOid;
597
598 /* First, get default permissions and set up proacl */
601 if (proacl != NULL)
603 else
604 nulls[Anum_pg_proc_proacl - 1] = true;
605
609 tup = heap_form_tuple(tupDesc, values, nulls);
611 is_update = false;
612 }
613
614
615 retval = ((Form_pg_proc) GETSTRUCT(tup))->oid;
616
617 /*
618 * Create dependencies for the new function. If we are updating an
619 * existing function, first delete any existing pg_depend entries.
620 * (However, since we are not changing ownership or permissions, the
621 * shared dependencies do *not* need to change, and we leave them alone.)
622 */
623 if (is_update)
625
626 addrs = new_object_addresses();
627
629
630 /* dependency on namespace */
633
634 /* dependency on implementation language */
637
638 /* dependency on return type */
641
642 /* dependency on parameter types */
643 for (i = 0; i < allParamCount; i++)
644 {
647 }
648
649 /* dependency on transforms, if any */
651 {
654 }
655
656 /* dependency on support function, if any */
658 {
661 }
662
663 /* dependencies appearing in new-style SQL routine body */
666
667 /* dependency on parameter default expressions */
670
671 /*
672 * Now that we have all the normal dependencies, thumb through them and
673 * warn if any are to temporary objects. This informs the user if their
674 * supposedly non-temp function will silently go away at session exit, due
675 * to a dependency on a temp object. However, do not complain when a
676 * function created in our own pg_temp namespace refers to other objects
677 * in that namespace, since then they'll have similar lifespans anyway.
678 */
681 (errmsg("function \"%s\" will be effectively temporary",
683 errdetail("It depends on temporary %s.",
685
686 /*
687 * Now record all normal dependencies at once. This will also remove any
688 * duplicates in the list. (Role and extension dependencies are handled
689 * separately below. Role dependencies would have to be separate anyway
690 * since they are shared dependencies. An extension dependency could be
691 * folded into the addrs list, but pg_depend.c doesn't make that easy, and
692 * it won't duplicate anything we've collected so far anyway.)
693 */
695
697
698 /* dependency on owner */
699 if (!is_update)
701
702 /* dependency on any roles mentioned in ACL */
703 if (!is_update)
706
707 /* dependency on extension */
709
711
712 /* Post creation hook for new function */
714
716
717 /* Verify function body */
719 {
721 int save_nestlevel = 0;
722
723 /* Advance command counter so new tuple can be seen by validator */
725
726 /*
727 * Set per-function configuration parameters so that the validation is
728 * done with the environment the function expects. However, if
729 * check_function_bodies is off, we don't do this, because that would
730 * create dump ordering hazards that pg_dump doesn't know how to deal
731 * with. (For example, a SET clause might refer to a not-yet-created
732 * text search configuration.) This means that the validator
733 * shouldn't complain about anything that might depend on a GUC
734 * parameter when check_function_bodies is off.
735 */
737 {
739 if (set_items) /* Need a new GUC nesting level */
740 {
741 save_nestlevel = NewGUCNestLevel();
746 }
747 }
748
750
751 if (set_items)
752 AtEOXact_GUC(true, save_nestlevel);
753 }
754
755 /* ensure that stats are dropped if transaction aborts */
756 if (!is_update)
758
759 return myself;
760}
761
762
763
764/*
765 * Validator for internal functions
766 *
767 * Check that the given internal function name (the "prosrc" value) is
768 * a known builtin function.
769 */
770Datum
772{
774 HeapTuple tuple;
775 Datum tmp;
776 char *prosrc;
777
778 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
780
781 /*
782 * We do not honor check_function_bodies since it's unlikely the function
783 * name will be found later if it isn't there now.
784 */
785
787 if (!HeapTupleIsValid(tuple))
788 elog(ERROR, "cache lookup failed for function %u", funcoid);
789
791 prosrc = TextDatumGetCString(tmp);
792
793 if (fmgr_internal_function(prosrc) == InvalidOid)
796 errmsg("there is no built-in function named \"%s\"",
797 prosrc)));
798
799 ReleaseSysCache(tuple);
800
802}
803
804
805
806/*
807 * Validator for C language functions
808 *
809 * Make sure that the library file exists, is loadable, and contains
810 * the specified link symbol. Also check for a valid function
811 * information record.
812 */
813Datum
815{
817 void *libraryhandle;
818 HeapTuple tuple;
819 Datum tmp;
820 char *prosrc;
821 char *probin;
822
823 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
825
826 /*
827 * It'd be most consistent to skip the check if !check_function_bodies,
828 * but the purpose of that switch is to be helpful for pg_dump loading,
829 * and for pg_dump loading it's much better if we *do* check.
830 */
831
833 if (!HeapTupleIsValid(tuple))
834 elog(ERROR, "cache lookup failed for function %u", funcoid);
835
837 prosrc = TextDatumGetCString(tmp);
838
841
844
845 ReleaseSysCache(tuple);
846
848}
849
850
851/*
852 * Validator for SQL language functions
853 *
854 * Parse it here in order to be sure that it contains no syntax errors.
855 */
856Datum
858{
860 HeapTuple tuple;
861 Form_pg_proc proc;
864 ListCell *lc;
865 bool isnull;
866 Datum tmp;
867 char *prosrc;
868 parse_error_callback_arg callback_arg;
870 bool haspolyarg;
871 int i;
872
873 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
875
877 if (!HeapTupleIsValid(tuple))
878 elog(ERROR, "cache lookup failed for function %u", funcoid);
879 proc = (Form_pg_proc) GETSTRUCT(tuple);
880
881 /* Disallow pseudotype result */
882 /* except for RECORD, VOID, or polymorphic */
883 if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
884 proc->prorettype != RECORDOID &&
885 proc->prorettype != VOIDOID &&
886 !IsPolymorphicType(proc->prorettype))
889 errmsg("SQL functions cannot return type %s",
890 format_type_be(proc->prorettype))));
891
892 /* Disallow pseudotypes in arguments */
893 /* except for polymorphic */
894 haspolyarg = false;
895 for (i = 0; i < proc->pronargs; i++)
896 {
897 if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
898 {
899 if (IsPolymorphicType(proc->proargtypes.values[i]))
900 haspolyarg = true;
901 else
904 errmsg("SQL functions cannot have arguments of type %s",
905 format_type_be(proc->proargtypes.values[i]))));
906 }
907 }
908
909 /* Postpone body checks if !check_function_bodies */
911 {
913 prosrc = TextDatumGetCString(tmp);
914
915 /*
916 * Setup error traceback support for ereport().
917 */
918 callback_arg.proname = NameStr(proc->proname);
919 callback_arg.prosrc = prosrc;
920
922 sqlerrcontext.arg = &callback_arg;
925
926 /* If we have prosqlbody, pay attention to that not prosrc */
927 tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
928 if (!isnull)
929 {
930 Node *n;
932
934 if (IsA(n, List))
936 else
938
940 foreach(lc, stored_query_list)
941 {
942 Query *parsetree = lfirst_node(Query, lc);
944
945 /*
946 * Typically, we'd have acquired locks already while parsing
947 * the body of the CREATE FUNCTION command. However, a
948 * validator function cannot assume that it's only called in
949 * that context.
950 */
951 AcquireRewriteLocks(parsetree, true, false);
954 }
955 }
956 else
957 {
958 /*
959 * We can't do full prechecking of the function definition if
960 * there are any polymorphic input types, because actual datatypes
961 * of expression results will be unresolvable. The check will be
962 * done at runtime instead.
963 *
964 * We can run the text through the raw parser though; this will at
965 * least catch silly syntactic errors.
966 */
969
970 if (!haspolyarg)
971 {
972 /*
973 * OK to do full precheck: analyze and rewrite the queries,
974 * then verify the result type.
975 */
977
978 /* But first, set up parameter information */
980
981 foreach(lc, raw_parsetree_list)
982 {
983 RawStmt *parsetree = lfirst_node(RawStmt, lc);
985
987 prosrc,
989 pinfo,
990 NULL);
993 }
994 }
995 }
996
997 if (!haspolyarg)
998 {
999 Oid rettype;
1000 TupleDesc rettupdesc;
1001
1003
1004 (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
1005
1007 rettype, rettupdesc,
1008 proc->prokind,
1009 false);
1010 }
1011
1013 }
1014
1015 ReleaseSysCache(tuple);
1016
1018}
1019
1020/*
1021 * Error context callback for handling errors in SQL function definitions
1022 */
1023static void
1025{
1027
1028 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
1029 if (!function_parse_error_transpose(callback_arg->prosrc))
1030 {
1031 /* If it's not a syntax error, push info onto context stack */
1032 errcontext("SQL function \"%s\"", callback_arg->proname);
1033 }
1034}
1035
1036/*
1037 * Adjust a syntax error occurring inside the function body of a CREATE
1038 * FUNCTION or DO command. This can be used by any function validator or
1039 * anonymous-block handler, not only for SQL-language functions.
1040 * It is assumed that the syntax error position is initially relative to the
1041 * function body string (as passed in). If possible, we adjust the position
1042 * to reference the original command text; if we can't manage that, we set
1043 * up an "internal query" syntax error instead.
1044 *
1045 * Returns true if a syntax error was processed, false if not.
1046 */
1047bool
1049{
1050 int origerrposition;
1051 int newerrposition;
1052
1053 /*
1054 * Nothing to do unless we are dealing with a syntax error that has a
1055 * cursor position.
1056 *
1057 * Some PLs may prefer to report the error position as an internal error
1058 * to begin with, so check that too.
1059 */
1061 if (origerrposition <= 0)
1062 {
1064 if (origerrposition <= 0)
1065 return false;
1066 }
1067
1068 /* We can get the original query text from the active portal (hack...) */
1070 {
1071 const char *queryText = ActivePortal->sourceText;
1072
1073 /* Try to locate the prosrc in the original text */
1076 }
1077 else
1078 {
1079 /*
1080 * Quietly give up if no ActivePortal. This is an unusual situation
1081 * but it can happen in, e.g., logical replication workers.
1082 */
1083 newerrposition = -1;
1084 }
1085
1086 if (newerrposition > 0)
1087 {
1088 /* Successful, so fix error position to reference original query */
1090 /* Get rid of any report of the error as an "internal query" */
1093 }
1094 else
1095 {
1096 /*
1097 * If unsuccessful, convert the position to an internal position
1098 * marker and give the function text as the internal query.
1099 */
1100 errposition(0);
1102 internalerrquery(prosrc);
1103 }
1104
1105 return true;
1106}
1107
1108/*
1109 * Try to locate the string literal containing the function body in the
1110 * given text of the CREATE FUNCTION or DO command. If successful, return
1111 * the character (not byte) index within the command corresponding to the
1112 * given character index within the literal. If not successful, return 0.
1113 */
1114static int
1115match_prosrc_to_query(const char *prosrc, const char *queryText,
1116 int cursorpos)
1117{
1118 /*
1119 * Rather than fully parsing the original command, we just scan the
1120 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1121 * not in any very probable scenarios), so fail if we find more than one
1122 * match.
1123 */
1124 int prosrclen = strlen(prosrc);
1125 int querylen = strlen(queryText);
1126 int matchpos = 0;
1127 int curpos;
1128 int newcursorpos;
1129
1130 for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1131 {
1132 if (queryText[curpos] == '$' &&
1133 strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1134 queryText[curpos + 1 + prosrclen] == '$')
1135 {
1136 /*
1137 * Found a $foo$ match. Since there are no embedded quoting
1138 * characters in a dollar-quoted literal, we don't have to do any
1139 * fancy arithmetic; just offset by the starting position.
1140 */
1141 if (matchpos)
1142 return 0; /* multiple matches, fail */
1144 + cursorpos;
1145 }
1146 else if (queryText[curpos] == '\'' &&
1148 cursorpos, &newcursorpos))
1149 {
1150 /*
1151 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1152 * for any quotes or backslashes embedded in the literal.
1153 */
1154 if (matchpos)
1155 return 0; /* multiple matches, fail */
1157 + newcursorpos;
1158 }
1159 }
1160
1161 return matchpos;
1162}
1163
1164/*
1165 * Try to match the given source text to a single-quoted literal.
1166 * If successful, adjust newcursorpos to correspond to the character
1167 * (not byte) index corresponding to cursorpos in the source text.
1168 *
1169 * At entry, literal points just past a ' character. We must check for the
1170 * trailing quote.
1171 */
1172static bool
1173match_prosrc_to_literal(const char *prosrc, const char *literal,
1174 int cursorpos, int *newcursorpos)
1175{
1176 int newcp = cursorpos;
1177 int chlen;
1178
1179 /*
1180 * This implementation handles backslashes and doubled quotes in the
1181 * string literal. It does not handle the SQL syntax for literals
1182 * continued across line boundaries.
1183 *
1184 * We do the comparison a character at a time, not a byte at a time, so
1185 * that we can do the correct cursorpos math.
1186 */
1187 while (*prosrc)
1188 {
1189 cursorpos--; /* characters left before cursor */
1190
1191 /*
1192 * Check for backslashes and doubled quotes in the literal; adjust
1193 * newcp when one is found before the cursor.
1194 */
1195 if (*literal == '\\')
1196 {
1197 literal++;
1198 if (cursorpos > 0)
1199 newcp++;
1200 }
1201 else if (*literal == '\'')
1202 {
1203 if (literal[1] != '\'')
1204 goto fail;
1205 literal++;
1206 if (cursorpos > 0)
1207 newcp++;
1208 }
1209 chlen = pg_mblen(prosrc);
1210 if (strncmp(prosrc, literal, chlen) != 0)
1211 goto fail;
1212 prosrc += chlen;
1213 literal += chlen;
1214 }
1215
1216 if (*literal == '\'' && literal[1] != '\'')
1217 {
1218 /* success */
1220 return true;
1221 }
1222
1223fail:
1224 /* Must set *newcursorpos to suppress compiler warning */
1226 return false;
1227}
1228
1229List *
1231{
1232 ArrayType *array = DatumGetArrayTypeP(datum);
1233 Datum *values;
1234 int nelems;
1235 int i;
1236 List *result = NIL;
1237
1238 deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems);
1239 for (i = 0; i < nelems; i++)
1240 result = lappend_oid(result, DatumGetObjectId(values[i]));
1241 return result;
1242}
@ ACLCHECK_NOT_OWNER
Definition acl.h:185
void recordDependencyOnNewAcl(Oid classId, Oid objectId, int32 objsubId, Oid ownerId, Acl *acl)
Definition aclchk.c:4327
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2654
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4090
Acl * get_user_default_acl(ObjectType objtype, Oid ownerId, Oid nsp_oid)
Definition aclchk.c:4247
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define DatumGetArrayTypeP(X)
Definition array.h:261
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
#define ARR_HASNULL(a)
Definition array.h:291
void deconstruct_array_builtin(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
static Datum values[MAXATTR]
Definition bootstrap.c:155
#define CStringGetTextDatum(s)
Definition builtins.h:97
#define TextDatumGetCString(d)
Definition builtins.h:98
#define NameStr(name)
Definition c.h:765
#define Assert(condition)
Definition c.h:873
float float4
Definition c.h:643
#define OidIsValid(objectId)
Definition c.h:788
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
void record_object_address_dependencies(const ObjectAddress *depender, ObjectAddresses *referenced, DependencyType behavior)
void collectDependenciesOfExpr(ObjectAddresses *addrs, Node *expr, List *rtable)
bool find_temp_object(const ObjectAddresses *addrs, bool local_temp_okay, ObjectAddress *foundobj)
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
ObjectAddresses * new_object_addresses(void)
void free_object_addresses(ObjectAddresses *addrs)
@ DEPENDENCY_NORMAL
Definition dependency.h:33
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition dfmgr.c:95
int getinternalerrposition(void)
Definition elog.c:1629
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition elog.c:1193
int internalerrquery(const char *query)
Definition elog.c:1516
int internalerrposition(int cursorpos)
Definition elog.c:1496
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
int errdetail(const char *fmt,...)
Definition elog.c:1216
ErrorContextCallback * error_context_stack
Definition elog.c:95
int errhint(const char *fmt,...)
Definition elog.c:1330
int geterrposition(void)
Definition elog.c:1612
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
int errposition(int cursorpos)
Definition elog.c:1480
#define errcontext
Definition elog.h:198
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define NOTICE
Definition elog.h:35
#define ereport(elevel,...)
Definition elog.h:150
Oid fmgr_internal_function(const char *proname)
Definition fmgr.c:596
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition fmgr.c:2110
const Pg_finfo_record * fetch_finfo_record(void *filehandle, const char *funcname)
Definition fmgr.c:456
#define PG_RETURN_VOID()
Definition fmgr.h:350
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
char * format_type_be(Oid type_oid)
TupleDesc build_function_result_tupdesc_t(HeapTuple procTuple)
Definition funcapi.c:1705
TupleDesc build_function_result_tupdesc_d(char prokind, Datum proallargtypes, Datum proargmodes, Datum proargnames)
Definition funcapi.c:1751
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition funcapi.c:1522
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition funcapi.c:410
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, char prokind, bool insertDroppedCols)
Definition functions.c:2116
void check_sql_fn_statements(List *queryTreeLists)
Definition functions.c:2035
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition functions.c:340
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition functions.c:251
int NewGUCNestLevel(void)
Definition guc.c:2110
void ProcessGUCArray(ArrayType *array, GucContext context, GucSource source, GucAction action)
Definition guc.c:6296
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2137
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_SUSET
Definition guc.h:78
@ PGC_USERSET
Definition guc.h:79
bool check_function_bodies
Definition guc_tables.c:529
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1117
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
int j
Definition isn.c:78
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
#define RowExclusiveLock
Definition lockdefs.h:38
Oid get_element_type(Oid typid)
Definition lsyscache.c:2909
char get_typtype(Oid typid)
Definition lsyscache.c:2779
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition mbutils.c:1060
int pg_mblen(const char *mbstr)
Definition mbutils.c:1026
void namestrcpy(Name name, const char *str)
Definition name.c:233
bool isTempNamespace(Oid namespaceId)
Definition namespace.c:3719
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define castNode(_type_, nodeptr)
Definition nodes.h:182
#define InvokeObjectPostCreateHook(classId, objectId, subId)
char * getObjectDescription(const ObjectAddress *object, bool missing_ok)
#define ObjectAddressSet(addr, class_id, object_id)
char * nodeToString(const void *obj)
Definition outfuncs.c:802
void(* ParserSetupHook)(ParseState *pstate, void *arg)
Definition params.h:107
char * check_valid_internal_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
char * check_valid_polymorphic_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
@ OBJECT_FUNCTION
void * arg
#define FUNC_MAX_ARGS
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition pg_depend.c:301
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition pg_depend.c:193
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:212
#define linitial(l)
Definition pg_list.h:178
static ListCell * list_nth_cell(const List *list, int n)
Definition pg_list.h:277
#define foreach_oid(var, lst)
Definition pg_list.h:471
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:343
ObjectAddress ProcedureCreate(const char *procedureName, Oid procNamespace, bool replace, bool returnsSet, Oid returnType, Oid proowner, Oid languageObjectId, Oid languageValidator, const char *prosrc, const char *probin, Node *prosqlbody, char prokind, bool security_definer, bool isLeakProof, bool isStrict, char volatility, char parallel, oidvector *parameterTypes, Datum allParameterTypes, Datum parameterModes, Datum parameterNames, List *parameterDefaults, Datum trftypes, List *trfoids, Datum proconfig, Oid prosupport, float4 procost, float4 prorows)
Definition pg_proc.c:99
static void sql_function_parse_error_callback(void *arg)
Definition pg_proc.c:1024
Datum fmgr_internal_validator(PG_FUNCTION_ARGS)
Definition pg_proc.c:771
Datum fmgr_c_validator(PG_FUNCTION_ARGS)
Definition pg_proc.c:814
List * oid_array_to_list(Datum datum)
Definition pg_proc.c:1230
static bool match_prosrc_to_literal(const char *prosrc, const char *literal, int cursorpos, int *newcursorpos)
Definition pg_proc.c:1173
bool function_parse_error_transpose(const char *prosrc)
Definition pg_proc.c:1048
Datum fmgr_sql_validator(PG_FUNCTION_ARGS)
Definition pg_proc.c:857
static int match_prosrc_to_query(const char *prosrc, const char *queryText, int cursorpos)
Definition pg_proc.c:1115
FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:136
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
void pgstat_create_function(Oid proid)
@ PORTAL_ACTIVE
Definition portal.h:108
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition postgres.c:763
List * pg_parse_query(const char *query_string)
Definition postgres.c:604
List * pg_rewrite_query(Query *query)
Definition postgres.c:803
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum Float4GetDatum(float4 X)
Definition postgres.h:478
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:252
static Datum UInt16GetDatum(uint16 X)
Definition postgres.h:202
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
static Datum NameGetDatum(const NameData *X)
Definition postgres.h:403
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static Datum CharGetDatum(char X)
Definition postgres.h:132
#define InvalidOid
unsigned int Oid
Portal ActivePortal
Definition pquery.c:36
static int fb(int x)
void * stringToNode(const char *str)
Definition read.c:90
char * format_procedure(Oid procedure_oid)
Definition regproc.c:305
#define RelationGetDescr(relation)
Definition rel.h:540
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
struct ErrorContextCallback * previous
Definition elog.h:297
Definition pg_list.h:54
Definition nodes.h:135
const char * sourceText
Definition portal.h:136
PortalStatus status
Definition portal.h:150
Definition c.h:760
Definition c.h:745
int dim1
Definition c.h:750
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition c.h:752
bool superuser(void)
Definition superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition syscache.c:240
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
bool equalRowTypes(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition tupdesc.c:777
void CommandCounterIncrement(void)
Definition xact.c:1101