PostgreSQL Source Code  git master
parse_coerce.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_coerce.c
4  * handle type coercions/conversions for parser
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/parser/parse_coerce.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_class.h"
19 #include "catalog/pg_inherits.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/nodeFuncs.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/datum.h" /* needed for datumIsEqual() */
29 #include "utils/fmgroids.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/typcache.h"
33 
34 
35 static Node *coerce_type_typmod(Node *node,
36  Oid targetTypeId, int32 targetTypMod,
37  CoercionContext ccontext, CoercionForm cformat,
38  int location,
39  bool hideInputCoercion);
40 static void hide_coercion_node(Node *node);
41 static Node *build_coercion_expression(Node *node,
42  CoercionPathType pathtype,
43  Oid funcId,
44  Oid targetTypeId, int32 targetTypMod,
45  CoercionContext ccontext, CoercionForm cformat,
46  int location);
47 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
48  Oid targetTypeId,
49  CoercionContext ccontext,
50  CoercionForm cformat,
51  int location);
52 static bool is_complex_array(Oid typid);
53 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
54 
55 
56 /*
57  * coerce_to_target_type()
58  * Convert an expression to a target type and typmod.
59  *
60  * This is the general-purpose entry point for arbitrary type coercion
61  * operations. Direct use of the component operations can_coerce_type,
62  * coerce_type, and coerce_type_typmod should be restricted to special
63  * cases (eg, when the conversion is expected to succeed).
64  *
65  * Returns the possibly-transformed expression tree, or NULL if the type
66  * conversion is not possible. (We do this, rather than ereport'ing directly,
67  * so that callers can generate custom error messages indicating context.)
68  *
69  * pstate - parse state (can be NULL, see coerce_type)
70  * expr - input expression tree (already transformed by transformExpr)
71  * exprtype - result type of expr
72  * targettype - desired result type
73  * targettypmod - desired result typmod
74  * ccontext, cformat - context indicators to control coercions
75  * location - parse location of the coercion request, or -1 if unknown/implicit
76  */
77 Node *
78 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
79  Oid targettype, int32 targettypmod,
80  CoercionContext ccontext,
81  CoercionForm cformat,
82  int location)
83 {
84  Node *result;
85  Node *origexpr;
86 
87  if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
88  return NULL;
89 
90  /*
91  * If the input has a CollateExpr at the top, strip it off, perform the
92  * coercion, and put a new one back on. This is annoying since it
93  * duplicates logic in coerce_type, but if we don't do this then it's too
94  * hard to tell whether coerce_type actually changed anything, and we
95  * *must* know that to avoid possibly calling hide_coercion_node on
96  * something that wasn't generated by coerce_type. Note that if there are
97  * multiple stacked CollateExprs, we just discard all but the topmost.
98  */
99  origexpr = expr;
100  while (expr && IsA(expr, CollateExpr))
101  expr = (Node *) ((CollateExpr *) expr)->arg;
102 
103  result = coerce_type(pstate, expr, exprtype,
104  targettype, targettypmod,
105  ccontext, cformat, location);
106 
107  /*
108  * If the target is a fixed-length type, it may need a length coercion as
109  * well as a type coercion. If we find ourselves adding both, force the
110  * inner coercion node to implicit display form.
111  */
112  result = coerce_type_typmod(result,
113  targettype, targettypmod,
114  ccontext, cformat, location,
115  (result != expr && !IsA(result, Const)));
116 
117  if (expr != origexpr)
118  {
119  /* Reinstall top CollateExpr */
120  CollateExpr *coll = (CollateExpr *) origexpr;
121  CollateExpr *newcoll = makeNode(CollateExpr);
122 
123  newcoll->arg = (Expr *) result;
124  newcoll->collOid = coll->collOid;
125  newcoll->location = coll->location;
126  result = (Node *) newcoll;
127  }
128 
129  return result;
130 }
131 
132 
133 /*
134  * coerce_type()
135  * Convert an expression to a different type.
136  *
137  * The caller should already have determined that the coercion is possible;
138  * see can_coerce_type.
139  *
140  * Normally, no coercion to a typmod (length) is performed here. The caller
141  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
142  * (But if the target type is a domain, it may internally contain a
143  * typmod constraint, which will be applied inside coerce_to_domain.)
144  * In some cases pg_cast specifies a type coercion function that also
145  * applies length conversion, and in those cases only, the result will
146  * already be properly coerced to the specified typmod.
147  *
148  * pstate is only used in the case that we are able to resolve the type of
149  * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
150  * caller does not want type information updated for Params.
151  *
152  * Note: this function must not modify the given expression tree, only add
153  * decoration on top of it. See transformSetOperationTree, for example.
154  */
155 Node *
156 coerce_type(ParseState *pstate, Node *node,
157  Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
158  CoercionContext ccontext, CoercionForm cformat, int location)
159 {
160  Node *result;
161  CoercionPathType pathtype;
162  Oid funcId;
163 
164  if (targetTypeId == inputTypeId ||
165  node == NULL)
166  {
167  /* no conversion needed */
168  return node;
169  }
170  if (targetTypeId == ANYOID ||
171  targetTypeId == ANYELEMENTOID ||
172  targetTypeId == ANYNONARRAYOID ||
173  targetTypeId == ANYCOMPATIBLEOID ||
174  targetTypeId == ANYCOMPATIBLENONARRAYOID)
175  {
176  /*
177  * Assume can_coerce_type verified that implicit coercion is okay.
178  *
179  * Note: by returning the unmodified node here, we are saying that
180  * it's OK to treat an UNKNOWN constant as a valid input for a
181  * function accepting one of these pseudotypes. This should be all
182  * right, since an UNKNOWN value is still a perfectly valid Datum.
183  *
184  * NB: we do NOT want a RelabelType here: the exposed type of the
185  * function argument must be its actual type, not the polymorphic
186  * pseudotype.
187  */
188  return node;
189  }
190  if (targetTypeId == ANYARRAYOID ||
191  targetTypeId == ANYENUMOID ||
192  targetTypeId == ANYRANGEOID ||
193  targetTypeId == ANYMULTIRANGEOID ||
194  targetTypeId == ANYCOMPATIBLEARRAYOID ||
195  targetTypeId == ANYCOMPATIBLERANGEOID ||
196  targetTypeId == ANYCOMPATIBLEMULTIRANGEOID)
197  {
198  /*
199  * Assume can_coerce_type verified that implicit coercion is okay.
200  *
201  * These cases are unlike the ones above because the exposed type of
202  * the argument must be an actual array, enum, range, or multirange
203  * type. In particular the argument must *not* be an UNKNOWN
204  * constant. If it is, we just fall through; below, we'll call the
205  * pseudotype's input function, which will produce an error. Also, if
206  * what we have is a domain over array, enum, range, or multirange, we
207  * have to relabel it to its base type.
208  *
209  * Note: currently, we can't actually see a domain-over-enum here,
210  * since the other functions in this file will not match such a
211  * parameter to ANYENUM. But that should get changed eventually.
212  */
213  if (inputTypeId != UNKNOWNOID)
214  {
215  Oid baseTypeId = getBaseType(inputTypeId);
216 
217  if (baseTypeId != inputTypeId)
218  {
219  RelabelType *r = makeRelabelType((Expr *) node,
220  baseTypeId, -1,
221  InvalidOid,
222  cformat);
223 
224  r->location = location;
225  return (Node *) r;
226  }
227  /* Not a domain type, so return it as-is */
228  return node;
229  }
230  }
231  if (inputTypeId == UNKNOWNOID && IsA(node, Const))
232  {
233  /*
234  * Input is a string constant with previously undetermined type. Apply
235  * the target type's typinput function to it to produce a constant of
236  * the target type.
237  *
238  * NOTE: this case cannot be folded together with the other
239  * constant-input case, since the typinput function does not
240  * necessarily behave the same as a type conversion function. For
241  * example, int4's typinput function will reject "1.2", whereas
242  * float-to-int type conversion will round to integer.
243  *
244  * XXX if the typinput function is not immutable, we really ought to
245  * postpone evaluation of the function call until runtime. But there
246  * is no way to represent a typinput function call as an expression
247  * tree, because C-string values are not Datums. (XXX This *is*
248  * possible as of 7.3, do we want to do it?)
249  */
250  Const *con = (Const *) node;
251  Const *newcon = makeNode(Const);
252  Oid baseTypeId;
253  int32 baseTypeMod;
254  int32 inputTypeMod;
255  Type baseType;
256  ParseCallbackState pcbstate;
257 
258  /*
259  * If the target type is a domain, we want to call its base type's
260  * input routine, not domain_in(). This is to avoid premature failure
261  * when the domain applies a typmod: existing input routines follow
262  * implicit-coercion semantics for length checks, which is not always
263  * what we want here. The needed check will be applied properly
264  * inside coerce_to_domain().
265  */
266  baseTypeMod = targetTypeMod;
267  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
268 
269  /*
270  * For most types we pass typmod -1 to the input routine, because
271  * existing input routines follow implicit-coercion semantics for
272  * length checks, which is not always what we want here. Any length
273  * constraint will be applied later by our caller. An exception
274  * however is the INTERVAL type, for which we *must* pass the typmod
275  * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
276  * as sin, but so is this part of the spec...)
277  */
278  if (baseTypeId == INTERVALOID)
279  inputTypeMod = baseTypeMod;
280  else
281  inputTypeMod = -1;
282 
283  baseType = typeidType(baseTypeId);
284 
285  newcon->consttype = baseTypeId;
286  newcon->consttypmod = inputTypeMod;
287  newcon->constcollid = typeTypeCollation(baseType);
288  newcon->constlen = typeLen(baseType);
289  newcon->constbyval = typeByVal(baseType);
290  newcon->constisnull = con->constisnull;
291 
292  /*
293  * We use the original literal's location regardless of the position
294  * of the coercion. This is a change from pre-9.2 behavior, meant to
295  * simplify life for pg_stat_statements.
296  */
297  newcon->location = con->location;
298 
299  /*
300  * Set up to point at the constant's text if the input routine throws
301  * an error.
302  */
303  setup_parser_errposition_callback(&pcbstate, pstate, con->location);
304 
305  /*
306  * We assume here that UNKNOWN's internal representation is the same
307  * as CSTRING.
308  */
309  if (!con->constisnull)
310  newcon->constvalue = stringTypeDatum(baseType,
312  inputTypeMod);
313  else
314  newcon->constvalue = stringTypeDatum(baseType,
315  NULL,
316  inputTypeMod);
317 
318  /*
319  * If it's a varlena value, force it to be in non-expanded
320  * (non-toasted) format; this avoids any possible dependency on
321  * external values and improves consistency of representation.
322  */
323  if (!con->constisnull && newcon->constlen == -1)
324  newcon->constvalue =
326 
327 #ifdef RANDOMIZE_ALLOCATED_MEMORY
328 
329  /*
330  * For pass-by-reference data types, repeat the conversion to see if
331  * the input function leaves any uninitialized bytes in the result. We
332  * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
333  * enabled, so we don't bother testing otherwise. The reason we don't
334  * want any instability in the input function is that comparison of
335  * Const nodes relies on bytewise comparison of the datums, so if the
336  * input function leaves garbage then subexpressions that should be
337  * identical may not get recognized as such. See pgsql-hackers
338  * discussion of 2008-04-04.
339  */
340  if (!con->constisnull && !newcon->constbyval)
341  {
342  Datum val2;
343 
344  val2 = stringTypeDatum(baseType,
346  inputTypeMod);
347  if (newcon->constlen == -1)
348  val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
349  if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
350  elog(WARNING, "type %s has unstable input conversion for \"%s\"",
351  typeTypeName(baseType), DatumGetCString(con->constvalue));
352  }
353 #endif
354 
356 
357  result = (Node *) newcon;
358 
359  /* If target is a domain, apply constraints. */
360  if (baseTypeId != targetTypeId)
361  result = coerce_to_domain(result,
362  baseTypeId, baseTypeMod,
363  targetTypeId,
364  ccontext, cformat, location,
365  false);
366 
367  ReleaseSysCache(baseType);
368 
369  return result;
370  }
371  if (IsA(node, Param) &&
372  pstate != NULL && pstate->p_coerce_param_hook != NULL)
373  {
374  /*
375  * Allow the CoerceParamHook to decide what happens. It can return a
376  * transformed node (very possibly the same Param node), or return
377  * NULL to indicate we should proceed with normal coercion.
378  */
379  result = pstate->p_coerce_param_hook(pstate,
380  (Param *) node,
381  targetTypeId,
382  targetTypeMod,
383  location);
384  if (result)
385  return result;
386  }
387  if (IsA(node, CollateExpr))
388  {
389  /*
390  * If we have a COLLATE clause, we have to push the coercion
391  * underneath the COLLATE. This is really ugly, but there is little
392  * choice because the above hacks on Consts and Params wouldn't happen
393  * otherwise. This kluge has consequences in coerce_to_target_type.
394  */
395  CollateExpr *coll = (CollateExpr *) node;
396  CollateExpr *newcoll = makeNode(CollateExpr);
397 
398  newcoll->arg = (Expr *)
399  coerce_type(pstate, (Node *) coll->arg,
400  inputTypeId, targetTypeId, targetTypeMod,
401  ccontext, cformat, location);
402  newcoll->collOid = coll->collOid;
403  newcoll->location = coll->location;
404  return (Node *) newcoll;
405  }
406  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
407  &funcId);
408  if (pathtype != COERCION_PATH_NONE)
409  {
410  if (pathtype != COERCION_PATH_RELABELTYPE)
411  {
412  /*
413  * Generate an expression tree representing run-time application
414  * of the conversion function. If we are dealing with a domain
415  * target type, the conversion function will yield the base type,
416  * and we need to extract the correct typmod to use from the
417  * domain's typtypmod.
418  */
419  Oid baseTypeId;
420  int32 baseTypeMod;
421 
422  baseTypeMod = targetTypeMod;
423  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
424 
425  result = build_coercion_expression(node, pathtype, funcId,
426  baseTypeId, baseTypeMod,
427  ccontext, cformat, location);
428 
429  /*
430  * If domain, coerce to the domain type and relabel with domain
431  * type ID, hiding the previous coercion node.
432  */
433  if (targetTypeId != baseTypeId)
434  result = coerce_to_domain(result, baseTypeId, baseTypeMod,
435  targetTypeId,
436  ccontext, cformat, location,
437  true);
438  }
439  else
440  {
441  /*
442  * We don't need to do a physical conversion, but we do need to
443  * attach a RelabelType node so that the expression will be seen
444  * to have the intended type when inspected by higher-level code.
445  *
446  * Also, domains may have value restrictions beyond the base type
447  * that must be accounted for. If the destination is a domain
448  * then we won't need a RelabelType node.
449  */
450  result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
451  ccontext, cformat, location,
452  false);
453  if (result == node)
454  {
455  /*
456  * XXX could we label result with exprTypmod(node) instead of
457  * default -1 typmod, to save a possible length-coercion
458  * later? Would work if both types have same interpretation of
459  * typmod, which is likely but not certain.
460  */
461  RelabelType *r = makeRelabelType((Expr *) result,
462  targetTypeId, -1,
463  InvalidOid,
464  cformat);
465 
466  r->location = location;
467  result = (Node *) r;
468  }
469  }
470  return result;
471  }
472  if (inputTypeId == RECORDOID &&
473  ISCOMPLEX(targetTypeId))
474  {
475  /* Coerce a RECORD to a specific complex type */
476  return coerce_record_to_complex(pstate, node, targetTypeId,
477  ccontext, cformat, location);
478  }
479  if (targetTypeId == RECORDOID &&
480  ISCOMPLEX(inputTypeId))
481  {
482  /* Coerce a specific complex type to RECORD */
483  /* NB: we do NOT want a RelabelType here */
484  return node;
485  }
486 #ifdef NOT_USED
487  if (inputTypeId == RECORDARRAYOID &&
488  is_complex_array(targetTypeId))
489  {
490  /* Coerce record[] to a specific complex array type */
491  /* not implemented yet ... */
492  }
493 #endif
494  if (targetTypeId == RECORDARRAYOID &&
495  is_complex_array(inputTypeId))
496  {
497  /* Coerce a specific complex array type to record[] */
498  /* NB: we do NOT want a RelabelType here */
499  return node;
500  }
501  if (typeInheritsFrom(inputTypeId, targetTypeId)
502  || typeIsOfTypedTable(inputTypeId, targetTypeId))
503  {
504  /*
505  * Input class type is a subclass of target, so generate an
506  * appropriate runtime conversion (removing unneeded columns and
507  * possibly rearranging the ones that are wanted).
508  *
509  * We will also get here when the input is a domain over a subclass of
510  * the target type. To keep life simple for the executor, we define
511  * ConvertRowtypeExpr as only working between regular composite types;
512  * therefore, in such cases insert a RelabelType to smash the input
513  * expression down to its base type.
514  */
515  Oid baseTypeId = getBaseType(inputTypeId);
517 
518  if (baseTypeId != inputTypeId)
519  {
520  RelabelType *rt = makeRelabelType((Expr *) node,
521  baseTypeId, -1,
522  InvalidOid,
524 
525  rt->location = location;
526  node = (Node *) rt;
527  }
528  r->arg = (Expr *) node;
529  r->resulttype = targetTypeId;
530  r->convertformat = cformat;
531  r->location = location;
532  return (Node *) r;
533  }
534  /* If we get here, caller blew it */
535  elog(ERROR, "failed to find conversion function from %s to %s",
536  format_type_be(inputTypeId), format_type_be(targetTypeId));
537  return NULL; /* keep compiler quiet */
538 }
539 
540 
541 /*
542  * can_coerce_type()
543  * Can input_typeids be coerced to target_typeids?
544  *
545  * We must be told the context (CAST construct, assignment, implicit coercion)
546  * as this determines the set of available casts.
547  */
548 bool
549 can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids,
550  CoercionContext ccontext)
551 {
552  bool have_generics = false;
553  int i;
554 
555  /* run through argument list... */
556  for (i = 0; i < nargs; i++)
557  {
558  Oid inputTypeId = input_typeids[i];
559  Oid targetTypeId = target_typeids[i];
560  CoercionPathType pathtype;
561  Oid funcId;
562 
563  /* no problem if same type */
564  if (inputTypeId == targetTypeId)
565  continue;
566 
567  /* accept if target is ANY */
568  if (targetTypeId == ANYOID)
569  continue;
570 
571  /* accept if target is polymorphic, for now */
572  if (IsPolymorphicType(targetTypeId))
573  {
574  have_generics = true; /* do more checking later */
575  continue;
576  }
577 
578  /*
579  * If input is an untyped string constant, assume we can convert it to
580  * anything.
581  */
582  if (inputTypeId == UNKNOWNOID)
583  continue;
584 
585  /*
586  * If pg_cast shows that we can coerce, accept. This test now covers
587  * both binary-compatible and coercion-function cases.
588  */
589  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
590  &funcId);
591  if (pathtype != COERCION_PATH_NONE)
592  continue;
593 
594  /*
595  * If input is RECORD and target is a composite type, assume we can
596  * coerce (may need tighter checking here)
597  */
598  if (inputTypeId == RECORDOID &&
599  ISCOMPLEX(targetTypeId))
600  continue;
601 
602  /*
603  * If input is a composite type and target is RECORD, accept
604  */
605  if (targetTypeId == RECORDOID &&
606  ISCOMPLEX(inputTypeId))
607  continue;
608 
609 #ifdef NOT_USED /* not implemented yet */
610 
611  /*
612  * If input is record[] and target is a composite array type, assume
613  * we can coerce (may need tighter checking here)
614  */
615  if (inputTypeId == RECORDARRAYOID &&
616  is_complex_array(targetTypeId))
617  continue;
618 #endif
619 
620  /*
621  * If input is a composite array type and target is record[], accept
622  */
623  if (targetTypeId == RECORDARRAYOID &&
624  is_complex_array(inputTypeId))
625  continue;
626 
627  /*
628  * If input is a class type that inherits from target, accept
629  */
630  if (typeInheritsFrom(inputTypeId, targetTypeId)
631  || typeIsOfTypedTable(inputTypeId, targetTypeId))
632  continue;
633 
634  /*
635  * Else, cannot coerce at this argument position
636  */
637  return false;
638  }
639 
640  /* If we found any generic argument types, cross-check them */
641  if (have_generics)
642  {
643  if (!check_generic_type_consistency(input_typeids, target_typeids,
644  nargs))
645  return false;
646  }
647 
648  return true;
649 }
650 
651 
652 /*
653  * Create an expression tree to represent coercion to a domain type.
654  *
655  * 'arg': input expression
656  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
657  * has not bothered to look this up)
658  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
659  * has not bothered to look this up)
660  * 'typeId': target type to coerce to
661  * 'ccontext': context indicator to control coercions
662  * 'cformat': coercion display format
663  * 'location': coercion request location
664  * 'hideInputCoercion': if true, hide the input coercion under this one.
665  *
666  * If the target type isn't a domain, the given 'arg' is returned as-is.
667  */
668 Node *
669 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
670  CoercionContext ccontext, CoercionForm cformat, int location,
671  bool hideInputCoercion)
672 {
673  CoerceToDomain *result;
674 
675  /* Get the base type if it hasn't been supplied */
676  if (baseTypeId == InvalidOid)
677  baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
678 
679  /* If it isn't a domain, return the node as it was passed in */
680  if (baseTypeId == typeId)
681  return arg;
682 
683  /* Suppress display of nested coercion steps */
684  if (hideInputCoercion)
685  hide_coercion_node(arg);
686 
687  /*
688  * If the domain applies a typmod to its base type, build the appropriate
689  * coercion step. Mark it implicit for display purposes, because we don't
690  * want it shown separately by ruleutils.c; but the isExplicit flag passed
691  * to the conversion function depends on the manner in which the domain
692  * coercion is invoked, so that the semantics of implicit and explicit
693  * coercion differ. (Is that really the behavior we want?)
694  *
695  * NOTE: because we apply this as part of the fixed expression structure,
696  * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
697  * would be safe to do anyway, without lots of knowledge about what the
698  * base type thinks the typmod means.
699  */
700  arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
701  ccontext, COERCE_IMPLICIT_CAST, location,
702  false);
703 
704  /*
705  * Now build the domain coercion node. This represents run-time checking
706  * of any constraints currently attached to the domain. This also ensures
707  * that the expression is properly labeled as to result type.
708  */
709  result = makeNode(CoerceToDomain);
710  result->arg = (Expr *) arg;
711  result->resulttype = typeId;
712  result->resulttypmod = -1; /* currently, always -1 for domains */
713  /* resultcollid will be set by parse_collate.c */
714  result->coercionformat = cformat;
715  result->location = location;
716 
717  return (Node *) result;
718 }
719 
720 
721 /*
722  * coerce_type_typmod()
723  * Force a value to a particular typmod, if meaningful and possible.
724  *
725  * This is applied to values that are going to be stored in a relation
726  * (where we have an atttypmod for the column) as well as values being
727  * explicitly CASTed (where the typmod comes from the target type spec).
728  *
729  * The caller must have already ensured that the value is of the correct
730  * type, typically by applying coerce_type.
731  *
732  * ccontext may affect semantics, depending on whether the length coercion
733  * function pays attention to the isExplicit flag it's passed.
734  *
735  * cformat determines the display properties of the generated node (if any).
736  *
737  * If hideInputCoercion is true *and* we generate a node, the input node is
738  * forced to IMPLICIT display form, so that only the typmod coercion node will
739  * be visible when displaying the expression.
740  *
741  * NOTE: this does not need to work on domain types, because any typmod
742  * coercion for a domain is considered to be part of the type coercion
743  * needed to produce the domain value in the first place. So, no getBaseType.
744  */
745 static Node *
746 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
747  CoercionContext ccontext, CoercionForm cformat,
748  int location,
749  bool hideInputCoercion)
750 {
751  CoercionPathType pathtype;
752  Oid funcId;
753 
754  /*
755  * A negative typmod is assumed to mean that no coercion is wanted. Also,
756  * skip coercion if already done.
757  */
758  if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
759  return node;
760 
761  pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
762 
763  if (pathtype != COERCION_PATH_NONE)
764  {
765  /* Suppress display of nested coercion steps */
766  if (hideInputCoercion)
767  hide_coercion_node(node);
768 
769  node = build_coercion_expression(node, pathtype, funcId,
770  targetTypeId, targetTypMod,
771  ccontext, cformat, location);
772  }
773 
774  return node;
775 }
776 
777 /*
778  * Mark a coercion node as IMPLICIT so it will never be displayed by
779  * ruleutils.c. We use this when we generate a nest of coercion nodes
780  * to implement what is logically one conversion; the inner nodes are
781  * forced to IMPLICIT_CAST format. This does not change their semantics,
782  * only display behavior.
783  *
784  * It is caller error to call this on something that doesn't have a
785  * CoercionForm field.
786  */
787 static void
789 {
790  if (IsA(node, FuncExpr))
791  ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
792  else if (IsA(node, RelabelType))
793  ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
794  else if (IsA(node, CoerceViaIO))
795  ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
796  else if (IsA(node, ArrayCoerceExpr))
797  ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
798  else if (IsA(node, ConvertRowtypeExpr))
799  ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
800  else if (IsA(node, RowExpr))
801  ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
802  else if (IsA(node, CoerceToDomain))
803  ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
804  else
805  elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
806 }
807 
808 /*
809  * build_coercion_expression()
810  * Construct an expression tree for applying a pg_cast entry.
811  *
812  * This is used for both type-coercion and length-coercion operations,
813  * since there is no difference in terms of the calling convention.
814  */
815 static Node *
817  CoercionPathType pathtype,
818  Oid funcId,
819  Oid targetTypeId, int32 targetTypMod,
820  CoercionContext ccontext, CoercionForm cformat,
821  int location)
822 {
823  int nargs = 0;
824 
825  if (OidIsValid(funcId))
826  {
827  HeapTuple tp;
828  Form_pg_proc procstruct;
829 
831  if (!HeapTupleIsValid(tp))
832  elog(ERROR, "cache lookup failed for function %u", funcId);
833  procstruct = (Form_pg_proc) GETSTRUCT(tp);
834 
835  /*
836  * These Asserts essentially check that function is a legal coercion
837  * function. We can't make the seemingly obvious tests on prorettype
838  * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
839  * various binary-compatibility cases.
840  */
841  /* Assert(targetTypeId == procstruct->prorettype); */
842  Assert(!procstruct->proretset);
843  Assert(procstruct->prokind == PROKIND_FUNCTION);
844  nargs = procstruct->pronargs;
845  Assert(nargs >= 1 && nargs <= 3);
846  /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
847  Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
848  Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
849 
850  ReleaseSysCache(tp);
851  }
852 
853  if (pathtype == COERCION_PATH_FUNC)
854  {
855  /* We build an ordinary FuncExpr with special arguments */
856  FuncExpr *fexpr;
857  List *args;
858  Const *cons;
859 
860  Assert(OidIsValid(funcId));
861 
862  args = list_make1(node);
863 
864  if (nargs >= 2)
865  {
866  /* Pass target typmod as an int4 constant */
867  cons = makeConst(INT4OID,
868  -1,
869  InvalidOid,
870  sizeof(int32),
871  Int32GetDatum(targetTypMod),
872  false,
873  true);
874 
875  args = lappend(args, cons);
876  }
877 
878  if (nargs == 3)
879  {
880  /* Pass it a boolean isExplicit parameter, too */
881  cons = makeConst(BOOLOID,
882  -1,
883  InvalidOid,
884  sizeof(bool),
885  BoolGetDatum(ccontext == COERCION_EXPLICIT),
886  false,
887  true);
888 
889  args = lappend(args, cons);
890  }
891 
892  fexpr = makeFuncExpr(funcId, targetTypeId, args,
893  InvalidOid, InvalidOid, cformat);
894  fexpr->location = location;
895  return (Node *) fexpr;
896  }
897  else if (pathtype == COERCION_PATH_ARRAYCOERCE)
898  {
899  /* We need to build an ArrayCoerceExpr */
902  Oid sourceBaseTypeId;
903  int32 sourceBaseTypeMod;
904  Oid targetElementType;
905  Node *elemexpr;
906 
907  /*
908  * Look through any domain over the source array type. Note we don't
909  * expect that the target type is a domain; it must be a plain array.
910  * (To get to a domain target type, we'll do coerce_to_domain later.)
911  */
912  sourceBaseTypeMod = exprTypmod(node);
913  sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
914  &sourceBaseTypeMod);
915 
916  /*
917  * Set up a CaseTestExpr representing one element of the source array.
918  * This is an abuse of CaseTestExpr, but it's OK as long as there
919  * can't be any CaseExpr or ArrayCoerceExpr within the completed
920  * elemexpr.
921  */
922  ctest->typeId = get_element_type(sourceBaseTypeId);
923  Assert(OidIsValid(ctest->typeId));
924  ctest->typeMod = sourceBaseTypeMod;
925  ctest->collation = InvalidOid; /* Assume coercions don't care */
926 
927  /* And coerce it to the target element type */
928  targetElementType = get_element_type(targetTypeId);
929  Assert(OidIsValid(targetElementType));
930 
931  elemexpr = coerce_to_target_type(NULL,
932  (Node *) ctest,
933  ctest->typeId,
934  targetElementType,
935  targetTypMod,
936  ccontext,
937  cformat,
938  location);
939  if (elemexpr == NULL) /* shouldn't happen */
940  elog(ERROR, "failed to coerce array element type as expected");
941 
942  acoerce->arg = (Expr *) node;
943  acoerce->elemexpr = (Expr *) elemexpr;
944  acoerce->resulttype = targetTypeId;
945 
946  /*
947  * Label the output as having a particular element typmod only if we
948  * ended up with a per-element expression that is labeled that way.
949  */
950  acoerce->resulttypmod = exprTypmod(elemexpr);
951  /* resultcollid will be set by parse_collate.c */
952  acoerce->coerceformat = cformat;
953  acoerce->location = location;
954 
955  return (Node *) acoerce;
956  }
957  else if (pathtype == COERCION_PATH_COERCEVIAIO)
958  {
959  /* We need to build a CoerceViaIO node */
960  CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
961 
962  Assert(!OidIsValid(funcId));
963 
964  iocoerce->arg = (Expr *) node;
965  iocoerce->resulttype = targetTypeId;
966  /* resultcollid will be set by parse_collate.c */
967  iocoerce->coerceformat = cformat;
968  iocoerce->location = location;
969 
970  return (Node *) iocoerce;
971  }
972  else
973  {
974  elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
975  (int) pathtype);
976  return NULL; /* keep compiler quiet */
977  }
978 }
979 
980 
981 /*
982  * coerce_record_to_complex
983  * Coerce a RECORD to a specific composite type.
984  *
985  * Currently we only support this for inputs that are RowExprs or whole-row
986  * Vars.
987  */
988 static Node *
990  Oid targetTypeId,
991  CoercionContext ccontext,
992  CoercionForm cformat,
993  int location)
994 {
995  RowExpr *rowexpr;
996  Oid baseTypeId;
997  int32 baseTypeMod = -1;
998  TupleDesc tupdesc;
999  List *args = NIL;
1000  List *newargs;
1001  int i;
1002  int ucolno;
1003  ListCell *arg;
1004 
1005  if (node && IsA(node, RowExpr))
1006  {
1007  /*
1008  * Since the RowExpr must be of type RECORD, we needn't worry about it
1009  * containing any dropped columns.
1010  */
1011  args = ((RowExpr *) node)->args;
1012  }
1013  else if (node && IsA(node, Var) &&
1014  ((Var *) node)->varattno == InvalidAttrNumber)
1015  {
1016  int rtindex = ((Var *) node)->varno;
1017  int sublevels_up = ((Var *) node)->varlevelsup;
1018  int vlocation = ((Var *) node)->location;
1019  ParseNamespaceItem *nsitem;
1020 
1021  nsitem = GetNSItemByRangeTablePosn(pstate, rtindex, sublevels_up);
1022  args = expandNSItemVars(nsitem, sublevels_up, vlocation, NULL);
1023  }
1024  else
1025  ereport(ERROR,
1026  (errcode(ERRCODE_CANNOT_COERCE),
1027  errmsg("cannot cast type %s to %s",
1028  format_type_be(RECORDOID),
1029  format_type_be(targetTypeId)),
1030  parser_coercion_errposition(pstate, location, node)));
1031 
1032  /*
1033  * Look up the composite type, accounting for possibility that what we are
1034  * given is a domain over composite.
1035  */
1036  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
1037  tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
1038 
1039  /* Process the fields */
1040  newargs = NIL;
1041  ucolno = 1;
1042  arg = list_head(args);
1043  for (i = 0; i < tupdesc->natts; i++)
1044  {
1045  Node *expr;
1046  Node *cexpr;
1047  Oid exprtype;
1048  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1049 
1050  /* Fill in NULLs for dropped columns in rowtype */
1051  if (attr->attisdropped)
1052  {
1053  /*
1054  * can't use atttypid here, but it doesn't really matter what type
1055  * the Const claims to be.
1056  */
1057  newargs = lappend(newargs,
1058  makeNullConst(INT4OID, -1, InvalidOid));
1059  continue;
1060  }
1061 
1062  if (arg == NULL)
1063  ereport(ERROR,
1064  (errcode(ERRCODE_CANNOT_COERCE),
1065  errmsg("cannot cast type %s to %s",
1066  format_type_be(RECORDOID),
1067  format_type_be(targetTypeId)),
1068  errdetail("Input has too few columns."),
1069  parser_coercion_errposition(pstate, location, node)));
1070  expr = (Node *) lfirst(arg);
1071  exprtype = exprType(expr);
1072 
1073  cexpr = coerce_to_target_type(pstate,
1074  expr, exprtype,
1075  attr->atttypid,
1076  attr->atttypmod,
1077  ccontext,
1079  -1);
1080  if (cexpr == NULL)
1081  ereport(ERROR,
1082  (errcode(ERRCODE_CANNOT_COERCE),
1083  errmsg("cannot cast type %s to %s",
1084  format_type_be(RECORDOID),
1085  format_type_be(targetTypeId)),
1086  errdetail("Cannot cast type %s to %s in column %d.",
1087  format_type_be(exprtype),
1088  format_type_be(attr->atttypid),
1089  ucolno),
1090  parser_coercion_errposition(pstate, location, expr)));
1091  newargs = lappend(newargs, cexpr);
1092  ucolno++;
1093  arg = lnext(args, arg);
1094  }
1095  if (arg != NULL)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_CANNOT_COERCE),
1098  errmsg("cannot cast type %s to %s",
1099  format_type_be(RECORDOID),
1100  format_type_be(targetTypeId)),
1101  errdetail("Input has too many columns."),
1102  parser_coercion_errposition(pstate, location, node)));
1103 
1104  ReleaseTupleDesc(tupdesc);
1105 
1106  rowexpr = makeNode(RowExpr);
1107  rowexpr->args = newargs;
1108  rowexpr->row_typeid = baseTypeId;
1109  rowexpr->row_format = cformat;
1110  rowexpr->colnames = NIL; /* not needed for named target type */
1111  rowexpr->location = location;
1112 
1113  /* If target is a domain, apply constraints */
1114  if (baseTypeId != targetTypeId)
1115  {
1116  rowexpr->row_format = COERCE_IMPLICIT_CAST;
1117  return coerce_to_domain((Node *) rowexpr,
1118  baseTypeId, baseTypeMod,
1119  targetTypeId,
1120  ccontext, cformat, location,
1121  false);
1122  }
1123 
1124  return (Node *) rowexpr;
1125 }
1126 
1127 /*
1128  * coerce_to_boolean()
1129  * Coerce an argument of a construct that requires boolean input
1130  * (AND, OR, NOT, etc). Also check that input is not a set.
1131  *
1132  * Returns the possibly-transformed node tree.
1133  *
1134  * As with coerce_type, pstate may be NULL if no special unknown-Param
1135  * processing is wanted.
1136  */
1137 Node *
1139  const char *constructName)
1140 {
1141  Oid inputTypeId = exprType(node);
1142 
1143  if (inputTypeId != BOOLOID)
1144  {
1145  Node *newnode;
1146 
1147  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1148  BOOLOID, -1,
1151  -1);
1152  if (newnode == NULL)
1153  ereport(ERROR,
1154  (errcode(ERRCODE_DATATYPE_MISMATCH),
1155  /* translator: first %s is name of a SQL construct, eg WHERE */
1156  errmsg("argument of %s must be type %s, not type %s",
1157  constructName, "boolean",
1158  format_type_be(inputTypeId)),
1159  parser_errposition(pstate, exprLocation(node))));
1160  node = newnode;
1161  }
1162 
1163  if (expression_returns_set(node))
1164  ereport(ERROR,
1165  (errcode(ERRCODE_DATATYPE_MISMATCH),
1166  /* translator: %s is name of a SQL construct, eg WHERE */
1167  errmsg("argument of %s must not return a set",
1168  constructName),
1169  parser_errposition(pstate, exprLocation(node))));
1170 
1171  return node;
1172 }
1173 
1174 /*
1175  * coerce_to_specific_type_typmod()
1176  * Coerce an argument of a construct that requires a specific data type,
1177  * with a specific typmod. Also check that input is not a set.
1178  *
1179  * Returns the possibly-transformed node tree.
1180  *
1181  * As with coerce_type, pstate may be NULL if no special unknown-Param
1182  * processing is wanted.
1183  */
1184 Node *
1186  Oid targetTypeId, int32 targetTypmod,
1187  const char *constructName)
1188 {
1189  Oid inputTypeId = exprType(node);
1190 
1191  if (inputTypeId != targetTypeId)
1192  {
1193  Node *newnode;
1194 
1195  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1196  targetTypeId, targetTypmod,
1199  -1);
1200  if (newnode == NULL)
1201  ereport(ERROR,
1202  (errcode(ERRCODE_DATATYPE_MISMATCH),
1203  /* translator: first %s is name of a SQL construct, eg LIMIT */
1204  errmsg("argument of %s must be type %s, not type %s",
1205  constructName,
1206  format_type_be(targetTypeId),
1207  format_type_be(inputTypeId)),
1208  parser_errposition(pstate, exprLocation(node))));
1209  node = newnode;
1210  }
1211 
1212  if (expression_returns_set(node))
1213  ereport(ERROR,
1214  (errcode(ERRCODE_DATATYPE_MISMATCH),
1215  /* translator: %s is name of a SQL construct, eg LIMIT */
1216  errmsg("argument of %s must not return a set",
1217  constructName),
1218  parser_errposition(pstate, exprLocation(node))));
1219 
1220  return node;
1221 }
1222 
1223 /*
1224  * coerce_to_specific_type()
1225  * Coerce an argument of a construct that requires a specific data type.
1226  * Also check that input is not a set.
1227  *
1228  * Returns the possibly-transformed node tree.
1229  *
1230  * As with coerce_type, pstate may be NULL if no special unknown-Param
1231  * processing is wanted.
1232  */
1233 Node *
1235  Oid targetTypeId,
1236  const char *constructName)
1237 {
1238  return coerce_to_specific_type_typmod(pstate, node,
1239  targetTypeId, -1,
1240  constructName);
1241 }
1242 
1243 /*
1244  * parser_coercion_errposition - report coercion error location, if possible
1245  *
1246  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1247  * but there may be no such location in the case of an implicit coercion.
1248  * In that case point at the input expression.
1249  *
1250  * XXX possibly this is more generally useful than coercion errors;
1251  * if so, should rename and place with parser_errposition.
1252  */
1253 int
1255  int coerce_location,
1256  Node *input_expr)
1257 {
1258  if (coerce_location >= 0)
1259  return parser_errposition(pstate, coerce_location);
1260  else
1261  return parser_errposition(pstate, exprLocation(input_expr));
1262 }
1263 
1264 
1265 /*
1266  * select_common_type()
1267  * Determine the common supertype of a list of input expressions.
1268  * This is used for determining the output type of CASE, UNION,
1269  * and similar constructs.
1270  *
1271  * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1272  * in the list will be preferred if there is doubt.
1273  * 'context' is a phrase to use in the error message if we fail to select
1274  * a usable type. Pass NULL to have the routine return InvalidOid
1275  * rather than throwing an error on failure.
1276  * 'which_expr': if not NULL, receives a pointer to the particular input
1277  * expression from which the result type was taken.
1278  */
1279 Oid
1280 select_common_type(ParseState *pstate, List *exprs, const char *context,
1281  Node **which_expr)
1282 {
1283  Node *pexpr;
1284  Oid ptype;
1285  TYPCATEGORY pcategory;
1286  bool pispreferred;
1287  ListCell *lc;
1288 
1289  Assert(exprs != NIL);
1290  pexpr = (Node *) linitial(exprs);
1291  lc = list_second_cell(exprs);
1292  ptype = exprType(pexpr);
1293 
1294  /*
1295  * If all input types are valid and exactly the same, just pick that type.
1296  * This is the only way that we will resolve the result as being a domain
1297  * type; otherwise domains are smashed to their base types for comparison.
1298  */
1299  if (ptype != UNKNOWNOID)
1300  {
1301  for_each_cell(lc, exprs, lc)
1302  {
1303  Node *nexpr = (Node *) lfirst(lc);
1304  Oid ntype = exprType(nexpr);
1305 
1306  if (ntype != ptype)
1307  break;
1308  }
1309  if (lc == NULL) /* got to the end of the list? */
1310  {
1311  if (which_expr)
1312  *which_expr = pexpr;
1313  return ptype;
1314  }
1315  }
1316 
1317  /*
1318  * Nope, so set up for the full algorithm. Note that at this point, lc
1319  * points to the first list item with type different from pexpr's; we need
1320  * not re-examine any items the previous loop advanced over.
1321  */
1322  ptype = getBaseType(ptype);
1323  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1324 
1325  for_each_cell(lc, exprs, lc)
1326  {
1327  Node *nexpr = (Node *) lfirst(lc);
1328  Oid ntype = getBaseType(exprType(nexpr));
1329 
1330  /* move on to next one if no new information... */
1331  if (ntype != UNKNOWNOID && ntype != ptype)
1332  {
1333  TYPCATEGORY ncategory;
1334  bool nispreferred;
1335 
1336  get_type_category_preferred(ntype, &ncategory, &nispreferred);
1337  if (ptype == UNKNOWNOID)
1338  {
1339  /* so far, only unknowns so take anything... */
1340  pexpr = nexpr;
1341  ptype = ntype;
1342  pcategory = ncategory;
1343  pispreferred = nispreferred;
1344  }
1345  else if (ncategory != pcategory)
1346  {
1347  /*
1348  * both types in different categories? then not much hope...
1349  */
1350  if (context == NULL)
1351  return InvalidOid;
1352  ereport(ERROR,
1353  (errcode(ERRCODE_DATATYPE_MISMATCH),
1354  /*------
1355  translator: first %s is name of a SQL construct, eg CASE */
1356  errmsg("%s types %s and %s cannot be matched",
1357  context,
1358  format_type_be(ptype),
1359  format_type_be(ntype)),
1360  parser_errposition(pstate, exprLocation(nexpr))));
1361  }
1362  else if (!pispreferred &&
1363  can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1364  !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1365  {
1366  /*
1367  * take new type if can coerce to it implicitly but not the
1368  * other way; but if we have a preferred type, stay on it.
1369  */
1370  pexpr = nexpr;
1371  ptype = ntype;
1372  pcategory = ncategory;
1373  pispreferred = nispreferred;
1374  }
1375  }
1376  }
1377 
1378  /*
1379  * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1380  * then resolve as type TEXT. This situation comes up with constructs
1381  * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1382  * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1383  * output type as UNKNOWN, but that really doesn't work, because we'd
1384  * probably end up needing a runtime coercion from UNKNOWN to something
1385  * else, and we usually won't have it. We need to coerce the unknown
1386  * literals while they are still literals, so a decision has to be made
1387  * now.
1388  */
1389  if (ptype == UNKNOWNOID)
1390  ptype = TEXTOID;
1391 
1392  if (which_expr)
1393  *which_expr = pexpr;
1394  return ptype;
1395 }
1396 
1397 /*
1398  * select_common_type_from_oids()
1399  * Determine the common supertype of an array of type OIDs.
1400  *
1401  * This is the same logic as select_common_type(), but working from
1402  * an array of type OIDs not a list of expressions. As in that function,
1403  * earlier entries in the array have some preference over later ones.
1404  * On failure, return InvalidOid if noerror is true, else throw an error.
1405  *
1406  * Note: neither caller will pass any UNKNOWNOID entries, so the tests
1407  * for that in this function are dead code. However, they don't cost much,
1408  * and it seems better to keep this logic as close to select_common_type()
1409  * as possible.
1410  */
1411 static Oid
1412 select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
1413 {
1414  Oid ptype;
1415  TYPCATEGORY pcategory;
1416  bool pispreferred;
1417  int i = 1;
1418 
1419  Assert(nargs > 0);
1420  ptype = typeids[0];
1421 
1422  /* If all input types are valid and exactly the same, pick that type. */
1423  if (ptype != UNKNOWNOID)
1424  {
1425  for (; i < nargs; i++)
1426  {
1427  if (typeids[i] != ptype)
1428  break;
1429  }
1430  if (i == nargs)
1431  return ptype;
1432  }
1433 
1434  /*
1435  * Nope, so set up for the full algorithm. Note that at this point, we
1436  * can skip array entries before "i"; they are all equal to ptype.
1437  */
1438  ptype = getBaseType(ptype);
1439  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1440 
1441  for (; i < nargs; i++)
1442  {
1443  Oid ntype = getBaseType(typeids[i]);
1444 
1445  /* move on to next one if no new information... */
1446  if (ntype != UNKNOWNOID && ntype != ptype)
1447  {
1448  TYPCATEGORY ncategory;
1449  bool nispreferred;
1450 
1451  get_type_category_preferred(ntype, &ncategory, &nispreferred);
1452  if (ptype == UNKNOWNOID)
1453  {
1454  /* so far, only unknowns so take anything... */
1455  ptype = ntype;
1456  pcategory = ncategory;
1457  pispreferred = nispreferred;
1458  }
1459  else if (ncategory != pcategory)
1460  {
1461  /*
1462  * both types in different categories? then not much hope...
1463  */
1464  if (noerror)
1465  return InvalidOid;
1466  ereport(ERROR,
1467  (errcode(ERRCODE_DATATYPE_MISMATCH),
1468  errmsg("argument types %s and %s cannot be matched",
1469  format_type_be(ptype),
1470  format_type_be(ntype))));
1471  }
1472  else if (!pispreferred &&
1473  can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1474  !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1475  {
1476  /*
1477  * take new type if can coerce to it implicitly but not the
1478  * other way; but if we have a preferred type, stay on it.
1479  */
1480  ptype = ntype;
1481  pcategory = ncategory;
1482  pispreferred = nispreferred;
1483  }
1484  }
1485  }
1486 
1487  /* Like select_common_type(), choose TEXT if all inputs were UNKNOWN */
1488  if (ptype == UNKNOWNOID)
1489  ptype = TEXTOID;
1490 
1491  return ptype;
1492 }
1493 
1494 /*
1495  * coerce_to_common_type()
1496  * Coerce an expression to the given type.
1497  *
1498  * This is used following select_common_type() to coerce the individual
1499  * expressions to the desired type. 'context' is a phrase to use in the
1500  * error message if we fail to coerce.
1501  *
1502  * As with coerce_type, pstate may be NULL if no special unknown-Param
1503  * processing is wanted.
1504  */
1505 Node *
1507  Oid targetTypeId, const char *context)
1508 {
1509  Oid inputTypeId = exprType(node);
1510 
1511  if (inputTypeId == targetTypeId)
1512  return node; /* no work */
1513  if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1514  node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1516  else
1517  ereport(ERROR,
1518  (errcode(ERRCODE_CANNOT_COERCE),
1519  /* translator: first %s is name of a SQL construct, eg CASE */
1520  errmsg("%s could not convert type %s to %s",
1521  context,
1522  format_type_be(inputTypeId),
1523  format_type_be(targetTypeId)),
1524  parser_errposition(pstate, exprLocation(node))));
1525  return node;
1526 }
1527 
1528 /*
1529  * select_common_typmod()
1530  * Determine the common typmod of a list of input expressions.
1531  *
1532  * common_type is the selected common type of the expressions, typically
1533  * computed using select_common_type().
1534  */
1535 int32
1536 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
1537 {
1538  ListCell *lc;
1539  bool first = true;
1540  int32 result = -1;
1541 
1542  foreach(lc, exprs)
1543  {
1544  Node *expr = (Node *) lfirst(lc);
1545 
1546  /* Types must match */
1547  if (exprType(expr) != common_type)
1548  return -1;
1549  else if (first)
1550  {
1551  result = exprTypmod(expr);
1552  first = false;
1553  }
1554  else
1555  {
1556  /* As soon as we see a non-matching typmod, fall back to -1 */
1557  if (result != exprTypmod(expr))
1558  return -1;
1559  }
1560  }
1561 
1562  return result;
1563 }
1564 
1565 /*
1566  * check_generic_type_consistency()
1567  * Are the actual arguments potentially compatible with a
1568  * polymorphic function?
1569  *
1570  * The argument consistency rules are:
1571  *
1572  * 1) All arguments declared ANYELEMENT must have the same datatype.
1573  * 2) All arguments declared ANYARRAY must have the same datatype,
1574  * which must be a varlena array type.
1575  * 3) All arguments declared ANYRANGE or ANYMULTIRANGE must be a range or
1576  * multirange type, all derived from the same base datatype.
1577  * 4) If there are arguments of more than one of these polymorphic types,
1578  * the array element type and/or range subtype must be the same as each
1579  * other and the same as the ANYELEMENT type.
1580  * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
1581  * (alone or in combination with plain ANYELEMENT), we add the extra
1582  * condition that the ANYELEMENT type must be an enum.
1583  * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1584  * we add the extra condition that the ANYELEMENT type must not be an array.
1585  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1586  * is an extra restriction if not.)
1587  * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
1588  * to a common supertype (chosen as per select_common_type's rules).
1589  * ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
1590  * common supertype to not be an array. If there are ANYCOMPATIBLEARRAY
1591  * or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
1592  * types or subtypes are included while making the choice of common supertype.
1593  * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
1594  * type over the common supertype (which might not be the same array type
1595  * as any of the original arrays).
1596  * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
1597  * (after domain flattening), since we have no preference rule that would
1598  * let us choose one over another. Furthermore, that range's subtype
1599  * must exactly match the common supertype chosen by rule 7.
1600  * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
1601  * type (after domain flattening), since we have no preference rule that would
1602  * let us choose one over another. Furthermore, that multirange's range's
1603  * subtype must exactly match the common supertype chosen by rule 7.
1604  *
1605  * Domains over arrays match ANYARRAY, and are immediately flattened to their
1606  * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1607  * argument is a domain over int4[] while another one is just int4[].) Also
1608  * notice that such a domain does *not* match ANYNONARRAY. The same goes
1609  * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
1610  *
1611  * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
1612  * and are immediately flattened to their base type, and domains over
1613  * multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are immediately
1614  * flattened to their base type.
1615  *
1616  * Note that domains aren't currently considered to match ANYENUM,
1617  * even if their base type would match.
1618  *
1619  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1620  * argument, assume it is okay.
1621  *
1622  * We do not ereport here, but just return false if a rule is violated.
1623  */
1624 bool
1625 check_generic_type_consistency(const Oid *actual_arg_types,
1626  const Oid *declared_arg_types,
1627  int nargs)
1628 {
1629  Oid elem_typeid = InvalidOid;
1630  Oid array_typeid = InvalidOid;
1631  Oid range_typeid = InvalidOid;
1632  Oid multirange_typeid = InvalidOid;
1633  Oid anycompatible_range_typeid = InvalidOid;
1634  Oid anycompatible_range_typelem = InvalidOid;
1635  Oid anycompatible_multirange_typeid = InvalidOid;
1636  Oid anycompatible_multirange_typelem = InvalidOid;
1637  Oid range_typelem = InvalidOid;
1638  bool have_anynonarray = false;
1639  bool have_anyenum = false;
1640  bool have_anycompatible_nonarray = false;
1641  int n_anycompatible_args = 0;
1642  Oid anycompatible_actual_types[FUNC_MAX_ARGS];
1643 
1644  /*
1645  * Loop through the arguments to see if we have any that are polymorphic.
1646  * If so, require the actual types to be consistent.
1647  */
1648  Assert(nargs <= FUNC_MAX_ARGS);
1649  for (int j = 0; j < nargs; j++)
1650  {
1651  Oid decl_type = declared_arg_types[j];
1652  Oid actual_type = actual_arg_types[j];
1653 
1654  if (decl_type == ANYELEMENTOID ||
1655  decl_type == ANYNONARRAYOID ||
1656  decl_type == ANYENUMOID)
1657  {
1658  if (decl_type == ANYNONARRAYOID)
1659  have_anynonarray = true;
1660  else if (decl_type == ANYENUMOID)
1661  have_anyenum = true;
1662  if (actual_type == UNKNOWNOID)
1663  continue;
1664  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1665  return false;
1666  elem_typeid = actual_type;
1667  }
1668  else if (decl_type == ANYARRAYOID)
1669  {
1670  if (actual_type == UNKNOWNOID)
1671  continue;
1672  actual_type = getBaseType(actual_type); /* flatten domains */
1673  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1674  return false;
1675  array_typeid = actual_type;
1676  }
1677  else if (decl_type == ANYRANGEOID)
1678  {
1679  if (actual_type == UNKNOWNOID)
1680  continue;
1681  actual_type = getBaseType(actual_type); /* flatten domains */
1682  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1683  return false;
1684  range_typeid = actual_type;
1685  }
1686  else if (decl_type == ANYMULTIRANGEOID)
1687  {
1688  if (actual_type == UNKNOWNOID)
1689  continue;
1690  actual_type = getBaseType(actual_type); /* flatten domains */
1691  if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
1692  return false;
1693  multirange_typeid = actual_type;
1694  }
1695  else if (decl_type == ANYCOMPATIBLEOID ||
1696  decl_type == ANYCOMPATIBLENONARRAYOID)
1697  {
1698  if (decl_type == ANYCOMPATIBLENONARRAYOID)
1699  have_anycompatible_nonarray = true;
1700  if (actual_type == UNKNOWNOID)
1701  continue;
1702  /* collect the actual types of non-unknown COMPATIBLE args */
1703  anycompatible_actual_types[n_anycompatible_args++] = actual_type;
1704  }
1705  else if (decl_type == ANYCOMPATIBLEARRAYOID)
1706  {
1707  Oid elem_type;
1708 
1709  if (actual_type == UNKNOWNOID)
1710  continue;
1711  actual_type = getBaseType(actual_type); /* flatten domains */
1712  elem_type = get_element_type(actual_type);
1713  if (!OidIsValid(elem_type))
1714  return false; /* not an array */
1715  /* collect the element type for common-supertype choice */
1716  anycompatible_actual_types[n_anycompatible_args++] = elem_type;
1717  }
1718  else if (decl_type == ANYCOMPATIBLERANGEOID)
1719  {
1720  if (actual_type == UNKNOWNOID)
1721  continue;
1722  actual_type = getBaseType(actual_type); /* flatten domains */
1723  if (OidIsValid(anycompatible_range_typeid))
1724  {
1725  /* All ANYCOMPATIBLERANGE arguments must be the same type */
1726  if (anycompatible_range_typeid != actual_type)
1727  return false;
1728  }
1729  else
1730  {
1731  anycompatible_range_typeid = actual_type;
1732  anycompatible_range_typelem = get_range_subtype(actual_type);
1733  if (!OidIsValid(anycompatible_range_typelem))
1734  return false; /* not a range type */
1735  /* collect the subtype for common-supertype choice */
1736  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
1737  }
1738  }
1739  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
1740  {
1741  if (actual_type == UNKNOWNOID)
1742  continue;
1743  actual_type = getBaseType(actual_type); /* flatten domains */
1744  if (OidIsValid(anycompatible_multirange_typeid))
1745  {
1746  /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
1747  if (anycompatible_multirange_typeid != actual_type)
1748  return false;
1749  }
1750  else
1751  {
1752  anycompatible_multirange_typeid = actual_type;
1753  anycompatible_multirange_typelem = get_multirange_range(actual_type);
1754  if (!OidIsValid(anycompatible_multirange_typelem))
1755  return false; /* not a multirange type */
1756 
1757  if (OidIsValid(anycompatible_range_typeid))
1758  {
1759  /*
1760  * ANYCOMPATIBLEMULTIRANGE and ANYCOMPATIBLERANGE
1761  * arguments must match
1762  */
1763  if (anycompatible_range_typeid != anycompatible_multirange_typelem)
1764  return false;
1765  }
1766  else
1767  {
1768  anycompatible_range_typeid = anycompatible_multirange_typelem;
1769  anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
1770  if (!OidIsValid(anycompatible_range_typelem))
1771  return false; /* not a range type */
1772  }
1773  /* collect the subtype for common-supertype choice */
1774  anycompatible_actual_types[n_anycompatible_args++] =
1775  anycompatible_range_typelem;
1776  }
1777  }
1778  }
1779 
1780  /* Get the element type based on the array type, if we have one */
1781  if (OidIsValid(array_typeid))
1782  {
1783  if (array_typeid == ANYARRAYOID)
1784  {
1785  /*
1786  * Special case for matching ANYARRAY input to an ANYARRAY
1787  * argument: allow it for now. enforce_generic_type_consistency()
1788  * might complain later, depending on the presence of other
1789  * polymorphic arguments or results, but it will deliver a less
1790  * surprising error message than "function does not exist".
1791  *
1792  * (If you think to change this, note that can_coerce_type will
1793  * consider such a situation as a match, so that we might not even
1794  * get here.)
1795  */
1796  }
1797  else
1798  {
1799  Oid array_typelem;
1800 
1801  array_typelem = get_element_type(array_typeid);
1802  if (!OidIsValid(array_typelem))
1803  return false; /* should be an array, but isn't */
1804 
1805  if (!OidIsValid(elem_typeid))
1806  {
1807  /*
1808  * if we don't have an element type yet, use the one we just
1809  * got
1810  */
1811  elem_typeid = array_typelem;
1812  }
1813  else if (array_typelem != elem_typeid)
1814  {
1815  /* otherwise, they better match */
1816  return false;
1817  }
1818  }
1819  }
1820 
1821  /* Get the element type based on the range type, if we have one */
1822  if (OidIsValid(range_typeid))
1823  {
1824  range_typelem = get_range_subtype(range_typeid);
1825  if (!OidIsValid(range_typelem))
1826  return false; /* should be a range, but isn't */
1827 
1828  if (!OidIsValid(elem_typeid))
1829  {
1830  /*
1831  * if we don't have an element type yet, use the one we just got
1832  */
1833  elem_typeid = range_typelem;
1834  }
1835  else if (range_typelem != elem_typeid)
1836  {
1837  /* otherwise, they better match */
1838  return false;
1839  }
1840  }
1841 
1842  /* Get the element type based on the multirange type, if we have one */
1843  if (OidIsValid(multirange_typeid))
1844  {
1845  Oid multirange_typelem;
1846 
1847  multirange_typelem = get_multirange_range(multirange_typeid);
1848  if (!OidIsValid(multirange_typelem))
1849  return false; /* should be a multirange, but isn't */
1850 
1851  if (!OidIsValid(range_typeid))
1852  {
1853  /*
1854  * If we don't have a range type yet, use the one we just got
1855  */
1856  range_typeid = multirange_typelem;
1857  range_typelem = get_range_subtype(multirange_typelem);
1858  if (!OidIsValid(range_typelem))
1859  return false; /* should be a range, but isn't */
1860  }
1861  else if (multirange_typelem != range_typeid)
1862  {
1863  /* otherwise, they better match */
1864  return false;
1865  }
1866 
1867  if (!OidIsValid(elem_typeid))
1868  {
1869  /*
1870  * If we don't have an element type yet, use the one we just got
1871  */
1872  elem_typeid = range_typelem;
1873  }
1874  else if (range_typelem != elem_typeid)
1875  {
1876  /* otherwise, they better match */
1877  return false;
1878  }
1879  }
1880 
1881  if (have_anynonarray)
1882  {
1883  /* require the element type to not be an array or domain over array */
1884  if (type_is_array_domain(elem_typeid))
1885  return false;
1886  }
1887 
1888  if (have_anyenum)
1889  {
1890  /* require the element type to be an enum */
1891  if (!type_is_enum(elem_typeid))
1892  return false;
1893  }
1894 
1895  /* Check matching of ANYCOMPATIBLE-family arguments, if any */
1896  if (n_anycompatible_args > 0)
1897  {
1898  Oid anycompatible_typeid;
1899 
1900  anycompatible_typeid =
1901  select_common_type_from_oids(n_anycompatible_args,
1902  anycompatible_actual_types,
1903  true);
1904 
1905  if (!OidIsValid(anycompatible_typeid))
1906  return false; /* there's no common supertype */
1907 
1908  if (have_anycompatible_nonarray)
1909  {
1910  /*
1911  * require the anycompatible type to not be an array or domain
1912  * over array
1913  */
1914  if (type_is_array_domain(anycompatible_typeid))
1915  return false;
1916  }
1917 
1918  /*
1919  * The anycompatible type must exactly match the range element type,
1920  * if we were able to identify one. This checks compatibility for
1921  * anycompatiblemultirange too since that also sets
1922  * anycompatible_range_typelem above.
1923  */
1924  if (OidIsValid(anycompatible_range_typelem) &&
1925  anycompatible_range_typelem != anycompatible_typeid)
1926  return false;
1927  }
1928 
1929  /* Looks valid */
1930  return true;
1931 }
1932 
1933 /*
1934  * enforce_generic_type_consistency()
1935  * Make sure a polymorphic function is legally callable, and
1936  * deduce actual argument and result types.
1937  *
1938  * If any polymorphic pseudotype is used in a function's arguments or
1939  * return type, we make sure the actual data types are consistent with
1940  * each other. The argument consistency rules are shown above for
1941  * check_generic_type_consistency().
1942  *
1943  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1944  * argument, we attempt to deduce the actual type it should have. If
1945  * successful, we alter that position of declared_arg_types[] so that
1946  * make_fn_arguments will coerce the literal to the right thing.
1947  *
1948  * If we have polymorphic arguments of the ANYCOMPATIBLE family,
1949  * we similarly alter declared_arg_types[] entries to show the resolved
1950  * common supertype, so that make_fn_arguments will coerce the actual
1951  * arguments to the proper type.
1952  *
1953  * Rules are applied to the function's return type (possibly altering it)
1954  * if it is declared as a polymorphic type and there is at least one
1955  * polymorphic argument type:
1956  *
1957  * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1958  * argument's actual type as the function's return type.
1959  * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1960  * argument's actual type as the function's return type.
1961  * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
1962  * argument is ANYRANGE or ANYMULTIRANGE, use that argument's
1963  * actual type, range type or multirange type as the function's return
1964  * type.
1965  * 4) Otherwise, if return type is ANYMULTIRANGE, and any argument is
1966  * ANYMULTIRANGE, use the argument's actual type as the function's return
1967  * type. Or if any argument is ANYRANGE, use its multirange type as the
1968  * function's return type.
1969  * 5) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
1970  * at least one ANYELEMENT, ANYARRAY, or ANYRANGE input, deduce the
1971  * return type from those inputs, or throw error if we can't.
1972  * 6) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
1973  * (We have no way to select a specific range type if the arguments don't
1974  * include ANYRANGE.)
1975  * (alone or in combination with plain ANYELEMENT), we add the extra
1976  * condition that the ANYELEMENT type must be an enum.
1977  * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1978  * we add the extra condition that the ANYELEMENT type must not be an array.
1979  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1980  * is an extra restriction if not.)
1981  * 9) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLENONARRAY, and
1982  * ANYCOMPATIBLERANGE are handled by resolving the common supertype
1983  * of those arguments (or their element types/subtypes, for array and range
1984  * inputs), and then coercing all those arguments to the common supertype,
1985  * or the array type over the common supertype for ANYCOMPATIBLEARRAY.
1986  * For ANYCOMPATIBLERANGE, there must be at least one non-UNKNOWN input,
1987  * all such inputs must be the same range type, and that type's subtype
1988  * must equal the common supertype.
1989  *
1990  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
1991  * respectively, and are immediately flattened to their base type. (In
1992  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
1993  * it to the base type not the domain type.) The same is true for
1994  * ANYCOMPATIBLEARRAY and ANYCOMPATIBLERANGE.
1995  *
1996  * When allow_poly is false, we are not expecting any of the actual_arg_types
1997  * to be polymorphic, and we should not return a polymorphic result type
1998  * either. When allow_poly is true, it is okay to have polymorphic "actual"
1999  * arg types, and we can return a matching polymorphic type as the result.
2000  * (This case is currently used only to check compatibility of an aggregate's
2001  * declaration with the underlying transfn.)
2002  *
2003  * A special case is that we could see ANYARRAY as an actual_arg_type even
2004  * when allow_poly is false (this is possible only because pg_statistic has
2005  * columns shown as anyarray in the catalogs). We allow this to match a
2006  * declared ANYARRAY argument, but only if there is no other polymorphic
2007  * argument that we would need to match it with, and no need to determine
2008  * the element type to infer the result type. Note this means that functions
2009  * taking ANYARRAY had better behave sanely if applied to the pg_statistic
2010  * columns; they can't just assume that successive inputs are of the same
2011  * actual element type. There is no similar logic for ANYCOMPATIBLEARRAY;
2012  * there isn't a need for it since there are no catalog columns of that type,
2013  * so we won't see it as input. We could consider matching an actual ANYARRAY
2014  * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
2015  * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
2016  * at least one other ANYCOMPATIBLE-family argument or result.
2017  *
2018  * Also, if there are no arguments declared to be of polymorphic types,
2019  * we'll return the rettype unmodified even if it's polymorphic. This should
2020  * never occur for user-declared functions, because CREATE FUNCTION prevents
2021  * it. But it does happen for some built-in functions, such as array_in().
2022  */
2023 Oid
2024 enforce_generic_type_consistency(const Oid *actual_arg_types,
2025  Oid *declared_arg_types,
2026  int nargs,
2027  Oid rettype,
2028  bool allow_poly)
2029 {
2030  bool have_poly_anycompatible = false;
2031  bool have_poly_unknowns = false;
2032  Oid elem_typeid = InvalidOid;
2033  Oid array_typeid = InvalidOid;
2034  Oid range_typeid = InvalidOid;
2035  Oid multirange_typeid = InvalidOid;
2036  Oid anycompatible_typeid = InvalidOid;
2037  Oid anycompatible_array_typeid = InvalidOid;
2038  Oid anycompatible_range_typeid = InvalidOid;
2039  Oid anycompatible_range_typelem = InvalidOid;
2040  Oid anycompatible_multirange_typeid = InvalidOid;
2041  Oid anycompatible_multirange_typelem = InvalidOid;
2042  Oid range_typelem;
2043  Oid multirange_typelem;
2044  bool have_anynonarray = (rettype == ANYNONARRAYOID);
2045  bool have_anyenum = (rettype == ANYENUMOID);
2046  bool have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
2047  bool have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
2048  bool have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
2049  int n_poly_args = 0; /* this counts all family-1 arguments */
2050  int n_anycompatible_args = 0; /* this counts only non-unknowns */
2051  Oid anycompatible_actual_types[FUNC_MAX_ARGS];
2052 
2053  /*
2054  * Loop through the arguments to see if we have any that are polymorphic.
2055  * If so, require the actual types to be consistent.
2056  */
2057  Assert(nargs <= FUNC_MAX_ARGS);
2058  for (int j = 0; j < nargs; j++)
2059  {
2060  Oid decl_type = declared_arg_types[j];
2061  Oid actual_type = actual_arg_types[j];
2062 
2063  if (decl_type == ANYELEMENTOID ||
2064  decl_type == ANYNONARRAYOID ||
2065  decl_type == ANYENUMOID)
2066  {
2067  n_poly_args++;
2068  if (decl_type == ANYNONARRAYOID)
2069  have_anynonarray = true;
2070  else if (decl_type == ANYENUMOID)
2071  have_anyenum = true;
2072  if (actual_type == UNKNOWNOID)
2073  {
2074  have_poly_unknowns = true;
2075  continue;
2076  }
2077  if (allow_poly && decl_type == actual_type)
2078  continue; /* no new information here */
2079  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
2080  ereport(ERROR,
2081  (errcode(ERRCODE_DATATYPE_MISMATCH),
2082  errmsg("arguments declared \"anyelement\" are not all alike"),
2083  errdetail("%s versus %s",
2084  format_type_be(elem_typeid),
2085  format_type_be(actual_type))));
2086  elem_typeid = actual_type;
2087  }
2088  else if (decl_type == ANYARRAYOID)
2089  {
2090  n_poly_args++;
2091  if (actual_type == UNKNOWNOID)
2092  {
2093  have_poly_unknowns = true;
2094  continue;
2095  }
2096  if (allow_poly && decl_type == actual_type)
2097  continue; /* no new information here */
2098  actual_type = getBaseType(actual_type); /* flatten domains */
2099  if (OidIsValid(array_typeid) && actual_type != array_typeid)
2100  ereport(ERROR,
2101  (errcode(ERRCODE_DATATYPE_MISMATCH),
2102  errmsg("arguments declared \"anyarray\" are not all alike"),
2103  errdetail("%s versus %s",
2104  format_type_be(array_typeid),
2105  format_type_be(actual_type))));
2106  array_typeid = actual_type;
2107  }
2108  else if (decl_type == ANYRANGEOID)
2109  {
2110  n_poly_args++;
2111  if (actual_type == UNKNOWNOID)
2112  {
2113  have_poly_unknowns = true;
2114  continue;
2115  }
2116  if (allow_poly && decl_type == actual_type)
2117  continue; /* no new information here */
2118  actual_type = getBaseType(actual_type); /* flatten domains */
2119  if (OidIsValid(range_typeid) && actual_type != range_typeid)
2120  ereport(ERROR,
2121  (errcode(ERRCODE_DATATYPE_MISMATCH),
2122  errmsg("arguments declared \"anyrange\" are not all alike"),
2123  errdetail("%s versus %s",
2124  format_type_be(range_typeid),
2125  format_type_be(actual_type))));
2126  range_typeid = actual_type;
2127  }
2128  else if (decl_type == ANYMULTIRANGEOID)
2129  {
2130  n_poly_args++;
2131  if (actual_type == UNKNOWNOID)
2132  {
2133  have_poly_unknowns = true;
2134  continue;
2135  }
2136  if (allow_poly && decl_type == actual_type)
2137  continue; /* no new information here */
2138  actual_type = getBaseType(actual_type); /* flatten domains */
2139  if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
2140  ereport(ERROR,
2141  (errcode(ERRCODE_DATATYPE_MISMATCH),
2142  errmsg("arguments declared \"anymultirange\" are not all alike"),
2143  errdetail("%s versus %s",
2144  format_type_be(multirange_typeid),
2145  format_type_be(actual_type))));
2146  multirange_typeid = actual_type;
2147  }
2148  else if (decl_type == ANYCOMPATIBLEOID ||
2149  decl_type == ANYCOMPATIBLENONARRAYOID)
2150  {
2151  have_poly_anycompatible = true;
2152  if (decl_type == ANYCOMPATIBLENONARRAYOID)
2153  have_anycompatible_nonarray = true;
2154  if (actual_type == UNKNOWNOID)
2155  continue;
2156  if (allow_poly && decl_type == actual_type)
2157  continue; /* no new information here */
2158  /* collect the actual types of non-unknown COMPATIBLE args */
2159  anycompatible_actual_types[n_anycompatible_args++] = actual_type;
2160  }
2161  else if (decl_type == ANYCOMPATIBLEARRAYOID)
2162  {
2163  Oid anycompatible_elem_type;
2164 
2165  have_poly_anycompatible = true;
2166  have_anycompatible_array = true;
2167  if (actual_type == UNKNOWNOID)
2168  continue;
2169  if (allow_poly && decl_type == actual_type)
2170  continue; /* no new information here */
2171  actual_type = getBaseType(actual_type); /* flatten domains */
2172  anycompatible_elem_type = get_element_type(actual_type);
2173  if (!OidIsValid(anycompatible_elem_type))
2174  ereport(ERROR,
2175  (errcode(ERRCODE_DATATYPE_MISMATCH),
2176  errmsg("argument declared %s is not an array but type %s",
2177  "anycompatiblearray",
2178  format_type_be(actual_type))));
2179  /* collect the element type for common-supertype choice */
2180  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
2181  }
2182  else if (decl_type == ANYCOMPATIBLERANGEOID)
2183  {
2184  have_poly_anycompatible = true;
2185  have_anycompatible_range = true;
2186  if (actual_type == UNKNOWNOID)
2187  continue;
2188  if (allow_poly && decl_type == actual_type)
2189  continue; /* no new information here */
2190  actual_type = getBaseType(actual_type); /* flatten domains */
2191  if (OidIsValid(anycompatible_range_typeid))
2192  {
2193  /* All ANYCOMPATIBLERANGE arguments must be the same type */
2194  if (anycompatible_range_typeid != actual_type)
2195  ereport(ERROR,
2196  (errcode(ERRCODE_DATATYPE_MISMATCH),
2197  errmsg("arguments declared \"anycompatiblerange\" are not all alike"),
2198  errdetail("%s versus %s",
2199  format_type_be(anycompatible_range_typeid),
2200  format_type_be(actual_type))));
2201  }
2202  else
2203  {
2204  anycompatible_range_typeid = actual_type;
2205  anycompatible_range_typelem = get_range_subtype(actual_type);
2206  if (!OidIsValid(anycompatible_range_typelem))
2207  ereport(ERROR,
2208  (errcode(ERRCODE_DATATYPE_MISMATCH),
2209  errmsg("argument declared %s is not a range type but type %s",
2210  "anycompatiblerange",
2211  format_type_be(actual_type))));
2212  /* collect the subtype for common-supertype choice */
2213  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2214  }
2215  }
2216  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2217  {
2218  have_poly_anycompatible = true;
2219  if (actual_type == UNKNOWNOID)
2220  continue;
2221  if (allow_poly && decl_type == actual_type)
2222  continue; /* no new information here */
2223  actual_type = getBaseType(actual_type); /* flatten domains */
2224  if (OidIsValid(anycompatible_multirange_typeid))
2225  {
2226  /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
2227  if (anycompatible_multirange_typeid != actual_type)
2228  ereport(ERROR,
2229  (errcode(ERRCODE_DATATYPE_MISMATCH),
2230  errmsg("arguments declared \"anycompatiblemultirange\" are not all alike"),
2231  errdetail("%s versus %s",
2232  format_type_be(anycompatible_multirange_typeid),
2233  format_type_be(actual_type))));
2234  }
2235  else
2236  {
2237  anycompatible_multirange_typeid = actual_type;
2238  anycompatible_multirange_typelem = get_multirange_range(actual_type);
2239  anycompatible_range_typelem = get_range_subtype(anycompatible_multirange_typelem);
2240  if (!OidIsValid(anycompatible_multirange_typelem))
2241  ereport(ERROR,
2242  (errcode(ERRCODE_DATATYPE_MISMATCH),
2243  errmsg("argument declared %s is not a multirange type but type %s",
2244  "anycompatiblemultirange",
2245  format_type_be(actual_type))));
2246  /* collect the subtype for common-supertype choice */
2247  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2248  }
2249  }
2250  }
2251 
2252  /*
2253  * Fast Track: if none of the arguments are polymorphic, return the
2254  * unmodified rettype. Not our job to resolve it if it's polymorphic.
2255  */
2256  if (n_poly_args == 0 && !have_poly_anycompatible)
2257  return rettype;
2258 
2259  /* Check matching of family-1 polymorphic arguments, if any */
2260  if (n_poly_args)
2261  {
2262  /* Get the element type based on the array type, if we have one */
2263  if (OidIsValid(array_typeid))
2264  {
2265  Oid array_typelem;
2266 
2267  if (array_typeid == ANYARRAYOID)
2268  {
2269  /*
2270  * Special case for matching ANYARRAY input to an ANYARRAY
2271  * argument: allow it iff no other arguments are family-1
2272  * polymorphics (otherwise we couldn't be sure whether the
2273  * array element type matches up) and the result type doesn't
2274  * require us to infer a specific element type.
2275  */
2276  if (n_poly_args != 1 ||
2277  (rettype != ANYARRAYOID &&
2278  IsPolymorphicTypeFamily1(rettype)))
2279  ereport(ERROR,
2280  (errcode(ERRCODE_DATATYPE_MISMATCH),
2281  errmsg("cannot determine element type of \"anyarray\" argument")));
2282  array_typelem = ANYELEMENTOID;
2283  }
2284  else
2285  {
2286  array_typelem = get_element_type(array_typeid);
2287  if (!OidIsValid(array_typelem))
2288  ereport(ERROR,
2289  (errcode(ERRCODE_DATATYPE_MISMATCH),
2290  errmsg("argument declared %s is not an array but type %s",
2291  "anyarray", format_type_be(array_typeid))));
2292  }
2293 
2294  if (!OidIsValid(elem_typeid))
2295  {
2296  /*
2297  * if we don't have an element type yet, use the one we just
2298  * got
2299  */
2300  elem_typeid = array_typelem;
2301  }
2302  else if (array_typelem != elem_typeid)
2303  {
2304  /* otherwise, they better match */
2305  ereport(ERROR,
2306  (errcode(ERRCODE_DATATYPE_MISMATCH),
2307  errmsg("argument declared %s is not consistent with argument declared %s",
2308  "anyarray", "anyelement"),
2309  errdetail("%s versus %s",
2310  format_type_be(array_typeid),
2311  format_type_be(elem_typeid))));
2312  }
2313  }
2314 
2315  /* Get the element type based on the range type, if we have one */
2316  if (OidIsValid(range_typeid))
2317  {
2318  range_typelem = get_range_subtype(range_typeid);
2319  if (!OidIsValid(range_typelem))
2320  ereport(ERROR,
2321  (errcode(ERRCODE_DATATYPE_MISMATCH),
2322  errmsg("argument declared %s is not a range type but type %s",
2323  "anyrange",
2324  format_type_be(range_typeid))));
2325 
2326  if (!OidIsValid(elem_typeid))
2327  {
2328  /*
2329  * if we don't have an element type yet, use the one we just
2330  * got
2331  */
2332  elem_typeid = range_typelem;
2333  }
2334  else if (range_typelem != elem_typeid)
2335  {
2336  /* otherwise, they better match */
2337  ereport(ERROR,
2338  (errcode(ERRCODE_DATATYPE_MISMATCH),
2339  errmsg("argument declared %s is not consistent with argument declared %s",
2340  "anyrange", "anyelement"),
2341  errdetail("%s versus %s",
2342  format_type_be(range_typeid),
2343  format_type_be(elem_typeid))));
2344  }
2345  }
2346  else
2347  range_typelem = InvalidOid;
2348 
2349  /* Get the element type based on the multirange type, if we have one */
2350  if (OidIsValid(multirange_typeid))
2351  {
2352  multirange_typelem = get_multirange_range(multirange_typeid);
2353  if (!OidIsValid(multirange_typelem))
2354  ereport(ERROR,
2355  (errcode(ERRCODE_DATATYPE_MISMATCH),
2356  errmsg("argument declared %s is not a multirange type but type %s",
2357  "anymultirange",
2358  format_type_be(multirange_typeid))));
2359 
2360  if (!OidIsValid(range_typeid))
2361  {
2362  /*
2363  * If we don't have a range type yet, use the one we just got
2364  */
2365  range_typeid = multirange_typelem;
2366  range_typelem = get_range_subtype(range_typeid);
2367  }
2368  else if (multirange_typelem != range_typeid)
2369  {
2370  /* otherwise, they better match */
2371  ereport(ERROR,
2372  (errcode(ERRCODE_DATATYPE_MISMATCH),
2373  errmsg("argument declared %s is not consistent with argument declared %s",
2374  "anymultirange", "anyrange"),
2375  errdetail("%s versus %s",
2376  format_type_be(multirange_typeid),
2377  format_type_be(range_typeid))));
2378  }
2379 
2380  if (!OidIsValid(elem_typeid))
2381  {
2382  /*
2383  * if we don't have an element type yet, use the one we just
2384  * got
2385  */
2386  elem_typeid = range_typelem;
2387  }
2388  else if (range_typelem != elem_typeid)
2389  {
2390  /* otherwise, they better match */
2391  ereport(ERROR,
2392  (errcode(ERRCODE_DATATYPE_MISMATCH),
2393  errmsg("argument declared %s is not consistent with argument declared %s",
2394  "anymultirange", "anyelement"),
2395  errdetail("%s versus %s",
2396  format_type_be(multirange_typeid),
2397  format_type_be(elem_typeid))));
2398  }
2399  }
2400  else
2401  multirange_typelem = InvalidOid;
2402 
2403  if (!OidIsValid(elem_typeid))
2404  {
2405  if (allow_poly)
2406  {
2407  elem_typeid = ANYELEMENTOID;
2408  array_typeid = ANYARRAYOID;
2409  range_typeid = ANYRANGEOID;
2410  multirange_typeid = ANYMULTIRANGEOID;
2411  }
2412  else
2413  {
2414  /*
2415  * Only way to get here is if all the family-1 polymorphic
2416  * arguments have UNKNOWN inputs.
2417  */
2418  ereport(ERROR,
2419  (errcode(ERRCODE_DATATYPE_MISMATCH),
2420  errmsg("could not determine polymorphic type because input has type %s",
2421  "unknown")));
2422  }
2423  }
2424 
2425  if (have_anynonarray && elem_typeid != ANYELEMENTOID)
2426  {
2427  /*
2428  * require the element type to not be an array or domain over
2429  * array
2430  */
2431  if (type_is_array_domain(elem_typeid))
2432  ereport(ERROR,
2433  (errcode(ERRCODE_DATATYPE_MISMATCH),
2434  errmsg("type matched to anynonarray is an array type: %s",
2435  format_type_be(elem_typeid))));
2436  }
2437 
2438  if (have_anyenum && elem_typeid != ANYELEMENTOID)
2439  {
2440  /* require the element type to be an enum */
2441  if (!type_is_enum(elem_typeid))
2442  ereport(ERROR,
2443  (errcode(ERRCODE_DATATYPE_MISMATCH),
2444  errmsg("type matched to anyenum is not an enum type: %s",
2445  format_type_be(elem_typeid))));
2446  }
2447  }
2448 
2449  /* Check matching of family-2 polymorphic arguments, if any */
2450  if (have_poly_anycompatible)
2451  {
2452  if (n_anycompatible_args > 0)
2453  {
2454  anycompatible_typeid =
2455  select_common_type_from_oids(n_anycompatible_args,
2456  anycompatible_actual_types,
2457  false);
2458 
2459  if (have_anycompatible_array)
2460  {
2461  anycompatible_array_typeid = get_array_type(anycompatible_typeid);
2462  if (!OidIsValid(anycompatible_array_typeid))
2463  ereport(ERROR,
2464  (errcode(ERRCODE_UNDEFINED_OBJECT),
2465  errmsg("could not find array type for data type %s",
2466  format_type_be(anycompatible_typeid))));
2467  }
2468 
2469  if (have_anycompatible_range)
2470  {
2471  /* we can't infer a range type from the others */
2472  if (!OidIsValid(anycompatible_range_typeid))
2473  ereport(ERROR,
2474  (errcode(ERRCODE_DATATYPE_MISMATCH),
2475  errmsg("could not determine polymorphic type %s because input has type %s",
2476  "anycompatiblerange", "unknown")));
2477 
2478  /*
2479  * the anycompatible type must exactly match the range element
2480  * type
2481  */
2482  if (anycompatible_range_typelem != anycompatible_typeid)
2483  ereport(ERROR,
2484  (errcode(ERRCODE_DATATYPE_MISMATCH),
2485  errmsg("anycompatiblerange type %s does not match anycompatible type %s",
2486  format_type_be(anycompatible_range_typeid),
2487  format_type_be(anycompatible_typeid))));
2488  }
2489 
2490  if (have_anycompatible_nonarray)
2491  {
2492  /*
2493  * require the element type to not be an array or domain over
2494  * array
2495  */
2496  if (type_is_array_domain(anycompatible_typeid))
2497  ereport(ERROR,
2498  (errcode(ERRCODE_DATATYPE_MISMATCH),
2499  errmsg("type matched to anycompatiblenonarray is an array type: %s",
2500  format_type_be(anycompatible_typeid))));
2501  }
2502  }
2503  else
2504  {
2505  if (allow_poly)
2506  {
2507  anycompatible_typeid = ANYCOMPATIBLEOID;
2508  anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
2509  anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
2510  anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
2511  }
2512  else
2513  {
2514  /*
2515  * Only way to get here is if all the family-2 polymorphic
2516  * arguments have UNKNOWN inputs. Resolve to TEXT as
2517  * select_common_type() would do. That doesn't license us to
2518  * use TEXTRANGE, though.
2519  */
2520  anycompatible_typeid = TEXTOID;
2521  anycompatible_array_typeid = TEXTARRAYOID;
2522  if (have_anycompatible_range)
2523  ereport(ERROR,
2524  (errcode(ERRCODE_DATATYPE_MISMATCH),
2525  errmsg("could not determine polymorphic type %s because input has type %s",
2526  "anycompatiblerange", "unknown")));
2527  }
2528  }
2529 
2530  /* replace family-2 polymorphic types by selected types */
2531  for (int j = 0; j < nargs; j++)
2532  {
2533  Oid decl_type = declared_arg_types[j];
2534 
2535  if (decl_type == ANYCOMPATIBLEOID ||
2536  decl_type == ANYCOMPATIBLENONARRAYOID)
2537  declared_arg_types[j] = anycompatible_typeid;
2538  else if (decl_type == ANYCOMPATIBLEARRAYOID)
2539  declared_arg_types[j] = anycompatible_array_typeid;
2540  else if (decl_type == ANYCOMPATIBLERANGEOID)
2541  declared_arg_types[j] = anycompatible_range_typeid;
2542  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2543  declared_arg_types[j] = anycompatible_multirange_typeid;
2544  }
2545  }
2546 
2547  /*
2548  * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
2549  * re-scan to assign correct types to them.
2550  *
2551  * Note: we don't have to consider unknown inputs that were matched to
2552  * family-2 polymorphic arguments, because we forcibly updated their
2553  * declared_arg_types[] positions just above.
2554  */
2555  if (have_poly_unknowns)
2556  {
2557  for (int j = 0; j < nargs; j++)
2558  {
2559  Oid decl_type = declared_arg_types[j];
2560  Oid actual_type = actual_arg_types[j];
2561 
2562  if (actual_type != UNKNOWNOID)
2563  continue;
2564 
2565  if (decl_type == ANYELEMENTOID ||
2566  decl_type == ANYNONARRAYOID ||
2567  decl_type == ANYENUMOID)
2568  declared_arg_types[j] = elem_typeid;
2569  else if (decl_type == ANYARRAYOID)
2570  {
2571  if (!OidIsValid(array_typeid))
2572  {
2573  array_typeid = get_array_type(elem_typeid);
2574  if (!OidIsValid(array_typeid))
2575  ereport(ERROR,
2576  (errcode(ERRCODE_UNDEFINED_OBJECT),
2577  errmsg("could not find array type for data type %s",
2578  format_type_be(elem_typeid))));
2579  }
2580  declared_arg_types[j] = array_typeid;
2581  }
2582  else if (decl_type == ANYRANGEOID)
2583  {
2584  if (!OidIsValid(range_typeid))
2585  {
2586  /* we can't infer a range type from the others */
2587  ereport(ERROR,
2588  (errcode(ERRCODE_DATATYPE_MISMATCH),
2589  errmsg("could not determine polymorphic type %s because input has type %s",
2590  "anyrange", "unknown")));
2591  }
2592  declared_arg_types[j] = range_typeid;
2593  }
2594  else if (decl_type == ANYMULTIRANGEOID)
2595  {
2596  if (!OidIsValid(multirange_typeid))
2597  {
2598  ereport(ERROR,
2599  (errcode(ERRCODE_UNDEFINED_OBJECT),
2600  errmsg("could not find multirange type for data type %s",
2601  format_type_be(elem_typeid))));
2602  }
2603  declared_arg_types[j] = multirange_typeid;
2604  }
2605  }
2606  }
2607 
2608  /* if we return ANYELEMENT use the appropriate argument type */
2609  if (rettype == ANYELEMENTOID ||
2610  rettype == ANYNONARRAYOID ||
2611  rettype == ANYENUMOID)
2612  return elem_typeid;
2613 
2614  /* if we return ANYARRAY use the appropriate argument type */
2615  if (rettype == ANYARRAYOID)
2616  {
2617  if (!OidIsValid(array_typeid))
2618  {
2619  array_typeid = get_array_type(elem_typeid);
2620  if (!OidIsValid(array_typeid))
2621  ereport(ERROR,
2622  (errcode(ERRCODE_UNDEFINED_OBJECT),
2623  errmsg("could not find array type for data type %s",
2624  format_type_be(elem_typeid))));
2625  }
2626  return array_typeid;
2627  }
2628 
2629  /* if we return ANYRANGE use the appropriate argument type */
2630  if (rettype == ANYRANGEOID)
2631  {
2632  /* this error is unreachable if the function signature is valid: */
2633  if (!OidIsValid(range_typeid))
2634  ereport(ERROR,
2635  (errcode(ERRCODE_DATATYPE_MISMATCH),
2636  errmsg("could not determine polymorphic type %s because input has type %s",
2637  "anyrange", "unknown")));
2638  return range_typeid;
2639  }
2640 
2641  /* if we return ANYMULTIRANGE use the appropriate argument type */
2642  if (rettype == ANYMULTIRANGEOID)
2643  {
2644  if (!OidIsValid(multirange_typeid))
2645  {
2646  if (OidIsValid(range_typeid))
2647  multirange_typeid = get_range_multirange(range_typeid);
2648  else
2649  ereport(ERROR,
2650  (errcode(ERRCODE_UNDEFINED_OBJECT),
2651  errmsg("could not find multirange type for data type %s",
2652  format_type_be(elem_typeid))));
2653  }
2654  return multirange_typeid;
2655  }
2656 
2657  /* if we return ANYCOMPATIBLE use the appropriate type */
2658  if (rettype == ANYCOMPATIBLEOID ||
2659  rettype == ANYCOMPATIBLENONARRAYOID)
2660  {
2661  /* this error is unreachable if the function signature is valid: */
2662  if (!OidIsValid(anycompatible_typeid))
2663  ereport(ERROR,
2664  (errcode(ERRCODE_DATATYPE_MISMATCH),
2665  errmsg_internal("could not identify anycompatible type")));
2666  return anycompatible_typeid;
2667  }
2668 
2669  /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
2670  if (rettype == ANYCOMPATIBLEARRAYOID)
2671  {
2672  /* this error is unreachable if the function signature is valid: */
2673  if (!OidIsValid(anycompatible_array_typeid))
2674  ereport(ERROR,
2675  (errcode(ERRCODE_DATATYPE_MISMATCH),
2676  errmsg_internal("could not identify anycompatiblearray type")));
2677  return anycompatible_array_typeid;
2678  }
2679 
2680  /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
2681  if (rettype == ANYCOMPATIBLERANGEOID)
2682  {
2683  /* this error is unreachable if the function signature is valid: */
2684  if (!OidIsValid(anycompatible_range_typeid))
2685  ereport(ERROR,
2686  (errcode(ERRCODE_DATATYPE_MISMATCH),
2687  errmsg_internal("could not identify anycompatiblerange type")));
2688  return anycompatible_range_typeid;
2689  }
2690 
2691  /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
2692  if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
2693  {
2694  /* this error is unreachable if the function signature is valid: */
2695  if (!OidIsValid(anycompatible_multirange_typeid))
2696  ereport(ERROR,
2697  (errcode(ERRCODE_DATATYPE_MISMATCH),
2698  errmsg_internal("could not identify anycompatiblemultirange type")));
2699  return anycompatible_multirange_typeid;
2700  }
2701 
2702  /* we don't return a generic type; send back the original return type */
2703  return rettype;
2704 }
2705 
2706 /*
2707  * check_valid_polymorphic_signature()
2708  * Is a proposed function signature valid per polymorphism rules?
2709  *
2710  * Returns NULL if the signature is valid (either ret_type is not polymorphic,
2711  * or it can be deduced from the given declared argument types). Otherwise,
2712  * returns a palloc'd, already translated errdetail string saying why not.
2713  */
2714 char *
2716  const Oid *declared_arg_types,
2717  int nargs)
2718 {
2719  if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
2720  {
2721  /*
2722  * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
2723  * input, else we can't tell which of several range types with the
2724  * same element type to use.
2725  */
2726  for (int i = 0; i < nargs; i++)
2727  {
2728  if (declared_arg_types[i] == ANYRANGEOID ||
2729  declared_arg_types[i] == ANYMULTIRANGEOID)
2730  return NULL; /* OK */
2731  }
2732  return psprintf(_("A result of type %s requires at least one input of type anyrange or anymultirange."),
2733  format_type_be(ret_type));
2734  }
2735  else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
2736  {
2737  /*
2738  * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
2739  * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
2740  * tell which of several range types with the same element type to
2741  * use.
2742  */
2743  for (int i = 0; i < nargs; i++)
2744  {
2745  if (declared_arg_types[i] == ANYCOMPATIBLERANGEOID ||
2746  declared_arg_types[i] == ANYCOMPATIBLEMULTIRANGEOID)
2747  return NULL; /* OK */
2748  }
2749  return psprintf(_("A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
2750  format_type_be(ret_type));
2751  }
2752  else if (IsPolymorphicTypeFamily1(ret_type))
2753  {
2754  /* Otherwise, any family-1 type can be deduced from any other */
2755  for (int i = 0; i < nargs; i++)
2756  {
2757  if (IsPolymorphicTypeFamily1(declared_arg_types[i]))
2758  return NULL; /* OK */
2759  }
2760  /* Keep this list in sync with IsPolymorphicTypeFamily1! */
2761  return psprintf(_("A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
2762  format_type_be(ret_type));
2763  }
2764  else if (IsPolymorphicTypeFamily2(ret_type))
2765  {
2766  /* Otherwise, any family-2 type can be deduced from any other */
2767  for (int i = 0; i < nargs; i++)
2768  {
2769  if (IsPolymorphicTypeFamily2(declared_arg_types[i]))
2770  return NULL; /* OK */
2771  }
2772  /* Keep this list in sync with IsPolymorphicTypeFamily2! */
2773  return psprintf(_("A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, or anycompatiblerange."),
2774  format_type_be(ret_type));
2775  }
2776  else
2777  return NULL; /* OK, ret_type is not polymorphic */
2778 }
2779 
2780 /*
2781  * check_valid_internal_signature()
2782  * Is a proposed function signature valid per INTERNAL safety rules?
2783  *
2784  * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
2785  * none of the declared arg types are. (It's unsafe to create such a function
2786  * since it would allow invocation of INTERNAL-consuming functions directly
2787  * from SQL.) It's overkill to return the error detail message, since there
2788  * is only one possibility, but we do it like this to keep the API similar to
2789  * check_valid_polymorphic_signature().
2790  */
2791 char *
2793  const Oid *declared_arg_types,
2794  int nargs)
2795 {
2796  if (ret_type == INTERNALOID)
2797  {
2798  for (int i = 0; i < nargs; i++)
2799  {
2800  if (declared_arg_types[i] == ret_type)
2801  return NULL; /* OK */
2802  }
2803  return pstrdup(_("A result of type internal requires at least one input of type internal."));
2804  }
2805  else
2806  return NULL; /* OK, ret_type is not INTERNAL */
2807 }
2808 
2809 
2810 /* TypeCategory()
2811  * Assign a category to the specified type OID.
2812  *
2813  * NB: this must not return TYPCATEGORY_INVALID.
2814  */
2817 {
2818  char typcategory;
2819  bool typispreferred;
2820 
2821  get_type_category_preferred(type, &typcategory, &typispreferred);
2822  Assert(typcategory != TYPCATEGORY_INVALID);
2823  return (TYPCATEGORY) typcategory;
2824 }
2825 
2826 
2827 /* IsPreferredType()
2828  * Check if this type is a preferred type for the given category.
2829  *
2830  * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
2831  * types of any category; otherwise, only for preferred types of that
2832  * category.
2833  */
2834 bool
2836 {
2837  char typcategory;
2838  bool typispreferred;
2839 
2840  get_type_category_preferred(type, &typcategory, &typispreferred);
2841  if (category == typcategory || category == TYPCATEGORY_INVALID)
2842  return typispreferred;
2843  else
2844  return false;
2845 }
2846 
2847 
2848 /* IsBinaryCoercible()
2849  * Check if srctype is binary-coercible to targettype.
2850  *
2851  * This notion allows us to cheat and directly exchange values without
2852  * going through the trouble of calling a conversion function. Note that
2853  * in general, this should only be an implementation shortcut. Before 7.4,
2854  * this was also used as a heuristic for resolving overloaded functions and
2855  * operators, but that's basically a bad idea.
2856  *
2857  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
2858  * We consider two types binary-coercible if there is an implicitly
2859  * invokable, no-function-needed pg_cast entry. Also, a domain is always
2860  * binary-coercible to its base type, though *not* vice versa (in the other
2861  * direction, one must apply domain constraint checks before accepting the
2862  * value as legitimate). We also need to special-case various polymorphic
2863  * types.
2864  *
2865  * This function replaces IsBinaryCompatible(), which was an inherently
2866  * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
2867  * the order of the operands is now significant.
2868  */
2869 bool
2870 IsBinaryCoercible(Oid srctype, Oid targettype)
2871 {
2872  HeapTuple tuple;
2873  Form_pg_cast castForm;
2874  bool result;
2875 
2876  /* Fast path if same type */
2877  if (srctype == targettype)
2878  return true;
2879 
2880  /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
2881  if (targettype == ANYOID || targettype == ANYELEMENTOID ||
2882  targettype == ANYCOMPATIBLEOID)
2883  return true;
2884 
2885  /* If srctype is a domain, reduce to its base type */
2886  if (OidIsValid(srctype))
2887  srctype = getBaseType(srctype);
2888 
2889  /* Somewhat-fast path for domain -> base type case */
2890  if (srctype == targettype)
2891  return true;
2892 
2893  /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
2894  if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
2895  if (type_is_array(srctype))
2896  return true;
2897 
2898  /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
2899  if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
2900  if (!type_is_array(srctype))
2901  return true;
2902 
2903  /* Also accept any enum type as coercible to ANYENUM */
2904  if (targettype == ANYENUMOID)
2905  if (type_is_enum(srctype))
2906  return true;
2907 
2908  /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
2909  if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
2910  if (type_is_range(srctype))
2911  return true;
2912 
2913  /* Also accept any multirange type as coercible to ANMULTIYRANGE */
2914  if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
2915  if (type_is_multirange(srctype))
2916  return true;
2917 
2918  /* Also accept any composite type as coercible to RECORD */
2919  if (targettype == RECORDOID)
2920  if (ISCOMPLEX(srctype))
2921  return true;
2922 
2923  /* Also accept any composite array type as coercible to RECORD[] */
2924  if (targettype == RECORDARRAYOID)
2925  if (is_complex_array(srctype))
2926  return true;
2927 
2928  /* Else look in pg_cast */
2930  ObjectIdGetDatum(srctype),
2931  ObjectIdGetDatum(targettype));
2932  if (!HeapTupleIsValid(tuple))
2933  return false; /* no cast */
2934  castForm = (Form_pg_cast) GETSTRUCT(tuple);
2935 
2936  result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2937  castForm->castcontext == COERCION_CODE_IMPLICIT);
2938 
2939  ReleaseSysCache(tuple);
2940 
2941  return result;
2942 }
2943 
2944 
2945 /*
2946  * find_coercion_pathway
2947  * Look for a coercion pathway between two types.
2948  *
2949  * Currently, this deals only with scalar-type cases; it does not consider
2950  * polymorphic types nor casts between composite types. (Perhaps fold
2951  * those in someday?)
2952  *
2953  * ccontext determines the set of available casts.
2954  *
2955  * The possible result codes are:
2956  * COERCION_PATH_NONE: failed to find any coercion pathway
2957  * *funcid is set to InvalidOid
2958  * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
2959  * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
2960  * *funcid is set to InvalidOid
2961  * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
2962  * *funcid is set to InvalidOid
2963  * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
2964  * *funcid is set to InvalidOid
2965  *
2966  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
2967  * needed to do the coercion; if the target is a domain then we may need to
2968  * apply domain constraint checking. If you want to check for a zero-effort
2969  * conversion then use IsBinaryCoercible().
2970  */
2972 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
2973  CoercionContext ccontext,
2974  Oid *funcid)
2975 {
2977  HeapTuple tuple;
2978 
2979  *funcid = InvalidOid;
2980 
2981  /* Perhaps the types are domains; if so, look at their base types */
2982  if (OidIsValid(sourceTypeId))
2983  sourceTypeId = getBaseType(sourceTypeId);
2984  if (OidIsValid(targetTypeId))
2985  targetTypeId = getBaseType(targetTypeId);
2986 
2987  /* Domains are always coercible to and from their base type */
2988  if (sourceTypeId == targetTypeId)
2990 
2991  /* Look in pg_cast */
2993  ObjectIdGetDatum(sourceTypeId),
2994  ObjectIdGetDatum(targetTypeId));
2995 
2996  if (HeapTupleIsValid(tuple))
2997  {
2998  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2999  CoercionContext castcontext;
3000 
3001  /* convert char value for castcontext to CoercionContext enum */
3002  switch (castForm->castcontext)
3003  {
3004  case COERCION_CODE_IMPLICIT:
3005  castcontext = COERCION_IMPLICIT;
3006  break;
3007  case COERCION_CODE_ASSIGNMENT:
3008  castcontext = COERCION_ASSIGNMENT;
3009  break;
3010  case COERCION_CODE_EXPLICIT:
3011  castcontext = COERCION_EXPLICIT;
3012  break;
3013  default:
3014  elog(ERROR, "unrecognized castcontext: %d",
3015  (int) castForm->castcontext);
3016  castcontext = 0; /* keep compiler quiet */
3017  break;
3018  }
3019 
3020  /* Rely on ordering of enum for correct behavior here */
3021  if (ccontext >= castcontext)
3022  {
3023  switch (castForm->castmethod)
3024  {
3025  case COERCION_METHOD_FUNCTION:
3026  result = COERCION_PATH_FUNC;
3027  *funcid = castForm->castfunc;
3028  break;
3029  case COERCION_METHOD_INOUT:
3030  result = COERCION_PATH_COERCEVIAIO;
3031  break;
3032  case COERCION_METHOD_BINARY:
3033  result = COERCION_PATH_RELABELTYPE;
3034  break;
3035  default:
3036  elog(ERROR, "unrecognized castmethod: %d",
3037  (int) castForm->castmethod);
3038  break;
3039  }
3040  }
3041 
3042  ReleaseSysCache(tuple);
3043  }
3044  else
3045  {
3046  /*
3047  * If there's no pg_cast entry, perhaps we are dealing with a pair of
3048  * array types. If so, and if their element types have a conversion
3049  * pathway, report that we can coerce with an ArrayCoerceExpr.
3050  *
3051  * Hack: disallow coercions to oidvector and int2vector, which
3052  * otherwise tend to capture coercions that should go to "real" array
3053  * types. We want those types to be considered "real" arrays for many
3054  * purposes, but not this one. (Also, ArrayCoerceExpr isn't
3055  * guaranteed to produce an output that meets the restrictions of
3056  * these datatypes, such as being 1-dimensional.)
3057  */
3058  if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
3059  {
3060  Oid targetElem;
3061  Oid sourceElem;
3062 
3063  if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
3064  (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
3065  {
3066  CoercionPathType elempathtype;
3067  Oid elemfuncid;
3068 
3069  elempathtype = find_coercion_pathway(targetElem,
3070  sourceElem,
3071  ccontext,
3072  &elemfuncid);
3073  if (elempathtype != COERCION_PATH_NONE)
3074  {
3075  result = COERCION_PATH_ARRAYCOERCE;
3076  }
3077  }
3078  }
3079 
3080  /*
3081  * If we still haven't found a possibility, consider automatic casting
3082  * using I/O functions. We allow assignment casts to string types and
3083  * explicit casts from string types to be handled this way. (The
3084  * CoerceViaIO mechanism is a lot more general than that, but this is
3085  * all we want to allow in the absence of a pg_cast entry.) It would
3086  * probably be better to insist on explicit casts in both directions,
3087  * but this is a compromise to preserve something of the pre-8.3
3088  * behavior that many types had implicit (yipes!) casts to text.
3089  */
3090  if (result == COERCION_PATH_NONE)
3091  {
3092  if (ccontext >= COERCION_ASSIGNMENT &&
3093  TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
3094  result = COERCION_PATH_COERCEVIAIO;
3095  else if (ccontext >= COERCION_EXPLICIT &&
3096  TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
3097  result = COERCION_PATH_COERCEVIAIO;
3098  }
3099  }
3100 
3101  /*
3102  * When parsing PL/pgSQL assignments, allow an I/O cast to be used
3103  * whenever no normal coercion is available.
3104  */
3105  if (result == COERCION_PATH_NONE &&
3106  ccontext == COERCION_PLPGSQL)
3107  result = COERCION_PATH_COERCEVIAIO;
3108 
3109  return result;
3110 }
3111 
3112 
3113 /*
3114  * find_typmod_coercion_function -- does the given type need length coercion?
3115  *
3116  * If the target type possesses a pg_cast function from itself to itself,
3117  * it must need length coercion.
3118  *
3119  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
3120  *
3121  * If the given type is a varlena array type, we do not look for a coercion
3122  * function associated directly with the array type, but instead look for
3123  * one associated with the element type. An ArrayCoerceExpr node must be
3124  * used to apply such a function. (Note: currently, it's pointless to
3125  * return the funcid in this case, because it'll just get looked up again
3126  * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
3127  *
3128  * We use the same result enum as find_coercion_pathway, but the only possible
3129  * result codes are:
3130  * COERCION_PATH_NONE: no length coercion needed
3131  * COERCION_PATH_FUNC: apply the function returned in *funcid
3132  * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
3133  */
3136  Oid *funcid)
3137 {
3138  CoercionPathType result;
3139  Type targetType;
3140  Form_pg_type typeForm;
3141  HeapTuple tuple;
3142 
3143  *funcid = InvalidOid;
3144  result = COERCION_PATH_FUNC;
3145 
3146  targetType = typeidType(typeId);
3147  typeForm = (Form_pg_type) GETSTRUCT(targetType);
3148 
3149  /* Check for a "true" array type */
3150  if (IsTrueArrayType(typeForm))
3151  {
3152  /* Yes, switch our attention to the element type */
3153  typeId = typeForm->typelem;
3154  result = COERCION_PATH_ARRAYCOERCE;
3155  }
3156  ReleaseSysCache(targetType);
3157 
3158  /* Look in pg_cast */
3160  ObjectIdGetDatum(typeId),
3161  ObjectIdGetDatum(typeId));
3162 
3163  if (HeapTupleIsValid(tuple))
3164  {
3165  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3166 
3167  *funcid = castForm->castfunc;
3168  ReleaseSysCache(tuple);
3169  }
3170 
3171  if (!OidIsValid(*funcid))
3172  result = COERCION_PATH_NONE;
3173 
3174  return result;
3175 }
3176 
3177 /*
3178  * is_complex_array
3179  * Is this type an array of composite?
3180  *
3181  * Note: this will not return true for record[]; check for RECORDARRAYOID
3182  * separately if needed.
3183  */
3184 static bool
3186 {
3187  Oid elemtype = get_element_type(typid);
3188 
3189  return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
3190 }
3191 
3192 
3193 /*
3194  * Check whether reltypeId is the row type of a typed table of type
3195  * reloftypeId, or is a domain over such a row type. (This is conceptually
3196  * similar to the subtype relationship checked by typeInheritsFrom().)
3197  */
3198 static bool
3199 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
3200 {
3201  Oid relid = typeOrDomainTypeRelid(reltypeId);
3202  bool result = false;
3203 
3204  if (relid)
3205  {
3206  HeapTuple tp;
3207  Form_pg_class reltup;
3208 
3209  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3210  if (!HeapTupleIsValid(tp))
3211  elog(ERROR, "cache lookup failed for relation %u", relid);
3212 
3213  reltup = (Form_pg_class) GETSTRUCT(tp);
3214  if (reltup->reloftype == reloftypeId)
3215  result = true;
3216 
3217  ReleaseSysCache(tp);
3218  }
3219 
3220  return result;
3221 }
Datum constvalue
Definition: primnodes.h:214
bool check_generic_type_consistency(const Oid *actual_arg_types, const Oid *declared_arg_types, int nargs)
#define NIL
Definition: pg_list.h:65
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2485
List * args
Definition: primnodes.h:1046
Oid typeTypeCollation(Type typ)
Definition: parse_type.c:638
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
#define type_is_array_domain(typid)
Definition: lsyscache.h:204
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid typeOrDomainTypeRelid(Oid type_id)
Definition: parse_type.c:687
bool constbyval
Definition: primnodes.h:217
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1231
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1826
int32 resulttypmod
Definition: primnodes.h:1285
char * check_valid_polymorphic_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
int16 typeLen(Type t)
Definition: parse_type.c:597
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2706
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2734
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
char * pstrdup(const char *in)
Definition: mcxt.c:1187
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:549
Oid resulttype
Definition: primnodes.h:859
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:709
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:222
CoerceParamHook p_coerce_param_hook
Definition: parse_node.h:222
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:533
CoercionForm coercionformat
Definition: primnodes.h:1287
int errcode(int sqlerrcode)
Definition: elog.c:694
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
bool type_is_range(Oid typid)
Definition: lsyscache.c:2635
Oid get_range_multirange(Oid rangeOid)
Definition: lsyscache.c:3408
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
#define OidIsValid(objectId)
Definition: c.h:710
CoercionContext
Definition: primnodes.h:456
bool IsPreferredType(TYPCATEGORY category, Oid type)
static Oid select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
int32 typeMod
Definition: primnodes.h:997
CoercionPathType
Definition: parse_coerce.h:24
signed int int32
Definition: c.h:429
Oid get_multirange_range(Oid multirangeOid)
Definition: lsyscache.c:3433
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
static void hide_coercion_node(Node *node)
Definition: parse_coerce.c:788
#define FUNC_MAX_ARGS
#define list_make1(x1)
Definition: pg_list.h:206
int constlen
Definition: primnodes.h:213
Oid consttype
Definition: primnodes.h:210
char TYPCATEGORY
Definition: parse_coerce.h:21
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool typeByVal(Type t)
Definition: parse_type.c:607
#define linitial(l)
Definition: pg_list.h:174
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
List * colnames
Definition: primnodes.h:1062
#define DatumGetCString(X)
Definition: postgres.h:566
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
char * typeTypeName(Type t)
Definition: parse_type.c:617
Datum stringTypeDatum(Type tp, char *string, int32 atttypmod)
Definition: parse_type.c:652
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:669
Oid constcollid
Definition: primnodes.h:212
int location
Definition: primnodes.h:1063
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:402
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
int errdetail(const char *fmt,...)
Definition: elog.c:1038
static Node * build_coercion_expression(Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:816
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
static Node * coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:746
Expr * arg
Definition: primnodes.h:858
Expr * elemexpr
Definition: primnodes.h:883
FormData_pg_cast * Form_pg_cast
Definition: pg_cast.h:57
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
CoercionPathType find_typmod_coercion_function(Oid typeId, Oid *funcid)
List * lappend(List *list, void *datum)
Definition: list.c:336
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
CoercionForm coerceformat
Definition: primnodes.h:887
int location
Definition: primnodes.h:221
uintptr_t Datum
Definition: postgres.h:367
CoercionForm convertformat
Definition: primnodes.h:910
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
#define makeNode(_type_)
Definition: nodes.h:581
int location
Definition: primnodes.h:863
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
char * check_valid_internal_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
Definition: pg_inherits.c:316
List * expandNSItemVars(ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
bool type_is_multirange(Oid typid)
Definition: lsyscache.c:2645
bool type_is_enum(Oid typid)
Definition: lsyscache.c:2625
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
Oid row_typeid
Definition: primnodes.h:1047
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * arg
Definition: primnodes.h:924
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
#define type_is_array(typid)
Definition: lsyscache.h:202
#define InvalidAttrNumber
Definition: attnum.h:23
static Node * coerce_record_to_complex(ParseState *pstate, Node *node, Oid targetTypeId, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:989
#define nodeTag(nodeptr)
Definition: nodes.h:538
int32 consttypmod
Definition: primnodes.h:211
CoercionForm coerceformat
Definition: primnodes.h:862
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define Int32GetDatum(X)
Definition: postgres.h:479
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int errmsg(const char *fmt,...)
Definition: elog.c:905
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int parser_coercion_errposition(ParseState *pstate, int coerce_location, Node *input_expr)
#define elog(elevel,...)
Definition: elog.h:227
int i
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
void * arg
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
int location
Definition: primnodes.h:499
int32 resulttypmod
Definition: primnodes.h:885
static bool is_complex_array(Oid typid)
Type typeidType(Oid id)
Definition: parse_type.c:576
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
int location
Definition: primnodes.h:926
CoercionForm row_format
Definition: primnodes.h:1061
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2468
CoercionForm
Definition: primnodes.h:476
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2657
Definition: pg_list.h:50
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
#define _(x)
Definition: elog.c:89
Oid get_range_subtype(Oid rangeOid)
Definition: lsyscache.c:3357
int location
Definition: primnodes.h:843
bool constisnull
Definition: primnodes.h:215
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)