1 /*-------------------------------------------------------------------------
4 * routines to support manipulation of the pg_proc relation
6 * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/catalog/pg_proc.c
13 *-------------------------------------------------------------------------
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/objectaccess.h"
24 #include "catalog/pg_language.h"
25 #include "catalog/pg_namespace.h"
26 #include "catalog/pg_proc.h"
27 #include "catalog/pg_transform.h"
28 #include "catalog/pg_type.h"
29 #include "commands/defrem.h"
30 #include "executor/functions.h"
32 #include "mb/pg_wchar.h"
33 #include "miscadmin.h"
34 #include "nodes/nodeFuncs.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_type.h"
37 #include "tcop/pquery.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/acl.h"
40 #include "utils/builtins.h"
41 #include "utils/lsyscache.h"
42 #include "utils/regproc.h"
43 #include "utils/rel.h"
44 #include "utils/syscache.h"
51 } parse_error_callback_arg
;
53 static void sql_function_parse_error_callback(void *arg
);
54 static int match_prosrc_to_query(const char *prosrc
, const char *queryText
,
56 static bool match_prosrc_to_literal(const char *prosrc
, const char *literal
,
57 int cursorpos
, int *newcursorpos
);
60 /* ----------------------------------------------------------------
63 * Note: allParameterTypes, parameterModes, parameterNames, trftypes, and proconfig
64 * are either arrays of the proper types or NULL. We declare them Datum,
65 * not "ArrayType *", to avoid importing array.h into pg_proc.h.
66 * ----------------------------------------------------------------
69 ProcedureCreate(const char *procedureName
,
76 Oid languageValidator
,
80 bool security_definer
,
85 oidvector
*parameterTypes
,
86 Datum allParameterTypes
,
89 List
*parameterDefaults
,
100 char *paramModes
= NULL
;
101 Oid variadicType
= InvalidOid
;
106 bool nulls
[Natts_pg_proc
];
107 Datum values
[Natts_pg_proc
];
108 bool replaces
[Natts_pg_proc
];
112 ObjectAddress myself
,
121 Assert(PointerIsValid(prosrc
));
123 parameterCount
= parameterTypes
->dim1
;
124 if (parameterCount
< 0 || parameterCount
> FUNC_MAX_ARGS
)
126 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
127 errmsg_plural("functions cannot have more than %d argument",
128 "functions cannot have more than %d arguments",
131 /* note: the above is correct, we do NOT count output arguments */
133 /* Deconstruct array inputs */
134 if (allParameterTypes
!= PointerGetDatum(NULL
))
137 * We expect the array to be a 1-D OID array; verify that. We don't
138 * need to use deconstruct_array() since the array data is just going
139 * to look like a C array of OID values.
141 ArrayType
*allParamArray
= (ArrayType
*) DatumGetPointer(allParameterTypes
);
143 allParamCount
= ARR_DIMS(allParamArray
)[0];
144 if (ARR_NDIM(allParamArray
) != 1 ||
145 allParamCount
<= 0 ||
146 ARR_HASNULL(allParamArray
) ||
147 ARR_ELEMTYPE(allParamArray
) != OIDOID
)
148 elog(ERROR
, "allParameterTypes is not a 1-D Oid array");
149 allParams
= (Oid
*) ARR_DATA_PTR(allParamArray
);
150 Assert(allParamCount
>= parameterCount
);
151 /* we assume caller got the contents right */
155 allParamCount
= parameterCount
;
156 allParams
= parameterTypes
->values
;
159 if (parameterModes
!= PointerGetDatum(NULL
))
162 * We expect the array to be a 1-D CHAR array; verify that. We don't
163 * need to use deconstruct_array() since the array data is just going
164 * to look like a C array of char values.
166 ArrayType
*modesArray
= (ArrayType
*) DatumGetPointer(parameterModes
);
168 if (ARR_NDIM(modesArray
) != 1 ||
169 ARR_DIMS(modesArray
)[0] != allParamCount
||
170 ARR_HASNULL(modesArray
) ||
171 ARR_ELEMTYPE(modesArray
) != CHAROID
)
172 elog(ERROR
, "parameterModes is not a 1-D char array");
173 paramModes
= (char *) ARR_DATA_PTR(modesArray
);
177 * Do not allow polymorphic return type unless there is a polymorphic
178 * input argument that we can use to deduce the actual return type.
180 detailmsg
= check_valid_polymorphic_signature(returnType
,
181 parameterTypes
->values
,
185 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
186 errmsg("cannot determine result data type"),
187 errdetail_internal("%s", detailmsg
)));
190 * Also, do not allow return type INTERNAL unless at least one input
191 * argument is INTERNAL.
193 detailmsg
= check_valid_internal_signature(returnType
,
194 parameterTypes
->values
,
198 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
199 errmsg("unsafe use of pseudo-type \"internal\""),
200 errdetail_internal("%s", detailmsg
)));
203 * Apply the same tests to any OUT arguments.
205 if (allParameterTypes
!= PointerGetDatum(NULL
))
207 for (i
= 0; i
< allParamCount
; i
++)
209 if (paramModes
== NULL
||
210 paramModes
[i
] == PROARGMODE_IN
||
211 paramModes
[i
] == PROARGMODE_VARIADIC
)
212 continue; /* ignore input-only params */
214 detailmsg
= check_valid_polymorphic_signature(allParams
[i
],
215 parameterTypes
->values
,
219 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
220 errmsg("cannot determine result data type"),
221 errdetail_internal("%s", detailmsg
)));
222 detailmsg
= check_valid_internal_signature(allParams
[i
],
223 parameterTypes
->values
,
227 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
228 errmsg("unsafe use of pseudo-type \"internal\""),
229 errdetail_internal("%s", detailmsg
)));
233 /* Identify variadic argument type, if any */
234 if (paramModes
!= NULL
)
237 * Only the last input parameter can be variadic; if it is, save its
238 * element type. Errors here are just elog since caller should have
239 * checked this already.
241 for (i
= 0; i
< allParamCount
; i
++)
243 switch (paramModes
[i
])
246 case PROARGMODE_INOUT
:
247 if (OidIsValid(variadicType
))
248 elog(ERROR
, "variadic parameter must be last");
251 case PROARGMODE_TABLE
:
254 case PROARGMODE_VARIADIC
:
255 if (OidIsValid(variadicType
))
256 elog(ERROR
, "variadic parameter must be last");
257 switch (allParams
[i
])
260 variadicType
= ANYOID
;
263 variadicType
= ANYELEMENTOID
;
265 case ANYCOMPATIBLEARRAYOID
:
266 variadicType
= ANYCOMPATIBLEOID
;
269 variadicType
= get_element_type(allParams
[i
]);
270 if (!OidIsValid(variadicType
))
271 elog(ERROR
, "variadic parameter is not an array");
276 elog(ERROR
, "invalid parameter mode '%c'", paramModes
[i
]);
283 * All seems OK; prepare the data to be inserted into pg_proc.
286 for (i
= 0; i
< Natts_pg_proc
; ++i
)
289 values
[i
] = (Datum
) 0;
293 namestrcpy(&procname
, procedureName
);
294 values
[Anum_pg_proc_proname
- 1] = NameGetDatum(&procname
);
295 values
[Anum_pg_proc_pronamespace
- 1] = ObjectIdGetDatum(procNamespace
);
296 values
[Anum_pg_proc_proowner
- 1] = ObjectIdGetDatum(proowner
);
297 values
[Anum_pg_proc_prolang
- 1] = ObjectIdGetDatum(languageObjectId
);
298 values
[Anum_pg_proc_procost
- 1] = Float4GetDatum(procost
);
299 values
[Anum_pg_proc_prorows
- 1] = Float4GetDatum(prorows
);
300 values
[Anum_pg_proc_provariadic
- 1] = ObjectIdGetDatum(variadicType
);
301 values
[Anum_pg_proc_prosupport
- 1] = ObjectIdGetDatum(prosupport
);
302 values
[Anum_pg_proc_prokind
- 1] = CharGetDatum(prokind
);
303 values
[Anum_pg_proc_prosecdef
- 1] = BoolGetDatum(security_definer
);
304 values
[Anum_pg_proc_proleakproof
- 1] = BoolGetDatum(isLeakProof
);
305 values
[Anum_pg_proc_proisstrict
- 1] = BoolGetDatum(isStrict
);
306 values
[Anum_pg_proc_proretset
- 1] = BoolGetDatum(returnsSet
);
307 values
[Anum_pg_proc_provolatile
- 1] = CharGetDatum(volatility
);
308 values
[Anum_pg_proc_proparallel
- 1] = CharGetDatum(parallel
);
309 values
[Anum_pg_proc_pronargs
- 1] = UInt16GetDatum(parameterCount
);
310 values
[Anum_pg_proc_pronargdefaults
- 1] = UInt16GetDatum(list_length(parameterDefaults
));
311 values
[Anum_pg_proc_prorettype
- 1] = ObjectIdGetDatum(returnType
);
312 values
[Anum_pg_proc_proargtypes
- 1] = PointerGetDatum(parameterTypes
);
313 if (allParameterTypes
!= PointerGetDatum(NULL
))
314 values
[Anum_pg_proc_proallargtypes
- 1] = allParameterTypes
;
316 nulls
[Anum_pg_proc_proallargtypes
- 1] = true;
317 if (parameterModes
!= PointerGetDatum(NULL
))
318 values
[Anum_pg_proc_proargmodes
- 1] = parameterModes
;
320 nulls
[Anum_pg_proc_proargmodes
- 1] = true;
321 if (parameterNames
!= PointerGetDatum(NULL
))
322 values
[Anum_pg_proc_proargnames
- 1] = parameterNames
;
324 nulls
[Anum_pg_proc_proargnames
- 1] = true;
325 if (parameterDefaults
!= NIL
)
326 values
[Anum_pg_proc_proargdefaults
- 1] = CStringGetTextDatum(nodeToString(parameterDefaults
));
328 nulls
[Anum_pg_proc_proargdefaults
- 1] = true;
329 if (trftypes
!= PointerGetDatum(NULL
))
330 values
[Anum_pg_proc_protrftypes
- 1] = trftypes
;
332 nulls
[Anum_pg_proc_protrftypes
- 1] = true;
333 values
[Anum_pg_proc_prosrc
- 1] = CStringGetTextDatum(prosrc
);
335 values
[Anum_pg_proc_probin
- 1] = CStringGetTextDatum(probin
);
337 nulls
[Anum_pg_proc_probin
- 1] = true;
338 if (proconfig
!= PointerGetDatum(NULL
))
339 values
[Anum_pg_proc_proconfig
- 1] = proconfig
;
341 nulls
[Anum_pg_proc_proconfig
- 1] = true;
342 /* proacl will be determined later */
344 rel
= table_open(ProcedureRelationId
, RowExclusiveLock
);
345 tupDesc
= RelationGetDescr(rel
);
347 /* Check for pre-existing definition */
348 oldtup
= SearchSysCache3(PROCNAMEARGSNSP
,
349 PointerGetDatum(procedureName
),
350 PointerGetDatum(parameterTypes
),
351 ObjectIdGetDatum(procNamespace
));
353 if (HeapTupleIsValid(oldtup
))
355 /* There is one; okay to replace it? */
356 Form_pg_proc oldproc
= (Form_pg_proc
) GETSTRUCT(oldtup
);
363 (errcode(ERRCODE_DUPLICATE_FUNCTION
),
364 errmsg("function \"%s\" already exists with same argument types",
366 if (!pg_proc_ownercheck(oldproc
->oid
, proowner
))
367 aclcheck_error(ACLCHECK_NOT_OWNER
, OBJECT_FUNCTION
,
370 /* Not okay to change routine kind */
371 if (oldproc
->prokind
!= prokind
)
373 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
374 errmsg("cannot change routine kind"),
375 (oldproc
->prokind
== PROKIND_AGGREGATE
?
376 errdetail("\"%s\" is an aggregate function.", procedureName
) :
377 oldproc
->prokind
== PROKIND_FUNCTION
?
378 errdetail("\"%s\" is a function.", procedureName
) :
379 oldproc
->prokind
== PROKIND_PROCEDURE
?
380 errdetail("\"%s\" is a procedure.", procedureName
) :
381 oldproc
->prokind
== PROKIND_WINDOW
?
382 errdetail("\"%s\" is a window function.", procedureName
) :
385 dropcmd
= (prokind
== PROKIND_PROCEDURE
? "DROP PROCEDURE" :
386 prokind
== PROKIND_AGGREGATE
? "DROP AGGREGATE" :
390 * Not okay to change the return type of the existing proc, since
391 * existing rules, views, etc may depend on the return type.
393 * In case of a procedure, a changing return type means that whether
394 * the procedure has output parameters was changed. Since there is no
395 * user visible return type, we produce a more specific error message.
397 if (returnType
!= oldproc
->prorettype
||
398 returnsSet
!= oldproc
->proretset
)
400 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
401 prokind
== PROKIND_PROCEDURE
402 ? errmsg("cannot change whether a procedure has output parameters")
403 : errmsg("cannot change return type of existing function"),
406 * translator: first %s is DROP FUNCTION, DROP PROCEDURE, or DROP
409 errhint("Use %s %s first.",
411 format_procedure(oldproc
->oid
))));
414 * If it returns RECORD, check for possible change of record type
415 * implied by OUT parameters
417 if (returnType
== RECORDOID
)
422 olddesc
= build_function_result_tupdesc_t(oldtup
);
423 newdesc
= build_function_result_tupdesc_d(prokind
,
427 if (olddesc
== NULL
&& newdesc
== NULL
)
428 /* ok, both are runtime-defined RECORDs */ ;
429 else if (olddesc
== NULL
|| newdesc
== NULL
||
430 !equalTupleDescs(olddesc
, newdesc
))
432 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
433 errmsg("cannot change return type of existing function"),
434 errdetail("Row type defined by OUT parameters is different."),
435 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
436 errhint("Use %s %s first.",
438 format_procedure(oldproc
->oid
))));
442 * If there were any named input parameters, check to make sure the
443 * names have not been changed, as this could break existing calls. We
444 * allow adding names to formerly unnamed parameters, though.
446 proargnames
= SysCacheGetAttr(PROCNAMEARGSNSP
, oldtup
,
447 Anum_pg_proc_proargnames
,
452 char **old_arg_names
;
453 char **new_arg_names
;
458 proargmodes
= SysCacheGetAttr(PROCNAMEARGSNSP
, oldtup
,
459 Anum_pg_proc_proargmodes
,
462 proargmodes
= PointerGetDatum(NULL
); /* just to be sure */
464 n_old_arg_names
= get_func_input_arg_names(proargnames
,
467 n_new_arg_names
= get_func_input_arg_names(parameterNames
,
470 for (j
= 0; j
< n_old_arg_names
; j
++)
472 if (old_arg_names
[j
] == NULL
)
474 if (j
>= n_new_arg_names
|| new_arg_names
[j
] == NULL
||
475 strcmp(old_arg_names
[j
], new_arg_names
[j
]) != 0)
477 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
478 errmsg("cannot change name of input parameter \"%s\"",
480 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
481 errhint("Use %s %s first.",
483 format_procedure(oldproc
->oid
))));
488 * If there are existing defaults, check compatibility: redefinition
489 * must not remove any defaults nor change their types. (Removing a
490 * default might cause a function to fail to satisfy an existing call.
491 * Changing type would only be possible if the associated parameter is
492 * polymorphic, and in such cases a change of default type might alter
493 * the resolved output type of existing calls.)
495 if (oldproc
->pronargdefaults
!= 0)
497 Datum proargdefaults
;
502 if (list_length(parameterDefaults
) < oldproc
->pronargdefaults
)
504 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
505 errmsg("cannot remove parameter defaults from existing function"),
506 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
507 errhint("Use %s %s first.",
509 format_procedure(oldproc
->oid
))));
511 proargdefaults
= SysCacheGetAttr(PROCNAMEARGSNSP
, oldtup
,
512 Anum_pg_proc_proargdefaults
,
515 oldDefaults
= castNode(List
, stringToNode(TextDatumGetCString(proargdefaults
)));
516 Assert(list_length(oldDefaults
) == oldproc
->pronargdefaults
);
518 /* new list can have more defaults than old, advance over 'em */
519 newlc
= list_nth_cell(parameterDefaults
,
520 list_length(parameterDefaults
) -
521 oldproc
->pronargdefaults
);
523 foreach(oldlc
, oldDefaults
)
525 Node
*oldDef
= (Node
*) lfirst(oldlc
);
526 Node
*newDef
= (Node
*) lfirst(newlc
);
528 if (exprType(oldDef
) != exprType(newDef
))
530 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
531 errmsg("cannot change data type of existing parameter default value"),
532 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
533 errhint("Use %s %s first.",
535 format_procedure(oldproc
->oid
))));
536 newlc
= lnext(parameterDefaults
, newlc
);
541 * Do not change existing oid, ownership or permissions, either. Note
542 * dependency-update code below has to agree with this decision.
544 replaces
[Anum_pg_proc_oid
- 1] = false;
545 replaces
[Anum_pg_proc_proowner
- 1] = false;
546 replaces
[Anum_pg_proc_proacl
- 1] = false;
549 tup
= heap_modify_tuple(oldtup
, tupDesc
, values
, nulls
, replaces
);
550 CatalogTupleUpdate(rel
, &tup
->t_self
, tup
);
552 ReleaseSysCache(oldtup
);
557 /* Creating a new procedure */
560 /* First, get default permissions and set up proacl */
561 proacl
= get_user_default_acl(OBJECT_FUNCTION
, proowner
,
564 values
[Anum_pg_proc_proacl
- 1] = PointerGetDatum(proacl
);
566 nulls
[Anum_pg_proc_proacl
- 1] = true;
568 newOid
= GetNewOidWithIndex(rel
, ProcedureOidIndexId
,
570 values
[Anum_pg_proc_oid
- 1] = ObjectIdGetDatum(newOid
);
571 tup
= heap_form_tuple(tupDesc
, values
, nulls
);
572 CatalogTupleInsert(rel
, tup
);
577 retval
= ((Form_pg_proc
) GETSTRUCT(tup
))->oid
;
580 * Create dependencies for the new function. If we are updating an
581 * existing function, first delete any existing pg_depend entries.
582 * (However, since we are not changing ownership or permissions, the
583 * shared dependencies do *not* need to change, and we leave them alone.)
586 deleteDependencyRecordsFor(ProcedureRelationId
, retval
, true);
588 ObjectAddressSet(myself
, ProcedureRelationId
, retval
);
590 /* dependency on namespace */
591 ObjectAddressSet(referenced
, NamespaceRelationId
, procNamespace
);
592 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
594 /* dependency on implementation language */
595 ObjectAddressSet(referenced
, LanguageRelationId
, languageObjectId
);
596 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
598 /* dependency on return type */
599 ObjectAddressSet(referenced
, TypeRelationId
, returnType
);
600 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
602 /* dependency on transform used by return type, if any */
603 if ((trfid
= get_transform_oid(returnType
, languageObjectId
, true)))
605 ObjectAddressSet(referenced
, TransformRelationId
, trfid
);
606 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
609 /* dependency on parameter types */
610 for (i
= 0; i
< allParamCount
; i
++)
612 ObjectAddressSet(referenced
, TypeRelationId
, allParams
[i
]);
613 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
615 /* dependency on transform used by parameter type, if any */
616 if ((trfid
= get_transform_oid(allParams
[i
], languageObjectId
, true)))
618 ObjectAddressSet(referenced
, TransformRelationId
, trfid
);
619 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
623 /* dependency on parameter default expressions */
624 if (parameterDefaults
)
625 recordDependencyOnExpr(&myself
, (Node
*) parameterDefaults
,
626 NIL
, DEPENDENCY_NORMAL
);
628 /* dependency on support function, if any */
629 if (OidIsValid(prosupport
))
631 ObjectAddressSet(referenced
, ProcedureRelationId
, prosupport
);
632 recordDependencyOn(&myself
, &referenced
, DEPENDENCY_NORMAL
);
635 /* dependency on owner */
637 recordDependencyOnOwner(ProcedureRelationId
, retval
, proowner
);
639 /* dependency on any roles mentioned in ACL */
641 recordDependencyOnNewAcl(ProcedureRelationId
, retval
, 0,
644 /* dependency on extension */
645 recordDependencyOnCurrentExtension(&myself
, is_update
);
649 /* Post creation hook for new function */
650 InvokeObjectPostCreateHook(ProcedureRelationId
, retval
, 0);
652 table_close(rel
, RowExclusiveLock
);
654 /* Verify function body */
655 if (OidIsValid(languageValidator
))
657 ArrayType
*set_items
= NULL
;
658 int save_nestlevel
= 0;
660 /* Advance command counter so new tuple can be seen by validator */
661 CommandCounterIncrement();
664 * Set per-function configuration parameters so that the validation is
665 * done with the environment the function expects. However, if
666 * check_function_bodies is off, we don't do this, because that would
667 * create dump ordering hazards that pg_dump doesn't know how to deal
668 * with. (For example, a SET clause might refer to a not-yet-created
669 * text search configuration.) This means that the validator
670 * shouldn't complain about anything that might depend on a GUC
671 * parameter when check_function_bodies is off.
673 if (check_function_bodies
)
675 set_items
= (ArrayType
*) DatumGetPointer(proconfig
);
676 if (set_items
) /* Need a new GUC nesting level */
678 save_nestlevel
= NewGUCNestLevel();
679 ProcessGUCArray(set_items
,
680 (superuser() ? PGC_SUSET
: PGC_USERSET
),
686 OidFunctionCall1(languageValidator
, ObjectIdGetDatum(retval
));
689 AtEOXact_GUC(true, save_nestlevel
);
698 * Validator for internal functions
700 * Check that the given internal function name (the "prosrc" value) is
701 * a known builtin function.
704 fmgr_internal_validator(PG_FUNCTION_ARGS
)
706 Oid funcoid
= PG_GETARG_OID(0);
712 if (!CheckFunctionValidatorAccess(fcinfo
->flinfo
->fn_oid
, funcoid
))
716 * We do not honor check_function_bodies since it's unlikely the function
717 * name will be found later if it isn't there now.
720 tuple
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(funcoid
));
721 if (!HeapTupleIsValid(tuple
))
722 elog(ERROR
, "cache lookup failed for function %u", funcoid
);
724 tmp
= SysCacheGetAttr(PROCOID
, tuple
, Anum_pg_proc_prosrc
, &isnull
);
726 elog(ERROR
, "null prosrc");
727 prosrc
= TextDatumGetCString(tmp
);
729 if (fmgr_internal_function(prosrc
) == InvalidOid
)
731 (errcode(ERRCODE_UNDEFINED_FUNCTION
),
732 errmsg("there is no built-in function named \"%s\"",
735 ReleaseSysCache(tuple
);
743 * Validator for C language functions
745 * Make sure that the library file exists, is loadable, and contains
746 * the specified link symbol. Also check for a valid function
747 * information record.
750 fmgr_c_validator(PG_FUNCTION_ARGS
)
752 Oid funcoid
= PG_GETARG_OID(0);
760 if (!CheckFunctionValidatorAccess(fcinfo
->flinfo
->fn_oid
, funcoid
))
764 * It'd be most consistent to skip the check if !check_function_bodies,
765 * but the purpose of that switch is to be helpful for pg_dump loading,
766 * and for pg_dump loading it's much better if we *do* check.
769 tuple
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(funcoid
));
770 if (!HeapTupleIsValid(tuple
))
771 elog(ERROR
, "cache lookup failed for function %u", funcoid
);
773 tmp
= SysCacheGetAttr(PROCOID
, tuple
, Anum_pg_proc_prosrc
, &isnull
);
775 elog(ERROR
, "null prosrc for C function %u", funcoid
);
776 prosrc
= TextDatumGetCString(tmp
);
778 tmp
= SysCacheGetAttr(PROCOID
, tuple
, Anum_pg_proc_probin
, &isnull
);
780 elog(ERROR
, "null probin for C function %u", funcoid
);
781 probin
= TextDatumGetCString(tmp
);
783 (void) load_external_function(probin
, prosrc
, true, &libraryhandle
);
784 (void) fetch_finfo_record(libraryhandle
, prosrc
);
786 ReleaseSysCache(tuple
);
793 * Validator for SQL language functions
795 * Parse it here in order to be sure that it contains no syntax errors.
798 fmgr_sql_validator(PG_FUNCTION_ARGS
)
800 Oid funcoid
= PG_GETARG_OID(0);
803 List
*raw_parsetree_list
;
804 List
*querytree_list
;
809 parse_error_callback_arg callback_arg
;
810 ErrorContextCallback sqlerrcontext
;
814 if (!CheckFunctionValidatorAccess(fcinfo
->flinfo
->fn_oid
, funcoid
))
817 tuple
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(funcoid
));
818 if (!HeapTupleIsValid(tuple
))
819 elog(ERROR
, "cache lookup failed for function %u", funcoid
);
820 proc
= (Form_pg_proc
) GETSTRUCT(tuple
);
822 /* Disallow pseudotype result */
823 /* except for RECORD, VOID, or polymorphic */
824 if (get_typtype(proc
->prorettype
) == TYPTYPE_PSEUDO
&&
825 proc
->prorettype
!= RECORDOID
&&
826 proc
->prorettype
!= VOIDOID
&&
827 !IsPolymorphicType(proc
->prorettype
))
829 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
830 errmsg("SQL functions cannot return type %s",
831 format_type_be(proc
->prorettype
))));
833 /* Disallow pseudotypes in arguments */
834 /* except for polymorphic */
836 for (i
= 0; i
< proc
->pronargs
; i
++)
838 if (get_typtype(proc
->proargtypes
.values
[i
]) == TYPTYPE_PSEUDO
)
840 if (IsPolymorphicType(proc
->proargtypes
.values
[i
]))
844 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
845 errmsg("SQL functions cannot have arguments of type %s",
846 format_type_be(proc
->proargtypes
.values
[i
]))));
850 /* Postpone body checks if !check_function_bodies */
851 if (check_function_bodies
)
853 tmp
= SysCacheGetAttr(PROCOID
, tuple
, Anum_pg_proc_prosrc
, &isnull
);
855 elog(ERROR
, "null prosrc");
857 prosrc
= TextDatumGetCString(tmp
);
860 * Setup error traceback support for ereport().
862 callback_arg
.proname
= NameStr(proc
->proname
);
863 callback_arg
.prosrc
= prosrc
;
865 sqlerrcontext
.callback
= sql_function_parse_error_callback
;
866 sqlerrcontext
.arg
= (void *) &callback_arg
;
867 sqlerrcontext
.previous
= error_context_stack
;
868 error_context_stack
= &sqlerrcontext
;
871 * We can't do full prechecking of the function definition if there
872 * are any polymorphic input types, because actual datatypes of
873 * expression results will be unresolvable. The check will be done at
876 * We can run the text through the raw parser though; this will at
877 * least catch silly syntactic errors.
879 raw_parsetree_list
= pg_parse_query(prosrc
);
884 * OK to do full precheck: analyze and rewrite the queries, then
885 * verify the result type.
887 SQLFunctionParseInfoPtr pinfo
;
889 TupleDesc rettupdesc
;
891 /* But first, set up parameter information */
892 pinfo
= prepare_sql_fn_parse_info(tuple
, NULL
, InvalidOid
);
894 querytree_list
= NIL
;
895 foreach(lc
, raw_parsetree_list
)
897 RawStmt
*parsetree
= lfirst_node(RawStmt
, lc
);
898 List
*querytree_sublist
;
900 querytree_sublist
= pg_analyze_and_rewrite_params(parsetree
,
902 (ParserSetupHook
) sql_fn_parser_setup
,
905 querytree_list
= list_concat(querytree_list
,
909 check_sql_fn_statements(querytree_list
);
911 (void) get_func_result_type(funcoid
, &rettype
, &rettupdesc
);
913 (void) check_sql_fn_retval(querytree_list
,
918 error_context_stack
= sqlerrcontext
.previous
;
921 ReleaseSysCache(tuple
);
927 * Error context callback for handling errors in SQL function definitions
930 sql_function_parse_error_callback(void *arg
)
932 parse_error_callback_arg
*callback_arg
= (parse_error_callback_arg
*) arg
;
934 /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
935 if (!function_parse_error_transpose(callback_arg
->prosrc
))
937 /* If it's not a syntax error, push info onto context stack */
938 errcontext("SQL function \"%s\"", callback_arg
->proname
);
943 * Adjust a syntax error occurring inside the function body of a CREATE
944 * FUNCTION or DO command. This can be used by any function validator or
945 * anonymous-block handler, not only for SQL-language functions.
946 * It is assumed that the syntax error position is initially relative to the
947 * function body string (as passed in). If possible, we adjust the position
948 * to reference the original command text; if we can't manage that, we set
949 * up an "internal query" syntax error instead.
951 * Returns true if a syntax error was processed, false if not.
954 function_parse_error_transpose(const char *prosrc
)
958 const char *queryText
;
961 * Nothing to do unless we are dealing with a syntax error that has a
964 * Some PLs may prefer to report the error position as an internal error
965 * to begin with, so check that too.
967 origerrposition
= geterrposition();
968 if (origerrposition
<= 0)
970 origerrposition
= getinternalerrposition();
971 if (origerrposition
<= 0)
975 /* We can get the original query text from the active portal (hack...) */
976 Assert(ActivePortal
&& ActivePortal
->status
== PORTAL_ACTIVE
);
977 queryText
= ActivePortal
->sourceText
;
979 /* Try to locate the prosrc in the original text */
980 newerrposition
= match_prosrc_to_query(prosrc
, queryText
, origerrposition
);
982 if (newerrposition
> 0)
984 /* Successful, so fix error position to reference original query */
985 errposition(newerrposition
);
986 /* Get rid of any report of the error as an "internal query" */
987 internalerrposition(0);
988 internalerrquery(NULL
);
993 * If unsuccessful, convert the position to an internal position
994 * marker and give the function text as the internal query.
997 internalerrposition(origerrposition
);
998 internalerrquery(prosrc
);
1005 * Try to locate the string literal containing the function body in the
1006 * given text of the CREATE FUNCTION or DO command. If successful, return
1007 * the character (not byte) index within the command corresponding to the
1008 * given character index within the literal. If not successful, return 0.
1011 match_prosrc_to_query(const char *prosrc
, const char *queryText
,
1015 * Rather than fully parsing the original command, we just scan the
1016 * command looking for $prosrc$ or 'prosrc'. This could be fooled (though
1017 * not in any very probable scenarios), so fail if we find more than one
1020 int prosrclen
= strlen(prosrc
);
1021 int querylen
= strlen(queryText
);
1026 for (curpos
= 0; curpos
< querylen
- prosrclen
; curpos
++)
1028 if (queryText
[curpos
] == '$' &&
1029 strncmp(prosrc
, &queryText
[curpos
+ 1], prosrclen
) == 0 &&
1030 queryText
[curpos
+ 1 + prosrclen
] == '$')
1033 * Found a $foo$ match. Since there are no embedded quoting
1034 * characters in a dollar-quoted literal, we don't have to do any
1035 * fancy arithmetic; just offset by the starting position.
1038 return 0; /* multiple matches, fail */
1039 matchpos
= pg_mbstrlen_with_len(queryText
, curpos
+ 1)
1042 else if (queryText
[curpos
] == '\'' &&
1043 match_prosrc_to_literal(prosrc
, &queryText
[curpos
+ 1],
1044 cursorpos
, &newcursorpos
))
1047 * Found a 'foo' match. match_prosrc_to_literal() has adjusted
1048 * for any quotes or backslashes embedded in the literal.
1051 return 0; /* multiple matches, fail */
1052 matchpos
= pg_mbstrlen_with_len(queryText
, curpos
+ 1)
1061 * Try to match the given source text to a single-quoted literal.
1062 * If successful, adjust newcursorpos to correspond to the character
1063 * (not byte) index corresponding to cursorpos in the source text.
1065 * At entry, literal points just past a ' character. We must check for the
1069 match_prosrc_to_literal(const char *prosrc
, const char *literal
,
1070 int cursorpos
, int *newcursorpos
)
1072 int newcp
= cursorpos
;
1076 * This implementation handles backslashes and doubled quotes in the
1077 * string literal. It does not handle the SQL syntax for literals
1078 * continued across line boundaries.
1080 * We do the comparison a character at a time, not a byte at a time, so
1081 * that we can do the correct cursorpos math.
1085 cursorpos
--; /* characters left before cursor */
1088 * Check for backslashes and doubled quotes in the literal; adjust
1089 * newcp when one is found before the cursor.
1091 if (*literal
== '\\')
1097 else if (*literal
== '\'')
1099 if (literal
[1] != '\'')
1105 chlen
= pg_mblen(prosrc
);
1106 if (strncmp(prosrc
, literal
, chlen
) != 0)
1112 if (*literal
== '\'' && literal
[1] != '\'')
1115 *newcursorpos
= newcp
;
1120 /* Must set *newcursorpos to suppress compiler warning */
1121 *newcursorpos
= newcp
;
1126 oid_array_to_list(Datum datum
)
1128 ArrayType
*array
= DatumGetArrayTypeP(datum
);
1134 deconstruct_array(array
,
1136 sizeof(Oid
), true, TYPALIGN_INT
,
1137 &values
, NULL
, &nelems
);
1138 for (i
= 0; i
< nelems
; i
++)
1139 result
= lappend_oid(result
, values
[i
]);