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