Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pg_proc.c
4 : : * routines to support manipulation of the pg_proc relation
5 : : *
6 : : * Portions Copyright (c) 1996-2025, 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"
24 : : #include "catalog/objectaccess.h"
25 : : #include "catalog/pg_language.h"
26 : : #include "catalog/pg_namespace.h"
27 : : #include "catalog/pg_proc.h"
28 : : #include "catalog/pg_transform.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"
37 : : #include "rewrite/rewriteHandler.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 : :
48 : : typedef struct
49 : : {
50 : : char *proname;
51 : : char *prosrc;
52 : : } parse_error_callback_arg;
53 : :
54 : : static void sql_function_parse_error_callback(void *arg);
55 : : static int match_prosrc_to_query(const char *prosrc, const char *queryText,
56 : : int cursorpos);
57 : : static 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 : : */
98 : : ObjectAddress
8656 tgl@sss.pgh.pa.us 99 :CBC 13278 : ProcedureCreate(const char *procedureName,
100 : : Oid procNamespace,
101 : : bool replace,
102 : : bool returnsSet,
103 : : Oid returnType,
104 : : Oid proowner,
105 : : Oid languageObjectId,
106 : : Oid languageValidator,
107 : : const char *prosrc,
108 : : const char *probin,
109 : : Node *prosqlbody,
110 : : char prokind,
111 : : bool security_definer,
112 : : bool isLeakProof,
113 : : bool isStrict,
114 : : char volatility,
115 : : char parallel,
116 : : oidvector *parameterTypes,
117 : : Datum allParameterTypes,
118 : : Datum parameterModes,
119 : : Datum parameterNames,
120 : : List *parameterDefaults,
121 : : Datum trftypes,
122 : : List *trfoids,
123 : : Datum proconfig,
124 : : Oid prosupport,
125 : : float4 procost,
126 : : float4 prorows)
127 : : {
128 : : Oid retval;
129 : : int parameterCount;
130 : : int allParamCount;
131 : : Oid *allParams;
5140 132 : 13278 : char *paramModes = NULL;
6362 133 : 13278 : Oid variadicType = InvalidOid;
5916 134 : 13278 : Acl *proacl = NULL;
135 : : Relation rel;
136 : : HeapTuple tup;
137 : : HeapTuple oldtup;
138 : : bool nulls[Natts_pg_proc];
139 : : Datum values[Natts_pg_proc];
140 : : bool replaces[Natts_pg_proc];
141 : : NameData procname;
142 : : TupleDesc tupDesc;
143 : : bool is_update;
144 : : ObjectAddress myself,
145 : : referenced,
146 : : temp_object;
147 : : char *detailmsg;
148 : : int i;
149 : : ObjectAddresses *addrs;
150 : :
151 : : /*
152 : : * sanity checks
153 : : */
83 peter@eisentraut.org 154 [ - + ]:GNC 13278 : Assert(prosrc);
155 : :
7565 tgl@sss.pgh.pa.us 156 :CBC 13278 : parameterCount = parameterTypes->dim1;
8650 157 [ + - - + ]: 13278 : if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
8187 tgl@sss.pgh.pa.us 158 [ # # ]:UBC 0 : ereport(ERROR,
159 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
160 : : errmsg_plural("functions cannot have more than %d argument",
161 : : "functions cannot have more than %d arguments",
162 : : FUNC_MAX_ARGS,
163 : : FUNC_MAX_ARGS)));
164 : : /* note: the above is correct, we do NOT count output arguments */
165 : :
166 : : /* Deconstruct array inputs */
7565 tgl@sss.pgh.pa.us 167 [ + + ]:CBC 13278 : if (allParameterTypes != PointerGetDatum(NULL))
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 : : */
7329 bruce@momjian.us 174 : 1371 : ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
175 : :
7334 tgl@sss.pgh.pa.us 176 : 1371 : allParamCount = ARR_DIMS(allParamArray)[0];
177 [ + - + - ]: 1371 : if (ARR_NDIM(allParamArray) != 1 ||
7565 178 : 1371 : allParamCount <= 0 ||
7334 179 [ + - ]: 1371 : ARR_HASNULL(allParamArray) ||
180 [ - + ]: 1371 : ARR_ELEMTYPE(allParamArray) != OIDOID)
7565 tgl@sss.pgh.pa.us 181 [ # # ]:UBC 0 : elog(ERROR, "allParameterTypes is not a 1-D Oid array");
7334 tgl@sss.pgh.pa.us 182 [ - + ]:CBC 1371 : allParams = (Oid *) ARR_DATA_PTR(allParamArray);
7565 183 [ - + ]: 1371 : Assert(allParamCount >= parameterCount);
184 : : /* we assume caller got the contents right */
185 : : }
186 : : else
187 : : {
188 : 11907 : allParamCount = parameterCount;
189 : 11907 : allParams = parameterTypes->values;
190 : : }
191 : :
5157 heikki.linnakangas@i 192 [ + + ]: 13278 : if (parameterModes != PointerGetDatum(NULL))
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 : : */
199 : 1371 : ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
200 : :
201 [ + - ]: 1371 : if (ARR_NDIM(modesArray) != 1 ||
202 [ + - ]: 1371 : ARR_DIMS(modesArray)[0] != allParamCount ||
203 [ + - ]: 1371 : ARR_HASNULL(modesArray) ||
204 [ - + ]: 1371 : ARR_ELEMTYPE(modesArray) != CHAROID)
5157 heikki.linnakangas@i 205 [ # # ]:UBC 0 : elog(ERROR, "parameterModes is not a 1-D char array");
5140 tgl@sss.pgh.pa.us 206 [ - + ]:CBC 1371 : paramModes = (char *) ARR_DATA_PTR(modesArray);
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 : : */
2100 213 : 13278 : detailmsg = check_valid_polymorphic_signature(returnType,
214 : 13278 : parameterTypes->values,
215 : : parameterCount);
216 [ + + ]: 13278 : if (detailmsg)
217 [ + - ]: 39 : ereport(ERROR,
218 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 : 13239 : detailmsg = check_valid_internal_signature(returnType,
227 : 13239 : parameterTypes->values,
228 : : parameterCount);
229 [ - + ]: 13239 : if (detailmsg)
2100 tgl@sss.pgh.pa.us 230 [ # # ]:UBC 0 : ereport(ERROR,
231 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 : : */
7532 tgl@sss.pgh.pa.us 238 [ + + ]:CBC 13239 : if (allParameterTypes != PointerGetDatum(NULL))
239 : : {
240 [ + + ]: 10325 : for (i = 0; i < allParamCount; i++)
241 : : {
5140 242 [ + - ]: 8978 : if (paramModes == NULL ||
243 [ + + ]: 8978 : paramModes[i] == PROARGMODE_IN ||
244 [ + + ]: 6785 : paramModes[i] == PROARGMODE_VARIADIC)
245 : 2527 : continue; /* ignore input-only params */
246 : :
2100 247 : 6451 : detailmsg = check_valid_polymorphic_signature(allParams[i],
248 : 6451 : parameterTypes->values,
249 : : parameterCount);
250 [ + + ]: 6451 : if (detailmsg)
251 [ + - ]: 24 : ereport(ERROR,
252 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
253 : : errmsg("cannot determine result data type"),
254 : : errdetail_internal("%s", detailmsg)));
255 : 6427 : detailmsg = check_valid_internal_signature(allParams[i],
256 : 6427 : parameterTypes->values,
257 : : parameterCount);
258 [ - + ]: 6427 : if (detailmsg)
2100 tgl@sss.pgh.pa.us 259 [ # # ]:UBC 0 : ereport(ERROR,
260 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
261 : : errmsg("unsafe use of pseudo-type \"internal\""),
262 : : errdetail_internal("%s", detailmsg)));
263 : : }
264 : : }
265 : :
266 : : /* Identify variadic argument type, if any */
5140 tgl@sss.pgh.pa.us 267 [ + + ]:CBC 13215 : 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 : : */
6362 274 [ + + ]: 10271 : for (i = 0; i < allParamCount; i++)
275 : : {
5140 276 [ + + + + : 8924 : switch (paramModes[i])
- ]
277 : : {
6362 278 : 2255 : case PROARGMODE_IN:
279 : : case PROARGMODE_INOUT:
280 [ - + ]: 2255 : if (OidIsValid(variadicType))
6362 tgl@sss.pgh.pa.us 281 [ # # ]:UBC 0 : elog(ERROR, "variadic parameter must be last");
6362 tgl@sss.pgh.pa.us 282 :CBC 2255 : break;
283 : 6120 : case PROARGMODE_OUT:
1898 peter@eisentraut.org 284 [ + + - + ]: 6120 : if (OidIsValid(variadicType) && prokind == PROKIND_PROCEDURE)
1898 peter@eisentraut.org 285 [ # # ]:UBC 0 : elog(ERROR, "variadic parameter must be last");
1898 peter@eisentraut.org 286 :CBC 6120 : break;
6360 tgl@sss.pgh.pa.us 287 : 215 : case PROARGMODE_TABLE:
288 : : /* okay */
6362 289 : 215 : break;
290 : 334 : case PROARGMODE_VARIADIC:
291 [ - + ]: 334 : if (OidIsValid(variadicType))
6362 tgl@sss.pgh.pa.us 292 [ # # ]:UBC 0 : elog(ERROR, "variadic parameter must be last");
6362 tgl@sss.pgh.pa.us 293 [ + + + + ]:CBC 334 : switch (allParams[i])
294 : : {
295 : 4 : case ANYOID:
296 : 4 : variadicType = ANYOID;
297 : 4 : break;
298 : 20 : case ANYARRAYOID:
299 : 20 : variadicType = ANYELEMENTOID;
300 : 20 : break;
2098 301 : 11 : case ANYCOMPATIBLEARRAYOID:
302 : 11 : variadicType = ANYCOMPATIBLEOID;
303 : 11 : break;
6362 304 : 299 : default:
305 : 299 : variadicType = get_element_type(allParams[i]);
306 [ - + ]: 299 : if (!OidIsValid(variadicType))
6362 tgl@sss.pgh.pa.us 307 [ # # ]:UBC 0 : elog(ERROR, "variadic parameter is not an array");
6362 tgl@sss.pgh.pa.us 308 :CBC 299 : break;
309 : : }
310 : 334 : break;
6362 tgl@sss.pgh.pa.us 311 :UBC 0 : default:
5140 312 [ # # ]: 0 : 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 : :
10327 bruce@momjian.us 322 [ + + ]:CBC 409665 : for (i = 0; i < Natts_pg_proc; ++i)
323 : : {
6253 tgl@sss.pgh.pa.us 324 : 396450 : nulls[i] = false;
7567 325 : 396450 : values[i] = (Datum) 0;
6253 326 : 396450 : replaces[i] = true;
327 : : }
328 : :
10121 scrappy@hub.org 329 : 13215 : namestrcpy(&procname, procedureName);
7567 tgl@sss.pgh.pa.us 330 : 13215 : values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
331 : 13215 : values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
5919 332 : 13215 : values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
7567 333 : 13215 : values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
6903 334 : 13215 : values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
335 : 13215 : values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
6362 336 : 13215 : values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
2502 337 : 13215 : values[Anum_pg_proc_prosupport - 1] = ObjectIdGetDatum(prosupport);
2846 peter_e@gmx.net 338 : 13215 : values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
7567 tgl@sss.pgh.pa.us 339 : 13215 : values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
5055 rhaas@postgresql.org 340 : 13215 : values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
7567 tgl@sss.pgh.pa.us 341 : 13215 : values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
342 : 13215 : values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
343 : 13215 : values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
3744 rhaas@postgresql.org 344 : 13215 : values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
7567 tgl@sss.pgh.pa.us 345 : 13215 : values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
6221 peter_e@gmx.net 346 : 13215 : values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
7567 tgl@sss.pgh.pa.us 347 : 13215 : values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
7565 348 : 13215 : values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
349 [ + + ]: 13215 : if (allParameterTypes != PointerGetDatum(NULL))
350 : 1347 : values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
351 : : else
6253 352 : 11868 : nulls[Anum_pg_proc_proallargtypes - 1] = true;
7565 353 [ + + ]: 13215 : if (parameterModes != PointerGetDatum(NULL))
354 : 1347 : values[Anum_pg_proc_proargmodes - 1] = parameterModes;
355 : : else
6253 356 : 11868 : nulls[Anum_pg_proc_proargmodes - 1] = true;
7565 357 [ + + ]: 13215 : if (parameterNames != PointerGetDatum(NULL))
358 : 4025 : values[Anum_pg_proc_proargnames - 1] = parameterNames;
359 : : else
6253 360 : 9190 : nulls[Anum_pg_proc_proargnames - 1] = true;
6207 361 [ + + ]: 13215 : if (parameterDefaults != NIL)
6221 peter_e@gmx.net 362 : 1975 : values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
363 : : else
364 : 11240 : nulls[Anum_pg_proc_proargdefaults - 1] = true;
3887 365 [ + + ]: 13215 : if (trftypes != PointerGetDatum(NULL))
366 : 59 : values[Anum_pg_proc_protrftypes - 1] = trftypes;
367 : : else
368 : 13156 : nulls[Anum_pg_proc_protrftypes - 1] = true;
1706 tgl@sss.pgh.pa.us 369 : 13215 : values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
6362 370 [ + + ]: 13215 : if (probin)
371 : 3214 : values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
372 : : else
6253 373 : 10001 : nulls[Anum_pg_proc_probin - 1] = true;
1714 peter@eisentraut.org 374 [ + + ]: 13215 : if (prosqlbody)
375 : 2885 : values[Anum_pg_proc_prosqlbody - 1] = CStringGetTextDatum(nodeToString(prosqlbody));
376 : : else
377 : 10330 : nulls[Anum_pg_proc_prosqlbody - 1] = true;
6679 tgl@sss.pgh.pa.us 378 [ + + ]: 13215 : if (proconfig != PointerGetDatum(NULL))
379 : 38 : values[Anum_pg_proc_proconfig - 1] = proconfig;
380 : : else
6253 381 : 13177 : nulls[Anum_pg_proc_proconfig - 1] = true;
382 : : /* proacl will be determined later */
383 : :
2521 andres@anarazel.de 384 : 13215 : rel = table_open(ProcedureRelationId, RowExclusiveLock);
7628 neilc@samurai.com 385 : 13215 : tupDesc = RelationGetDescr(rel);
386 : :
387 : : /* Check for pre-existing definition */
5784 rhaas@postgresql.org 388 : 13215 : oldtup = SearchSysCache3(PROCNAMEARGSNSP,
389 : : PointerGetDatum(procedureName),
390 : : PointerGetDatum(parameterTypes),
391 : : ObjectIdGetDatum(procNamespace));
392 : :
8841 tgl@sss.pgh.pa.us 393 [ + + ]: 13215 : if (HeapTupleIsValid(oldtup))
394 : : {
395 : : /* There is one; okay to replace it? */
8818 bruce@momjian.us 396 : 4579 : Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
397 : : Datum proargnames;
398 : : bool isnull;
399 : : const char *dropcmd;
400 : :
8841 tgl@sss.pgh.pa.us 401 [ - + ]: 4579 : if (!replace)
8187 tgl@sss.pgh.pa.us 402 [ # # ]:UBC 0 : ereport(ERROR,
403 : : (errcode(ERRCODE_DUPLICATE_FUNCTION),
404 : : errmsg("function \"%s\" already exists with same argument types",
405 : : procedureName)));
1129 peter@eisentraut.org 406 [ - + ]:CBC 4579 : if (!object_ownercheck(ProcedureRelationId, oldproc->oid, proowner))
2936 peter_e@gmx.net 407 :UBC 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
408 : : procedureName);
409 : :
410 : : /* Not okay to change routine kind */
2846 peter_e@gmx.net 411 [ + + ]:CBC 4579 : if (oldproc->prokind != prokind)
412 [ + - - + : 9 : ereport(ERROR,
+ - - - -
- ]
413 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
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 : :
2464 rhodiumtoad@postgres 425 [ + + + + ]: 4570 : 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 : : */
8663 tgl@sss.pgh.pa.us 437 [ + + ]: 4570 : if (returnType != oldproc->prorettype ||
8841 438 [ - + ]: 4564 : returnsSet != oldproc->proretset)
8187 439 [ + - - + ]: 6 : ereport(ERROR,
440 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 : : */
7565 457 [ + + ]: 4564 : if (returnType == RECORDOID)
458 : : {
459 : : TupleDesc olddesc;
460 : : TupleDesc newdesc;
461 : :
462 : 488 : olddesc = build_function_result_tupdesc_t(oldtup);
2834 peter_e@gmx.net 463 : 488 : newdesc = build_function_result_tupdesc_d(prokind,
464 : : allParameterTypes,
465 : : parameterModes,
466 : : parameterNames);
7565 tgl@sss.pgh.pa.us 467 [ + + + - ]: 488 : if (olddesc == NULL && newdesc == NULL)
468 : : /* ok, both are runtime-defined RECORDs */ ;
469 [ + - + - ]: 476 : else if (olddesc == NULL || newdesc == NULL ||
639 peter@eisentraut.org 470 [ - + ]: 476 : !equalRowTypes(olddesc, newdesc))
7367 bruce@momjian.us 471 [ # # ]:UBC 0 : ereport(ERROR,
472 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 : : */
5913 tgl@sss.pgh.pa.us 486 :CBC 4564 : proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
487 : : Anum_pg_proc_proargnames,
488 : : &isnull);
489 [ + + ]: 4564 : if (!isnull)
490 : : {
491 : : Datum proargmodes;
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 : :
498 : 765 : proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
499 : : Anum_pg_proc_proargmodes,
500 : : &isnull);
501 [ + + ]: 765 : if (isnull)
502 : 280 : proargmodes = PointerGetDatum(NULL); /* just to be sure */
503 : :
1650 504 : 765 : n_old_arg_names = get_func_input_arg_names(proargnames,
505 : : proargmodes,
506 : : &old_arg_names);
507 : 765 : n_new_arg_names = get_func_input_arg_names(parameterNames,
508 : : parameterModes,
509 : : &new_arg_names);
5913 510 [ + + ]: 2951 : for (j = 0; j < n_old_arg_names; j++)
511 : : {
512 [ + + ]: 2195 : if (old_arg_names[j] == NULL)
513 : 3 : continue;
514 [ + - + + ]: 2192 : if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
515 [ + + ]: 2189 : strcmp(old_arg_names[j], new_arg_names[j]) != 0)
516 [ + - ]: 9 : ereport(ERROR,
517 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
518 : : errmsg("cannot change name of input parameter \"%s\"",
519 : : old_arg_names[j]),
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 : : */
6207 535 [ + + ]: 4555 : if (oldproc->pronargdefaults != 0)
536 : : {
537 : : Datum proargdefaults;
538 : : List *oldDefaults;
539 : : ListCell *oldlc;
540 : : ListCell *newlc;
541 : :
542 [ + - ]: 3 : if (list_length(parameterDefaults) < oldproc->pronargdefaults)
543 [ + - ]: 3 : ereport(ERROR,
544 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 : :
997 dgustafsson@postgres 551 :UBC 0 : proargdefaults = SysCacheGetAttrNotNull(PROCNAMEARGSNSP, oldtup,
552 : : Anum_pg_proc_proargdefaults);
3246 andres@anarazel.de 553 : 0 : oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
6207 tgl@sss.pgh.pa.us 554 [ # # ]: 0 : Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
555 : :
556 : : /* new list can have more defaults than old, advance over 'em */
2346 557 : 0 : newlc = list_nth_cell(parameterDefaults,
558 : 0 : list_length(parameterDefaults) -
559 : 0 : oldproc->pronargdefaults);
560 : :
6207 561 [ # # # # : 0 : foreach(oldlc, oldDefaults)
# # ]
562 : : {
6032 bruce@momjian.us 563 : 0 : Node *oldDef = (Node *) lfirst(oldlc);
564 : 0 : Node *newDef = (Node *) lfirst(newlc);
565 : :
6207 tgl@sss.pgh.pa.us 566 [ # # ]: 0 : if (exprType(oldDef) != exprType(newDef))
567 [ # # ]: 0 : ereport(ERROR,
568 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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))));
2346 574 : 0 : newlc = lnext(parameterDefaults, newlc);
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 : : */
2583 andres@anarazel.de 582 :CBC 4552 : replaces[Anum_pg_proc_oid - 1] = false;
6253 tgl@sss.pgh.pa.us 583 : 4552 : replaces[Anum_pg_proc_proowner - 1] = false;
584 : 4552 : replaces[Anum_pg_proc_proacl - 1] = false;
585 : :
586 : : /* Okay, do it... */
587 : 4552 : tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
3241 alvherre@alvh.no-ip. 588 : 4552 : CatalogTupleUpdate(rel, &tup->t_self, tup);
589 : :
8841 tgl@sss.pgh.pa.us 590 : 4552 : ReleaseSysCache(oldtup);
8554 591 : 4552 : 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 */
2988 peter_e@gmx.net 599 : 8636 : proacl = get_user_default_acl(OBJECT_FUNCTION, proowner,
600 : : procNamespace);
5916 tgl@sss.pgh.pa.us 601 [ + + ]: 8636 : if (proacl != NULL)
602 : 9 : values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
603 : : else
604 : 8627 : nulls[Anum_pg_proc_proacl - 1] = true;
605 : :
2583 andres@anarazel.de 606 : 8636 : newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId,
607 : : Anum_pg_proc_oid);
608 : 8636 : values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid);
6253 tgl@sss.pgh.pa.us 609 : 8636 : tup = heap_form_tuple(tupDesc, values, nulls);
3241 alvherre@alvh.no-ip. 610 : 8636 : CatalogTupleInsert(rel, tup);
8554 tgl@sss.pgh.pa.us 611 : 8636 : is_update = false;
612 : : }
613 : :
614 : :
2583 andres@anarazel.de 615 : 13188 : 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 : : */
8554 tgl@sss.pgh.pa.us 623 [ + + ]: 13188 : if (is_update)
5425 624 : 4552 : deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
625 : :
1928 michael@paquier.xyz 626 : 13188 : addrs = new_object_addresses();
627 : :
1994 628 : 13188 : ObjectAddressSet(myself, ProcedureRelationId, retval);
629 : :
630 : : /* dependency on namespace */
631 : 13188 : ObjectAddressSet(referenced, NamespaceRelationId, procNamespace);
1928 632 : 13188 : add_exact_object_address(&referenced, addrs);
633 : :
634 : : /* dependency on implementation language */
1994 635 : 13188 : ObjectAddressSet(referenced, LanguageRelationId, languageObjectId);
1928 636 : 13188 : add_exact_object_address(&referenced, addrs);
637 : :
638 : : /* dependency on return type */
1994 639 : 13188 : ObjectAddressSet(referenced, TypeRelationId, returnType);
1928 640 : 13188 : add_exact_object_address(&referenced, addrs);
641 : :
642 : : /* dependency on parameter types */
7565 tgl@sss.pgh.pa.us 643 [ + + ]: 42377 : for (i = 0; i < allParamCount; i++)
644 : : {
1994 michael@paquier.xyz 645 : 29189 : ObjectAddressSet(referenced, TypeRelationId, allParams[i]);
1928 646 : 29189 : add_exact_object_address(&referenced, addrs);
647 : : }
648 : :
649 : : /* dependency on transforms, if any */
253 tgl@sss.pgh.pa.us 650 [ + + + + : 26437 : foreach_oid(transformid, trfoids)
+ + ]
651 : : {
652 : 61 : ObjectAddressSet(referenced, TransformRelationId, transformid);
653 : 61 : add_exact_object_address(&referenced, addrs);
654 : : }
655 : :
656 : : /* dependency on support function, if any */
2502 657 [ + + ]: 13188 : if (OidIsValid(prosupport))
658 : : {
1994 michael@paquier.xyz 659 : 55 : ObjectAddressSet(referenced, ProcedureRelationId, prosupport);
1928 660 : 55 : add_exact_object_address(&referenced, addrs);
661 : : }
662 : :
663 : : /* dependencies appearing in new-style SQL routine body */
1714 peter@eisentraut.org 664 [ + + + + ]: 13188 : if (languageObjectId == SQLlanguageId && prosqlbody)
23 tgl@sss.pgh.pa.us 665 :GNC 2885 : collectDependenciesOfExpr(addrs, prosqlbody, NIL);
666 : :
667 : : /* dependency on parameter default expressions */
1928 michael@paquier.xyz 668 [ + + ]:CBC 13188 : if (parameterDefaults)
23 tgl@sss.pgh.pa.us 669 :GNC 1969 : collectDependenciesOfExpr(addrs, (Node *) parameterDefaults, NIL);
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 : : */
679 [ + + ]: 13188 : if (find_temp_object(addrs, isTempNamespace(procNamespace), &temp_object))
680 [ + - ]: 32 : ereport(NOTICE,
681 : : (errmsg("function \"%s\" will be effectively temporary",
682 : : procedureName),
683 : : errdetail("It depends on temporary %s.",
684 : : getObjectDescription(&temp_object, false))));
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 : : */
694 : 13188 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
695 : :
696 : 13188 : free_object_addresses(addrs);
697 : :
698 : : /* dependency on owner */
5919 tgl@sss.pgh.pa.us 699 [ + + ]:CBC 13188 : if (!is_update)
700 : 8636 : recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
701 : :
702 : : /* dependency on any roles mentioned in ACL */
2594 703 [ + + ]: 13188 : if (!is_update)
704 : 8636 : recordDependencyOnNewAcl(ProcedureRelationId, retval, 0,
705 : : proowner, proacl);
706 : :
707 : : /* dependency on extension */
5260 708 : 13188 : recordDependencyOnCurrentExtension(&myself, is_update);
709 : :
9316 bruce@momjian.us 710 : 13187 : heap_freetuple(tup);
711 : :
712 : : /* Post creation hook for new function */
4668 rhaas@postgresql.org 713 [ + + ]: 13187 : InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0);
714 : :
2521 andres@anarazel.de 715 : 13187 : table_close(rel, RowExclusiveLock);
716 : :
717 : : /* Verify function body */
8609 peter_e@gmx.net 718 [ + + ]: 13187 : if (OidIsValid(languageValidator))
719 : : {
4487 tgl@sss.pgh.pa.us 720 : 12827 : ArrayType *set_items = NULL;
721 : 12827 : int save_nestlevel = 0;
722 : :
723 : : /* Advance command counter so new tuple can be seen by validator */
8609 peter_e@gmx.net 724 : 12827 : CommandCounterIncrement();
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 : : */
4487 tgl@sss.pgh.pa.us 736 [ + + ]: 12827 : if (check_function_bodies)
737 : : {
738 : 9100 : set_items = (ArrayType *) DatumGetPointer(proconfig);
739 [ + + ]: 9100 : if (set_items) /* Need a new GUC nesting level */
740 : : {
741 : 32 : save_nestlevel = NewGUCNestLevel();
742 [ + - ]: 32 : ProcessGUCArray(set_items,
743 : 32 : (superuser() ? PGC_SUSET : PGC_USERSET),
744 : : PGC_S_SESSION,
745 : : GUC_ACTION_SAVE);
746 : : }
747 : : }
748 : :
8609 749 : 12821 : OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
750 : :
5698 itagaki.takahiro@gma 751 [ + + ]: 12731 : if (set_items)
752 : 26 : AtEOXact_GUC(true, save_nestlevel);
753 : : }
754 : :
755 : : /* ensure that stats are dropped if transaction aborts */
1350 andres@anarazel.de 756 [ + + ]: 13091 : if (!is_update)
757 : 8540 : pgstat_create_function(retval);
758 : :
3941 alvherre@alvh.no-ip. 759 : 13091 : 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 : : */
770 : : Datum
8609 peter_e@gmx.net 771 : 2601 : fmgr_internal_validator(PG_FUNCTION_ARGS)
772 : : {
773 : 2601 : Oid funcoid = PG_GETARG_OID(0);
774 : : HeapTuple tuple;
775 : : Datum tmp;
776 : : char *prosrc;
777 : :
4320 noah@leadboat.com 778 [ - + ]: 2601 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
4320 noah@leadboat.com 779 :UBC 0 : PG_RETURN_VOID();
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 : :
5784 rhaas@postgresql.org 786 :CBC 2601 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
8609 peter_e@gmx.net 787 [ - + ]: 2601 : if (!HeapTupleIsValid(tuple))
8187 tgl@sss.pgh.pa.us 788 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
789 : :
997 dgustafsson@postgres 790 :CBC 2601 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
6475 tgl@sss.pgh.pa.us 791 : 2601 : prosrc = TextDatumGetCString(tmp);
792 : :
8609 peter_e@gmx.net 793 [ + + ]: 2601 : if (fmgr_internal_function(prosrc) == InvalidOid)
8187 tgl@sss.pgh.pa.us 794 [ + - ]: 3 : ereport(ERROR,
795 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
796 : : errmsg("there is no built-in function named \"%s\"",
797 : : prosrc)));
798 : :
8609 peter_e@gmx.net 799 : 2598 : ReleaseSysCache(tuple);
800 : :
8517 tgl@sss.pgh.pa.us 801 : 2598 : PG_RETURN_VOID();
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 : : */
813 : : Datum
8609 peter_e@gmx.net 814 : 3214 : fmgr_c_validator(PG_FUNCTION_ARGS)
815 : : {
816 : 3214 : Oid funcoid = PG_GETARG_OID(0);
817 : : void *libraryhandle;
818 : : HeapTuple tuple;
819 : : Datum tmp;
820 : : char *prosrc;
821 : : char *probin;
822 : :
4320 noah@leadboat.com 823 [ - + ]: 3214 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
4320 noah@leadboat.com 824 :UBC 0 : PG_RETURN_VOID();
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 : :
5784 rhaas@postgresql.org 832 :CBC 3214 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
8609 peter_e@gmx.net 833 [ - + ]: 3214 : if (!HeapTupleIsValid(tuple))
8187 tgl@sss.pgh.pa.us 834 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
835 : :
997 dgustafsson@postgres 836 :CBC 3214 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
6475 tgl@sss.pgh.pa.us 837 : 3214 : prosrc = TextDatumGetCString(tmp);
838 : :
997 dgustafsson@postgres 839 : 3214 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_probin);
6475 tgl@sss.pgh.pa.us 840 : 3214 : probin = TextDatumGetCString(tmp);
841 : :
8609 peter_e@gmx.net 842 : 3214 : (void) load_external_function(probin, prosrc, true, &libraryhandle);
843 : 3208 : (void) fetch_finfo_record(libraryhandle, prosrc);
844 : :
845 : 3208 : ReleaseSysCache(tuple);
846 : :
8517 tgl@sss.pgh.pa.us 847 : 3208 : PG_RETURN_VOID();
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 : : */
856 : : Datum
8609 peter_e@gmx.net 857 : 4275 : fmgr_sql_validator(PG_FUNCTION_ARGS)
858 : : {
859 : 4275 : Oid funcoid = PG_GETARG_OID(0);
860 : : HeapTuple tuple;
861 : : Form_pg_proc proc;
862 : : List *raw_parsetree_list;
863 : : List *querytree_list;
864 : : ListCell *lc;
865 : : bool isnull;
866 : : Datum tmp;
867 : : char *prosrc;
868 : : parse_error_callback_arg callback_arg;
869 : : ErrorContextCallback sqlerrcontext;
870 : : bool haspolyarg;
871 : : int i;
872 : :
4320 noah@leadboat.com 873 [ - + ]: 4275 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
4320 noah@leadboat.com 874 :UBC 0 : PG_RETURN_VOID();
875 : :
5784 rhaas@postgresql.org 876 :CBC 4275 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
8609 peter_e@gmx.net 877 [ - + ]: 4275 : if (!HeapTupleIsValid(tuple))
8187 tgl@sss.pgh.pa.us 878 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
8609 peter_e@gmx.net 879 :CBC 4275 : proc = (Form_pg_proc) GETSTRUCT(tuple);
880 : :
881 : : /* Disallow pseudotype result */
882 : : /* except for RECORD, VOID, or polymorphic */
2846 883 [ + + ]: 4275 : if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
8516 tgl@sss.pgh.pa.us 884 [ + + ]: 752 : proc->prorettype != RECORDOID &&
8204 885 [ + + ]: 413 : proc->prorettype != VOIDOID &&
6833 886 [ + + + + : 185 : !IsPolymorphicType(proc->prorettype))
+ - + - +
+ + + + +
+ + + - +
+ + + ]
8187 887 [ + - ]: 3 : ereport(ERROR,
888 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
889 : : errmsg("SQL functions cannot return type %s",
890 : : format_type_be(proc->prorettype))));
891 : :
892 : : /* Disallow pseudotypes in arguments */
893 : : /* except for polymorphic */
8204 894 : 4272 : haspolyarg = false;
8517 895 [ + + ]: 11848 : for (i = 0; i < proc->pronargs; i++)
896 : : {
6833 897 [ + + ]: 7576 : if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
898 : : {
899 [ + + + + : 491 : if (IsPolymorphicType(proc->proargtypes.values[i]))
+ - + - +
+ + + + +
+ + + + +
+ + - ]
8204 900 : 491 : haspolyarg = true;
901 : : else
8187 tgl@sss.pgh.pa.us 902 [ # # ]:UBC 0 : ereport(ERROR,
903 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
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 */
8110 tgl@sss.pgh.pa.us 910 [ + + ]:CBC 4272 : if (check_function_bodies)
911 : : {
997 dgustafsson@postgres 912 : 4021 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
1706 tgl@sss.pgh.pa.us 913 : 4021 : prosrc = TextDatumGetCString(tmp);
914 : :
915 : : /*
916 : : * Setup error traceback support for ereport().
917 : : */
5751 918 : 4021 : callback_arg.proname = NameStr(proc->proname);
1706 919 : 4021 : callback_arg.prosrc = prosrc;
920 : :
7947 921 : 4021 : sqlerrcontext.callback = sql_function_parse_error_callback;
383 peter@eisentraut.org 922 : 4021 : sqlerrcontext.arg = &callback_arg;
7947 tgl@sss.pgh.pa.us 923 : 4021 : sqlerrcontext.previous = error_context_stack;
924 : 4021 : error_context_stack = &sqlerrcontext;
925 : :
926 : : /* If we have prosqlbody, pay attention to that not prosrc */
1706 927 : 4021 : tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
928 [ + + ]: 4021 : if (!isnull)
929 : : {
930 : : Node *n;
931 : : List *stored_query_list;
932 : :
1714 peter@eisentraut.org 933 : 2829 : n = stringToNode(TextDatumGetCString(tmp));
934 [ + + ]: 2829 : if (IsA(n, List))
1568 tgl@sss.pgh.pa.us 935 : 392 : stored_query_list = linitial(castNode(List, n));
936 : : else
937 : 2437 : stored_query_list = list_make1(n);
938 : :
939 : 2829 : querytree_list = NIL;
940 [ + + + + : 5658 : foreach(lc, stored_query_list)
+ + ]
941 : : {
942 : 2829 : Query *parsetree = lfirst_node(Query, lc);
943 : : List *querytree_sublist;
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 : 2829 : AcquireRewriteLocks(parsetree, true, false);
952 : 2829 : querytree_sublist = pg_rewrite_query(parsetree);
953 : 2829 : querytree_list = lappend(querytree_list, querytree_sublist);
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 : : */
1714 peter@eisentraut.org 967 : 1192 : raw_parsetree_list = pg_parse_query(prosrc);
1713 tgl@sss.pgh.pa.us 968 : 1188 : querytree_list = NIL;
969 : :
1714 peter@eisentraut.org 970 [ + + ]: 1188 : if (!haspolyarg)
971 : : {
972 : : /*
973 : : * OK to do full precheck: analyze and rewrite the queries,
974 : : * then verify the result type.
975 : : */
976 : : SQLFunctionParseInfoPtr pinfo;
977 : :
978 : : /* But first, set up parameter information */
979 : 879 : pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
980 : :
981 [ + + + + : 1816 : foreach(lc, raw_parsetree_list)
+ + ]
982 : : {
983 : 943 : RawStmt *parsetree = lfirst_node(RawStmt, lc);
984 : : List *querytree_sublist;
985 : :
1383 986 : 943 : querytree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
987 : : prosrc,
988 : : (ParserSetupHook) sql_fn_parser_setup,
989 : : pinfo,
990 : : NULL);
1714 991 : 937 : querytree_list = lappend(querytree_list,
992 : : querytree_sublist);
993 : : }
994 : : }
995 : : }
996 : :
997 [ + + ]: 4011 : if (!haspolyarg)
998 : : {
999 : : Oid rettype;
1000 : : TupleDesc rettupdesc;
1001 : :
2834 peter_e@gmx.net 1002 : 3702 : check_sql_fn_statements(querytree_list);
1003 : :
2169 tgl@sss.pgh.pa.us 1004 : 3699 : (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
1005 : :
1006 : 3699 : (void) check_sql_fn_retval(querytree_list,
1007 : : rettype, rettupdesc,
644 1008 : 3699 : proc->prokind,
1009 : : false);
1010 : : }
1011 : :
7947 1012 : 3999 : error_context_stack = sqlerrcontext.previous;
1013 : : }
1014 : :
8609 peter_e@gmx.net 1015 : 4250 : ReleaseSysCache(tuple);
1016 : :
8517 tgl@sss.pgh.pa.us 1017 : 4250 : PG_RETURN_VOID();
1018 : : }
1019 : :
1020 : : /*
1021 : : * Error context callback for handling errors in SQL function definitions
1022 : : */
1023 : : static void
7947 1024 : 22 : sql_function_parse_error_callback(void *arg)
1025 : : {
5751 1026 : 22 : parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
1027 : :
1028 : : /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
1029 [ + + ]: 22 : if (!function_parse_error_transpose(callback_arg->prosrc))
1030 : : {
1031 : : /* If it's not a syntax error, push info onto context stack */
1032 : 12 : errcontext("SQL function \"%s\"", callback_arg->proname);
1033 : : }
7940 1034 : 22 : }
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 : : */
1047 : : bool
1048 : 137 : function_parse_error_transpose(const char *prosrc)
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 : : */
1060 : 137 : origerrposition = geterrposition();
1061 [ + + ]: 137 : if (origerrposition <= 0)
1062 : : {
1063 : 121 : origerrposition = getinternalerrposition();
1064 [ + + ]: 121 : if (origerrposition <= 0)
1065 : 35 : return false;
1066 : : }
1067 : :
1068 : : /* We can get the original query text from the active portal (hack...) */
1139 1069 [ + - + - ]: 102 : if (ActivePortal && ActivePortal->status == PORTAL_ACTIVE)
1070 : 102 : {
1071 : 102 : const char *queryText = ActivePortal->sourceText;
1072 : :
1073 : : /* Try to locate the prosrc in the original text */
1074 : 102 : newerrposition = match_prosrc_to_query(prosrc, queryText,
1075 : : origerrposition);
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 : : */
1139 tgl@sss.pgh.pa.us 1083 :UBC 0 : newerrposition = -1;
1084 : : }
1085 : :
7940 tgl@sss.pgh.pa.us 1086 [ + + ]:CBC 102 : if (newerrposition > 0)
1087 : : {
1088 : : /* Successful, so fix error position to reference original query */
1089 : 101 : errposition(newerrposition);
1090 : : /* Get rid of any report of the error as an "internal query" */
1091 : 101 : internalerrposition(0);
1092 : 101 : internalerrquery(NULL);
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 : 1 : errposition(0);
1101 : 1 : internalerrposition(origerrposition);
1102 : 1 : internalerrquery(prosrc);
1103 : : }
1104 : :
1105 : 102 : 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 : : */
1114 : : static int
1115 : 102 : match_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 : : */
7779 bruce@momjian.us 1124 : 102 : int prosrclen = strlen(prosrc);
1125 : 102 : int querylen = strlen(queryText);
1126 : 102 : int matchpos = 0;
1127 : : int curpos;
1128 : : int newcursorpos;
1129 : :
1130 [ + + ]: 7012 : for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1131 : : {
7940 tgl@sss.pgh.pa.us 1132 [ + + ]: 6910 : if (queryText[curpos] == '$' &&
7779 bruce@momjian.us 1133 [ + + ]: 190 : strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1134 [ + - ]: 95 : 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 : : */
7940 tgl@sss.pgh.pa.us 1141 [ - + ]: 95 : if (matchpos)
7940 tgl@sss.pgh.pa.us 1142 :UBC 0 : return 0; /* multiple matches, fail */
7779 bruce@momjian.us 1143 :CBC 95 : matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1144 : : + cursorpos;
1145 : : }
7940 tgl@sss.pgh.pa.us 1146 [ + + + - ]: 6821 : else if (queryText[curpos] == '\'' &&
7779 bruce@momjian.us 1147 : 6 : match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
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 : : */
7940 tgl@sss.pgh.pa.us 1154 [ - + ]: 6 : if (matchpos)
7940 tgl@sss.pgh.pa.us 1155 :UBC 0 : return 0; /* multiple matches, fail */
7779 bruce@momjian.us 1156 :CBC 6 : matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
7940 tgl@sss.pgh.pa.us 1157 : 6 : + newcursorpos;
1158 : : }
1159 : : }
1160 : :
1161 : 102 : 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 : : */
1172 : : static bool
1173 : 6 : match_prosrc_to_literal(const char *prosrc, const char *literal,
1174 : : int cursorpos, int *newcursorpos)
1175 : : {
1176 : 6 : 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 [ + + ]: 72 : while (*prosrc)
1188 : : {
1189 : 66 : 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 [ - + ]: 66 : if (*literal == '\\')
1196 : : {
7940 tgl@sss.pgh.pa.us 1197 :UBC 0 : literal++;
1198 [ # # ]: 0 : if (cursorpos > 0)
1199 : 0 : newcp++;
1200 : : }
7940 tgl@sss.pgh.pa.us 1201 [ - + ]:CBC 66 : else if (*literal == '\'')
1202 : : {
7940 tgl@sss.pgh.pa.us 1203 [ # # ]:UBC 0 : if (literal[1] != '\'')
7388 1204 : 0 : goto fail;
7940 1205 : 0 : literal++;
1206 [ # # ]: 0 : if (cursorpos > 0)
1207 : 0 : newcp++;
1208 : : }
7940 tgl@sss.pgh.pa.us 1209 :CBC 66 : chlen = pg_mblen(prosrc);
1210 [ - + ]: 66 : if (strncmp(prosrc, literal, chlen) != 0)
7388 tgl@sss.pgh.pa.us 1211 :UBC 0 : goto fail;
7940 tgl@sss.pgh.pa.us 1212 :CBC 66 : prosrc += chlen;
1213 : 66 : literal += chlen;
1214 : : }
1215 : :
1216 [ + - - + ]: 6 : if (*literal == '\'' && literal[1] != '\'')
1217 : : {
1218 : : /* success */
7388 1219 : 6 : *newcursorpos = newcp;
7940 1220 : 6 : return true;
1221 : : }
1222 : :
7388 tgl@sss.pgh.pa.us 1223 :UBC 0 : fail:
1224 : : /* Must set *newcursorpos to suppress compiler warning */
1225 : 0 : *newcursorpos = newcp;
7940 1226 : 0 : return false;
1227 : : }
1228 : :
1229 : : List *
3887 peter_e@gmx.net 1230 :CBC 60 : oid_array_to_list(Datum datum)
1231 : : {
3860 bruce@momjian.us 1232 : 60 : ArrayType *array = DatumGetArrayTypeP(datum);
1233 : : Datum *values;
1234 : : int nelems;
1235 : : int i;
1236 : 60 : List *result = NIL;
1237 : :
1264 peter@eisentraut.org 1238 : 60 : deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems);
3887 peter_e@gmx.net 1239 [ + + ]: 122 : for (i = 0; i < nelems; i++)
130 peter@eisentraut.org 1240 :GNC 62 : result = lappend_oid(result, DatumGetObjectId(values[i]));
3887 peter_e@gmx.net 1241 :CBC 60 : return result;
1242 : : }
|