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