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