Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * functioncmds.c
4 : : *
5 : : * Routines for CREATE and DROP FUNCTION commands and CREATE and DROP
6 : : * CAST commands.
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/commands/functioncmds.c
14 : : *
15 : : * DESCRIPTION
16 : : * These routines take the parse tree and pick out the
17 : : * appropriate arguments/flags, and pass the results to the
18 : : * corresponding "FooCreate" routines (in src/backend/catalog) that do
19 : : * the actual catalog-munging. These routines also verify permission
20 : : * of the user to execute the command.
21 : : *
22 : : * NOTES
23 : : * These things must be defined and committed in the following order:
24 : : * "create function":
25 : : * input/output, recv/send procedures
26 : : * "create type":
27 : : * type
28 : : * "create operator":
29 : : * operators
30 : : *
31 : : *-------------------------------------------------------------------------
32 : : */
33 : : #include "postgres.h"
34 : :
35 : : #include "access/htup_details.h"
36 : : #include "access/table.h"
37 : : #include "access/xact.h"
38 : : #include "catalog/catalog.h"
39 : : #include "catalog/dependency.h"
40 : : #include "catalog/indexing.h"
41 : : #include "catalog/objectaccess.h"
42 : : #include "catalog/pg_aggregate.h"
43 : : #include "catalog/pg_cast.h"
44 : : #include "catalog/pg_language.h"
45 : : #include "catalog/pg_namespace.h"
46 : : #include "catalog/pg_proc.h"
47 : : #include "catalog/pg_transform.h"
48 : : #include "catalog/pg_type.h"
49 : : #include "commands/defrem.h"
50 : : #include "commands/extension.h"
51 : : #include "commands/proclang.h"
52 : : #include "executor/executor.h"
53 : : #include "executor/functions.h"
54 : : #include "funcapi.h"
55 : : #include "miscadmin.h"
56 : : #include "nodes/nodeFuncs.h"
57 : : #include "optimizer/optimizer.h"
58 : : #include "parser/analyze.h"
59 : : #include "parser/parse_coerce.h"
60 : : #include "parser/parse_collate.h"
61 : : #include "parser/parse_expr.h"
62 : : #include "parser/parse_func.h"
63 : : #include "parser/parse_type.h"
64 : : #include "pgstat.h"
65 : : #include "tcop/pquery.h"
66 : : #include "tcop/utility.h"
67 : : #include "utils/acl.h"
68 : : #include "utils/builtins.h"
69 : : #include "utils/guc.h"
70 : : #include "utils/lsyscache.h"
71 : : #include "utils/rel.h"
72 : : #include "utils/snapmgr.h"
73 : : #include "utils/syscache.h"
74 : : #include "utils/typcache.h"
75 : :
76 : : /*
77 : : * Examine the RETURNS clause of the CREATE FUNCTION statement
78 : : * and return information about it as *prorettype_p and *returnsSet_p.
79 : : *
80 : : * This is more complex than the average typename lookup because we want to
81 : : * allow a shell type to be used, or even created if the specified return type
82 : : * doesn't exist yet. (Without this, there's no way to define the I/O procs
83 : : * for a new type.) But SQL function creation won't cope, so error out if
84 : : * the target language is SQL. (We do this here, not in the SQL-function
85 : : * validator, so as not to produce a NOTICE and then an ERROR for the same
86 : : * condition.)
87 : : */
88 : : static void
89 : 13570 : compute_return_type(TypeName *returnType, Oid languageOid,
90 : : Oid *prorettype_p, bool *returnsSet_p)
91 : : {
92 : : Oid rettype;
93 : : Type typtup;
94 : : AclResult aclresult;
95 : : bool attempt_shell_creation;
96 : :
97 : : /*
98 : : * If this looks like it could be an input function, and the type doesn't
99 : : * exist, we'll create it as a shell type.
100 : : *
101 : : * If the type name contains any modifiers like %TYPE, type[] array
102 : : * syntax, or typmod decoration, it's not an input function, or at least
103 : : * not one for which we'd want to automatically create a shell type.
104 : : *
105 : : * Only C-coded functions can be I/O functions. We enforce this
106 : : * restriction here mainly to prevent littering the catalogs with shell
107 : : * types due to simple typos in user-defined function definitions.
108 : : */
109 : 13570 : attempt_shell_creation =
110 [ + + ]: 13558 : !returnType->pct_type && returnType->arrayBounds == NULL &&
111 [ + + + + : 39898 : returnType->typmods == NIL &&
+ + ]
112 [ + + ]: 12770 : (languageOid == INTERNALlanguageId || languageOid == ClanguageId);
113 : :
114 : 13570 : typtup = LookupTypeName(NULL, returnType, NULL, false);
115 [ + + ]: 13554 : if (typtup)
116 : : {
117 : : /*
118 : : * Found an existing type with the given name. Check if it's a shell
119 : : * type.
120 : : */
121 [ + + ]: 13486 : if (!((Form_pg_type) GETSTRUCT(typtup))->typisdefined)
122 : : {
123 [ - + ]: 101 : if (languageOid == SQLlanguageId)
124 [ # # ]: 0 : ereport(ERROR,
125 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
126 : : errmsg("SQL function cannot return shell type %s",
127 : : TypeNameToString(returnType))));
128 : : else
129 [ + + ]: 101 : ereport(NOTICE,
130 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
131 : : errmsg("return type %s is only a shell",
132 : : TypeNameToString(returnType))));
133 : : }
134 : 13486 : rettype = typeTypeId(typtup);
135 : 13486 : ReleaseSysCache(typtup);
136 : : }
137 [ + + ]: 68 : else if (!attempt_shell_creation)
138 : : {
139 : : /* Type not found and we don't want to create a shell type */
140 [ + - ]: 8 : ereport(ERROR,
141 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
142 : : errmsg("type \"%s\" does not exist",
143 : : TypeNameToString(returnType))));
144 : : }
145 : : else
146 : : {
147 : : /* Make a shell type */
148 : : Oid namespaceId;
149 : : char *typname;
150 : : ObjectAddress address;
151 : :
152 [ + + ]: 60 : ereport(NOTICE,
153 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
154 : : errmsg("type \"%s\" is not yet defined",
155 : : TypeNameToString(returnType)),
156 : : errdetail("Creating a shell type definition.")));
157 : :
158 : 60 : namespaceId = QualifiedNameGetCreationNamespace(returnType->names,
159 : : &typname);
160 : 60 : aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(),
161 : : ACL_CREATE);
162 [ - + ]: 60 : if (aclresult != ACLCHECK_OK)
163 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
164 : 0 : get_namespace_name(namespaceId));
165 : :
166 : 60 : address = TypeShellMake(typname, namespaceId, GetUserId());
167 : 60 : rettype = address.objectId;
168 : : Assert(OidIsValid(rettype));
169 : : /* Ensure the new shell type is visible to ProcedureCreate */
170 : 60 : CommandCounterIncrement();
171 : : }
172 : :
173 : 13546 : aclresult = object_aclcheck(TypeRelationId, rettype, GetUserId(), ACL_USAGE);
174 [ + + ]: 13546 : if (aclresult != ACLCHECK_OK)
175 : 4 : aclcheck_error_type(aclresult, rettype);
176 : :
177 : 13542 : *prorettype_p = rettype;
178 : 13542 : *returnsSet_p = returnType->setof;
179 : 13542 : }
180 : :
181 : : /*
182 : : * Interpret the function parameter list of a CREATE FUNCTION,
183 : : * CREATE PROCEDURE, or CREATE AGGREGATE statement.
184 : : *
185 : : * Input parameters:
186 : : * parameters: list of FunctionParameter structs
187 : : * languageOid: OID of function language (InvalidOid if it's CREATE AGGREGATE)
188 : : * objtype: identifies type of object being created
189 : : *
190 : : * Results are stored into output parameters. parameterTypes must always
191 : : * be created, but the other arrays/lists can be NULL pointers if not needed.
192 : : * variadicArgType is set to the variadic array type if there's a VARIADIC
193 : : * parameter (there can be only one); or to InvalidOid if not.
194 : : * requiredResultType is set to InvalidOid if there are no OUT parameters,
195 : : * else it is set to the OID of the implied result type.
196 : : */
197 : : void
198 : 14529 : interpret_function_parameter_list(ParseState *pstate,
199 : : List *parameters,
200 : : Oid languageOid,
201 : : ObjectType objtype,
202 : : oidvector **parameterTypes,
203 : : List **parameterTypes_list,
204 : : ArrayType **allParameterTypes,
205 : : ArrayType **parameterModes,
206 : : ArrayType **parameterNames,
207 : : List **inParameterNames_list,
208 : : List **parameterDefaults,
209 : : Oid *variadicArgType,
210 : : Oid *requiredResultType)
211 : : {
212 : 14529 : int parameterCount = list_length(parameters);
213 : : Oid *inTypes;
214 : 14529 : int inCount = 0;
215 : : Datum *allTypes;
216 : : Datum *paramModes;
217 : : Datum *paramNames;
218 : 14529 : int outCount = 0;
219 : 14529 : int varCount = 0;
220 : 14529 : bool have_names = false;
221 : 14529 : bool have_defaults = false;
222 : : ListCell *x;
223 : : int i;
224 : :
225 : 14529 : *variadicArgType = InvalidOid; /* default result */
226 : 14529 : *requiredResultType = InvalidOid; /* default result */
227 : :
228 : 14529 : inTypes = palloc_array(Oid, parameterCount);
229 : 14529 : allTypes = palloc_array(Datum, parameterCount);
230 : 14529 : paramModes = palloc_array(Datum, parameterCount);
231 : 14529 : paramNames = palloc0_array(Datum, parameterCount);
232 : 14529 : *parameterDefaults = NIL;
233 : :
234 : : /* Scan the list and extract data into work arrays */
235 : 14529 : i = 0;
236 [ + + + + : 42191 : foreach(x, parameters)
+ + ]
237 : : {
238 : 27710 : FunctionParameter *fp = (FunctionParameter *) lfirst(x);
239 : 27710 : TypeName *t = fp->argType;
240 : 27710 : FunctionParameterMode fpmode = fp->mode;
241 : 27710 : bool isinput = false;
242 : : Oid toid;
243 : : Type typtup;
244 : : AclResult aclresult;
245 : :
246 : : /* For our purposes here, a defaulted mode spec is identical to IN */
247 [ + + ]: 27710 : if (fpmode == FUNC_PARAM_DEFAULT)
248 : 18701 : fpmode = FUNC_PARAM_IN;
249 : :
250 : 27710 : typtup = LookupTypeName(pstate, t, NULL, false);
251 [ + - ]: 27702 : if (typtup)
252 : : {
253 [ + + ]: 27702 : if (!((Form_pg_type) GETSTRUCT(typtup))->typisdefined)
254 : : {
255 : : /* As above, hard error if language is SQL */
256 [ - + ]: 159 : if (languageOid == SQLlanguageId)
257 [ # # ]: 0 : ereport(ERROR,
258 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
259 : : errmsg("SQL function cannot accept shell type %s",
260 : : TypeNameToString(t)),
261 : : parser_errposition(pstate, t->location)));
262 : : /* We don't allow creating aggregates on shell types either */
263 [ - + ]: 159 : else if (objtype == OBJECT_AGGREGATE)
264 [ # # ]: 0 : ereport(ERROR,
265 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
266 : : errmsg("aggregate cannot accept shell type %s",
267 : : TypeNameToString(t)),
268 : : parser_errposition(pstate, t->location)));
269 : : else
270 [ + + ]: 159 : ereport(NOTICE,
271 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
272 : : errmsg("argument type %s is only a shell",
273 : : TypeNameToString(t)),
274 : : parser_errposition(pstate, t->location)));
275 : : }
276 : 27702 : toid = typeTypeId(typtup);
277 : 27702 : ReleaseSysCache(typtup);
278 : : }
279 : : else
280 : : {
281 [ # # ]: 0 : ereport(ERROR,
282 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
283 : : errmsg("type %s does not exist",
284 : : TypeNameToString(t)),
285 : : parser_errposition(pstate, t->location)));
286 : : toid = InvalidOid; /* keep compiler quiet */
287 : : }
288 : :
289 : 27702 : aclresult = object_aclcheck(TypeRelationId, toid, GetUserId(), ACL_USAGE);
290 [ + + ]: 27702 : if (aclresult != ACLCHECK_OK)
291 : 8 : aclcheck_error_type(aclresult, toid);
292 : :
293 [ - + ]: 27694 : if (t->setof)
294 : : {
295 [ # # ]: 0 : if (objtype == OBJECT_AGGREGATE)
296 [ # # ]: 0 : ereport(ERROR,
297 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
298 : : errmsg("aggregates cannot accept set arguments"),
299 : : parser_errposition(pstate, fp->location)));
300 [ # # ]: 0 : else if (objtype == OBJECT_PROCEDURE)
301 [ # # ]: 0 : ereport(ERROR,
302 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
303 : : errmsg("procedures cannot accept set arguments"),
304 : : parser_errposition(pstate, fp->location)));
305 : : else
306 [ # # ]: 0 : ereport(ERROR,
307 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
308 : : errmsg("functions cannot accept set arguments"),
309 : : parser_errposition(pstate, fp->location)));
310 : : }
311 : :
312 : : /* handle input parameters */
313 [ + + + + ]: 27694 : if (fpmode != FUNC_PARAM_OUT && fpmode != FUNC_PARAM_TABLE)
314 : : {
315 : : /* other input parameters can't follow a VARIADIC parameter */
316 [ - + ]: 20841 : if (varCount > 0)
317 [ # # ]: 0 : ereport(ERROR,
318 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
319 : : errmsg("VARIADIC parameter must be the last input parameter"),
320 : : parser_errposition(pstate, fp->location)));
321 : 20841 : inTypes[inCount++] = toid;
322 : 20841 : isinput = true;
323 [ + + ]: 20841 : if (parameterTypes_list)
324 : 20511 : *parameterTypes_list = lappend_oid(*parameterTypes_list, toid);
325 [ + + ]: 20841 : if (inParameterNames_list)
326 : 20511 : *inParameterNames_list = lappend(*inParameterNames_list,
327 [ + + ]: 20511 : makeString(fp->name ? fp->name : pstrdup("")));
328 : : }
329 : :
330 : : /* handle output parameters */
331 [ + + + + ]: 27694 : if (fpmode != FUNC_PARAM_IN && fpmode != FUNC_PARAM_VARIADIC)
332 : : {
333 [ + + ]: 6967 : if (objtype == OBJECT_PROCEDURE)
334 : : {
335 : : /*
336 : : * We disallow OUT-after-VARIADIC only for procedures. While
337 : : * such a case causes no confusion in ordinary function calls,
338 : : * it would cause confusion in a CALL statement.
339 : : */
340 [ + + ]: 112 : if (varCount > 0)
341 [ + - ]: 4 : ereport(ERROR,
342 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
343 : : errmsg("VARIADIC parameter must be the last parameter"),
344 : : parser_errposition(pstate, fp->location)));
345 : : /* Procedures with output parameters always return RECORD */
346 : 108 : *requiredResultType = RECORDOID;
347 : : }
348 [ + + ]: 6855 : else if (outCount == 0) /* save first output param's type */
349 : 1233 : *requiredResultType = toid;
350 : 6963 : outCount++;
351 : : }
352 : :
353 [ + + ]: 27690 : if (fpmode == FUNC_PARAM_VARIADIC)
354 : : {
355 : 78 : *variadicArgType = toid;
356 : 78 : varCount++;
357 : : /* validate variadic parameter type */
358 [ + + ]: 78 : switch (toid)
359 : : {
360 : 44 : case ANYARRAYOID:
361 : : case ANYCOMPATIBLEARRAYOID:
362 : : case ANYOID:
363 : : /* okay */
364 : 44 : break;
365 : 34 : default:
366 [ - + ]: 34 : if (!OidIsValid(get_element_type(toid)))
367 [ # # ]: 0 : ereport(ERROR,
368 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
369 : : errmsg("VARIADIC parameter must be an array"),
370 : : parser_errposition(pstate, fp->location)));
371 : 34 : break;
372 : : }
373 : : }
374 : :
375 : 27690 : allTypes[i] = ObjectIdGetDatum(toid);
376 : :
377 : 27690 : paramModes[i] = CharGetDatum(fpmode);
378 : :
379 [ + + + - ]: 27690 : if (fp->name && fp->name[0])
380 : : {
381 : : ListCell *px;
382 : :
383 : : /*
384 : : * As of Postgres 9.0 we disallow using the same name for two
385 : : * input or two output function parameters. Depending on the
386 : : * function's language, conflicting input and output names might
387 : : * be bad too, but we leave it to the PL to complain if so.
388 : : */
389 [ + - + - : 79306 : foreach(px, parameters)
+ - ]
390 : : {
391 : 79306 : FunctionParameter *prevfp = (FunctionParameter *) lfirst(px);
392 : : FunctionParameterMode prevfpmode;
393 : :
394 [ + + ]: 79306 : if (prevfp == fp)
395 : 13032 : break;
396 : : /* as above, default mode is IN */
397 : 66274 : prevfpmode = prevfp->mode;
398 [ + + ]: 66274 : if (prevfpmode == FUNC_PARAM_DEFAULT)
399 : 5688 : prevfpmode = FUNC_PARAM_IN;
400 : : /* pure in doesn't conflict with pure out */
401 [ + + + + ]: 66274 : if ((fpmode == FUNC_PARAM_IN ||
402 [ + + ]: 4306 : fpmode == FUNC_PARAM_VARIADIC) &&
403 [ - + ]: 4230 : (prevfpmode == FUNC_PARAM_OUT ||
404 : : prevfpmode == FUNC_PARAM_TABLE))
405 : 76 : continue;
406 [ + + - + ]: 66198 : if ((prevfpmode == FUNC_PARAM_IN ||
407 [ + + ]: 13441 : prevfpmode == FUNC_PARAM_VARIADIC) &&
408 [ + + ]: 4626 : (fpmode == FUNC_PARAM_OUT ||
409 : : fpmode == FUNC_PARAM_TABLE))
410 : 9187 : continue;
411 [ + + + - ]: 57011 : if (prevfp->name && prevfp->name[0] &&
412 [ + + ]: 56980 : strcmp(prevfp->name, fp->name) == 0)
413 [ + - ]: 16 : ereport(ERROR,
414 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
415 : : errmsg("parameter name \"%s\" used more than once",
416 : : fp->name),
417 : : parser_errposition(pstate, fp->location)));
418 : : }
419 : :
420 : 13032 : paramNames[i] = CStringGetTextDatum(fp->name);
421 : 13032 : have_names = true;
422 : : }
423 : :
424 [ + + ]: 27674 : if (fp->defexpr)
425 : : {
426 : : Node *def;
427 : :
428 [ + + ]: 744 : if (!isinput)
429 [ + - ]: 4 : ereport(ERROR,
430 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
431 : : errmsg("only input parameters can have default values"),
432 : : parser_errposition(pstate, fp->location)));
433 : :
434 : 740 : def = transformExpr(pstate, fp->defexpr,
435 : : EXPR_KIND_FUNCTION_DEFAULT);
436 : 740 : def = coerce_to_specific_type(pstate, def, toid, "DEFAULT");
437 : 740 : assign_expr_collations(pstate, def);
438 : :
439 : : /*
440 : : * Make sure no variables are referred to (this is probably dead
441 : : * code now that add_missing_from is history).
442 : : */
443 [ + - - + ]: 1480 : if (pstate->p_rtable != NIL ||
444 : 740 : contain_var_clause(def))
445 [ # # ]: 0 : ereport(ERROR,
446 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
447 : : errmsg("cannot use table references in parameter default value"),
448 : : parser_errposition(pstate, fp->location)));
449 : :
450 : : /*
451 : : * transformExpr() should have already rejected subqueries,
452 : : * aggregates, and window functions, based on the EXPR_KIND_ for a
453 : : * default expression.
454 : : *
455 : : * It can't return a set either --- but coerce_to_specific_type
456 : : * already checked that for us.
457 : : *
458 : : * Note: the point of these restrictions is to ensure that an
459 : : * expression that, on its face, hasn't got subplans, aggregates,
460 : : * etc cannot suddenly have them after function default arguments
461 : : * are inserted.
462 : : */
463 : :
464 : 740 : *parameterDefaults = lappend(*parameterDefaults, def);
465 : 740 : have_defaults = true;
466 : : }
467 : : else
468 : : {
469 [ + + + + ]: 26930 : if (isinput && have_defaults)
470 [ + - ]: 4 : ereport(ERROR,
471 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
472 : : errmsg("input parameters after one with a default value must also have defaults"),
473 : : parser_errposition(pstate, fp->location)));
474 : :
475 : : /*
476 : : * For procedures, we also can't allow OUT parameters after one
477 : : * with a default, because the same sort of confusion arises in a
478 : : * CALL statement.
479 : : */
480 [ + + + + ]: 26926 : if (objtype == OBJECT_PROCEDURE && have_defaults)
481 [ + - ]: 4 : ereport(ERROR,
482 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
483 : : errmsg("procedure OUT parameters cannot appear after one with a default value"),
484 : : parser_errposition(pstate, fp->location)));
485 : : }
486 : :
487 : 27662 : i++;
488 : : }
489 : :
490 : : /* Now construct the proper outputs as needed */
491 : 14481 : *parameterTypes = buildoidvector(inTypes, inCount);
492 : :
493 [ + + + + ]: 14481 : if (outCount > 0 || varCount > 0)
494 : : {
495 : 1353 : *allParameterTypes = construct_array_builtin(allTypes, parameterCount, OIDOID);
496 : 1353 : *parameterModes = construct_array_builtin(paramModes, parameterCount, CHAROID);
497 [ + + ]: 1353 : if (outCount > 1)
498 : 1108 : *requiredResultType = RECORDOID;
499 : : /* otherwise we set requiredResultType correctly above */
500 : : }
501 : : else
502 : : {
503 : 13128 : *allParameterTypes = NULL;
504 : 13128 : *parameterModes = NULL;
505 : : }
506 : :
507 [ + + ]: 14481 : if (have_names)
508 : : {
509 [ + + ]: 16993 : for (i = 0; i < parameterCount; i++)
510 : : {
511 [ + + ]: 13175 : if (paramNames[i] == PointerGetDatum(NULL))
512 : 179 : paramNames[i] = CStringGetTextDatum("");
513 : : }
514 : 3818 : *parameterNames = construct_array_builtin(paramNames, parameterCount, TEXTOID);
515 : : }
516 : : else
517 : 10663 : *parameterNames = NULL;
518 : 14481 : }
519 : :
520 : :
521 : : /*
522 : : * Recognize one of the options that can be passed to both CREATE
523 : : * FUNCTION and ALTER FUNCTION and return it via one of the out
524 : : * parameters. Returns true if the passed option was recognized. If
525 : : * the out parameter we were going to assign to points to non-NULL,
526 : : * raise a duplicate-clause error. (We don't try to detect duplicate
527 : : * SET parameters though --- if you're redundant, the last one wins.)
528 : : */
529 : : static bool
530 : 23512 : compute_common_attribute(ParseState *pstate,
531 : : bool is_procedure,
532 : : DefElem *defel,
533 : : DefElem **volatility_item,
534 : : DefElem **strict_item,
535 : : DefElem **security_item,
536 : : DefElem **leakproof_item,
537 : : List **set_items,
538 : : DefElem **cost_item,
539 : : DefElem **rows_item,
540 : : DefElem **support_item,
541 : : DefElem **parallel_item)
542 : : {
543 [ + + ]: 23512 : if (strcmp(defel->defname, "volatility") == 0)
544 : : {
545 [ - + ]: 6571 : if (is_procedure)
546 : 0 : goto procedure_error;
547 [ - + ]: 6571 : if (*volatility_item)
548 : 0 : errorConflictingDefElem(defel, pstate);
549 : :
550 : 6571 : *volatility_item = defel;
551 : : }
552 [ + + ]: 16941 : else if (strcmp(defel->defname, "strict") == 0)
553 : : {
554 [ + + ]: 7300 : if (is_procedure)
555 : 8 : goto procedure_error;
556 [ - + ]: 7292 : if (*strict_item)
557 : 0 : errorConflictingDefElem(defel, pstate);
558 : :
559 : 7292 : *strict_item = defel;
560 : : }
561 [ + + ]: 9641 : else if (strcmp(defel->defname, "security") == 0)
562 : : {
563 [ - + ]: 48 : if (*security_item)
564 : 0 : errorConflictingDefElem(defel, pstate);
565 : :
566 : 48 : *security_item = defel;
567 : : }
568 [ + + ]: 9593 : else if (strcmp(defel->defname, "leakproof") == 0)
569 : : {
570 [ - + ]: 38 : if (is_procedure)
571 : 0 : goto procedure_error;
572 [ - + ]: 38 : if (*leakproof_item)
573 : 0 : errorConflictingDefElem(defel, pstate);
574 : :
575 : 38 : *leakproof_item = defel;
576 : : }
577 [ + + ]: 9555 : else if (strcmp(defel->defname, "set") == 0)
578 : : {
579 : 109 : *set_items = lappend(*set_items, defel->arg);
580 : : }
581 [ + + ]: 9446 : else if (strcmp(defel->defname, "cost") == 0)
582 : : {
583 [ - + ]: 2287 : if (is_procedure)
584 : 0 : goto procedure_error;
585 [ - + ]: 2287 : if (*cost_item)
586 : 0 : errorConflictingDefElem(defel, pstate);
587 : :
588 : 2287 : *cost_item = defel;
589 : : }
590 [ + + ]: 7159 : else if (strcmp(defel->defname, "rows") == 0)
591 : : {
592 [ - + ]: 71 : if (is_procedure)
593 : 0 : goto procedure_error;
594 [ - + ]: 71 : if (*rows_item)
595 : 0 : errorConflictingDefElem(defel, pstate);
596 : :
597 : 71 : *rows_item = defel;
598 : : }
599 [ + + ]: 7088 : else if (strcmp(defel->defname, "support") == 0)
600 : : {
601 [ - + ]: 73 : if (is_procedure)
602 : 0 : goto procedure_error;
603 [ - + ]: 73 : if (*support_item)
604 : 0 : errorConflictingDefElem(defel, pstate);
605 : :
606 : 73 : *support_item = defel;
607 : : }
608 [ + - ]: 7015 : else if (strcmp(defel->defname, "parallel") == 0)
609 : : {
610 [ - + ]: 7015 : if (is_procedure)
611 : 0 : goto procedure_error;
612 [ - + ]: 7015 : if (*parallel_item)
613 : 0 : errorConflictingDefElem(defel, pstate);
614 : :
615 : 7015 : *parallel_item = defel;
616 : : }
617 : : else
618 : 0 : return false;
619 : :
620 : : /* Recognized an option */
621 : 23504 : return true;
622 : :
623 : 8 : procedure_error:
624 [ + - ]: 8 : ereport(ERROR,
625 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
626 : : errmsg("invalid attribute in procedure definition"),
627 : : parser_errposition(pstate, defel->location)));
628 : : return false;
629 : : }
630 : :
631 : : static char
632 : 6571 : interpret_func_volatility(DefElem *defel)
633 : : {
634 : 6571 : char *str = strVal(defel->arg);
635 : :
636 [ + + ]: 6571 : if (strcmp(str, "immutable") == 0)
637 : 5291 : return PROVOLATILE_IMMUTABLE;
638 [ + + ]: 1280 : else if (strcmp(str, "stable") == 0)
639 : 1031 : return PROVOLATILE_STABLE;
640 [ + - ]: 249 : else if (strcmp(str, "volatile") == 0)
641 : 249 : return PROVOLATILE_VOLATILE;
642 : : else
643 : : {
644 [ # # ]: 0 : elog(ERROR, "invalid volatility \"%s\"", str);
645 : : return 0; /* keep compiler quiet */
646 : : }
647 : : }
648 : :
649 : : static char
650 : 7015 : interpret_func_parallel(DefElem *defel)
651 : : {
652 : 7015 : char *str = strVal(defel->arg);
653 : :
654 [ + + ]: 7015 : if (strcmp(str, "safe") == 0)
655 : 5828 : return PROPARALLEL_SAFE;
656 [ + + ]: 1187 : else if (strcmp(str, "unsafe") == 0)
657 : 683 : return PROPARALLEL_UNSAFE;
658 [ + - ]: 504 : else if (strcmp(str, "restricted") == 0)
659 : 504 : return PROPARALLEL_RESTRICTED;
660 : : else
661 : : {
662 [ # # ]: 0 : ereport(ERROR,
663 : : (errcode(ERRCODE_SYNTAX_ERROR),
664 : : errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
665 : : return PROPARALLEL_UNSAFE; /* keep compiler quiet */
666 : : }
667 : : }
668 : :
669 : : /*
670 : : * Update a proconfig value according to a list of VariableSetStmt items.
671 : : *
672 : : * The input and result may be NULL to signify a null entry.
673 : : */
674 : : static ArrayType *
675 : 84 : update_proconfig_value(ArrayType *a, List *set_items)
676 : : {
677 : : ListCell *l;
678 : :
679 [ + - + + : 193 : foreach(l, set_items)
+ + ]
680 : : {
681 : 109 : VariableSetStmt *sstmt = lfirst_node(VariableSetStmt, l);
682 : :
683 [ + + ]: 109 : if (sstmt->kind == VAR_RESET_ALL)
684 : 8 : a = NULL;
685 : : else
686 : : {
687 : 101 : char *valuestr = ExtractSetVariableArgs(sstmt);
688 : :
689 [ + - ]: 101 : if (valuestr)
690 : 101 : a = GUCArrayAdd(a, sstmt->name, valuestr);
691 : : else /* RESET */
692 : 0 : a = GUCArrayDelete(a, sstmt->name);
693 : : }
694 : : }
695 : :
696 : 84 : return a;
697 : : }
698 : :
699 : : static Oid
700 : 73 : interpret_func_support(DefElem *defel)
701 : : {
702 : 73 : List *procName = defGetQualifiedName(defel);
703 : : Oid procOid;
704 : : Oid argList[1];
705 : :
706 : : /*
707 : : * Support functions always take one INTERNAL argument and return
708 : : * INTERNAL.
709 : : */
710 : 73 : argList[0] = INTERNALOID;
711 : :
712 : 73 : procOid = LookupFuncName(procName, 1, argList, true);
713 [ - + ]: 73 : if (!OidIsValid(procOid))
714 [ # # ]: 0 : ereport(ERROR,
715 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
716 : : errmsg("function %s does not exist",
717 : : func_signature_string(procName, 1, NIL, argList))));
718 : :
719 [ - + ]: 73 : if (get_func_rettype(procOid) != INTERNALOID)
720 [ # # ]: 0 : ereport(ERROR,
721 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
722 : : errmsg("support function %s must return type %s",
723 : : NameListToString(procName), "internal")));
724 : :
725 : : /*
726 : : * Someday we might want an ACL check here; but for now, we insist that
727 : : * you be superuser to specify a support function, so privilege on the
728 : : * support function is moot.
729 : : */
730 [ - + ]: 73 : if (!superuser())
731 [ # # ]: 0 : ereport(ERROR,
732 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
733 : : errmsg("must be superuser to specify a support function")));
734 : :
735 : 73 : return procOid;
736 : : }
737 : :
738 : :
739 : : /*
740 : : * Dissect the list of options assembled in gram.y into function
741 : : * attributes.
742 : : */
743 : : static void
744 : 14209 : compute_function_attributes(ParseState *pstate,
745 : : bool is_procedure,
746 : : List *options,
747 : : List **as,
748 : : char **language,
749 : : Node **transform,
750 : : bool *windowfunc_p,
751 : : char *volatility_p,
752 : : bool *strict_p,
753 : : bool *security_definer,
754 : : bool *leakproof_p,
755 : : ArrayType **proconfig,
756 : : float4 *procost,
757 : : float4 *prorows,
758 : : Oid *prosupport,
759 : : char *parallel_p)
760 : : {
761 : : ListCell *option;
762 : 14209 : DefElem *as_item = NULL;
763 : 14209 : DefElem *language_item = NULL;
764 : 14209 : DefElem *transform_item = NULL;
765 : 14209 : DefElem *windowfunc_item = NULL;
766 : 14209 : DefElem *volatility_item = NULL;
767 : 14209 : DefElem *strict_item = NULL;
768 : 14209 : DefElem *security_item = NULL;
769 : 14209 : DefElem *leakproof_item = NULL;
770 : 14209 : List *set_items = NIL;
771 : 14209 : DefElem *cost_item = NULL;
772 : 14209 : DefElem *rows_item = NULL;
773 : 14209 : DefElem *support_item = NULL;
774 : 14209 : DefElem *parallel_item = NULL;
775 : :
776 [ + + + + : 62448 : foreach(option, options)
+ + ]
777 : : {
778 : 48247 : DefElem *defel = (DefElem *) lfirst(option);
779 : :
780 [ + + ]: 48247 : if (strcmp(defel->defname, "as") == 0)
781 : : {
782 [ - + ]: 10741 : if (as_item)
783 : 0 : errorConflictingDefElem(defel, pstate);
784 : 10741 : as_item = defel;
785 : : }
786 [ + + ]: 37506 : else if (strcmp(defel->defname, "language") == 0)
787 : : {
788 [ - + ]: 14116 : if (language_item)
789 : 0 : errorConflictingDefElem(defel, pstate);
790 : 14116 : language_item = defel;
791 : : }
792 [ + + ]: 23390 : else if (strcmp(defel->defname, "transform") == 0)
793 : : {
794 [ - + ]: 76 : if (transform_item)
795 : 0 : errorConflictingDefElem(defel, pstate);
796 : 76 : transform_item = defel;
797 : : }
798 [ + + ]: 23314 : else if (strcmp(defel->defname, "window") == 0)
799 : : {
800 [ - + ]: 13 : if (windowfunc_item)
801 : 0 : errorConflictingDefElem(defel, pstate);
802 [ + + ]: 13 : if (is_procedure)
803 [ + - ]: 4 : ereport(ERROR,
804 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
805 : : errmsg("invalid attribute in procedure definition"),
806 : : parser_errposition(pstate, defel->location)));
807 : 9 : windowfunc_item = defel;
808 : : }
809 [ + - ]: 23301 : else if (compute_common_attribute(pstate,
810 : : is_procedure,
811 : : defel,
812 : : &volatility_item,
813 : : &strict_item,
814 : : &security_item,
815 : : &leakproof_item,
816 : : &set_items,
817 : : &cost_item,
818 : : &rows_item,
819 : : &support_item,
820 : : ¶llel_item))
821 : : {
822 : : /* recognized common option */
823 : 23297 : continue;
824 : : }
825 : : else
826 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
827 : : defel->defname);
828 : : }
829 : :
830 [ + + ]: 14201 : if (as_item)
831 : 10741 : *as = (List *) as_item->arg;
832 [ + + ]: 14201 : if (language_item)
833 : 14108 : *language = strVal(language_item->arg);
834 [ + + ]: 14201 : if (transform_item)
835 : 76 : *transform = transform_item->arg;
836 [ + + ]: 14201 : if (windowfunc_item)
837 : 9 : *windowfunc_p = boolVal(windowfunc_item->arg);
838 [ + + ]: 14201 : if (volatility_item)
839 : 6539 : *volatility_p = interpret_func_volatility(volatility_item);
840 [ + + ]: 14201 : if (strict_item)
841 : 7276 : *strict_p = boolVal(strict_item->arg);
842 [ + + ]: 14201 : if (security_item)
843 : 32 : *security_definer = boolVal(security_item->arg);
844 [ + + ]: 14201 : if (leakproof_item)
845 : 22 : *leakproof_p = boolVal(leakproof_item->arg);
846 [ + + ]: 14201 : if (set_items)
847 : 71 : *proconfig = update_proconfig_value(NULL, set_items);
848 [ + + ]: 14201 : if (cost_item)
849 : : {
850 : 2279 : *procost = defGetNumeric(cost_item);
851 [ - + ]: 2279 : if (*procost <= 0)
852 [ # # ]: 0 : ereport(ERROR,
853 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
854 : : errmsg("COST must be positive")));
855 : : }
856 [ + + ]: 14201 : if (rows_item)
857 : : {
858 : 71 : *prorows = defGetNumeric(rows_item);
859 [ - + ]: 71 : if (*prorows <= 0)
860 [ # # ]: 0 : ereport(ERROR,
861 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
862 : : errmsg("ROWS must be positive")));
863 : : }
864 [ + + ]: 14201 : if (support_item)
865 : 65 : *prosupport = interpret_func_support(support_item);
866 [ + + ]: 14201 : if (parallel_item)
867 : 6917 : *parallel_p = interpret_func_parallel(parallel_item);
868 : 14201 : }
869 : :
870 : :
871 : : /*
872 : : * For a dynamically linked C language object, the form of the clause is
873 : : *
874 : : * AS <object file name> [, <link symbol name> ]
875 : : *
876 : : * In all other cases
877 : : *
878 : : * AS <object reference, or sql code>
879 : : */
880 : : static void
881 : 14112 : interpret_AS_clause(Oid languageOid, const char *languageName,
882 : : char *funcname, List *as, Node *sql_body_in,
883 : : List *parameterTypes, List *inParameterNames,
884 : : char **prosrc_str_p, char **probin_str_p,
885 : : Node **sql_body_out,
886 : : const char *queryString)
887 : : {
888 [ + + - + ]: 14112 : if (!sql_body_in && !as)
889 [ # # ]: 0 : ereport(ERROR,
890 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
891 : : errmsg("no function body specified")));
892 : :
893 [ + + + + ]: 14112 : if (sql_body_in && as)
894 [ + - ]: 4 : ereport(ERROR,
895 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
896 : : errmsg("duplicate function body specified")));
897 : :
898 [ + + - + ]: 14108 : if (sql_body_in && languageOid != SQLlanguageId)
899 [ # # ]: 0 : ereport(ERROR,
900 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
901 : : errmsg("inline SQL function body only valid for language SQL")));
902 : :
903 : 14108 : *sql_body_out = NULL;
904 : :
905 [ + + ]: 14108 : if (languageOid == ClanguageId)
906 : : {
907 : : /*
908 : : * For "C" language, store the file name in probin and, when given,
909 : : * the link symbol name in prosrc. If link symbol is omitted,
910 : : * substitute procedure name. We also allow link symbol to be
911 : : * specified as "-", since that was the habit in PG versions before
912 : : * 8.4, and there might be dump files out there that don't translate
913 : : * that back to "omitted".
914 : : */
915 : 4414 : *probin_str_p = strVal(linitial(as));
916 [ + + ]: 4414 : if (list_length(as) == 1)
917 : 2149 : *prosrc_str_p = funcname;
918 : : else
919 : : {
920 : 2265 : *prosrc_str_p = strVal(lsecond(as));
921 [ - + ]: 2265 : if (strcmp(*prosrc_str_p, "-") == 0)
922 : 0 : *prosrc_str_p = funcname;
923 : : }
924 : : }
925 [ + + ]: 9694 : else if (sql_body_in)
926 : : {
927 : : SQLFunctionParseInfoPtr pinfo;
928 : :
929 : 3460 : pinfo = palloc0_object(SQLFunctionParseInfo);
930 : :
931 : 3460 : pinfo->fname = funcname;
932 : 3460 : pinfo->nargs = list_length(parameterTypes);
933 : : Assert(pinfo->nargs == list_length(inParameterNames));
934 : 3460 : pinfo->argtypes = palloc_array(Oid, pinfo->nargs);
935 : 3460 : pinfo->argnames = palloc_array(char *, pinfo->nargs);
936 [ + + ]: 10410 : for (int i = 0; i < pinfo->nargs; i++)
937 : : {
938 : 6954 : char *s = strVal(list_nth(inParameterNames, i));
939 : :
940 : 6954 : pinfo->argtypes[i] = list_nth_oid(parameterTypes, i);
941 [ + - + + : 6954 : if (IsPolymorphicType(pinfo->argtypes[i]))
+ - + - +
- + - + -
+ - + - +
- - + ]
942 [ + - ]: 4 : ereport(ERROR,
943 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
944 : : errmsg("SQL function with unquoted function body cannot have polymorphic arguments")));
945 : :
946 [ + + ]: 6950 : if (s[0] != '\0')
947 : 1202 : pinfo->argnames[i] = s;
948 : : else
949 : 5748 : pinfo->argnames[i] = NULL;
950 : : }
951 : :
952 [ + + ]: 3456 : if (IsA(sql_body_in, List))
953 : : {
954 : 540 : List *stmts = linitial_node(List, castNode(List, sql_body_in));
955 : : ListCell *lc;
956 : 540 : List *transformed_stmts = NIL;
957 : :
958 [ + + + + : 1071 : foreach(lc, stmts)
+ + ]
959 : : {
960 : 539 : Node *stmt = lfirst(lc);
961 : : Query *q;
962 : 539 : ParseState *pstate = make_parsestate(NULL);
963 : :
964 : 539 : pstate->p_sourcetext = queryString;
965 : 539 : sql_fn_parser_setup(pstate, pinfo);
966 : 539 : q = transformStmt(pstate, stmt);
967 [ + + ]: 535 : if (q->commandType == CMD_UTILITY)
968 [ + - ]: 4 : ereport(ERROR,
969 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
970 : : errmsg("%s is not yet supported in unquoted SQL function body",
971 : : GetCommandTagName(CreateCommandTag(q->utilityStmt))));
972 : 531 : transformed_stmts = lappend(transformed_stmts, q);
973 : 531 : free_parsestate(pstate);
974 : : }
975 : :
976 : 532 : *sql_body_out = (Node *) list_make1(transformed_stmts);
977 : : }
978 : : else
979 : : {
980 : : Query *q;
981 : 2916 : ParseState *pstate = make_parsestate(NULL);
982 : :
983 : 2916 : pstate->p_sourcetext = queryString;
984 : 2916 : sql_fn_parser_setup(pstate, pinfo);
985 : 2916 : q = transformStmt(pstate, sql_body_in);
986 [ - + ]: 2912 : if (q->commandType == CMD_UTILITY)
987 [ # # ]: 0 : ereport(ERROR,
988 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
989 : : errmsg("%s is not yet supported in unquoted SQL function body",
990 : : GetCommandTagName(CreateCommandTag(q->utilityStmt))));
991 : 2912 : free_parsestate(pstate);
992 : :
993 : 2912 : *sql_body_out = (Node *) q;
994 : : }
995 : :
996 : : /*
997 : : * We must put something in prosrc. For the moment, just record an
998 : : * empty string. It might be useful to store the original text of the
999 : : * CREATE FUNCTION statement --- but to make actual use of that in
1000 : : * error reports, we'd also have to adjust readfuncs.c to not throw
1001 : : * away node location fields when reading prosqlbody.
1002 : : */
1003 : 3444 : *prosrc_str_p = pstrdup("");
1004 : :
1005 : : /* But we definitely don't need probin. */
1006 : 3444 : *probin_str_p = NULL;
1007 : : }
1008 : : else
1009 : : {
1010 : : /* Everything else wants the given string in prosrc. */
1011 : 6234 : *prosrc_str_p = strVal(linitial(as));
1012 : 6234 : *probin_str_p = NULL;
1013 : :
1014 [ + + ]: 6234 : if (list_length(as) != 1)
1015 [ + - ]: 4 : ereport(ERROR,
1016 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1017 : : errmsg("only one AS item needed for language \"%s\"",
1018 : : languageName)));
1019 : :
1020 [ + + ]: 6230 : if (languageOid == INTERNALlanguageId)
1021 : : {
1022 : : /*
1023 : : * In PostgreSQL versions before 6.5, the SQL name of the created
1024 : : * function could not be different from the internal name, and
1025 : : * "prosrc" wasn't used. So there is code out there that does
1026 : : * CREATE FUNCTION xyz AS '' LANGUAGE internal. To preserve some
1027 : : * modicum of backwards compatibility, accept an empty "prosrc"
1028 : : * value as meaning the supplied SQL function name.
1029 : : */
1030 [ - + ]: 497 : if (strlen(*prosrc_str_p) == 0)
1031 : 0 : *prosrc_str_p = funcname;
1032 : : }
1033 : : }
1034 : 14088 : }
1035 : :
1036 : :
1037 : : /*
1038 : : * CreateFunction
1039 : : * Execute a CREATE FUNCTION (or CREATE PROCEDURE) utility statement.
1040 : : */
1041 : : ObjectAddress
1042 : 14209 : CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
1043 : : {
1044 : : char *probin_str;
1045 : : char *prosrc_str;
1046 : : Node *prosqlbody;
1047 : : Oid prorettype;
1048 : : bool returnsSet;
1049 : : char *language;
1050 : : Oid languageOid;
1051 : : Oid languageValidator;
1052 : 14209 : Node *transformDefElem = NULL;
1053 : : char *funcname;
1054 : : Oid namespaceId;
1055 : : AclResult aclresult;
1056 : : oidvector *parameterTypes;
1057 : 14209 : List *parameterTypes_list = NIL;
1058 : : ArrayType *allParameterTypes;
1059 : : ArrayType *parameterModes;
1060 : : ArrayType *parameterNames;
1061 : 14209 : List *inParameterNames_list = NIL;
1062 : : List *parameterDefaults;
1063 : : Oid variadicArgType;
1064 : 14209 : List *trftypes_list = NIL;
1065 : 14209 : List *trfoids_list = NIL;
1066 : : ArrayType *trftypes;
1067 : : Oid requiredResultType;
1068 : : bool isWindowFunc,
1069 : : isStrict,
1070 : : security,
1071 : : isLeakProof;
1072 : : char volatility;
1073 : : ArrayType *proconfig;
1074 : : float4 procost;
1075 : : float4 prorows;
1076 : : Oid prosupport;
1077 : : HeapTuple languageTuple;
1078 : : Form_pg_language languageStruct;
1079 : : List *as_clause;
1080 : : char parallel;
1081 : :
1082 : : /* Convert list of names to a name and namespace */
1083 : 14209 : namespaceId = QualifiedNameGetCreationNamespace(stmt->funcname,
1084 : : &funcname);
1085 : :
1086 : : /* Check we have creation rights in target namespace */
1087 : 14209 : aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(), ACL_CREATE);
1088 [ - + ]: 14209 : if (aclresult != ACLCHECK_OK)
1089 : 0 : aclcheck_error(aclresult, OBJECT_SCHEMA,
1090 : 0 : get_namespace_name(namespaceId));
1091 : :
1092 : : /* Set default attributes */
1093 : 14209 : as_clause = NIL;
1094 : 14209 : language = NULL;
1095 : 14209 : isWindowFunc = false;
1096 : 14209 : isStrict = false;
1097 : 14209 : security = false;
1098 : 14209 : isLeakProof = false;
1099 : 14209 : volatility = PROVOLATILE_VOLATILE;
1100 : 14209 : proconfig = NULL;
1101 : 14209 : procost = -1; /* indicates not set */
1102 : 14209 : prorows = -1; /* indicates not set */
1103 : 14209 : prosupport = InvalidOid;
1104 : 14209 : parallel = PROPARALLEL_UNSAFE;
1105 : :
1106 : : /* Extract non-default attributes from stmt->options list */
1107 : 14209 : compute_function_attributes(pstate,
1108 : 14209 : stmt->is_procedure,
1109 : : stmt->options,
1110 : : &as_clause, &language, &transformDefElem,
1111 : : &isWindowFunc, &volatility,
1112 : : &isStrict, &security, &isLeakProof,
1113 : : &proconfig, &procost, &prorows,
1114 : : &prosupport, ¶llel);
1115 : :
1116 [ + + ]: 14201 : if (!language)
1117 : : {
1118 [ + - ]: 93 : if (stmt->sql_body)
1119 : 93 : language = "sql";
1120 : : else
1121 [ # # ]: 0 : ereport(ERROR,
1122 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1123 : : errmsg("no language specified")));
1124 : : }
1125 : :
1126 : : /* Look up the language and validate permissions */
1127 : 14201 : languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
1128 [ - + ]: 14201 : if (!HeapTupleIsValid(languageTuple))
1129 [ # # # # ]: 0 : ereport(ERROR,
1130 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
1131 : : errmsg("language \"%s\" does not exist", language),
1132 : : (extension_file_exists(language) ?
1133 : : errhint("Use CREATE EXTENSION to load the language into the database.") : 0)));
1134 : :
1135 : 14201 : languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
1136 : 14201 : languageOid = languageStruct->oid;
1137 : :
1138 [ + + ]: 14201 : if (languageStruct->lanpltrusted)
1139 : : {
1140 : : /* if trusted language, need USAGE privilege */
1141 : 8960 : aclresult = object_aclcheck(LanguageRelationId, languageOid, GetUserId(), ACL_USAGE);
1142 [ + + ]: 8960 : if (aclresult != ACLCHECK_OK)
1143 : 5 : aclcheck_error(aclresult, OBJECT_LANGUAGE,
1144 : 5 : NameStr(languageStruct->lanname));
1145 : : }
1146 : : else
1147 : : {
1148 : : /* if untrusted language, must be superuser */
1149 [ - + ]: 5241 : if (!superuser())
1150 : 0 : aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_LANGUAGE,
1151 : 0 : NameStr(languageStruct->lanname));
1152 : : }
1153 : :
1154 : 14196 : languageValidator = languageStruct->lanvalidator;
1155 : :
1156 : 14196 : ReleaseSysCache(languageTuple);
1157 : :
1158 : : /*
1159 : : * Only superuser is allowed to create leakproof functions because
1160 : : * leakproof functions can see tuples which have not yet been filtered out
1161 : : * by security barrier views or row-level security policies.
1162 : : */
1163 [ + + + + ]: 14196 : if (isLeakProof && !superuser())
1164 [ + - ]: 4 : ereport(ERROR,
1165 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1166 : : errmsg("only superuser can define a leakproof function")));
1167 : :
1168 [ + + ]: 14192 : if (transformDefElem)
1169 : : {
1170 : : ListCell *lc;
1171 : :
1172 [ + - + + : 154 : foreach(lc, castNode(List, transformDefElem))
+ + ]
1173 : : {
1174 : 78 : Oid typeid = typenameTypeId(NULL,
1175 : 78 : lfirst_node(TypeName, lc));
1176 : 78 : Oid elt = get_base_element_type(typeid);
1177 : : Oid transformid;
1178 : :
1179 [ - + ]: 78 : typeid = elt ? elt : typeid;
1180 : 78 : transformid = get_transform_oid(typeid, languageOid, false);
1181 : 78 : trftypes_list = lappend_oid(trftypes_list, typeid);
1182 : 78 : trfoids_list = lappend_oid(trfoids_list, transformid);
1183 : : }
1184 : : }
1185 : :
1186 : : /*
1187 : : * Convert remaining parameters of CREATE to form wanted by
1188 : : * ProcedureCreate.
1189 : : */
1190 : 14192 : interpret_function_parameter_list(pstate,
1191 : : stmt->parameters,
1192 : : languageOid,
1193 [ + + ]: 14192 : stmt->is_procedure ? OBJECT_PROCEDURE : OBJECT_FUNCTION,
1194 : : ¶meterTypes,
1195 : : ¶meterTypes_list,
1196 : : &allParameterTypes,
1197 : : ¶meterModes,
1198 : : ¶meterNames,
1199 : : &inParameterNames_list,
1200 : : ¶meterDefaults,
1201 : : &variadicArgType,
1202 : : &requiredResultType);
1203 : :
1204 [ + + ]: 14148 : if (stmt->is_procedure)
1205 : : {
1206 : : Assert(!stmt->returnType);
1207 [ + + ]: 217 : prorettype = requiredResultType ? requiredResultType : VOIDOID;
1208 : 217 : returnsSet = false;
1209 : : }
1210 [ + + ]: 13931 : else if (stmt->returnType)
1211 : : {
1212 : : /* explicit RETURNS clause */
1213 : 13570 : compute_return_type(stmt->returnType, languageOid,
1214 : : &prorettype, &returnsSet);
1215 [ + + + + ]: 13542 : if (OidIsValid(requiredResultType) && prorettype != requiredResultType)
1216 [ + - ]: 8 : ereport(ERROR,
1217 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1218 : : errmsg("function result type must be %s because of OUT parameters",
1219 : : format_type_be(requiredResultType))));
1220 : : }
1221 [ + - ]: 361 : else if (OidIsValid(requiredResultType))
1222 : : {
1223 : : /* default RETURNS clause from OUT parameters */
1224 : 361 : prorettype = requiredResultType;
1225 : 361 : returnsSet = false;
1226 : : }
1227 : : else
1228 : : {
1229 [ # # ]: 0 : ereport(ERROR,
1230 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1231 : : errmsg("function result type must be specified")));
1232 : : /* Alternative possibility: default to RETURNS VOID */
1233 : : prorettype = VOIDOID;
1234 : : returnsSet = false;
1235 : : }
1236 : :
1237 [ + + ]: 14112 : if (trftypes_list != NIL)
1238 : : {
1239 : : ListCell *lc;
1240 : : Datum *arr;
1241 : : int i;
1242 : :
1243 : 76 : arr = palloc_array(Datum, list_length(trftypes_list));
1244 : 76 : i = 0;
1245 [ + - + + : 154 : foreach(lc, trftypes_list)
+ + ]
1246 : 78 : arr[i++] = ObjectIdGetDatum(lfirst_oid(lc));
1247 : 76 : trftypes = construct_array_builtin(arr, list_length(trftypes_list), OIDOID);
1248 : : }
1249 : : else
1250 : : {
1251 : : /* store SQL NULL instead of empty array */
1252 : 14036 : trftypes = NULL;
1253 : : }
1254 : :
1255 : 14112 : interpret_AS_clause(languageOid, language, funcname, as_clause, stmt->sql_body,
1256 : : parameterTypes_list, inParameterNames_list,
1257 : : &prosrc_str, &probin_str, &prosqlbody,
1258 : : pstate->p_sourcetext);
1259 : :
1260 : : /*
1261 : : * Set default values for COST and ROWS depending on other parameters;
1262 : : * reject ROWS if it's not returnsSet. NB: pg_dump knows these default
1263 : : * values, keep it in sync if you change them.
1264 : : */
1265 [ + + ]: 14088 : if (procost < 0)
1266 : : {
1267 : : /* SQL and PL-language functions are assumed more expensive */
1268 [ + + + + ]: 11809 : if (languageOid == INTERNALlanguageId ||
1269 : : languageOid == ClanguageId)
1270 : 4911 : procost = 1;
1271 : : else
1272 : 6898 : procost = 100;
1273 : : }
1274 [ + + ]: 14088 : if (prorows < 0)
1275 : : {
1276 [ + + ]: 14017 : if (returnsSet)
1277 : 1222 : prorows = 1000;
1278 : : else
1279 : 12795 : prorows = 0; /* dummy value if not returnsSet */
1280 : : }
1281 [ - + ]: 71 : else if (!returnsSet)
1282 [ # # ]: 0 : ereport(ERROR,
1283 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1284 : : errmsg("ROWS is not applicable when function does not return a set")));
1285 : :
1286 : : /*
1287 : : * And now that we have all the parameters, and know we're permitted to do
1288 : : * so, go ahead and create the function.
1289 : : */
1290 : 14088 : return ProcedureCreate(funcname,
1291 : : namespaceId,
1292 : 14088 : stmt->replace,
1293 : : returnsSet,
1294 : : prorettype,
1295 : : GetUserId(),
1296 : : languageOid,
1297 : : languageValidator,
1298 : : prosrc_str, /* converted to text later */
1299 : : probin_str, /* converted to text later */
1300 : : prosqlbody,
1301 [ + + + + ]: 14088 : stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
1302 : : security,
1303 : : isLeakProof,
1304 : : isStrict,
1305 : : volatility,
1306 : : parallel,
1307 : : parameterTypes,
1308 : : PointerGetDatum(allParameterTypes),
1309 : : PointerGetDatum(parameterModes),
1310 : : PointerGetDatum(parameterNames),
1311 : : parameterDefaults,
1312 : : PointerGetDatum(trftypes),
1313 : : trfoids_list,
1314 : : PointerGetDatum(proconfig),
1315 : : prosupport,
1316 : : procost,
1317 : : prorows);
1318 : : }
1319 : :
1320 : : /*
1321 : : * Guts of function deletion.
1322 : : *
1323 : : * Note: this is also used for aggregate deletion, since the OIDs of
1324 : : * both functions and aggregates point to pg_proc.
1325 : : */
1326 : : void
1327 : 5959 : RemoveFunctionById(Oid funcOid)
1328 : : {
1329 : : Relation relation;
1330 : : HeapTuple tup;
1331 : : char prokind;
1332 : :
1333 : : /*
1334 : : * Delete the pg_proc tuple.
1335 : : */
1336 : 5959 : relation = table_open(ProcedureRelationId, RowExclusiveLock);
1337 : :
1338 : 5959 : tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
1339 [ - + ]: 5959 : if (!HeapTupleIsValid(tup)) /* should not happen */
1340 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcOid);
1341 : :
1342 : 5959 : prokind = ((Form_pg_proc) GETSTRUCT(tup))->prokind;
1343 : :
1344 : 5959 : CatalogTupleDelete(relation, &tup->t_self);
1345 : :
1346 : 5959 : ReleaseSysCache(tup);
1347 : :
1348 : 5959 : table_close(relation, RowExclusiveLock);
1349 : :
1350 : 5959 : pgstat_drop_function(funcOid);
1351 : :
1352 : : /*
1353 : : * If there's a pg_aggregate tuple, delete that too.
1354 : : */
1355 [ + + ]: 5959 : if (prokind == PROKIND_AGGREGATE)
1356 : : {
1357 : 76 : relation = table_open(AggregateRelationId, RowExclusiveLock);
1358 : :
1359 : 76 : tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcOid));
1360 [ - + ]: 76 : if (!HeapTupleIsValid(tup)) /* should not happen */
1361 [ # # ]: 0 : elog(ERROR, "cache lookup failed for pg_aggregate tuple for function %u", funcOid);
1362 : :
1363 : 76 : CatalogTupleDelete(relation, &tup->t_self);
1364 : :
1365 : 76 : ReleaseSysCache(tup);
1366 : :
1367 : 76 : table_close(relation, RowExclusiveLock);
1368 : : }
1369 : 5959 : }
1370 : :
1371 : : /*
1372 : : * Implements the ALTER FUNCTION utility command (except for the
1373 : : * RENAME and OWNER clauses, which are handled as part of the generic
1374 : : * ALTER framework).
1375 : : */
1376 : : ObjectAddress
1377 : 221 : AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
1378 : : {
1379 : : HeapTuple tup;
1380 : : Oid funcOid;
1381 : : Form_pg_proc procForm;
1382 : : bool is_procedure;
1383 : : Relation rel;
1384 : : ListCell *l;
1385 : 221 : DefElem *volatility_item = NULL;
1386 : 221 : DefElem *strict_item = NULL;
1387 : 221 : DefElem *security_def_item = NULL;
1388 : 221 : DefElem *leakproof_item = NULL;
1389 : 221 : List *set_items = NIL;
1390 : 221 : DefElem *cost_item = NULL;
1391 : 221 : DefElem *rows_item = NULL;
1392 : 221 : DefElem *support_item = NULL;
1393 : 221 : DefElem *parallel_item = NULL;
1394 : : ObjectAddress address;
1395 : :
1396 : 221 : rel = table_open(ProcedureRelationId, RowExclusiveLock);
1397 : :
1398 : 221 : funcOid = LookupFuncWithArgs(stmt->objtype, stmt->func, false);
1399 : :
1400 : 209 : ObjectAddressSet(address, ProcedureRelationId, funcOid);
1401 : :
1402 : 209 : tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1403 [ - + ]: 209 : if (!HeapTupleIsValid(tup)) /* should not happen */
1404 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcOid);
1405 : :
1406 : 209 : procForm = (Form_pg_proc) GETSTRUCT(tup);
1407 : :
1408 : : /* Permission check: must own function */
1409 [ - + ]: 209 : if (!object_ownercheck(ProcedureRelationId, funcOid, GetUserId()))
1410 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, stmt->objtype,
1411 : 0 : NameListToString(stmt->func->objname));
1412 : :
1413 [ - + ]: 209 : if (procForm->prokind == PROKIND_AGGREGATE)
1414 [ # # ]: 0 : ereport(ERROR,
1415 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1416 : : errmsg("\"%s\" is an aggregate function",
1417 : : NameListToString(stmt->func->objname))));
1418 : :
1419 : 209 : is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
1420 : :
1421 : : /* Examine requested actions. */
1422 [ + - + + : 416 : foreach(l, stmt->actions)
+ + ]
1423 : : {
1424 : 211 : DefElem *defel = (DefElem *) lfirst(l);
1425 : :
1426 : 211 : if (compute_common_attribute(pstate,
1427 : : is_procedure,
1428 : : defel,
1429 : : &volatility_item,
1430 : : &strict_item,
1431 : : &security_def_item,
1432 : : &leakproof_item,
1433 : : &set_items,
1434 : : &cost_item,
1435 : : &rows_item,
1436 : : &support_item,
1437 [ - + ]: 207 : ¶llel_item) == false)
1438 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized", defel->defname);
1439 : : }
1440 : :
1441 [ + + ]: 205 : if (volatility_item)
1442 : 32 : procForm->provolatile = interpret_func_volatility(volatility_item);
1443 [ + + ]: 205 : if (strict_item)
1444 : 16 : procForm->proisstrict = boolVal(strict_item->arg);
1445 [ + + ]: 205 : if (security_def_item)
1446 : 16 : procForm->prosecdef = boolVal(security_def_item->arg);
1447 [ + + ]: 205 : if (leakproof_item)
1448 : : {
1449 : 16 : procForm->proleakproof = boolVal(leakproof_item->arg);
1450 [ + + + + ]: 16 : if (procForm->proleakproof && !superuser())
1451 [ + - ]: 4 : ereport(ERROR,
1452 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1453 : : errmsg("only superuser can define a leakproof function")));
1454 : : }
1455 [ + + ]: 201 : if (cost_item)
1456 : : {
1457 : 8 : procForm->procost = defGetNumeric(cost_item);
1458 [ - + ]: 8 : if (procForm->procost <= 0)
1459 [ # # ]: 0 : ereport(ERROR,
1460 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1461 : : errmsg("COST must be positive")));
1462 : : }
1463 [ - + ]: 201 : if (rows_item)
1464 : : {
1465 : 0 : procForm->prorows = defGetNumeric(rows_item);
1466 [ # # ]: 0 : if (procForm->prorows <= 0)
1467 [ # # ]: 0 : ereport(ERROR,
1468 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1469 : : errmsg("ROWS must be positive")));
1470 [ # # ]: 0 : if (!procForm->proretset)
1471 [ # # ]: 0 : ereport(ERROR,
1472 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1473 : : errmsg("ROWS is not applicable when function does not return a set")));
1474 : : }
1475 [ + + ]: 201 : if (support_item)
1476 : : {
1477 : : /* interpret_func_support handles the privilege check */
1478 : 8 : Oid newsupport = interpret_func_support(support_item);
1479 : :
1480 : : /* Add or replace dependency on support function */
1481 [ - + ]: 8 : if (OidIsValid(procForm->prosupport))
1482 : : {
1483 [ # # ]: 0 : if (changeDependencyFor(ProcedureRelationId, funcOid,
1484 : : ProcedureRelationId, procForm->prosupport,
1485 : : newsupport) != 1)
1486 [ # # ]: 0 : elog(ERROR, "could not change support dependency for function %s",
1487 : : get_func_name(funcOid));
1488 : : }
1489 : : else
1490 : : {
1491 : : ObjectAddress referenced;
1492 : :
1493 : 8 : referenced.classId = ProcedureRelationId;
1494 : 8 : referenced.objectId = newsupport;
1495 : 8 : referenced.objectSubId = 0;
1496 : 8 : recordDependencyOn(&address, &referenced, DEPENDENCY_NORMAL);
1497 : : }
1498 : :
1499 : 8 : procForm->prosupport = newsupport;
1500 : : }
1501 [ + + ]: 201 : if (parallel_item)
1502 : 98 : procForm->proparallel = interpret_func_parallel(parallel_item);
1503 [ + + ]: 201 : if (set_items)
1504 : : {
1505 : : Datum datum;
1506 : : bool isnull;
1507 : : ArrayType *a;
1508 : : Datum repl_val[Natts_pg_proc];
1509 : : bool repl_null[Natts_pg_proc];
1510 : : bool repl_repl[Natts_pg_proc];
1511 : :
1512 : : /* extract existing proconfig setting */
1513 : 13 : datum = SysCacheGetAttr(PROCOID, tup, Anum_pg_proc_proconfig, &isnull);
1514 [ + + ]: 13 : a = isnull ? NULL : DatumGetArrayTypeP(datum);
1515 : :
1516 : : /* update according to each SET or RESET item, left to right */
1517 : 13 : a = update_proconfig_value(a, set_items);
1518 : :
1519 : : /* update the tuple */
1520 : 13 : memset(repl_repl, false, sizeof(repl_repl));
1521 : 13 : repl_repl[Anum_pg_proc_proconfig - 1] = true;
1522 : :
1523 [ + + ]: 13 : if (a == NULL)
1524 : : {
1525 : 8 : repl_val[Anum_pg_proc_proconfig - 1] = (Datum) 0;
1526 : 8 : repl_null[Anum_pg_proc_proconfig - 1] = true;
1527 : : }
1528 : : else
1529 : : {
1530 : 5 : repl_val[Anum_pg_proc_proconfig - 1] = PointerGetDatum(a);
1531 : 5 : repl_null[Anum_pg_proc_proconfig - 1] = false;
1532 : : }
1533 : :
1534 : 13 : tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1535 : : repl_val, repl_null, repl_repl);
1536 : : }
1537 : : /* DO NOT put more touches of procForm below here; it's now dangling. */
1538 : :
1539 : : /* Do the update */
1540 : 201 : CatalogTupleUpdate(rel, &tup->t_self, tup);
1541 : :
1542 [ - + ]: 201 : InvokeObjectPostAlterHook(ProcedureRelationId, funcOid, 0);
1543 : :
1544 : 201 : table_close(rel, NoLock);
1545 : 201 : heap_freetuple(tup);
1546 : :
1547 : 201 : return address;
1548 : : }
1549 : :
1550 : :
1551 : : /*
1552 : : * CREATE CAST
1553 : : */
1554 : : ObjectAddress
1555 : 218 : CreateCast(CreateCastStmt *stmt)
1556 : : {
1557 : : Oid sourcetypeid;
1558 : : Oid targettypeid;
1559 : : char sourcetyptype;
1560 : : char targettyptype;
1561 : : Oid funcid;
1562 : 218 : Oid incastid = InvalidOid;
1563 : 218 : Oid outcastid = InvalidOid;
1564 : : int nargs;
1565 : : char castcontext;
1566 : : char castmethod;
1567 : : HeapTuple tuple;
1568 : : AclResult aclresult;
1569 : : ObjectAddress myself;
1570 : :
1571 : 218 : sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1572 : 218 : targettypeid = typenameTypeId(NULL, stmt->targettype);
1573 : 218 : sourcetyptype = get_typtype(sourcetypeid);
1574 : 218 : targettyptype = get_typtype(targettypeid);
1575 : :
1576 : : /* No pseudo-types allowed */
1577 [ - + ]: 218 : if (sourcetyptype == TYPTYPE_PSEUDO)
1578 [ # # ]: 0 : ereport(ERROR,
1579 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1580 : : errmsg("source data type %s is a pseudo-type",
1581 : : TypeNameToString(stmt->sourcetype))));
1582 : :
1583 [ - + ]: 218 : if (targettyptype == TYPTYPE_PSEUDO)
1584 [ # # ]: 0 : ereport(ERROR,
1585 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1586 : : errmsg("target data type %s is a pseudo-type",
1587 : : TypeNameToString(stmt->targettype))));
1588 : :
1589 : : /* Permission check */
1590 [ + + ]: 218 : if (!object_ownercheck(TypeRelationId, sourcetypeid, GetUserId())
1591 [ - + ]: 8 : && !object_ownercheck(TypeRelationId, targettypeid, GetUserId()))
1592 [ # # ]: 0 : ereport(ERROR,
1593 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1594 : : errmsg("must be owner of type %s or type %s",
1595 : : format_type_be(sourcetypeid),
1596 : : format_type_be(targettypeid))));
1597 : :
1598 : 218 : aclresult = object_aclcheck(TypeRelationId, sourcetypeid, GetUserId(), ACL_USAGE);
1599 [ + + ]: 218 : if (aclresult != ACLCHECK_OK)
1600 : 4 : aclcheck_error_type(aclresult, sourcetypeid);
1601 : :
1602 : 214 : aclresult = object_aclcheck(TypeRelationId, targettypeid, GetUserId(), ACL_USAGE);
1603 [ - + ]: 214 : if (aclresult != ACLCHECK_OK)
1604 : 0 : aclcheck_error_type(aclresult, targettypeid);
1605 : :
1606 : : /* Domains are allowed for historical reasons, but we warn */
1607 [ + + ]: 214 : if (sourcetyptype == TYPTYPE_DOMAIN)
1608 [ + - ]: 4 : ereport(WARNING,
1609 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1610 : : errmsg("cast will be ignored because the source data type is a domain")));
1611 : :
1612 [ - + ]: 210 : else if (targettyptype == TYPTYPE_DOMAIN)
1613 [ # # ]: 0 : ereport(WARNING,
1614 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1615 : : errmsg("cast will be ignored because the target data type is a domain")));
1616 : :
1617 : : /* Determine the cast method */
1618 [ + + ]: 214 : if (stmt->func != NULL)
1619 : 104 : castmethod = COERCION_METHOD_FUNCTION;
1620 [ + + ]: 110 : else if (stmt->inout)
1621 : 9 : castmethod = COERCION_METHOD_INOUT;
1622 : : else
1623 : 101 : castmethod = COERCION_METHOD_BINARY;
1624 : :
1625 [ + + ]: 214 : if (castmethod == COERCION_METHOD_FUNCTION)
1626 : : {
1627 : : Form_pg_proc procstruct;
1628 : :
1629 : 104 : funcid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->func, false);
1630 : :
1631 : 104 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1632 [ - + ]: 104 : if (!HeapTupleIsValid(tuple))
1633 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
1634 : :
1635 : 104 : procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1636 : 104 : nargs = procstruct->pronargs;
1637 [ + - - + ]: 104 : if (nargs < 1 || nargs > 3)
1638 [ # # ]: 0 : ereport(ERROR,
1639 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1640 : : errmsg("cast function must take one to three arguments")));
1641 [ - + ]: 104 : if (!IsBinaryCoercibleWithCast(sourcetypeid,
1642 : : procstruct->proargtypes.values[0],
1643 : : &incastid))
1644 [ # # ]: 0 : ereport(ERROR,
1645 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1646 : : errmsg("argument of cast function must match or be binary-coercible from source data type")));
1647 [ - + - - ]: 104 : if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1648 [ # # ]: 0 : ereport(ERROR,
1649 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1650 : : errmsg("second argument of cast function must be type %s",
1651 : : "integer")));
1652 [ - + - - ]: 104 : if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1653 [ # # ]: 0 : ereport(ERROR,
1654 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1655 : : errmsg("third argument of cast function must be type %s",
1656 : : "boolean")));
1657 [ - + ]: 104 : if (!IsBinaryCoercibleWithCast(procstruct->prorettype,
1658 : : targettypeid,
1659 : : &outcastid))
1660 [ # # ]: 0 : ereport(ERROR,
1661 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1662 : : errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1663 : :
1664 : : /*
1665 : : * Restricting the volatility of a cast function may or may not be a
1666 : : * good idea in the abstract, but it definitely breaks many old
1667 : : * user-defined types. Disable this check --- tgl 2/1/03
1668 : : */
1669 : : #ifdef NOT_USED
1670 : : if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1671 : : ereport(ERROR,
1672 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1673 : : errmsg("cast function must not be volatile")));
1674 : : #endif
1675 [ - + ]: 104 : if (procstruct->prokind != PROKIND_FUNCTION)
1676 [ # # ]: 0 : ereport(ERROR,
1677 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1678 : : errmsg("cast function must be a normal function")));
1679 [ - + ]: 104 : if (procstruct->proretset)
1680 [ # # ]: 0 : ereport(ERROR,
1681 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1682 : : errmsg("cast function must not return a set")));
1683 : :
1684 : 104 : ReleaseSysCache(tuple);
1685 : : }
1686 : : else
1687 : : {
1688 : 110 : funcid = InvalidOid;
1689 : 110 : nargs = 0;
1690 : : }
1691 : :
1692 [ + + ]: 214 : if (castmethod == COERCION_METHOD_BINARY)
1693 : : {
1694 : : int16 typ1len;
1695 : : int16 typ2len;
1696 : : bool typ1byval;
1697 : : bool typ2byval;
1698 : : char typ1align;
1699 : : char typ2align;
1700 : :
1701 : : /*
1702 : : * Must be superuser to create binary-compatible casts, since
1703 : : * erroneous casts can easily crash the backend.
1704 : : */
1705 [ - + ]: 101 : if (!superuser())
1706 [ # # ]: 0 : ereport(ERROR,
1707 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1708 : : errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1709 : :
1710 : : /*
1711 : : * Also, insist that the types match as to size, alignment, and
1712 : : * pass-by-value attributes; this provides at least a crude check that
1713 : : * they have similar representations. A pair of types that fail this
1714 : : * test should certainly not be equated.
1715 : : */
1716 : 101 : get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1717 : 101 : get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1718 [ + - ]: 101 : if (typ1len != typ2len ||
1719 [ + - ]: 101 : typ1byval != typ2byval ||
1720 [ - + ]: 101 : typ1align != typ2align)
1721 [ # # ]: 0 : ereport(ERROR,
1722 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1723 : : errmsg("source and target data types are not physically compatible")));
1724 : :
1725 : : /*
1726 : : * We know that composite, array, range and enum types are never
1727 : : * binary-compatible with each other. They all have OIDs embedded in
1728 : : * them.
1729 : : *
1730 : : * Theoretically you could build a user-defined base type that is
1731 : : * binary-compatible with such a type. But we disallow it anyway, as
1732 : : * in practice such a cast is surely a mistake. You can always work
1733 : : * around that by writing a cast function.
1734 : : *
1735 : : * NOTE: if we ever have a kind of container type that doesn't need to
1736 : : * be rejected for this reason, we'd likely need to recursively apply
1737 : : * all of these same checks to the contained type(s).
1738 : : */
1739 [ + - - + ]: 101 : if (sourcetyptype == TYPTYPE_COMPOSITE ||
1740 : : targettyptype == TYPTYPE_COMPOSITE)
1741 [ # # ]: 0 : ereport(ERROR,
1742 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1743 : : errmsg("composite data types are not binary-compatible")));
1744 : :
1745 [ + - - + ]: 202 : if (OidIsValid(get_element_type(sourcetypeid)) ||
1746 : 101 : OidIsValid(get_element_type(targettypeid)))
1747 [ # # ]: 0 : ereport(ERROR,
1748 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1749 : : errmsg("array data types are not binary-compatible")));
1750 : :
1751 [ + - + - ]: 101 : if (sourcetyptype == TYPTYPE_RANGE ||
1752 [ + - ]: 101 : targettyptype == TYPTYPE_RANGE ||
1753 [ - + ]: 101 : sourcetyptype == TYPTYPE_MULTIRANGE ||
1754 : : targettyptype == TYPTYPE_MULTIRANGE)
1755 [ # # ]: 0 : ereport(ERROR,
1756 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1757 : : errmsg("range data types are not binary-compatible")));
1758 : :
1759 [ + - - + ]: 101 : if (sourcetyptype == TYPTYPE_ENUM ||
1760 : : targettyptype == TYPTYPE_ENUM)
1761 [ # # ]: 0 : ereport(ERROR,
1762 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1763 : : errmsg("enum data types are not binary-compatible")));
1764 : :
1765 : : /*
1766 : : * We also disallow creating binary-compatibility casts involving
1767 : : * domains. Casting from a domain to its base type is already
1768 : : * allowed, and casting the other way ought to go through domain
1769 : : * coercion to permit constraint checking. Again, if you're intent on
1770 : : * having your own semantics for that, create a no-op cast function.
1771 : : *
1772 : : * NOTE: if we were to relax this, the above checks for composites
1773 : : * etc. would have to be modified to look through domains to their
1774 : : * base types.
1775 : : */
1776 [ + - - + ]: 101 : if (sourcetyptype == TYPTYPE_DOMAIN ||
1777 : : targettyptype == TYPTYPE_DOMAIN)
1778 [ # # ]: 0 : ereport(ERROR,
1779 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1780 : : errmsg("domain data types must not be marked binary-compatible")));
1781 : : }
1782 : :
1783 : : /*
1784 : : * Allow source and target types to be same only for length coercion
1785 : : * functions. We assume a multi-arg function does length coercion.
1786 : : */
1787 [ - + - - ]: 214 : if (sourcetypeid == targettypeid && nargs < 2)
1788 [ # # ]: 0 : ereport(ERROR,
1789 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1790 : : errmsg("source data type and target data type are the same")));
1791 : :
1792 : : /* convert CoercionContext enum to char value for castcontext */
1793 [ + + + - ]: 214 : switch (stmt->context)
1794 : : {
1795 : 67 : case COERCION_IMPLICIT:
1796 : 67 : castcontext = COERCION_CODE_IMPLICIT;
1797 : 67 : break;
1798 : 32 : case COERCION_ASSIGNMENT:
1799 : 32 : castcontext = COERCION_CODE_ASSIGNMENT;
1800 : 32 : break;
1801 : : /* COERCION_PLPGSQL is intentionally not covered here */
1802 : 115 : case COERCION_EXPLICIT:
1803 : 115 : castcontext = COERCION_CODE_EXPLICIT;
1804 : 115 : break;
1805 : 0 : default:
1806 [ # # ]: 0 : elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1807 : : castcontext = 0; /* keep compiler quiet */
1808 : : break;
1809 : : }
1810 : :
1811 : 214 : myself = CastCreate(sourcetypeid, targettypeid, funcid, incastid, outcastid,
1812 : : castcontext, castmethod, DEPENDENCY_NORMAL);
1813 : 214 : return myself;
1814 : : }
1815 : :
1816 : :
1817 : : static void
1818 : 42 : check_transform_function(Form_pg_proc procstruct)
1819 : : {
1820 [ - + ]: 42 : if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1821 [ # # ]: 0 : ereport(ERROR,
1822 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1823 : : errmsg("transform function must not be volatile")));
1824 [ - + ]: 42 : if (procstruct->prokind != PROKIND_FUNCTION)
1825 [ # # ]: 0 : ereport(ERROR,
1826 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1827 : : errmsg("transform function must be a normal function")));
1828 [ - + ]: 42 : if (procstruct->proretset)
1829 [ # # ]: 0 : ereport(ERROR,
1830 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1831 : : errmsg("transform function must not return a set")));
1832 [ - + ]: 42 : if (procstruct->pronargs != 1)
1833 [ # # ]: 0 : ereport(ERROR,
1834 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1835 : : errmsg("transform function must take one argument")));
1836 [ + + ]: 42 : if (procstruct->proargtypes.values[0] != INTERNALOID)
1837 [ + - ]: 1 : ereport(ERROR,
1838 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1839 : : errmsg("first argument of transform function must be type %s",
1840 : : "internal")));
1841 : 41 : }
1842 : :
1843 : :
1844 : : /*
1845 : : * CREATE TRANSFORM
1846 : : */
1847 : : ObjectAddress
1848 : 26 : CreateTransform(CreateTransformStmt *stmt)
1849 : : {
1850 : : Oid typeid;
1851 : : char typtype;
1852 : : Oid langid;
1853 : : Oid fromsqlfuncid;
1854 : : Oid tosqlfuncid;
1855 : : AclResult aclresult;
1856 : : Form_pg_proc procstruct;
1857 : : Datum values[Natts_pg_transform];
1858 : 26 : bool nulls[Natts_pg_transform] = {0};
1859 : 26 : bool replaces[Natts_pg_transform] = {0};
1860 : : Oid transformid;
1861 : : HeapTuple tuple;
1862 : : HeapTuple newtuple;
1863 : : Relation relation;
1864 : : ObjectAddress myself,
1865 : : referenced;
1866 : : ObjectAddresses *addrs;
1867 : : bool is_replace;
1868 : :
1869 : : /*
1870 : : * Get the type
1871 : : */
1872 : 26 : typeid = typenameTypeId(NULL, stmt->type_name);
1873 : 25 : typtype = get_typtype(typeid);
1874 : :
1875 [ - + ]: 25 : if (typtype == TYPTYPE_PSEUDO)
1876 [ # # ]: 0 : ereport(ERROR,
1877 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1878 : : errmsg("data type %s is a pseudo-type",
1879 : : TypeNameToString(stmt->type_name))));
1880 : :
1881 [ - + ]: 25 : if (typtype == TYPTYPE_DOMAIN)
1882 [ # # ]: 0 : ereport(ERROR,
1883 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1884 : : errmsg("data type %s is a domain",
1885 : : TypeNameToString(stmt->type_name))));
1886 : :
1887 [ - + ]: 25 : if (!object_ownercheck(TypeRelationId, typeid, GetUserId()))
1888 : 0 : aclcheck_error_type(ACLCHECK_NOT_OWNER, typeid);
1889 : :
1890 : 25 : aclresult = object_aclcheck(TypeRelationId, typeid, GetUserId(), ACL_USAGE);
1891 [ - + ]: 25 : if (aclresult != ACLCHECK_OK)
1892 : 0 : aclcheck_error_type(aclresult, typeid);
1893 : :
1894 : : /*
1895 : : * Get the language
1896 : : */
1897 : 25 : langid = get_language_oid(stmt->lang, false);
1898 : :
1899 : 24 : aclresult = object_aclcheck(LanguageRelationId, langid, GetUserId(), ACL_USAGE);
1900 [ - + ]: 24 : if (aclresult != ACLCHECK_OK)
1901 : 0 : aclcheck_error(aclresult, OBJECT_LANGUAGE, stmt->lang);
1902 : :
1903 : : /*
1904 : : * Get the functions
1905 : : */
1906 [ + + ]: 24 : if (stmt->fromsql)
1907 : : {
1908 : 23 : fromsqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->fromsql, false);
1909 : :
1910 [ - + ]: 23 : if (!object_ownercheck(ProcedureRelationId, fromsqlfuncid, GetUserId()))
1911 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION, NameListToString(stmt->fromsql->objname));
1912 : :
1913 : 23 : aclresult = object_aclcheck(ProcedureRelationId, fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1914 [ - + ]: 23 : if (aclresult != ACLCHECK_OK)
1915 : 0 : aclcheck_error(aclresult, OBJECT_FUNCTION, NameListToString(stmt->fromsql->objname));
1916 : :
1917 : 23 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1918 [ - + ]: 23 : if (!HeapTupleIsValid(tuple))
1919 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1920 : 23 : procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1921 [ + + ]: 23 : if (procstruct->prorettype != INTERNALOID)
1922 [ + - ]: 1 : ereport(ERROR,
1923 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1924 : : errmsg("return data type of FROM SQL function must be %s",
1925 : : "internal")));
1926 : 22 : check_transform_function(procstruct);
1927 : 21 : ReleaseSysCache(tuple);
1928 : : }
1929 : : else
1930 : 1 : fromsqlfuncid = InvalidOid;
1931 : :
1932 [ + + ]: 22 : if (stmt->tosql)
1933 : : {
1934 : 20 : tosqlfuncid = LookupFuncWithArgs(OBJECT_FUNCTION, stmt->tosql, false);
1935 : :
1936 [ - + ]: 20 : if (!object_ownercheck(ProcedureRelationId, tosqlfuncid, GetUserId()))
1937 : 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION, NameListToString(stmt->tosql->objname));
1938 : :
1939 : 20 : aclresult = object_aclcheck(ProcedureRelationId, tosqlfuncid, GetUserId(), ACL_EXECUTE);
1940 [ - + ]: 20 : if (aclresult != ACLCHECK_OK)
1941 : 0 : aclcheck_error(aclresult, OBJECT_FUNCTION, NameListToString(stmt->tosql->objname));
1942 : :
1943 : 20 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1944 [ - + ]: 20 : if (!HeapTupleIsValid(tuple))
1945 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1946 : 20 : procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1947 [ - + ]: 20 : if (procstruct->prorettype != typeid)
1948 [ # # ]: 0 : ereport(ERROR,
1949 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1950 : : errmsg("return data type of TO SQL function must be the transform data type")));
1951 : 20 : check_transform_function(procstruct);
1952 : 20 : ReleaseSysCache(tuple);
1953 : : }
1954 : : else
1955 : 2 : tosqlfuncid = InvalidOid;
1956 : :
1957 : : /*
1958 : : * Ready to go
1959 : : */
1960 : 22 : values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1961 : 22 : values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1962 : 22 : values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1963 : 22 : values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1964 : :
1965 : 22 : relation = table_open(TransformRelationId, RowExclusiveLock);
1966 : :
1967 : 22 : tuple = SearchSysCache2(TRFTYPELANG,
1968 : : ObjectIdGetDatum(typeid),
1969 : : ObjectIdGetDatum(langid));
1970 [ + + ]: 22 : if (HeapTupleIsValid(tuple))
1971 : : {
1972 : 4 : Form_pg_transform form = (Form_pg_transform) GETSTRUCT(tuple);
1973 : :
1974 [ + + ]: 4 : if (!stmt->replace)
1975 [ + - ]: 1 : ereport(ERROR,
1976 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
1977 : : errmsg("transform for type %s language \"%s\" already exists",
1978 : : format_type_be(typeid),
1979 : : stmt->lang)));
1980 : :
1981 : 3 : replaces[Anum_pg_transform_trffromsql - 1] = true;
1982 : 3 : replaces[Anum_pg_transform_trftosql - 1] = true;
1983 : :
1984 : 3 : newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1985 : 3 : CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
1986 : :
1987 : 3 : transformid = form->oid;
1988 : 3 : ReleaseSysCache(tuple);
1989 : 3 : is_replace = true;
1990 : : }
1991 : : else
1992 : : {
1993 : 18 : transformid = GetNewOidWithIndex(relation, TransformOidIndexId,
1994 : : Anum_pg_transform_oid);
1995 : 18 : values[Anum_pg_transform_oid - 1] = ObjectIdGetDatum(transformid);
1996 : 18 : newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1997 : 18 : CatalogTupleInsert(relation, newtuple);
1998 : 18 : is_replace = false;
1999 : : }
2000 : :
2001 [ + + ]: 21 : if (is_replace)
2002 : 3 : deleteDependencyRecordsFor(TransformRelationId, transformid, true);
2003 : :
2004 : 21 : addrs = new_object_addresses();
2005 : :
2006 : : /* make dependency entries */
2007 : 21 : ObjectAddressSet(myself, TransformRelationId, transformid);
2008 : :
2009 : : /* dependency on language */
2010 : 21 : ObjectAddressSet(referenced, LanguageRelationId, langid);
2011 : 21 : add_exact_object_address(&referenced, addrs);
2012 : :
2013 : : /* dependency on type */
2014 : 21 : ObjectAddressSet(referenced, TypeRelationId, typeid);
2015 : 21 : add_exact_object_address(&referenced, addrs);
2016 : :
2017 : : /* dependencies on functions */
2018 [ + + ]: 21 : if (OidIsValid(fromsqlfuncid))
2019 : : {
2020 : 20 : ObjectAddressSet(referenced, ProcedureRelationId, fromsqlfuncid);
2021 : 20 : add_exact_object_address(&referenced, addrs);
2022 : : }
2023 [ + + ]: 21 : if (OidIsValid(tosqlfuncid))
2024 : : {
2025 : 19 : ObjectAddressSet(referenced, ProcedureRelationId, tosqlfuncid);
2026 : 19 : add_exact_object_address(&referenced, addrs);
2027 : : }
2028 : :
2029 : 21 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
2030 : 21 : free_object_addresses(addrs);
2031 : :
2032 : : /* dependency on extension */
2033 : 21 : recordDependencyOnCurrentExtension(&myself, is_replace);
2034 : :
2035 : : /* Post creation hook for new transform */
2036 [ - + ]: 21 : InvokeObjectPostCreateHook(TransformRelationId, transformid, 0);
2037 : :
2038 : 21 : heap_freetuple(newtuple);
2039 : :
2040 : 21 : table_close(relation, RowExclusiveLock);
2041 : :
2042 : 21 : return myself;
2043 : : }
2044 : :
2045 : :
2046 : : /*
2047 : : * get_transform_oid - given type OID and language OID, look up a transform OID
2048 : : *
2049 : : * If missing_ok is false, throw an error if the transform is not found. If
2050 : : * true, just return InvalidOid.
2051 : : */
2052 : : Oid
2053 : 100 : get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
2054 : : {
2055 : : Oid oid;
2056 : :
2057 : 100 : oid = GetSysCacheOid2(TRFTYPELANG, Anum_pg_transform_oid,
2058 : : ObjectIdGetDatum(type_id),
2059 : : ObjectIdGetDatum(lang_id));
2060 [ + + - + ]: 100 : if (!OidIsValid(oid) && !missing_ok)
2061 [ # # ]: 0 : ereport(ERROR,
2062 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2063 : : errmsg("transform for type %s language \"%s\" does not exist",
2064 : : format_type_be(type_id),
2065 : : get_language_name(lang_id, false))));
2066 : 100 : return oid;
2067 : : }
2068 : :
2069 : :
2070 : : /*
2071 : : * Subroutine for ALTER FUNCTION/AGGREGATE SET SCHEMA/RENAME
2072 : : *
2073 : : * Is there a function with the given name and signature already in the given
2074 : : * namespace? If so, raise an appropriate error message.
2075 : : */
2076 : : void
2077 : 88 : IsThereFunctionInNamespace(const char *proname, int pronargs,
2078 : : oidvector *proargtypes, Oid nspOid)
2079 : : {
2080 : : /* check for duplicate name (more friendly than unique-index failure) */
2081 [ + + ]: 88 : if (SearchSysCacheExists3(PROCNAMEARGSNSP,
2082 : : CStringGetDatum(proname),
2083 : : PointerGetDatum(proargtypes),
2084 : : ObjectIdGetDatum(nspOid)))
2085 [ + - ]: 16 : ereport(ERROR,
2086 : : (errcode(ERRCODE_DUPLICATE_FUNCTION),
2087 : : errmsg("function %s already exists in schema \"%s\"",
2088 : : funcname_signature_string(proname, pronargs,
2089 : : NIL, proargtypes->values),
2090 : : get_namespace_name(nspOid))));
2091 : 72 : }
2092 : :
2093 : : /*
2094 : : * ExecuteDoStmt
2095 : : * Execute inline procedural-language code
2096 : : *
2097 : : * See at ExecuteCallStmt() about the atomic argument.
2098 : : */
2099 : : void
2100 : 1135 : ExecuteDoStmt(ParseState *pstate, DoStmt *stmt, bool atomic)
2101 : : {
2102 : 1135 : InlineCodeBlock *codeblock = makeNode(InlineCodeBlock);
2103 : : ListCell *arg;
2104 : 1135 : DefElem *as_item = NULL;
2105 : 1135 : DefElem *language_item = NULL;
2106 : : char *language;
2107 : : Oid laninline;
2108 : : HeapTuple languageTuple;
2109 : : Form_pg_language languageStruct;
2110 : :
2111 : : /* Process options we got from gram.y */
2112 [ + - + + : 2376 : foreach(arg, stmt->args)
+ + ]
2113 : : {
2114 : 1241 : DefElem *defel = (DefElem *) lfirst(arg);
2115 : :
2116 [ + + ]: 1241 : if (strcmp(defel->defname, "as") == 0)
2117 : : {
2118 [ - + ]: 1135 : if (as_item)
2119 : 0 : errorConflictingDefElem(defel, pstate);
2120 : 1135 : as_item = defel;
2121 : : }
2122 [ + - ]: 106 : else if (strcmp(defel->defname, "language") == 0)
2123 : : {
2124 [ - + ]: 106 : if (language_item)
2125 : 0 : errorConflictingDefElem(defel, pstate);
2126 : 106 : language_item = defel;
2127 : : }
2128 : : else
2129 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
2130 : : defel->defname);
2131 : : }
2132 : :
2133 [ + - ]: 1135 : if (as_item)
2134 : 1135 : codeblock->source_text = strVal(as_item->arg);
2135 : : else
2136 [ # # ]: 0 : ereport(ERROR,
2137 : : (errcode(ERRCODE_SYNTAX_ERROR),
2138 : : errmsg("no inline code specified")));
2139 : :
2140 : : /* if LANGUAGE option wasn't specified, use the default */
2141 [ + + ]: 1135 : if (language_item)
2142 : 106 : language = strVal(language_item->arg);
2143 : : else
2144 : 1029 : language = "plpgsql";
2145 : :
2146 : : /* Look up the language and validate permissions */
2147 : 1135 : languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
2148 [ - + ]: 1135 : if (!HeapTupleIsValid(languageTuple))
2149 [ # # # # ]: 0 : ereport(ERROR,
2150 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2151 : : errmsg("language \"%s\" does not exist", language),
2152 : : (extension_file_exists(language) ?
2153 : : errhint("Use CREATE EXTENSION to load the language into the database.") : 0)));
2154 : :
2155 : 1135 : languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
2156 : 1135 : codeblock->langOid = languageStruct->oid;
2157 : 1135 : codeblock->langIsTrusted = languageStruct->lanpltrusted;
2158 : 1135 : codeblock->atomic = atomic;
2159 : :
2160 [ + + ]: 1135 : if (languageStruct->lanpltrusted)
2161 : : {
2162 : : /* if trusted language, need USAGE privilege */
2163 : : AclResult aclresult;
2164 : :
2165 : 1113 : aclresult = object_aclcheck(LanguageRelationId, codeblock->langOid, GetUserId(),
2166 : : ACL_USAGE);
2167 [ - + ]: 1113 : if (aclresult != ACLCHECK_OK)
2168 : 0 : aclcheck_error(aclresult, OBJECT_LANGUAGE,
2169 : 0 : NameStr(languageStruct->lanname));
2170 : : }
2171 : : else
2172 : : {
2173 : : /* if untrusted language, must be superuser */
2174 [ - + ]: 22 : if (!superuser())
2175 : 0 : aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_LANGUAGE,
2176 : 0 : NameStr(languageStruct->lanname));
2177 : : }
2178 : :
2179 : : /* get the handler function's OID */
2180 : 1135 : laninline = languageStruct->laninline;
2181 [ - + ]: 1135 : if (!OidIsValid(laninline))
2182 [ # # ]: 0 : ereport(ERROR,
2183 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2184 : : errmsg("language \"%s\" does not support inline code execution",
2185 : : NameStr(languageStruct->lanname))));
2186 : :
2187 : 1135 : ReleaseSysCache(languageTuple);
2188 : :
2189 : : /* execute the inline handler */
2190 : 1135 : OidFunctionCall1(laninline, PointerGetDatum(codeblock));
2191 : 744 : }
2192 : :
2193 : : /*
2194 : : * Execute CALL statement
2195 : : *
2196 : : * Inside a top-level CALL statement, transaction-terminating commands such as
2197 : : * COMMIT or a PL-specific equivalent are allowed. The terminology in the SQL
2198 : : * standard is that CALL establishes a non-atomic execution context. Most
2199 : : * other commands establish an atomic execution context, in which transaction
2200 : : * control actions are not allowed. If there are nested executions of CALL,
2201 : : * we want to track the execution context recursively, so that the nested
2202 : : * CALLs can also do transaction control. Note, however, that for example in
2203 : : * CALL -> SELECT -> CALL, the second call cannot do transaction control,
2204 : : * because the SELECT in between establishes an atomic execution context.
2205 : : *
2206 : : * So when ExecuteCallStmt() is called from the top level, we pass in atomic =
2207 : : * false (recall that that means transactions = yes). We then create a
2208 : : * CallContext node with content atomic = false, which is passed in the
2209 : : * fcinfo->context field to the procedure invocation. The language
2210 : : * implementation should then take appropriate measures to allow or prevent
2211 : : * transaction commands based on that information, e.g., call
2212 : : * SPI_connect_ext(SPI_OPT_NONATOMIC). The language should also pass on the
2213 : : * atomic flag to any nested invocations to CALL.
2214 : : *
2215 : : * The expression data structures and execution context that we create
2216 : : * within this function are children of the portalContext of the Portal
2217 : : * that the CALL utility statement runs in. Therefore, any pass-by-ref
2218 : : * values that we're passing to the procedure will survive transaction
2219 : : * commits that might occur inside the procedure.
2220 : : */
2221 : : void
2222 : 298 : ExecuteCallStmt(CallStmt *stmt, ParamListInfo params, bool atomic, DestReceiver *dest)
2223 : : {
2224 : 298 : LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
2225 : : ListCell *lc;
2226 : : FuncExpr *fexpr;
2227 : : int nargs;
2228 : : int i;
2229 : : AclResult aclresult;
2230 : : FmgrInfo flinfo;
2231 : : CallContext *callcontext;
2232 : : EState *estate;
2233 : : ExprContext *econtext;
2234 : : HeapTuple tp;
2235 : : PgStat_FunctionCallUsage fcusage;
2236 : : Datum retval;
2237 : :
2238 : 298 : fexpr = stmt->funcexpr;
2239 : : Assert(fexpr);
2240 : : Assert(IsA(fexpr, FuncExpr));
2241 : :
2242 : 298 : aclresult = object_aclcheck(ProcedureRelationId, fexpr->funcid, GetUserId(), ACL_EXECUTE);
2243 [ + + ]: 298 : if (aclresult != ACLCHECK_OK)
2244 : 8 : aclcheck_error(aclresult, OBJECT_PROCEDURE, get_func_name(fexpr->funcid));
2245 : :
2246 : : /* Prep the context object we'll pass to the procedure */
2247 : 290 : callcontext = makeNode(CallContext);
2248 : 290 : callcontext->atomic = atomic;
2249 : :
2250 : 290 : tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
2251 [ - + ]: 290 : if (!HeapTupleIsValid(tp))
2252 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
2253 : :
2254 : : /*
2255 : : * If proconfig is set we can't allow transaction commands because of the
2256 : : * way the GUC stacking works: The transaction boundary would have to pop
2257 : : * the proconfig setting off the stack. That restriction could be lifted
2258 : : * by redesigning the GUC nesting mechanism a bit.
2259 : : */
2260 [ + + ]: 290 : if (!heap_attisnull(tp, Anum_pg_proc_proconfig, NULL))
2261 : 1 : callcontext->atomic = true;
2262 : :
2263 : : /*
2264 : : * In security definer procedures, we can't allow transaction commands.
2265 : : * StartTransaction() insists that the security context stack is empty,
2266 : : * and AbortTransaction() resets the security context. This could be
2267 : : * reorganized, but right now it doesn't work.
2268 : : */
2269 [ + + ]: 290 : if (((Form_pg_proc) GETSTRUCT(tp))->prosecdef)
2270 : 1 : callcontext->atomic = true;
2271 : :
2272 : 290 : ReleaseSysCache(tp);
2273 : :
2274 : : /* safety check; see ExecInitFunc() */
2275 : 290 : nargs = list_length(fexpr->args);
2276 [ - + ]: 290 : if (nargs > FUNC_MAX_ARGS)
2277 [ # # ]: 0 : ereport(ERROR,
2278 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2279 : : errmsg_plural("cannot pass more than %d argument to a procedure",
2280 : : "cannot pass more than %d arguments to a procedure",
2281 : : FUNC_MAX_ARGS,
2282 : : FUNC_MAX_ARGS)));
2283 : :
2284 : : /* Initialize function call structure */
2285 [ - + ]: 290 : InvokeFunctionExecuteHook(fexpr->funcid);
2286 : 290 : fmgr_info(fexpr->funcid, &flinfo);
2287 : 290 : fmgr_info_set_expr((Node *) fexpr, &flinfo);
2288 : 290 : InitFunctionCallInfoData(*fcinfo, &flinfo, nargs, fexpr->inputcollid,
2289 : : (Node *) callcontext, NULL);
2290 : :
2291 : : /*
2292 : : * Evaluate procedure arguments inside a suitable execution context. Note
2293 : : * we can't free this context till the procedure returns.
2294 : : */
2295 : 290 : estate = CreateExecutorState();
2296 : 290 : estate->es_param_list_info = params;
2297 : 290 : econtext = CreateExprContext(estate);
2298 : :
2299 : : /*
2300 : : * If we're called in non-atomic context, we also have to ensure that the
2301 : : * argument expressions run with an up-to-date snapshot. Our caller will
2302 : : * have provided a current snapshot in atomic contexts, but not in
2303 : : * non-atomic contexts, because the possibility of a COMMIT/ROLLBACK
2304 : : * destroying the snapshot makes higher-level management too complicated.
2305 : : */
2306 [ + + ]: 290 : if (!atomic)
2307 : 269 : PushActiveSnapshot(GetTransactionSnapshot());
2308 : :
2309 : 290 : i = 0;
2310 [ + + + + : 660 : foreach(lc, fexpr->args)
+ + ]
2311 : : {
2312 : : ExprState *exprstate;
2313 : : Datum val;
2314 : : bool isnull;
2315 : :
2316 : 370 : exprstate = ExecPrepareExpr(lfirst(lc), estate);
2317 : :
2318 : 370 : val = ExecEvalExprSwitchContext(exprstate, econtext, &isnull);
2319 : :
2320 : 370 : fcinfo->args[i].value = val;
2321 : 370 : fcinfo->args[i].isnull = isnull;
2322 : :
2323 : 370 : i++;
2324 : : }
2325 : :
2326 : : /* Get rid of temporary snapshot for arguments, if we made one */
2327 [ + + ]: 290 : if (!atomic)
2328 : 269 : PopActiveSnapshot();
2329 : :
2330 : : /* Here we actually call the procedure */
2331 : 290 : pgstat_init_function_usage(fcinfo, &fcusage);
2332 : 290 : retval = FunctionCallInvoke(fcinfo);
2333 : 265 : pgstat_end_function_usage(&fcusage, true);
2334 : :
2335 : : /* Handle the procedure's outputs */
2336 [ + + ]: 265 : if (fexpr->funcresulttype == VOIDOID)
2337 : : {
2338 : : /* do nothing */
2339 : : }
2340 [ + - ]: 119 : else if (fexpr->funcresulttype == RECORDOID)
2341 : : {
2342 : : /* send tuple to client */
2343 : : HeapTupleHeader td;
2344 : : Oid tupType;
2345 : : int32 tupTypmod;
2346 : : TupleDesc retdesc;
2347 : : HeapTupleData rettupdata;
2348 : : TupOutputState *tstate;
2349 : : TupleTableSlot *slot;
2350 : :
2351 [ - + ]: 119 : if (fcinfo->isnull)
2352 [ # # ]: 0 : elog(ERROR, "procedure returned null record");
2353 : :
2354 : : /*
2355 : : * Ensure there's an active snapshot whilst we execute whatever's
2356 : : * involved here. Note that this is *not* sufficient to make the
2357 : : * world safe for TOAST pointers to be included in the returned data:
2358 : : * the referenced data could have gone away while we didn't hold a
2359 : : * snapshot. Hence, it's incumbent on PLs that can do COMMIT/ROLLBACK
2360 : : * to not return TOAST pointers, unless those pointers were fetched
2361 : : * after the last COMMIT/ROLLBACK in the procedure.
2362 : : *
2363 : : * XXX that is a really nasty, hard-to-test requirement. Is there a
2364 : : * way to remove it?
2365 : : */
2366 : 119 : EnsurePortalSnapshotExists();
2367 : :
2368 : 119 : td = DatumGetHeapTupleHeader(retval);
2369 : 119 : tupType = HeapTupleHeaderGetTypeId(td);
2370 : 119 : tupTypmod = HeapTupleHeaderGetTypMod(td);
2371 : 119 : retdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2372 : :
2373 : 119 : tstate = begin_tup_output_tupdesc(dest, retdesc,
2374 : : &TTSOpsHeapTuple);
2375 : :
2376 : 119 : rettupdata.t_len = HeapTupleHeaderGetDatumLength(td);
2377 : 119 : ItemPointerSetInvalid(&(rettupdata.t_self));
2378 : 119 : rettupdata.t_tableOid = InvalidOid;
2379 : 119 : rettupdata.t_data = td;
2380 : :
2381 : 119 : slot = ExecStoreHeapTuple(&rettupdata, tstate->slot, false);
2382 : 119 : tstate->dest->receiveSlot(slot, tstate->dest);
2383 : :
2384 : 119 : end_tup_output(tstate);
2385 : :
2386 [ + - ]: 119 : ReleaseTupleDesc(retdesc);
2387 : : }
2388 : : else
2389 [ # # ]: 0 : elog(ERROR, "unexpected result type for procedure: %u",
2390 : : fexpr->funcresulttype);
2391 : :
2392 : 265 : FreeExecutorState(estate);
2393 : 265 : }
2394 : :
2395 : : /*
2396 : : * Construct the tuple descriptor for a CALL statement return
2397 : : */
2398 : : TupleDesc
2399 : 117 : CallStmtResultDesc(CallStmt *stmt)
2400 : : {
2401 : : FuncExpr *fexpr;
2402 : : HeapTuple tuple;
2403 : : TupleDesc tupdesc;
2404 : :
2405 : 117 : fexpr = stmt->funcexpr;
2406 : :
2407 : 117 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
2408 [ - + ]: 117 : if (!HeapTupleIsValid(tuple))
2409 [ # # ]: 0 : elog(ERROR, "cache lookup failed for procedure %u", fexpr->funcid);
2410 : :
2411 : 117 : tupdesc = build_function_result_tupdesc_t(tuple);
2412 : :
2413 : 117 : ReleaseSysCache(tuple);
2414 : :
2415 : : /*
2416 : : * The result of build_function_result_tupdesc_t has the right column
2417 : : * names, but it just has the declared output argument types, which is the
2418 : : * wrong thing in polymorphic cases. Get the correct types by examining
2419 : : * stmt->outargs. We intentionally keep the atttypmod as -1 and the
2420 : : * attcollation as the type's default, since that's always the appropriate
2421 : : * thing for function outputs; there's no point in considering any
2422 : : * additional info available from outargs. Note that tupdesc is null if
2423 : : * there are no outargs.
2424 : : */
2425 [ + - ]: 117 : if (tupdesc)
2426 : : {
2427 : : Assert(tupdesc->natts == list_length(stmt->outargs));
2428 [ + + ]: 296 : for (int i = 0; i < tupdesc->natts; i++)
2429 : : {
2430 : 179 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2431 : 179 : Node *outarg = (Node *) list_nth(stmt->outargs, i);
2432 : :
2433 : 179 : TupleDescInitEntry(tupdesc,
2434 : 179 : i + 1,
2435 : 179 : NameStr(att->attname),
2436 : : exprType(outarg),
2437 : : -1,
2438 : : 0);
2439 : : }
2440 : 117 : TupleDescFinalize(tupdesc);
2441 : : }
2442 : :
2443 : 117 : return tupdesc;
2444 : : }
|