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