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