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-2016, 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  * queryString: likewise, needed only for error handling
171  *
172  * Results are stored into output parameters. parameterTypes must always
173  * be created, but the other arrays are set to NULL if not needed.
174  * variadicArgType is set to the variadic array type if there's a VARIADIC
175  * parameter (there can be only one); or to InvalidOid if not.
176  * requiredResultType is set to InvalidOid if there are no OUT parameters,
177  * else it is set to the OID of the implied result type.
178  */
179 void
181  Oid languageOid,
182  bool is_aggregate,
183  const char *queryString,
184  oidvector **parameterTypes,
185  ArrayType **allParameterTypes,
186  ArrayType **parameterModes,
187  ArrayType **parameterNames,
188  List **parameterDefaults,
189  Oid *variadicArgType,
190  Oid *requiredResultType)
191 {
192  int parameterCount = list_length(parameters);
193  Oid *inTypes;
194  int inCount = 0;
195  Datum *allTypes;
196  Datum *paramModes;
197  Datum *paramNames;
198  int outCount = 0;
199  int varCount = 0;
200  bool have_names = false;
201  bool have_defaults = false;
202  ListCell *x;
203  int i;
204  ParseState *pstate;
205 
206  *variadicArgType = InvalidOid; /* default result */
207  *requiredResultType = InvalidOid; /* default result */
208 
209  inTypes = (Oid *) palloc(parameterCount * sizeof(Oid));
210  allTypes = (Datum *) palloc(parameterCount * sizeof(Datum));
211  paramModes = (Datum *) palloc(parameterCount * sizeof(Datum));
212  paramNames = (Datum *) palloc0(parameterCount * sizeof(Datum));
213  *parameterDefaults = NIL;
214 
215  /* may need a pstate for parse analysis of default exprs */
216  pstate = make_parsestate(NULL);
217  pstate->p_sourcetext = queryString;
218 
219  /* Scan the list and extract data into work arrays */
220  i = 0;
221  foreach(x, parameters)
222  {
224  TypeName *t = fp->argType;
225  bool isinput = false;
226  Oid toid;
227  Type typtup;
228  AclResult aclresult;
229 
230  typtup = LookupTypeName(NULL, t, NULL, false);
231  if (typtup)
232  {
233  if (!((Form_pg_type) GETSTRUCT(typtup))->typisdefined)
234  {
235  /* As above, hard error if language is SQL */
236  if (languageOid == SQLlanguageId)
237  ereport(ERROR,
238  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
239  errmsg("SQL function cannot accept shell type %s",
240  TypeNameToString(t))));
241  /* We don't allow creating aggregates on shell types either */
242  else if (is_aggregate)
243  ereport(ERROR,
244  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
245  errmsg("aggregate cannot accept shell type %s",
246  TypeNameToString(t))));
247  else
248  ereport(NOTICE,
249  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
250  errmsg("argument type %s is only a shell",
251  TypeNameToString(t))));
252  }
253  toid = typeTypeId(typtup);
254  ReleaseSysCache(typtup);
255  }
256  else
257  {
258  ereport(ERROR,
259  (errcode(ERRCODE_UNDEFINED_OBJECT),
260  errmsg("type %s does not exist",
261  TypeNameToString(t))));
262  toid = InvalidOid; /* keep compiler quiet */
263  }
264 
265  aclresult = pg_type_aclcheck(toid, GetUserId(), ACL_USAGE);
266  if (aclresult != ACLCHECK_OK)
267  aclcheck_error_type(aclresult, toid);
268 
269  if (t->setof)
270  {
271  if (is_aggregate)
272  ereport(ERROR,
273  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
274  errmsg("aggregates cannot accept set arguments")));
275  else
276  ereport(ERROR,
277  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
278  errmsg("functions cannot accept set arguments")));
279  }
280 
281  /* handle input parameters */
282  if (fp->mode != FUNC_PARAM_OUT && fp->mode != FUNC_PARAM_TABLE)
283  {
284  /* other input parameters can't follow a VARIADIC parameter */
285  if (varCount > 0)
286  ereport(ERROR,
287  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
288  errmsg("VARIADIC parameter must be the last input parameter")));
289  inTypes[inCount++] = toid;
290  isinput = true;
291  }
292 
293  /* handle output parameters */
294  if (fp->mode != FUNC_PARAM_IN && fp->mode != FUNC_PARAM_VARIADIC)
295  {
296  if (outCount == 0) /* save first output param's type */
297  *requiredResultType = toid;
298  outCount++;
299  }
300 
301  if (fp->mode == FUNC_PARAM_VARIADIC)
302  {
303  *variadicArgType = toid;
304  varCount++;
305  /* validate variadic parameter type */
306  switch (toid)
307  {
308  case ANYARRAYOID:
309  case ANYOID:
310  /* okay */
311  break;
312  default:
313  if (!OidIsValid(get_element_type(toid)))
314  ereport(ERROR,
315  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
316  errmsg("VARIADIC parameter must be an array")));
317  break;
318  }
319  }
320 
321  allTypes[i] = ObjectIdGetDatum(toid);
322 
323  paramModes[i] = CharGetDatum(fp->mode);
324 
325  if (fp->name && fp->name[0])
326  {
327  ListCell *px;
328 
329  /*
330  * As of Postgres 9.0 we disallow using the same name for two
331  * input or two output function parameters. Depending on the
332  * function's language, conflicting input and output names might
333  * be bad too, but we leave it to the PL to complain if so.
334  */
335  foreach(px, parameters)
336  {
337  FunctionParameter *prevfp = (FunctionParameter *) lfirst(px);
338 
339  if (prevfp == fp)
340  break;
341  /* pure in doesn't conflict with pure out */
342  if ((fp->mode == FUNC_PARAM_IN ||
343  fp->mode == FUNC_PARAM_VARIADIC) &&
344  (prevfp->mode == FUNC_PARAM_OUT ||
345  prevfp->mode == FUNC_PARAM_TABLE))
346  continue;
347  if ((prevfp->mode == FUNC_PARAM_IN ||
348  prevfp->mode == FUNC_PARAM_VARIADIC) &&
349  (fp->mode == FUNC_PARAM_OUT ||
350  fp->mode == FUNC_PARAM_TABLE))
351  continue;
352  if (prevfp->name && prevfp->name[0] &&
353  strcmp(prevfp->name, fp->name) == 0)
354  ereport(ERROR,
355  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
356  errmsg("parameter name \"%s\" used more than once",
357  fp->name)));
358  }
359 
360  paramNames[i] = CStringGetTextDatum(fp->name);
361  have_names = true;
362  }
363 
364  if (fp->defexpr)
365  {
366  Node *def;
367 
368  if (!isinput)
369  ereport(ERROR,
370  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
371  errmsg("only input parameters can have default values")));
372 
373  def = transformExpr(pstate, fp->defexpr,
375  def = coerce_to_specific_type(pstate, def, toid, "DEFAULT");
376  assign_expr_collations(pstate, def);
377 
378  /*
379  * Make sure no variables are referred to (this is probably dead
380  * code now that add_missing_from is history).
381  */
382  if (list_length(pstate->p_rtable) != 0 ||
383  contain_var_clause(def))
384  ereport(ERROR,
385  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
386  errmsg("cannot use table references in parameter default value")));
387 
388  /*
389  * transformExpr() should have already rejected subqueries,
390  * aggregates, and window functions, based on the EXPR_KIND_ for a
391  * default expression.
392  *
393  * It can't return a set either --- but coerce_to_specific_type
394  * already checked that for us.
395  *
396  * Note: the point of these restrictions is to ensure that an
397  * expression that, on its face, hasn't got subplans, aggregates,
398  * etc cannot suddenly have them after function default arguments
399  * are inserted.
400  */
401 
402  *parameterDefaults = lappend(*parameterDefaults, def);
403  have_defaults = true;
404  }
405  else
406  {
407  if (isinput && have_defaults)
408  ereport(ERROR,
409  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
410  errmsg("input parameters after one with a default value must also have defaults")));
411  }
412 
413  i++;
414  }
415 
416  free_parsestate(pstate);
417 
418  /* Now construct the proper outputs as needed */
419  *parameterTypes = buildoidvector(inTypes, inCount);
420 
421  if (outCount > 0 || varCount > 0)
422  {
423  *allParameterTypes = construct_array(allTypes, parameterCount, OIDOID,
424  sizeof(Oid), true, 'i');
425  *parameterModes = construct_array(paramModes, parameterCount, CHAROID,
426  1, true, 'c');
427  if (outCount > 1)
428  *requiredResultType = RECORDOID;
429  /* otherwise we set requiredResultType correctly above */
430  }
431  else
432  {
433  *allParameterTypes = NULL;
434  *parameterModes = NULL;
435  }
436 
437  if (have_names)
438  {
439  for (i = 0; i < parameterCount; i++)
440  {
441  if (paramNames[i] == PointerGetDatum(NULL))
442  paramNames[i] = CStringGetTextDatum("");
443  }
444  *parameterNames = construct_array(paramNames, parameterCount, TEXTOID,
445  -1, false, 'i');
446  }
447  else
448  *parameterNames = NULL;
449 }
450 
451 
452 /*
453  * Recognize one of the options that can be passed to both CREATE
454  * FUNCTION and ALTER FUNCTION and return it via one of the out
455  * parameters. Returns true if the passed option was recognized. If
456  * the out parameter we were going to assign to points to non-NULL,
457  * raise a duplicate-clause error. (We don't try to detect duplicate
458  * SET parameters though --- if you're redundant, the last one wins.)
459  */
460 static bool
462  DefElem **volatility_item,
463  DefElem **strict_item,
464  DefElem **security_item,
465  DefElem **leakproof_item,
466  List **set_items,
467  DefElem **cost_item,
468  DefElem **rows_item,
469  DefElem **parallel_item)
470 {
471  if (strcmp(defel->defname, "volatility") == 0)
472  {
473  if (*volatility_item)
474  goto duplicate_error;
475 
476  *volatility_item = defel;
477  }
478  else if (strcmp(defel->defname, "strict") == 0)
479  {
480  if (*strict_item)
481  goto duplicate_error;
482 
483  *strict_item = defel;
484  }
485  else if (strcmp(defel->defname, "security") == 0)
486  {
487  if (*security_item)
488  goto duplicate_error;
489 
490  *security_item = defel;
491  }
492  else if (strcmp(defel->defname, "leakproof") == 0)
493  {
494  if (*leakproof_item)
495  goto duplicate_error;
496 
497  *leakproof_item = defel;
498  }
499  else if (strcmp(defel->defname, "set") == 0)
500  {
501  *set_items = lappend(*set_items, defel->arg);
502  }
503  else if (strcmp(defel->defname, "cost") == 0)
504  {
505  if (*cost_item)
506  goto duplicate_error;
507 
508  *cost_item = defel;
509  }
510  else if (strcmp(defel->defname, "rows") == 0)
511  {
512  if (*rows_item)
513  goto duplicate_error;
514 
515  *rows_item = defel;
516  }
517  else if (strcmp(defel->defname, "parallel") == 0)
518  {
519  if (*parallel_item)
520  goto duplicate_error;
521 
522  *parallel_item = defel;
523  }
524  else
525  return false;
526 
527  /* Recognized an option */
528  return true;
529 
530 duplicate_error:
531  ereport(ERROR,
532  (errcode(ERRCODE_SYNTAX_ERROR),
533  errmsg("conflicting or redundant options")));
534  return false; /* keep compiler quiet */
535 }
536 
537 static char
539 {
540  char *str = strVal(defel->arg);
541 
542  if (strcmp(str, "immutable") == 0)
543  return PROVOLATILE_IMMUTABLE;
544  else if (strcmp(str, "stable") == 0)
545  return PROVOLATILE_STABLE;
546  else if (strcmp(str, "volatile") == 0)
547  return PROVOLATILE_VOLATILE;
548  else
549  {
550  elog(ERROR, "invalid volatility \"%s\"", str);
551  return 0; /* keep compiler quiet */
552  }
553 }
554 
555 static char
557 {
558  char *str = strVal(defel->arg);
559 
560  if (strcmp(str, "safe") == 0)
561  return PROPARALLEL_SAFE;
562  else if (strcmp(str, "unsafe") == 0)
563  return PROPARALLEL_UNSAFE;
564  else if (strcmp(str, "restricted") == 0)
565  return PROPARALLEL_RESTRICTED;
566  else
567  {
568  ereport(ERROR,
569  (errcode(ERRCODE_SYNTAX_ERROR),
570  errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
571  return PROPARALLEL_UNSAFE; /* keep compiler quiet */
572  }
573 }
574 
575 /*
576  * Update a proconfig value according to a list of VariableSetStmt items.
577  *
578  * The input and result may be NULL to signify a null entry.
579  */
580 static ArrayType *
582 {
583  ListCell *l;
584 
585  foreach(l, set_items)
586  {
587  VariableSetStmt *sstmt = (VariableSetStmt *) lfirst(l);
588 
589  Assert(IsA(sstmt, VariableSetStmt));
590  if (sstmt->kind == VAR_RESET_ALL)
591  a = NULL;
592  else
593  {
594  char *valuestr = ExtractSetVariableArgs(sstmt);
595 
596  if (valuestr)
597  a = GUCArrayAdd(a, sstmt->name, valuestr);
598  else /* RESET */
599  a = GUCArrayDelete(a, sstmt->name);
600  }
601  }
602 
603  return a;
604 }
605 
606 
607 /*
608  * Dissect the list of options assembled in gram.y into function
609  * attributes.
610  */
611 static void
613  List **as,
614  char **language,
615  Node **transform,
616  bool *windowfunc_p,
617  char *volatility_p,
618  bool *strict_p,
619  bool *security_definer,
620  bool *leakproof_p,
621  ArrayType **proconfig,
622  float4 *procost,
623  float4 *prorows,
624  char *parallel_p)
625 {
626  ListCell *option;
627  DefElem *as_item = NULL;
628  DefElem *language_item = NULL;
629  DefElem *transform_item = NULL;
630  DefElem *windowfunc_item = NULL;
631  DefElem *volatility_item = NULL;
632  DefElem *strict_item = NULL;
633  DefElem *security_item = NULL;
634  DefElem *leakproof_item = NULL;
635  List *set_items = NIL;
636  DefElem *cost_item = NULL;
637  DefElem *rows_item = NULL;
638  DefElem *parallel_item = NULL;
639 
640  foreach(option, options)
641  {
642  DefElem *defel = (DefElem *) lfirst(option);
643 
644  if (strcmp(defel->defname, "as") == 0)
645  {
646  if (as_item)
647  ereport(ERROR,
648  (errcode(ERRCODE_SYNTAX_ERROR),
649  errmsg("conflicting or redundant options")));
650  as_item = defel;
651  }
652  else if (strcmp(defel->defname, "language") == 0)
653  {
654  if (language_item)
655  ereport(ERROR,
656  (errcode(ERRCODE_SYNTAX_ERROR),
657  errmsg("conflicting or redundant options")));
658  language_item = defel;
659  }
660  else if (strcmp(defel->defname, "transform") == 0)
661  {
662  if (transform_item)
663  ereport(ERROR,
664  (errcode(ERRCODE_SYNTAX_ERROR),
665  errmsg("conflicting or redundant options")));
666  transform_item = defel;
667  }
668  else if (strcmp(defel->defname, "window") == 0)
669  {
670  if (windowfunc_item)
671  ereport(ERROR,
672  (errcode(ERRCODE_SYNTAX_ERROR),
673  errmsg("conflicting or redundant options")));
674  windowfunc_item = defel;
675  }
676  else if (compute_common_attribute(defel,
677  &volatility_item,
678  &strict_item,
679  &security_item,
680  &leakproof_item,
681  &set_items,
682  &cost_item,
683  &rows_item,
684  &parallel_item))
685  {
686  /* recognized common option */
687  continue;
688  }
689  else
690  elog(ERROR, "option \"%s\" not recognized",
691  defel->defname);
692  }
693 
694  /* process required items */
695  if (as_item)
696  *as = (List *) as_item->arg;
697  else
698  {
699  ereport(ERROR,
700  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
701  errmsg("no function body specified")));
702  *as = NIL; /* keep compiler quiet */
703  }
704 
705  if (language_item)
706  *language = strVal(language_item->arg);
707  else
708  {
709  ereport(ERROR,
710  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
711  errmsg("no language specified")));
712  *language = NULL; /* keep compiler quiet */
713  }
714 
715  /* process optional items */
716  if (transform_item)
717  *transform = transform_item->arg;
718  if (windowfunc_item)
719  *windowfunc_p = intVal(windowfunc_item->arg);
720  if (volatility_item)
721  *volatility_p = interpret_func_volatility(volatility_item);
722  if (strict_item)
723  *strict_p = intVal(strict_item->arg);
724  if (security_item)
725  *security_definer = intVal(security_item->arg);
726  if (leakproof_item)
727  *leakproof_p = intVal(leakproof_item->arg);
728  if (set_items)
729  *proconfig = update_proconfig_value(NULL, set_items);
730  if (cost_item)
731  {
732  *procost = defGetNumeric(cost_item);
733  if (*procost <= 0)
734  ereport(ERROR,
735  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
736  errmsg("COST must be positive")));
737  }
738  if (rows_item)
739  {
740  *prorows = defGetNumeric(rows_item);
741  if (*prorows <= 0)
742  ereport(ERROR,
743  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
744  errmsg("ROWS must be positive")));
745  }
746  if (parallel_item)
747  *parallel_p = interpret_func_parallel(parallel_item);
748 }
749 
750 
751 /*-------------
752  * Interpret the parameters *parameters and return their contents via
753  * *isStrict_p and *volatility_p.
754  *
755  * These parameters supply optional information about a function.
756  * All have defaults if not specified. Parameters:
757  *
758  * * isStrict means the function should not be called when any NULL
759  * inputs are present; instead a NULL result value should be assumed.
760  *
761  * * volatility tells the optimizer whether the function's result can
762  * be assumed to be repeatable over multiple evaluations.
763  *------------
764  */
765 static void
766 compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatility_p)
767 {
768  ListCell *pl;
769 
770  foreach(pl, parameters)
771  {
772  DefElem *param = (DefElem *) lfirst(pl);
773 
774  if (pg_strcasecmp(param->defname, "isstrict") == 0)
775  *isStrict_p = defGetBoolean(param);
776  else if (pg_strcasecmp(param->defname, "iscachable") == 0)
777  {
778  /* obsolete spelling of isImmutable */
779  if (defGetBoolean(param))
780  *volatility_p = PROVOLATILE_IMMUTABLE;
781  }
782  else
784  (errcode(ERRCODE_SYNTAX_ERROR),
785  errmsg("unrecognized function attribute \"%s\" ignored",
786  param->defname)));
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  */
861 CreateFunction(CreateFunctionStmt *stmt, const char *queryString)
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  &as_clause, &language, &transformDefElem,
920  &isWindowFunc, &volatility,
921  &isStrict, &security, &isLeakProof,
922  &proconfig, &procost, &prorows, &parallel);
923 
924  /* Look up the language and validate permissions */
925  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
926  if (!HeapTupleIsValid(languageTuple))
927  ereport(ERROR,
928  (errcode(ERRCODE_UNDEFINED_OBJECT),
929  errmsg("language \"%s\" does not exist", language),
930  (PLTemplateExists(language) ?
931  errhint("Use CREATE LANGUAGE to load the language into the database.") : 0)));
932 
933  languageOid = HeapTupleGetOid(languageTuple);
934  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
935 
936  if (languageStruct->lanpltrusted)
937  {
938  /* if trusted language, need USAGE privilege */
939  AclResult aclresult;
940 
941  aclresult = pg_language_aclcheck(languageOid, GetUserId(), ACL_USAGE);
942  if (aclresult != ACLCHECK_OK)
944  NameStr(languageStruct->lanname));
945  }
946  else
947  {
948  /* if untrusted language, must be superuser */
949  if (!superuser())
951  NameStr(languageStruct->lanname));
952  }
953 
954  languageValidator = languageStruct->lanvalidator;
955 
956  ReleaseSysCache(languageTuple);
957 
958  /*
959  * Only superuser is allowed to create leakproof functions because
960  * leakproof functions can see tuples which have not yet been filtered out
961  * by security barrier views or row level security policies.
962  */
963  if (isLeakProof && !superuser())
964  ereport(ERROR,
965  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
966  errmsg("only superuser can define a leakproof function")));
967 
968  if (transformDefElem)
969  {
970  ListCell *lc;
971 
972  Assert(IsA(transformDefElem, List));
973 
974  foreach(lc, (List *) transformDefElem)
975  {
976  Oid typeid = typenameTypeId(NULL, lfirst(lc));
977  Oid elt = get_base_element_type(typeid);
978 
979  typeid = elt ? elt : typeid;
980 
981  get_transform_oid(typeid, languageOid, false);
982  trftypes_list = lappend_oid(trftypes_list, typeid);
983  }
984  }
985 
986  /*
987  * Convert remaining parameters of CREATE to form wanted by
988  * ProcedureCreate.
989  */
991  languageOid,
992  false, /* not an aggregate */
993  queryString,
994  &parameterTypes,
995  &allParameterTypes,
996  &parameterModes,
997  &parameterNames,
998  &parameterDefaults,
999  &variadicArgType,
1000  &requiredResultType);
1001 
1002  if (stmt->returnType)
1003  {
1004  /* explicit RETURNS clause */
1005  compute_return_type(stmt->returnType, languageOid,
1006  &prorettype, &returnsSet);
1007  if (OidIsValid(requiredResultType) && prorettype != requiredResultType)
1008  ereport(ERROR,
1009  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1010  errmsg("function result type must be %s because of OUT parameters",
1011  format_type_be(requiredResultType))));
1012  }
1013  else if (OidIsValid(requiredResultType))
1014  {
1015  /* default RETURNS clause from OUT parameters */
1016  prorettype = requiredResultType;
1017  returnsSet = false;
1018  }
1019  else
1020  {
1021  ereport(ERROR,
1022  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1023  errmsg("function result type must be specified")));
1024  /* Alternative possibility: default to RETURNS VOID */
1025  prorettype = VOIDOID;
1026  returnsSet = false;
1027  }
1028 
1029  if (list_length(trftypes_list) > 0)
1030  {
1031  ListCell *lc;
1032  Datum *arr;
1033  int i;
1034 
1035  arr = palloc(list_length(trftypes_list) * sizeof(Datum));
1036  i = 0;
1037  foreach(lc, trftypes_list)
1038  arr[i++] = ObjectIdGetDatum(lfirst_oid(lc));
1039  trftypes = construct_array(arr, list_length(trftypes_list),
1040  OIDOID, sizeof(Oid), true, 'i');
1041  }
1042  else
1043  {
1044  /* store SQL NULL instead of emtpy array */
1045  trftypes = NULL;
1046  }
1047 
1048  compute_attributes_with_style(stmt->withClause, &isStrict, &volatility);
1049 
1050  interpret_AS_clause(languageOid, language, funcname, as_clause,
1051  &prosrc_str, &probin_str);
1052 
1053  /*
1054  * Set default values for COST and ROWS depending on other parameters;
1055  * reject ROWS if it's not returnsSet. NB: pg_dump knows these default
1056  * values, keep it in sync if you change them.
1057  */
1058  if (procost < 0)
1059  {
1060  /* SQL and PL-language functions are assumed more expensive */
1061  if (languageOid == INTERNALlanguageId ||
1062  languageOid == ClanguageId)
1063  procost = 1;
1064  else
1065  procost = 100;
1066  }
1067  if (prorows < 0)
1068  {
1069  if (returnsSet)
1070  prorows = 1000;
1071  else
1072  prorows = 0; /* dummy value if not returnsSet */
1073  }
1074  else if (!returnsSet)
1075  ereport(ERROR,
1076  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1077  errmsg("ROWS is not applicable when function does not return a set")));
1078 
1079  /*
1080  * And now that we have all the parameters, and know we're permitted to do
1081  * so, go ahead and create the function.
1082  */
1083  return ProcedureCreate(funcname,
1084  namespaceId,
1085  stmt->replace,
1086  returnsSet,
1087  prorettype,
1088  GetUserId(),
1089  languageOid,
1090  languageValidator,
1091  prosrc_str, /* converted to text later */
1092  probin_str, /* converted to text later */
1093  false, /* not an aggregate */
1094  isWindowFunc,
1095  security,
1096  isLeakProof,
1097  isStrict,
1098  volatility,
1099  parallel,
1100  parameterTypes,
1101  PointerGetDatum(allParameterTypes),
1102  PointerGetDatum(parameterModes),
1103  PointerGetDatum(parameterNames),
1104  parameterDefaults,
1105  PointerGetDatum(trftypes),
1106  PointerGetDatum(proconfig),
1107  procost,
1108  prorows);
1109 }
1110 
1111 /*
1112  * Guts of function deletion.
1113  *
1114  * Note: this is also used for aggregate deletion, since the OIDs of
1115  * both functions and aggregates point to pg_proc.
1116  */
1117 void
1119 {
1120  Relation relation;
1121  HeapTuple tup;
1122  bool isagg;
1123 
1124  /*
1125  * Delete the pg_proc tuple.
1126  */
1128 
1129  tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
1130  if (!HeapTupleIsValid(tup)) /* should not happen */
1131  elog(ERROR, "cache lookup failed for function %u", funcOid);
1132 
1133  isagg = ((Form_pg_proc) GETSTRUCT(tup))->proisagg;
1134 
1135  simple_heap_delete(relation, &tup->t_self);
1136 
1137  ReleaseSysCache(tup);
1138 
1139  heap_close(relation, RowExclusiveLock);
1140 
1141  /*
1142  * If there's a pg_aggregate tuple, delete that too.
1143  */
1144  if (isagg)
1145  {
1147 
1148  tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcOid));
1149  if (!HeapTupleIsValid(tup)) /* should not happen */
1150  elog(ERROR, "cache lookup failed for pg_aggregate tuple for function %u", funcOid);
1151 
1152  simple_heap_delete(relation, &tup->t_self);
1153 
1154  ReleaseSysCache(tup);
1155 
1156  heap_close(relation, RowExclusiveLock);
1157  }
1158 }
1159 
1160 /*
1161  * Implements the ALTER FUNCTION utility command (except for the
1162  * RENAME and OWNER clauses, which are handled as part of the generic
1163  * ALTER framework).
1164  */
1167 {
1168  HeapTuple tup;
1169  Oid funcOid;
1170  Form_pg_proc procForm;
1171  Relation rel;
1172  ListCell *l;
1173  DefElem *volatility_item = NULL;
1174  DefElem *strict_item = NULL;
1175  DefElem *security_def_item = NULL;
1176  DefElem *leakproof_item = NULL;
1177  List *set_items = NIL;
1178  DefElem *cost_item = NULL;
1179  DefElem *rows_item = NULL;
1180  DefElem *parallel_item = NULL;
1181  ObjectAddress address;
1182 
1184 
1185  funcOid = LookupFuncNameTypeNames(stmt->func->funcname,
1186  stmt->func->funcargs,
1187  false);
1188 
1189  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1190  if (!HeapTupleIsValid(tup)) /* should not happen */
1191  elog(ERROR, "cache lookup failed for function %u", funcOid);
1192 
1193  procForm = (Form_pg_proc) GETSTRUCT(tup);
1194 
1195  /* Permission check: must own function */
1196  if (!pg_proc_ownercheck(funcOid, GetUserId()))
1198  NameListToString(stmt->func->funcname));
1199 
1200  if (procForm->proisagg)
1201  ereport(ERROR,
1202  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1203  errmsg("\"%s\" is an aggregate function",
1204  NameListToString(stmt->func->funcname))));
1205 
1206  /* Examine requested actions. */
1207  foreach(l, stmt->actions)
1208  {
1209  DefElem *defel = (DefElem *) lfirst(l);
1210 
1211  if (compute_common_attribute(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  simple_heap_update(rel, &tup->t_self, tup);
1296  CatalogUpdateIndexes(rel, tup);
1297 
1299 
1300  ObjectAddressSet(address, ProcedureRelationId, funcOid);
1301 
1302  heap_close(rel, NoLock);
1303  heap_freetuple(tup);
1304 
1305  return address;
1306 }
1307 
1308 /*
1309  * SetFunctionReturnType - change declared return type of a function
1310  *
1311  * This is presently only used for adjusting legacy functions that return
1312  * OPAQUE to return whatever we find their correct definition should be.
1313  * The caller should emit a suitable warning explaining what we did.
1314  */
1315 void
1316 SetFunctionReturnType(Oid funcOid, Oid newRetType)
1317 {
1318  Relation pg_proc_rel;
1319  HeapTuple tup;
1320  Form_pg_proc procForm;
1321 
1323 
1324  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1325  if (!HeapTupleIsValid(tup)) /* should not happen */
1326  elog(ERROR, "cache lookup failed for function %u", funcOid);
1327  procForm = (Form_pg_proc) GETSTRUCT(tup);
1328 
1329  if (procForm->prorettype != OPAQUEOID) /* caller messed up */
1330  elog(ERROR, "function %u doesn't return OPAQUE", funcOid);
1331 
1332  /* okay to overwrite copied tuple */
1333  procForm->prorettype = newRetType;
1334 
1335  /* update the catalog and its indexes */
1336  simple_heap_update(pg_proc_rel, &tup->t_self, tup);
1337 
1338  CatalogUpdateIndexes(pg_proc_rel, tup);
1339 
1340  heap_close(pg_proc_rel, RowExclusiveLock);
1341 }
1342 
1343 
1344 /*
1345  * SetFunctionArgType - change declared argument type of a function
1346  *
1347  * As above, but change an argument's type.
1348  */
1349 void
1350 SetFunctionArgType(Oid funcOid, int argIndex, Oid newArgType)
1351 {
1352  Relation pg_proc_rel;
1353  HeapTuple tup;
1354  Form_pg_proc procForm;
1355 
1357 
1358  tup = SearchSysCacheCopy1(PROCOID, ObjectIdGetDatum(funcOid));
1359  if (!HeapTupleIsValid(tup)) /* should not happen */
1360  elog(ERROR, "cache lookup failed for function %u", funcOid);
1361  procForm = (Form_pg_proc) GETSTRUCT(tup);
1362 
1363  if (argIndex < 0 || argIndex >= procForm->pronargs ||
1364  procForm->proargtypes.values[argIndex] != OPAQUEOID)
1365  elog(ERROR, "function %u doesn't take OPAQUE", funcOid);
1366 
1367  /* okay to overwrite copied tuple */
1368  procForm->proargtypes.values[argIndex] = newArgType;
1369 
1370  /* update the catalog and its indexes */
1371  simple_heap_update(pg_proc_rel, &tup->t_self, tup);
1372 
1373  CatalogUpdateIndexes(pg_proc_rel, tup);
1374 
1375  heap_close(pg_proc_rel, RowExclusiveLock);
1376 }
1377 
1378 
1379 
1380 /*
1381  * CREATE CAST
1382  */
1385 {
1386  Oid sourcetypeid;
1387  Oid targettypeid;
1388  char sourcetyptype;
1389  char targettyptype;
1390  Oid funcid;
1391  Oid castid;
1392  int nargs;
1393  char castcontext;
1394  char castmethod;
1395  Relation relation;
1396  HeapTuple tuple;
1398  bool nulls[Natts_pg_cast];
1399  ObjectAddress myself,
1400  referenced;
1401  AclResult aclresult;
1402 
1403  sourcetypeid = typenameTypeId(NULL, stmt->sourcetype);
1404  targettypeid = typenameTypeId(NULL, stmt->targettype);
1405  sourcetyptype = get_typtype(sourcetypeid);
1406  targettyptype = get_typtype(targettypeid);
1407 
1408  /* No pseudo-types allowed */
1409  if (sourcetyptype == TYPTYPE_PSEUDO)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1412  errmsg("source data type %s is a pseudo-type",
1413  TypeNameToString(stmt->sourcetype))));
1414 
1415  if (targettyptype == TYPTYPE_PSEUDO)
1416  ereport(ERROR,
1417  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1418  errmsg("target data type %s is a pseudo-type",
1419  TypeNameToString(stmt->targettype))));
1420 
1421  /* Permission check */
1422  if (!pg_type_ownercheck(sourcetypeid, GetUserId())
1423  && !pg_type_ownercheck(targettypeid, GetUserId()))
1424  ereport(ERROR,
1425  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1426  errmsg("must be owner of type %s or type %s",
1427  format_type_be(sourcetypeid),
1428  format_type_be(targettypeid))));
1429 
1430  aclresult = pg_type_aclcheck(sourcetypeid, GetUserId(), ACL_USAGE);
1431  if (aclresult != ACLCHECK_OK)
1432  aclcheck_error_type(aclresult, sourcetypeid);
1433 
1434  aclresult = pg_type_aclcheck(targettypeid, GetUserId(), ACL_USAGE);
1435  if (aclresult != ACLCHECK_OK)
1436  aclcheck_error_type(aclresult, targettypeid);
1437 
1438  /* Domains are allowed for historical reasons, but we warn */
1439  if (sourcetyptype == TYPTYPE_DOMAIN)
1440  ereport(WARNING,
1441  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1442  errmsg("cast will be ignored because the source data type is a domain")));
1443 
1444  else if (targettyptype == TYPTYPE_DOMAIN)
1445  ereport(WARNING,
1446  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1447  errmsg("cast will be ignored because the target data type is a domain")));
1448 
1449  /* Detemine the cast method */
1450  if (stmt->func != NULL)
1451  castmethod = COERCION_METHOD_FUNCTION;
1452  else if (stmt->inout)
1453  castmethod = COERCION_METHOD_INOUT;
1454  else
1455  castmethod = COERCION_METHOD_BINARY;
1456 
1457  if (castmethod == COERCION_METHOD_FUNCTION)
1458  {
1459  Form_pg_proc procstruct;
1460 
1461  funcid = LookupFuncNameTypeNames(stmt->func->funcname,
1462  stmt->func->funcargs,
1463  false);
1464 
1465  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1466  if (!HeapTupleIsValid(tuple))
1467  elog(ERROR, "cache lookup failed for function %u", funcid);
1468 
1469  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1470  nargs = procstruct->pronargs;
1471  if (nargs < 1 || nargs > 3)
1472  ereport(ERROR,
1473  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1474  errmsg("cast function must take one to three arguments")));
1475  if (!IsBinaryCoercible(sourcetypeid, procstruct->proargtypes.values[0]))
1476  ereport(ERROR,
1477  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1478  errmsg("argument of cast function must match or be binary-coercible from source data type")));
1479  if (nargs > 1 && procstruct->proargtypes.values[1] != INT4OID)
1480  ereport(ERROR,
1481  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1482  errmsg("second argument of cast function must be type integer")));
1483  if (nargs > 2 && procstruct->proargtypes.values[2] != BOOLOID)
1484  ereport(ERROR,
1485  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1486  errmsg("third argument of cast function must be type boolean")));
1487  if (!IsBinaryCoercible(procstruct->prorettype, targettypeid))
1488  ereport(ERROR,
1489  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1490  errmsg("return data type of cast function must match or be binary-coercible to target data type")));
1491 
1492  /*
1493  * Restricting the volatility of a cast function may or may not be a
1494  * good idea in the abstract, but it definitely breaks many old
1495  * user-defined types. Disable this check --- tgl 2/1/03
1496  */
1497 #ifdef NOT_USED
1498  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1499  ereport(ERROR,
1500  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1501  errmsg("cast function must not be volatile")));
1502 #endif
1503  if (procstruct->proisagg)
1504  ereport(ERROR,
1505  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1506  errmsg("cast function must not be an aggregate function")));
1507  if (procstruct->proiswindow)
1508  ereport(ERROR,
1509  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1510  errmsg("cast function must not be a window function")));
1511  if (procstruct->proretset)
1512  ereport(ERROR,
1513  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1514  errmsg("cast function must not return a set")));
1515 
1516  ReleaseSysCache(tuple);
1517  }
1518  else
1519  {
1520  funcid = InvalidOid;
1521  nargs = 0;
1522  }
1523 
1524  if (castmethod == COERCION_METHOD_BINARY)
1525  {
1526  int16 typ1len;
1527  int16 typ2len;
1528  bool typ1byval;
1529  bool typ2byval;
1530  char typ1align;
1531  char typ2align;
1532 
1533  /*
1534  * Must be superuser to create binary-compatible casts, since
1535  * erroneous casts can easily crash the backend.
1536  */
1537  if (!superuser())
1538  ereport(ERROR,
1539  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1540  errmsg("must be superuser to create a cast WITHOUT FUNCTION")));
1541 
1542  /*
1543  * Also, insist that the types match as to size, alignment, and
1544  * pass-by-value attributes; this provides at least a crude check that
1545  * they have similar representations. A pair of types that fail this
1546  * test should certainly not be equated.
1547  */
1548  get_typlenbyvalalign(sourcetypeid, &typ1len, &typ1byval, &typ1align);
1549  get_typlenbyvalalign(targettypeid, &typ2len, &typ2byval, &typ2align);
1550  if (typ1len != typ2len ||
1551  typ1byval != typ2byval ||
1552  typ1align != typ2align)
1553  ereport(ERROR,
1554  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1555  errmsg("source and target data types are not physically compatible")));
1556 
1557  /*
1558  * We know that composite, enum and array types are never binary-
1559  * compatible with each other. They all have OIDs embedded in them.
1560  *
1561  * Theoretically you could build a user-defined base type that is
1562  * binary-compatible with a composite, enum, or array type. But we
1563  * disallow that too, as in practice such a cast is surely a mistake.
1564  * You can always work around that by writing a cast function.
1565  */
1566  if (sourcetyptype == TYPTYPE_COMPOSITE ||
1567  targettyptype == TYPTYPE_COMPOSITE)
1568  ereport(ERROR,
1569  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1570  errmsg("composite data types are not binary-compatible")));
1571 
1572  if (sourcetyptype == TYPTYPE_ENUM ||
1573  targettyptype == TYPTYPE_ENUM)
1574  ereport(ERROR,
1575  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1576  errmsg("enum data types are not binary-compatible")));
1577 
1578  if (OidIsValid(get_element_type(sourcetypeid)) ||
1579  OidIsValid(get_element_type(targettypeid)))
1580  ereport(ERROR,
1581  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1582  errmsg("array data types are not binary-compatible")));
1583 
1584  /*
1585  * We also disallow creating binary-compatibility casts involving
1586  * domains. Casting from a domain to its base type is already
1587  * allowed, and casting the other way ought to go through domain
1588  * coercion to permit constraint checking. Again, if you're intent on
1589  * having your own semantics for that, create a no-op cast function.
1590  *
1591  * NOTE: if we were to relax this, the above checks for composites
1592  * etc. would have to be modified to look through domains to their
1593  * base types.
1594  */
1595  if (sourcetyptype == TYPTYPE_DOMAIN ||
1596  targettyptype == TYPTYPE_DOMAIN)
1597  ereport(ERROR,
1598  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1599  errmsg("domain data types must not be marked binary-compatible")));
1600  }
1601 
1602  /*
1603  * Allow source and target types to be same only for length coercion
1604  * functions. We assume a multi-arg function does length coercion.
1605  */
1606  if (sourcetypeid == targettypeid && nargs < 2)
1607  ereport(ERROR,
1608  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1609  errmsg("source data type and target data type are the same")));
1610 
1611  /* convert CoercionContext enum to char value for castcontext */
1612  switch (stmt->context)
1613  {
1614  case COERCION_IMPLICIT:
1615  castcontext = COERCION_CODE_IMPLICIT;
1616  break;
1617  case COERCION_ASSIGNMENT:
1618  castcontext = COERCION_CODE_ASSIGNMENT;
1619  break;
1620  case COERCION_EXPLICIT:
1621  castcontext = COERCION_CODE_EXPLICIT;
1622  break;
1623  default:
1624  elog(ERROR, "unrecognized CoercionContext: %d", stmt->context);
1625  castcontext = 0; /* keep compiler quiet */
1626  break;
1627  }
1628 
1630 
1631  /*
1632  * Check for duplicate. This is just to give a friendly error message,
1633  * the unique index would catch it anyway (so no need to sweat about race
1634  * conditions).
1635  */
1637  ObjectIdGetDatum(sourcetypeid),
1638  ObjectIdGetDatum(targettypeid));
1639  if (HeapTupleIsValid(tuple))
1640  ereport(ERROR,
1642  errmsg("cast from type %s to type %s already exists",
1643  format_type_be(sourcetypeid),
1644  format_type_be(targettypeid))));
1645 
1646  /* ready to go */
1647  values[Anum_pg_cast_castsource - 1] = ObjectIdGetDatum(sourcetypeid);
1648  values[Anum_pg_cast_casttarget - 1] = ObjectIdGetDatum(targettypeid);
1649  values[Anum_pg_cast_castfunc - 1] = ObjectIdGetDatum(funcid);
1650  values[Anum_pg_cast_castcontext - 1] = CharGetDatum(castcontext);
1651  values[Anum_pg_cast_castmethod - 1] = CharGetDatum(castmethod);
1652 
1653  MemSet(nulls, false, sizeof(nulls));
1654 
1655  tuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1656 
1657  castid = simple_heap_insert(relation, tuple);
1658 
1659  CatalogUpdateIndexes(relation, tuple);
1660 
1661  /* make dependency entries */
1662  myself.classId = CastRelationId;
1663  myself.objectId = castid;
1664  myself.objectSubId = 0;
1665 
1666  /* dependency on source type */
1667  referenced.classId = TypeRelationId;
1668  referenced.objectId = sourcetypeid;
1669  referenced.objectSubId = 0;
1670  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1671 
1672  /* dependency on target type */
1673  referenced.classId = TypeRelationId;
1674  referenced.objectId = targettypeid;
1675  referenced.objectSubId = 0;
1676  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1677 
1678  /* dependency on function */
1679  if (OidIsValid(funcid))
1680  {
1681  referenced.classId = ProcedureRelationId;
1682  referenced.objectId = funcid;
1683  referenced.objectSubId = 0;
1684  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1685  }
1686 
1687  /* dependency on extension */
1688  recordDependencyOnCurrentExtension(&myself, false);
1689 
1690  /* Post creation hook for new cast */
1692 
1693  heap_freetuple(tuple);
1694 
1695  heap_close(relation, RowExclusiveLock);
1696 
1697  return myself;
1698 }
1699 
1700 /*
1701  * get_cast_oid - given two type OIDs, look up a cast OID
1702  *
1703  * If missing_ok is false, throw an error if the cast is not found. If
1704  * true, just return InvalidOid.
1705  */
1706 Oid
1707 get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok)
1708 {
1709  Oid oid;
1710 
1712  ObjectIdGetDatum(sourcetypeid),
1713  ObjectIdGetDatum(targettypeid));
1714  if (!OidIsValid(oid) && !missing_ok)
1715  ereport(ERROR,
1716  (errcode(ERRCODE_UNDEFINED_OBJECT),
1717  errmsg("cast from type %s to type %s does not exist",
1718  format_type_be(sourcetypeid),
1719  format_type_be(targettypeid))));
1720  return oid;
1721 }
1722 
1723 void
1725 {
1726  Relation relation;
1727  ScanKeyData scankey;
1728  SysScanDesc scan;
1729  HeapTuple tuple;
1730 
1732 
1733  ScanKeyInit(&scankey,
1735  BTEqualStrategyNumber, F_OIDEQ,
1736  ObjectIdGetDatum(castOid));
1737  scan = systable_beginscan(relation, CastOidIndexId, true,
1738  NULL, 1, &scankey);
1739 
1740  tuple = systable_getnext(scan);
1741  if (!HeapTupleIsValid(tuple))
1742  elog(ERROR, "could not find tuple for cast %u", castOid);
1743  simple_heap_delete(relation, &tuple->t_self);
1744 
1745  systable_endscan(scan);
1746  heap_close(relation, RowExclusiveLock);
1747 }
1748 
1749 
1750 static void
1752 {
1753  if (procstruct->provolatile == PROVOLATILE_VOLATILE)
1754  ereport(ERROR,
1755  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1756  errmsg("transform function must not be volatile")));
1757  if (procstruct->proisagg)
1758  ereport(ERROR,
1759  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1760  errmsg("transform function must not be an aggregate function")));
1761  if (procstruct->proiswindow)
1762  ereport(ERROR,
1763  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1764  errmsg("transform function must not be a window function")));
1765  if (procstruct->proretset)
1766  ereport(ERROR,
1767  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1768  errmsg("transform function must not return a set")));
1769  if (procstruct->pronargs != 1)
1770  ereport(ERROR,
1771  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1772  errmsg("transform function must take one argument")));
1773  if (procstruct->proargtypes.values[0] != INTERNALOID)
1774  ereport(ERROR,
1775  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1776  errmsg("first argument of transform function must be type \"internal\"")));
1777 }
1778 
1779 
1780 /*
1781  * CREATE TRANSFORM
1782  */
1785 {
1786  Oid typeid;
1787  char typtype;
1788  Oid langid;
1789  Oid fromsqlfuncid;
1790  Oid tosqlfuncid;
1791  AclResult aclresult;
1792  Form_pg_proc procstruct;
1794  bool nulls[Natts_pg_transform];
1795  bool replaces[Natts_pg_transform];
1796  Oid transformid;
1797  HeapTuple tuple;
1798  HeapTuple newtuple;
1799  Relation relation;
1800  ObjectAddress myself,
1801  referenced;
1802  bool is_replace;
1803 
1804  /*
1805  * Get the type
1806  */
1807  typeid = typenameTypeId(NULL, stmt->type_name);
1808  typtype = get_typtype(typeid);
1809 
1810  if (typtype == TYPTYPE_PSEUDO)
1811  ereport(ERROR,
1812  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1813  errmsg("data type %s is a pseudo-type",
1814  TypeNameToString(stmt->type_name))));
1815 
1816  if (typtype == TYPTYPE_DOMAIN)
1817  ereport(ERROR,
1818  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1819  errmsg("data type %s is a domain",
1820  TypeNameToString(stmt->type_name))));
1821 
1822  if (!pg_type_ownercheck(typeid, GetUserId()))
1824 
1825  aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
1826  if (aclresult != ACLCHECK_OK)
1827  aclcheck_error_type(aclresult, typeid);
1828 
1829  /*
1830  * Get the language
1831  */
1832  langid = get_language_oid(stmt->lang, false);
1833 
1834  aclresult = pg_language_aclcheck(langid, GetUserId(), ACL_USAGE);
1835  if (aclresult != ACLCHECK_OK)
1836  aclcheck_error(aclresult, ACL_KIND_LANGUAGE, stmt->lang);
1837 
1838  /*
1839  * Get the functions
1840  */
1841  if (stmt->fromsql)
1842  {
1843  fromsqlfuncid = LookupFuncNameTypeNames(stmt->fromsql->funcname, stmt->fromsql->funcargs, false);
1844 
1845  if (!pg_proc_ownercheck(fromsqlfuncid, GetUserId()))
1847 
1848  aclresult = pg_proc_aclcheck(fromsqlfuncid, GetUserId(), ACL_EXECUTE);
1849  if (aclresult != ACLCHECK_OK)
1851 
1852  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(fromsqlfuncid));
1853  if (!HeapTupleIsValid(tuple))
1854  elog(ERROR, "cache lookup failed for function %u", fromsqlfuncid);
1855  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1856  if (procstruct->prorettype != INTERNALOID)
1857  ereport(ERROR,
1858  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1859  errmsg("return data type of FROM SQL function must be \"internal\"")));
1860  check_transform_function(procstruct);
1861  ReleaseSysCache(tuple);
1862  }
1863  else
1864  fromsqlfuncid = InvalidOid;
1865 
1866  if (stmt->tosql)
1867  {
1868  tosqlfuncid = LookupFuncNameTypeNames(stmt->tosql->funcname, stmt->tosql->funcargs, false);
1869 
1870  if (!pg_proc_ownercheck(tosqlfuncid, GetUserId()))
1872 
1873  aclresult = pg_proc_aclcheck(tosqlfuncid, GetUserId(), ACL_EXECUTE);
1874  if (aclresult != ACLCHECK_OK)
1876 
1877  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(tosqlfuncid));
1878  if (!HeapTupleIsValid(tuple))
1879  elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
1880  procstruct = (Form_pg_proc) GETSTRUCT(tuple);
1881  if (procstruct->prorettype != typeid)
1882  ereport(ERROR,
1883  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1884  errmsg("return data type of TO SQL function must be the transform data type")));
1885  check_transform_function(procstruct);
1886  ReleaseSysCache(tuple);
1887  }
1888  else
1889  tosqlfuncid = InvalidOid;
1890 
1891  /*
1892  * Ready to go
1893  */
1894  values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
1895  values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
1896  values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
1897  values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
1898 
1899  MemSet(nulls, false, sizeof(nulls));
1900 
1902 
1903  tuple = SearchSysCache2(TRFTYPELANG,
1904  ObjectIdGetDatum(typeid),
1905  ObjectIdGetDatum(langid));
1906  if (HeapTupleIsValid(tuple))
1907  {
1908  if (!stmt->replace)
1909  ereport(ERROR,
1911  errmsg("transform for type %s language \"%s\" already exists",
1912  format_type_be(typeid),
1913  stmt->lang)));
1914 
1915  MemSet(replaces, false, sizeof(replaces));
1916  replaces[Anum_pg_transform_trffromsql - 1] = true;
1917  replaces[Anum_pg_transform_trftosql - 1] = true;
1918 
1919  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values, nulls, replaces);
1920  simple_heap_update(relation, &newtuple->t_self, newtuple);
1921 
1922  transformid = HeapTupleGetOid(tuple);
1923  ReleaseSysCache(tuple);
1924  is_replace = true;
1925  }
1926  else
1927  {
1928  newtuple = heap_form_tuple(RelationGetDescr(relation), values, nulls);
1929  transformid = simple_heap_insert(relation, newtuple);
1930  is_replace = false;
1931  }
1932 
1933  CatalogUpdateIndexes(relation, newtuple);
1934 
1935  if (is_replace)
1936  deleteDependencyRecordsFor(TransformRelationId, transformid, true);
1937 
1938  /* make dependency entries */
1939  myself.classId = TransformRelationId;
1940  myself.objectId = transformid;
1941  myself.objectSubId = 0;
1942 
1943  /* dependency on language */
1944  referenced.classId = LanguageRelationId;
1945  referenced.objectId = langid;
1946  referenced.objectSubId = 0;
1947  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1948 
1949  /* dependency on type */
1950  referenced.classId = TypeRelationId;
1951  referenced.objectId = typeid;
1952  referenced.objectSubId = 0;
1953  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1954 
1955  /* dependencies on functions */
1956  if (OidIsValid(fromsqlfuncid))
1957  {
1958  referenced.classId = ProcedureRelationId;
1959  referenced.objectId = fromsqlfuncid;
1960  referenced.objectSubId = 0;
1961  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1962  }
1963  if (OidIsValid(tosqlfuncid))
1964  {
1965  referenced.classId = ProcedureRelationId;
1966  referenced.objectId = tosqlfuncid;
1967  referenced.objectSubId = 0;
1968  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1969  }
1970 
1971  /* dependency on extension */
1972  recordDependencyOnCurrentExtension(&myself, is_replace);
1973 
1974  /* Post creation hook for new transform */
1976 
1977  heap_freetuple(newtuple);
1978 
1979  heap_close(relation, RowExclusiveLock);
1980 
1981  return myself;
1982 }
1983 
1984 
1985 /*
1986  * get_transform_oid - given type OID and language OID, look up a transform OID
1987  *
1988  * If missing_ok is false, throw an error if the transform is not found. If
1989  * true, just return InvalidOid.
1990  */
1991 Oid
1992 get_transform_oid(Oid type_id, Oid lang_id, bool missing_ok)
1993 {
1994  Oid oid;
1995 
1997  ObjectIdGetDatum(type_id),
1998  ObjectIdGetDatum(lang_id));
1999  if (!OidIsValid(oid) && !missing_ok)
2000  ereport(ERROR,
2001  (errcode(ERRCODE_UNDEFINED_OBJECT),
2002  errmsg("transform for type %s language \"%s\" does not exist",
2003  format_type_be(type_id),
2004  get_language_name(lang_id, false))));
2005  return oid;
2006 }
2007 
2008 
2009 void
2010 DropTransformById(Oid transformOid)
2011 {
2012  Relation relation;
2013  ScanKeyData scankey;
2014  SysScanDesc scan;
2015  HeapTuple tuple;
2016 
2018 
2019  ScanKeyInit(&scankey,
2021  BTEqualStrategyNumber, F_OIDEQ,
2022  ObjectIdGetDatum(transformOid));
2023  scan = systable_beginscan(relation, TransformOidIndexId, true,
2024  NULL, 1, &scankey);
2025 
2026  tuple = systable_getnext(scan);
2027  if (!HeapTupleIsValid(tuple))
2028  elog(ERROR, "could not find tuple for transform %u", transformOid);
2029  simple_heap_delete(relation, &tuple->t_self);
2030 
2031  systable_endscan(scan);
2032  heap_close(relation, RowExclusiveLock);
2033 }
2034 
2035 
2036 /*
2037  * Subroutine for ALTER FUNCTION/AGGREGATE SET SCHEMA/RENAME
2038  *
2039  * Is there a function with the given name and signature already in the given
2040  * namespace? If so, raise an appropriate error message.
2041  */
2042 void
2043 IsThereFunctionInNamespace(const char *proname, int pronargs,
2044  oidvector *proargtypes, Oid nspOid)
2045 {
2046  /* check for duplicate name (more friendly than unique-index failure) */
2048  CStringGetDatum(proname),
2049  PointerGetDatum(proargtypes),
2050  ObjectIdGetDatum(nspOid)))
2051  ereport(ERROR,
2052  (errcode(ERRCODE_DUPLICATE_FUNCTION),
2053  errmsg("function %s already exists in schema \"%s\"",
2054  funcname_signature_string(proname, pronargs,
2055  NIL, proargtypes->values),
2056  get_namespace_name(nspOid))));
2057 }
2058 
2059 /*
2060  * ExecuteDoStmt
2061  * Execute inline procedural-language code
2062  */
2063 void
2065 {
2067  ListCell *arg;
2068  DefElem *as_item = NULL;
2069  DefElem *language_item = NULL;
2070  char *language;
2071  Oid laninline;
2072  HeapTuple languageTuple;
2073  Form_pg_language languageStruct;
2074 
2075  /* Process options we got from gram.y */
2076  foreach(arg, stmt->args)
2077  {
2078  DefElem *defel = (DefElem *) lfirst(arg);
2079 
2080  if (strcmp(defel->defname, "as") == 0)
2081  {
2082  if (as_item)
2083  ereport(ERROR,
2084  (errcode(ERRCODE_SYNTAX_ERROR),
2085  errmsg("conflicting or redundant options")));
2086  as_item = defel;
2087  }
2088  else if (strcmp(defel->defname, "language") == 0)
2089  {
2090  if (language_item)
2091  ereport(ERROR,
2092  (errcode(ERRCODE_SYNTAX_ERROR),
2093  errmsg("conflicting or redundant options")));
2094  language_item = defel;
2095  }
2096  else
2097  elog(ERROR, "option \"%s\" not recognized",
2098  defel->defname);
2099  }
2100 
2101  if (as_item)
2102  codeblock->source_text = strVal(as_item->arg);
2103  else
2104  ereport(ERROR,
2105  (errcode(ERRCODE_SYNTAX_ERROR),
2106  errmsg("no inline code specified")));
2107 
2108  /* if LANGUAGE option wasn't specified, use the default */
2109  if (language_item)
2110  language = strVal(language_item->arg);
2111  else
2112  language = "plpgsql";
2113 
2114  /* Look up the language and validate permissions */
2115  languageTuple = SearchSysCache1(LANGNAME, PointerGetDatum(language));
2116  if (!HeapTupleIsValid(languageTuple))
2117  ereport(ERROR,
2118  (errcode(ERRCODE_UNDEFINED_OBJECT),
2119  errmsg("language \"%s\" does not exist", language),
2120  (PLTemplateExists(language) ?
2121  errhint("Use CREATE LANGUAGE to load the language into the database.") : 0)));
2122 
2123  codeblock->langOid = HeapTupleGetOid(languageTuple);
2124  languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
2125  codeblock->langIsTrusted = languageStruct->lanpltrusted;
2126 
2127  if (languageStruct->lanpltrusted)
2128  {
2129  /* if trusted language, need USAGE privilege */
2130  AclResult aclresult;
2131 
2132  aclresult = pg_language_aclcheck(codeblock->langOid, GetUserId(),
2133  ACL_USAGE);
2134  if (aclresult != ACLCHECK_OK)
2135  aclcheck_error(aclresult, ACL_KIND_LANGUAGE,
2136  NameStr(languageStruct->lanname));
2137  }
2138  else
2139  {
2140  /* if untrusted language, must be superuser */
2141  if (!superuser())
2143  NameStr(languageStruct->lanname));
2144  }
2145 
2146  /* get the handler function's OID */
2147  laninline = languageStruct->laninline;
2148  if (!OidIsValid(laninline))
2149  ereport(ERROR,
2150  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2151  errmsg("language \"%s\" does not support inline code execution",
2152  NameStr(languageStruct->lanname))));
2153 
2154  ReleaseSysCache(languageTuple);
2155 
2156  /* execute the inline handler */
2157  OidFunctionCall1(laninline, PointerGetDatum(codeblock));
2158 }
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:2986
#define IsA(nodeptr, _type_)
Definition: nodes.h:543
ArrayType * GUCArrayAdd(ArrayType *array, const char *name, const char *value)
Definition: guc.c:9348
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
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5330
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
List * names
Definition: parsenodes.h:191
VariableSetKind kind
Definition: parsenodes.h:1719
char * get_language_name(Oid langoid, bool missing_ok)
Definition: lsyscache.c:986
#define TransformRelationId
Definition: pg_transform.h:25
#define INTERNALlanguageId
Definition: pg_language.h:74
#define RelationGetDescr(relation)
Definition: rel.h:383
Oid GetUserId(void)
Definition: miscinit.c:282
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
void DropTransformById(Oid transformOid)
#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:2805
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:1629
#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:141
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:193
Oid get_language_oid(const char *langname, bool missing_ok)
Definition: proclang.c:555
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:492
#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:849
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
#define PROPARALLEL_RESTRICTED
Definition: pg_proc.h:5340
FuncWithArgs * func
Definition: parsenodes.h:2988
FuncWithArgs * tosql
Definition: parsenodes.h:3004
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:1306
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:4561
#define TypeRelationId
Definition: pg_type.h:34
FuncWithArgs * func
Definition: parsenodes.h:2495
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:530
#define Anum_pg_transform_trftosql
Definition: pg_transform.h:45
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4473
AclResult pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4447
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:141
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition: aclchk.c:3450
#define GetSysCacheOid2(cacheId, key1, key2)
Definition: syscache.h:170
#define AggregateRelationId
Definition: pg_aggregate.h:53
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
FuncWithArgs * fromsql
Definition: parsenodes.h:3003
#define Natts_pg_cast
Definition: pg_cast.h:77
void assign_expr_collations(ParseState *pstate, Node *expr)
static void compute_attributes_sql_style(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:612
#define Anum_pg_cast_castsource
Definition: pg_cast.h:78
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:73
#define SearchSysCacheExists3(cacheId, key1, key2, key3)
Definition: syscache.h:163
#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:5331
ObjectAddress CreateFunction(CreateFunctionStmt *stmt, const char *queryString)
Definition: functioncmds.c:861
bool setof
Definition: parsenodes.h:193
ItemPointerData t_self
Definition: htup.h:65
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:586
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:3392
CoercionContext context
Definition: parsenodes.h:2989
#define RowExclusiveLock
Definition: lockdefs.h:38
static void compute_attributes_with_style(List *parameters, bool *isStrict_p, char *volatility_p)
Definition: functioncmds.c:766
#define CastOidIndexId
Definition: indexing.h:101
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
ObjectAddress AlterFunction(AlterFunctionStmt *stmt)
#define TransformOidIndexId
Definition: indexing.h:226
const char * funcname_signature_string(const char *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1848
Oid LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
Definition: parse_func.c:1936
#define ACL_USAGE
Definition: parsenodes.h:71
#define RECORDOID
Definition: pg_type.h:668
TypeName * argType
Definition: parsenodes.h:2487
const char * p_sourcetext
Definition: parse_node.h:134
#define PROPARALLEL_SAFE
Definition: pg_proc.h:5339
void interpret_function_parameter_list(List *parameters, Oid languageOid, bool is_aggregate, const char *queryString, oidvector **parameterTypes, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:180
#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:538
#define PROPARALLEL_UNSAFE
Definition: pg_proc.h:5341
Node * arg
Definition: parsenodes.h:666
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5332
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:2912
ArrayType * GUCArrayDelete(ArrayType *array, const char *name)
Definition: guc.c:9428
#define ANYARRAYOID
Definition: pg_type.h:676
void * palloc0(Size size)
Definition: mcxt.c:923
AclResult
Definition: acl.h:169
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
static ArrayType * update_proconfig_value(ArrayType *a, List *set_items)
Definition: functioncmds.c:581
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1152
Oid simple_heap_insert(Relation relation, HeapTuple tup)
Definition: heapam.c:2914
List * typmods
Definition: parsenodes.h:195
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1286
void SetFunctionReturnType(Oid funcOid, Oid newRetType)
bool PLTemplateExists(const char *languageName)
Definition: proclang.c:521
#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:70
#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:540
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:164
#define lfirst(lc)
Definition: pg_list.h:106
TypeName * returnType
Definition: parsenodes.h:2468
void CatalogUpdateIndexes(Relation heapRel, HeapTuple heapTuple)
Definition: indexing.c:157
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:141
static int list_length(const List *l)
Definition: pg_list.h:89
void simple_heap_delete(Relation relation, ItemPointer tid)
Definition: heapam.c:3373
void simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
Definition: heapam.c:4411
#define CastRelationId
Definition: pg_cast.h:31
#define BOOLOID
Definition: pg_type.h:288
List * args
Definition: parsenodes.h:2508
#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:3001
static Datum values[MAXATTR]
Definition: bootstrap.c:160
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2525
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:150
#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:894
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ACL_EXECUTE
Definition: parsenodes.h:70
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4435
int i
TypeName * targettype
Definition: parsenodes.h:2987
#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:806
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:2514
char * defname
Definition: parsenodes.h:665
#define LanguageRelationId
Definition: pg_language.h:29
void DropCastById(Oid castOid)
List * funcname
Definition: parsenodes.h:1628
#define elog
Definition: elog.h:218
FunctionParameterMode mode
Definition: parsenodes.h:2488
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4523
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:74
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:791
char * ExtractSetVariableArgs(VariableSetStmt *stmt)
Definition: guc.c:7306
static bool compute_common_attribute(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:461
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
Definition: pg_list.h:45
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool pg_proc_ownercheck(Oid proc_oid, Oid roleid)
Definition: aclchk.c:4613
#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:556
List * p_rtable
Definition: parse_node.h:135
#define DatumGetArrayTypeP(X)
Definition: array.h:242
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:143