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