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 must be the same range type.
1583  * Similarly, all arguments declared ANYMULTIRANGE must be the same
1584  * multirange type; and if both of these appear, the ANYRANGE type
1585  * must be the element type of the ANYMULTIRANGE type.
1586  * 4) If there are arguments of more than one of these polymorphic types,
1587  * the array element type and/or range subtype must be the same as each
1588  * other and the same as the ANYELEMENT type.
1589  * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
1590  * (alone or in combination with plain ANYELEMENT), we add the extra
1591  * condition that the ANYELEMENT type must be an enum.
1592  * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1593  * we add the extra condition that the ANYELEMENT type must not be an array.
1594  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1595  * is an extra restriction if not.)
1596  * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
1597  * to a common supertype (chosen as per select_common_type's rules).
1598  * ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
1599  * common supertype to not be an array. If there are ANYCOMPATIBLEARRAY
1600  * or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
1601  * types or subtypes are included while making the choice of common supertype.
1602  * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
1603  * type over the common supertype (which might not be the same array type
1604  * as any of the original arrays).
1605  * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
1606  * (after domain flattening), since we have no preference rule that would
1607  * let us choose one over another. Furthermore, that range's subtype
1608  * must exactly match the common supertype chosen by rule 7.
1609  * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
1610  * type (after domain flattening), since we have no preference rule that
1611  * would let us choose one over another. Furthermore, if ANYCOMPATIBLERANGE
1612  * also appears, that range type must be the multirange's element type;
1613  * otherwise, the multirange's range's subtype must exactly match the
1614  * common supertype chosen by rule 7.
1615  *
1616  * Domains over arrays match ANYARRAY, and are immediately flattened to their
1617  * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1618  * argument is a domain over int4[] while another one is just int4[].) Also
1619  * notice that such a domain does *not* match ANYNONARRAY. The same goes
1620  * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
1621  *
1622  * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
1623  * and are immediately flattened to their base type. Likewise, domains
1624  * over multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are
1625  * immediately flattened to their base type.
1626  *
1627  * Note that domains aren't currently considered to match ANYENUM,
1628  * even if their base type would match.
1629  *
1630  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1631  * argument, assume it is okay.
1632  *
1633  * We do not ereport here, but just return false if a rule is violated.
1634  */
1635 bool
1636 check_generic_type_consistency(const Oid *actual_arg_types,
1637  const Oid *declared_arg_types,
1638  int nargs)
1639 {
1640  Oid elem_typeid = InvalidOid;
1641  Oid array_typeid = InvalidOid;
1642  Oid range_typeid = InvalidOid;
1643  Oid multirange_typeid = InvalidOid;
1644  Oid anycompatible_range_typeid = InvalidOid;
1645  Oid anycompatible_range_typelem = InvalidOid;
1646  Oid anycompatible_multirange_typeid = InvalidOid;
1647  Oid anycompatible_multirange_typelem = InvalidOid;
1648  Oid range_typelem = InvalidOid;
1649  bool have_anynonarray = false;
1650  bool have_anyenum = false;
1651  bool have_anycompatible_nonarray = false;
1652  int n_anycompatible_args = 0;
1653  Oid anycompatible_actual_types[FUNC_MAX_ARGS];
1654 
1655  /*
1656  * Loop through the arguments to see if we have any that are polymorphic.
1657  * If so, require the actual types to be consistent.
1658  */
1659  Assert(nargs <= FUNC_MAX_ARGS);
1660  for (int j = 0; j < nargs; j++)
1661  {
1662  Oid decl_type = declared_arg_types[j];
1663  Oid actual_type = actual_arg_types[j];
1664 
1665  if (decl_type == ANYELEMENTOID ||
1666  decl_type == ANYNONARRAYOID ||
1667  decl_type == ANYENUMOID)
1668  {
1669  if (decl_type == ANYNONARRAYOID)
1670  have_anynonarray = true;
1671  else if (decl_type == ANYENUMOID)
1672  have_anyenum = true;
1673  if (actual_type == UNKNOWNOID)
1674  continue;
1675  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1676  return false;
1677  elem_typeid = actual_type;
1678  }
1679  else if (decl_type == ANYARRAYOID)
1680  {
1681  if (actual_type == UNKNOWNOID)
1682  continue;
1683  actual_type = getBaseType(actual_type); /* flatten domains */
1684  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1685  return false;
1686  array_typeid = actual_type;
1687  }
1688  else if (decl_type == ANYRANGEOID)
1689  {
1690  if (actual_type == UNKNOWNOID)
1691  continue;
1692  actual_type = getBaseType(actual_type); /* flatten domains */
1693  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1694  return false;
1695  range_typeid = actual_type;
1696  }
1697  else if (decl_type == ANYMULTIRANGEOID)
1698  {
1699  if (actual_type == UNKNOWNOID)
1700  continue;
1701  actual_type = getBaseType(actual_type); /* flatten domains */
1702  if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
1703  return false;
1704  multirange_typeid = actual_type;
1705  }
1706  else if (decl_type == ANYCOMPATIBLEOID ||
1707  decl_type == ANYCOMPATIBLENONARRAYOID)
1708  {
1709  if (decl_type == ANYCOMPATIBLENONARRAYOID)
1710  have_anycompatible_nonarray = true;
1711  if (actual_type == UNKNOWNOID)
1712  continue;
1713  /* collect the actual types of non-unknown COMPATIBLE args */
1714  anycompatible_actual_types[n_anycompatible_args++] = actual_type;
1715  }
1716  else if (decl_type == ANYCOMPATIBLEARRAYOID)
1717  {
1718  Oid elem_type;
1719 
1720  if (actual_type == UNKNOWNOID)
1721  continue;
1722  actual_type = getBaseType(actual_type); /* flatten domains */
1723  elem_type = get_element_type(actual_type);
1724  if (!OidIsValid(elem_type))
1725  return false; /* not an array */
1726  /* collect the element type for common-supertype choice */
1727  anycompatible_actual_types[n_anycompatible_args++] = elem_type;
1728  }
1729  else if (decl_type == ANYCOMPATIBLERANGEOID)
1730  {
1731  if (actual_type == UNKNOWNOID)
1732  continue;
1733  actual_type = getBaseType(actual_type); /* flatten domains */
1734  if (OidIsValid(anycompatible_range_typeid))
1735  {
1736  /* All ANYCOMPATIBLERANGE arguments must be the same type */
1737  if (anycompatible_range_typeid != actual_type)
1738  return false;
1739  }
1740  else
1741  {
1742  anycompatible_range_typeid = actual_type;
1743  anycompatible_range_typelem = get_range_subtype(actual_type);
1744  if (!OidIsValid(anycompatible_range_typelem))
1745  return false; /* not a range type */
1746  /* collect the subtype for common-supertype choice */
1747  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
1748  }
1749  }
1750  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
1751  {
1752  if (actual_type == UNKNOWNOID)
1753  continue;
1754  actual_type = getBaseType(actual_type); /* flatten domains */
1755  if (OidIsValid(anycompatible_multirange_typeid))
1756  {
1757  /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
1758  if (anycompatible_multirange_typeid != actual_type)
1759  return false;
1760  }
1761  else
1762  {
1763  anycompatible_multirange_typeid = actual_type;
1764  anycompatible_multirange_typelem = get_multirange_range(actual_type);
1765  if (!OidIsValid(anycompatible_multirange_typelem))
1766  return false; /* not a multirange type */
1767  /* we'll consider the subtype below */
1768  }
1769  }
1770  }
1771 
1772  /* Get the element type based on the array type, if we have one */
1773  if (OidIsValid(array_typeid))
1774  {
1775  if (array_typeid == ANYARRAYOID)
1776  {
1777  /*
1778  * Special case for matching ANYARRAY input to an ANYARRAY
1779  * argument: allow it for now. enforce_generic_type_consistency()
1780  * might complain later, depending on the presence of other
1781  * polymorphic arguments or results, but it will deliver a less
1782  * surprising error message than "function does not exist".
1783  *
1784  * (If you think to change this, note that can_coerce_type will
1785  * consider such a situation as a match, so that we might not even
1786  * get here.)
1787  */
1788  }
1789  else
1790  {
1791  Oid array_typelem;
1792 
1793  array_typelem = get_element_type(array_typeid);
1794  if (!OidIsValid(array_typelem))
1795  return false; /* should be an array, but isn't */
1796 
1797  if (!OidIsValid(elem_typeid))
1798  {
1799  /*
1800  * if we don't have an element type yet, use the one we just
1801  * got
1802  */
1803  elem_typeid = array_typelem;
1804  }
1805  else if (array_typelem != elem_typeid)
1806  {
1807  /* otherwise, they better match */
1808  return false;
1809  }
1810  }
1811  }
1812 
1813  /* Deduce range type from multirange type, or check that they agree */
1814  if (OidIsValid(multirange_typeid))
1815  {
1816  Oid multirange_typelem;
1817 
1818  multirange_typelem = get_multirange_range(multirange_typeid);
1819  if (!OidIsValid(multirange_typelem))
1820  return false; /* should be a multirange, but isn't */
1821 
1822  if (!OidIsValid(range_typeid))
1823  {
1824  /* If we don't have a range type yet, use the one we just got */
1825  range_typeid = multirange_typelem;
1826  range_typelem = get_range_subtype(multirange_typelem);
1827  if (!OidIsValid(range_typelem))
1828  return false; /* should be a range, but isn't */
1829  }
1830  else if (multirange_typelem != range_typeid)
1831  {
1832  /* otherwise, they better match */
1833  return false;
1834  }
1835  }
1836 
1837  /* Get the element type based on the range type, if we have one */
1838  if (OidIsValid(range_typeid))
1839  {
1840  range_typelem = get_range_subtype(range_typeid);
1841  if (!OidIsValid(range_typelem))
1842  return false; /* should be a range, but isn't */
1843 
1844  if (!OidIsValid(elem_typeid))
1845  {
1846  /*
1847  * If we don't have an element type yet, use the one we just got
1848  */
1849  elem_typeid = range_typelem;
1850  }
1851  else if (range_typelem != elem_typeid)
1852  {
1853  /* otherwise, they better match */
1854  return false;
1855  }
1856  }
1857 
1858  if (have_anynonarray)
1859  {
1860  /* require the element type to not be an array or domain over array */
1861  if (type_is_array_domain(elem_typeid))
1862  return false;
1863  }
1864 
1865  if (have_anyenum)
1866  {
1867  /* require the element type to be an enum */
1868  if (!type_is_enum(elem_typeid))
1869  return false;
1870  }
1871 
1872  /* Deduce range type from multirange type, or check that they agree */
1873  if (OidIsValid(anycompatible_multirange_typeid))
1874  {
1875  if (OidIsValid(anycompatible_range_typeid))
1876  {
1877  if (anycompatible_multirange_typelem !=
1878  anycompatible_range_typeid)
1879  return false;
1880  }
1881  else
1882  {
1883  anycompatible_range_typeid = anycompatible_multirange_typelem;
1884  anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
1885  if (!OidIsValid(anycompatible_range_typelem))
1886  return false; /* not a range type */
1887  /* collect the subtype for common-supertype choice */
1888  anycompatible_actual_types[n_anycompatible_args++] =
1889  anycompatible_range_typelem;
1890  }
1891  }
1892 
1893  /* Check matching of ANYCOMPATIBLE-family arguments, if any */
1894  if (n_anycompatible_args > 0)
1895  {
1896  Oid anycompatible_typeid;
1897 
1898  anycompatible_typeid =
1899  select_common_type_from_oids(n_anycompatible_args,
1900  anycompatible_actual_types,
1901  true);
1902 
1903  if (!OidIsValid(anycompatible_typeid))
1904  return false; /* there's no common supertype */
1905 
1906  if (have_anycompatible_nonarray)
1907  {
1908  /*
1909  * require the anycompatible type to not be an array or domain
1910  * over array
1911  */
1912  if (type_is_array_domain(anycompatible_typeid))
1913  return false;
1914  }
1915 
1916  /*
1917  * The anycompatible type must exactly match the range element type,
1918  * if we were able to identify one. This checks compatibility for
1919  * anycompatiblemultirange too since that also sets
1920  * anycompatible_range_typelem above.
1921  */
1922  if (OidIsValid(anycompatible_range_typelem) &&
1923  anycompatible_range_typelem != anycompatible_typeid)
1924  return false;
1925  }
1926 
1927  /* Looks valid */
1928  return true;
1929 }
1930 
1931 /*
1932  * enforce_generic_type_consistency()
1933  * Make sure a polymorphic function is legally callable, and
1934  * deduce actual argument and result types.
1935  *
1936  * If any polymorphic pseudotype is used in a function's arguments or
1937  * return type, we make sure the actual data types are consistent with
1938  * each other. The argument consistency rules are shown above for
1939  * check_generic_type_consistency().
1940  *
1941  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1942  * argument, we attempt to deduce the actual type it should have. If
1943  * successful, we alter that position of declared_arg_types[] so that
1944  * make_fn_arguments will coerce the literal to the right thing.
1945  *
1946  * If we have polymorphic arguments of the ANYCOMPATIBLE family,
1947  * we similarly alter declared_arg_types[] entries to show the resolved
1948  * common supertype, so that make_fn_arguments will coerce the actual
1949  * arguments to the proper type.
1950  *
1951  * Rules are applied to the function's return type (possibly altering it)
1952  * if it is declared as a polymorphic type and there is at least one
1953  * polymorphic argument type:
1954  *
1955  * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1956  * argument's actual type as the function's return type.
1957  * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1958  * argument's actual type as the function's return type.
1959  * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
1960  * argument is ANYRANGE or ANYMULTIRANGE, use that argument's actual type
1961  * (or the corresponding range or multirange type) as the function's return
1962  * type.
1963  * 4) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
1964  * at least one ANYELEMENT, ANYARRAY, ANYRANGE, or ANYMULTIRANGE input,
1965  * deduce the return type from those inputs, or throw error if we can't.
1966  * 5) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
1967  * (We have no way to select a specific range type if the arguments don't
1968  * include ANYRANGE or ANYMULTIRANGE.)
1969  * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
1970  * (alone or in combination with plain ANYELEMENT), we add the extra
1971  * condition that the ANYELEMENT type must be an enum.
1972  * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1973  * we add the extra condition that the ANYELEMENT type must not be an array.
1974  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1975  * is an extra restriction if not.)
1976  * 8) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, and ANYCOMPATIBLENONARRAY are handled
1977  * by resolving the common supertype of those arguments (or their element
1978  * types, for array inputs), and then coercing all those arguments to the
1979  * common supertype, or the array type over the common supertype for
1980  * ANYCOMPATIBLEARRAY.
1981  * 9) For ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE, there must be at
1982  * least one non-UNKNOWN input matching those arguments, and all such
1983  * inputs must be the same range type (or its multirange type, as
1984  * appropriate), since we cannot deduce a range type from non-range types.
1985  * Furthermore, the range type's subtype is included while choosing the
1986  * common supertype for ANYCOMPATIBLE et al, and it must exactly match
1987  * that common supertype.
1988  *
1989  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
1990  * respectively, and are immediately flattened to their base type. (In
1991  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
1992  * it to the base type not the domain type.) The same is true for
1993  * ANYMULTIRANGE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLERANGE, and
1994  * ANYCOMPATIBLEMULTIRANGE.
1995  *
1996  * When allow_poly is false, we are not expecting any of the actual_arg_types
1997  * to be polymorphic, and we should not return a polymorphic result type
1998  * either. When allow_poly is true, it is okay to have polymorphic "actual"
1999  * arg types, and we can return a matching polymorphic type as the result.
2000  * (This case is currently used only to check compatibility of an aggregate's
2001  * declaration with the underlying transfn.)
2002  *
2003  * A special case is that we could see ANYARRAY as an actual_arg_type even
2004  * when allow_poly is false (this is possible only because pg_statistic has
2005  * columns shown as anyarray in the catalogs). We allow this to match a
2006  * declared ANYARRAY argument, but only if there is no other polymorphic
2007  * argument that we would need to match it with, and no need to determine
2008  * the element type to infer the result type. Note this means that functions
2009  * taking ANYARRAY had better behave sanely if applied to the pg_statistic
2010  * columns; they can't just assume that successive inputs are of the same
2011  * actual element type. There is no similar logic for ANYCOMPATIBLEARRAY;
2012  * there isn't a need for it since there are no catalog columns of that type,
2013  * so we won't see it as input. We could consider matching an actual ANYARRAY
2014  * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
2015  * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
2016  * at least one other ANYCOMPATIBLE-family argument or result.
2017  *
2018  * Also, if there are no arguments declared to be of polymorphic types,
2019  * we'll return the rettype unmodified even if it's polymorphic. This should
2020  * never occur for user-declared functions, because CREATE FUNCTION prevents
2021  * it. But it does happen for some built-in functions, such as array_in().
2022  */
2023 Oid
2024 enforce_generic_type_consistency(const Oid *actual_arg_types,
2025  Oid *declared_arg_types,
2026  int nargs,
2027  Oid rettype,
2028  bool allow_poly)
2029 {
2030  bool have_poly_anycompatible = false;
2031  bool have_poly_unknowns = false;
2032  Oid elem_typeid = InvalidOid;
2033  Oid array_typeid = InvalidOid;
2034  Oid range_typeid = InvalidOid;
2035  Oid multirange_typeid = InvalidOid;
2036  Oid anycompatible_typeid = InvalidOid;
2037  Oid anycompatible_array_typeid = InvalidOid;
2038  Oid anycompatible_range_typeid = InvalidOid;
2039  Oid anycompatible_range_typelem = InvalidOid;
2040  Oid anycompatible_multirange_typeid = InvalidOid;
2041  Oid anycompatible_multirange_typelem = InvalidOid;
2042  bool have_anynonarray = (rettype == ANYNONARRAYOID);
2043  bool have_anyenum = (rettype == ANYENUMOID);
2044  bool have_anymultirange = (rettype == ANYMULTIRANGEOID);
2045  bool have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
2046  bool have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
2047  bool have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
2048  bool have_anycompatible_multirange = (rettype == ANYCOMPATIBLEMULTIRANGEOID);
2049  int n_poly_args = 0; /* this counts all family-1 arguments */
2050  int n_anycompatible_args = 0; /* this counts only non-unknowns */
2051  Oid anycompatible_actual_types[FUNC_MAX_ARGS];
2052 
2053  /*
2054  * Loop through the arguments to see if we have any that are polymorphic.
2055  * If so, require the actual types to be consistent.
2056  */
2057  Assert(nargs <= FUNC_MAX_ARGS);
2058  for (int j = 0; j < nargs; j++)
2059  {
2060  Oid decl_type = declared_arg_types[j];
2061  Oid actual_type = actual_arg_types[j];
2062 
2063  if (decl_type == ANYELEMENTOID ||
2064  decl_type == ANYNONARRAYOID ||
2065  decl_type == ANYENUMOID)
2066  {
2067  n_poly_args++;
2068  if (decl_type == ANYNONARRAYOID)
2069  have_anynonarray = true;
2070  else if (decl_type == ANYENUMOID)
2071  have_anyenum = true;
2072  if (actual_type == UNKNOWNOID)
2073  {
2074  have_poly_unknowns = true;
2075  continue;
2076  }
2077  if (allow_poly && decl_type == actual_type)
2078  continue; /* no new information here */
2079  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
2080  ereport(ERROR,
2081  (errcode(ERRCODE_DATATYPE_MISMATCH),
2082  errmsg("arguments declared \"%s\" are not all alike", "anyelement"),
2083  errdetail("%s versus %s",
2084  format_type_be(elem_typeid),
2085  format_type_be(actual_type))));
2086  elem_typeid = actual_type;
2087  }
2088  else if (decl_type == ANYARRAYOID)
2089  {
2090  n_poly_args++;
2091  if (actual_type == UNKNOWNOID)
2092  {
2093  have_poly_unknowns = true;
2094  continue;
2095  }
2096  if (allow_poly && decl_type == actual_type)
2097  continue; /* no new information here */
2098  actual_type = getBaseType(actual_type); /* flatten domains */
2099  if (OidIsValid(array_typeid) && actual_type != array_typeid)
2100  ereport(ERROR,
2101  (errcode(ERRCODE_DATATYPE_MISMATCH),
2102  errmsg("arguments declared \"%s\" are not all alike", "anyarray"),
2103  errdetail("%s versus %s",
2104  format_type_be(array_typeid),
2105  format_type_be(actual_type))));
2106  array_typeid = actual_type;
2107  }
2108  else if (decl_type == ANYRANGEOID)
2109  {
2110  n_poly_args++;
2111  if (actual_type == UNKNOWNOID)
2112  {
2113  have_poly_unknowns = true;
2114  continue;
2115  }
2116  if (allow_poly && decl_type == actual_type)
2117  continue; /* no new information here */
2118  actual_type = getBaseType(actual_type); /* flatten domains */
2119  if (OidIsValid(range_typeid) && actual_type != range_typeid)
2120  ereport(ERROR,
2121  (errcode(ERRCODE_DATATYPE_MISMATCH),
2122  errmsg("arguments declared \"%s\" are not all alike", "anyrange"),
2123  errdetail("%s versus %s",
2124  format_type_be(range_typeid),
2125  format_type_be(actual_type))));
2126  range_typeid = actual_type;
2127  }
2128  else if (decl_type == ANYMULTIRANGEOID)
2129  {
2130  n_poly_args++;
2131  have_anymultirange = true;
2132  if (actual_type == UNKNOWNOID)
2133  {
2134  have_poly_unknowns = true;
2135  continue;
2136  }
2137  if (allow_poly && decl_type == actual_type)
2138  continue; /* no new information here */
2139  actual_type = getBaseType(actual_type); /* flatten domains */
2140  if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
2141  ereport(ERROR,
2142  (errcode(ERRCODE_DATATYPE_MISMATCH),
2143  errmsg("arguments declared \"%s\" are not all alike", "anymultirange"),
2144  errdetail("%s versus %s",
2145  format_type_be(multirange_typeid),
2146  format_type_be(actual_type))));
2147  multirange_typeid = actual_type;
2148  }
2149  else if (decl_type == ANYCOMPATIBLEOID ||
2150  decl_type == ANYCOMPATIBLENONARRAYOID)
2151  {
2152  have_poly_anycompatible = true;
2153  if (decl_type == ANYCOMPATIBLENONARRAYOID)
2154  have_anycompatible_nonarray = true;
2155  if (actual_type == UNKNOWNOID)
2156  continue;
2157  if (allow_poly && decl_type == actual_type)
2158  continue; /* no new information here */
2159  /* collect the actual types of non-unknown COMPATIBLE args */
2160  anycompatible_actual_types[n_anycompatible_args++] = actual_type;
2161  }
2162  else if (decl_type == ANYCOMPATIBLEARRAYOID)
2163  {
2164  Oid anycompatible_elem_type;
2165 
2166  have_poly_anycompatible = true;
2167  have_anycompatible_array = true;
2168  if (actual_type == UNKNOWNOID)
2169  continue;
2170  if (allow_poly && decl_type == actual_type)
2171  continue; /* no new information here */
2172  actual_type = getBaseType(actual_type); /* flatten domains */
2173  anycompatible_elem_type = get_element_type(actual_type);
2174  if (!OidIsValid(anycompatible_elem_type))
2175  ereport(ERROR,
2176  (errcode(ERRCODE_DATATYPE_MISMATCH),
2177  errmsg("argument declared %s is not an array but type %s",
2178  "anycompatiblearray",
2179  format_type_be(actual_type))));
2180  /* collect the element type for common-supertype choice */
2181  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
2182  }
2183  else if (decl_type == ANYCOMPATIBLERANGEOID)
2184  {
2185  have_poly_anycompatible = true;
2186  have_anycompatible_range = true;
2187  if (actual_type == UNKNOWNOID)
2188  continue;
2189  if (allow_poly && decl_type == actual_type)
2190  continue; /* no new information here */
2191  actual_type = getBaseType(actual_type); /* flatten domains */
2192  if (OidIsValid(anycompatible_range_typeid))
2193  {
2194  /* All ANYCOMPATIBLERANGE arguments must be the same type */
2195  if (anycompatible_range_typeid != actual_type)
2196  ereport(ERROR,
2197  (errcode(ERRCODE_DATATYPE_MISMATCH),
2198  errmsg("arguments declared \"%s\" are not all alike", "anycompatiblerange"),
2199  errdetail("%s versus %s",
2200  format_type_be(anycompatible_range_typeid),
2201  format_type_be(actual_type))));
2202  }
2203  else
2204  {
2205  anycompatible_range_typeid = actual_type;
2206  anycompatible_range_typelem = get_range_subtype(actual_type);
2207  if (!OidIsValid(anycompatible_range_typelem))
2208  ereport(ERROR,
2209  (errcode(ERRCODE_DATATYPE_MISMATCH),
2210  errmsg("argument declared %s is not a range type but type %s",
2211  "anycompatiblerange",
2212  format_type_be(actual_type))));
2213  /* collect the subtype for common-supertype choice */
2214  anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2215  }
2216  }
2217  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2218  {
2219  have_poly_anycompatible = true;
2220  have_anycompatible_multirange = true;
2221  if (actual_type == UNKNOWNOID)
2222  continue;
2223  if (allow_poly && decl_type == actual_type)
2224  continue; /* no new information here */
2225  actual_type = getBaseType(actual_type); /* flatten domains */
2226  if (OidIsValid(anycompatible_multirange_typeid))
2227  {
2228  /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
2229  if (anycompatible_multirange_typeid != actual_type)
2230  ereport(ERROR,
2231  (errcode(ERRCODE_DATATYPE_MISMATCH),
2232  errmsg("arguments declared \"%s\" are not all alike", "anycompatiblemultirange"),
2233  errdetail("%s versus %s",
2234  format_type_be(anycompatible_multirange_typeid),
2235  format_type_be(actual_type))));
2236  }
2237  else
2238  {
2239  anycompatible_multirange_typeid = actual_type;
2240  anycompatible_multirange_typelem = get_multirange_range(actual_type);
2241  if (!OidIsValid(anycompatible_multirange_typelem))
2242  ereport(ERROR,
2243  (errcode(ERRCODE_DATATYPE_MISMATCH),
2244  errmsg("argument declared %s is not a multirange type but type %s",
2245  "anycompatiblemultirange",
2246  format_type_be(actual_type))));
2247  /* we'll consider the subtype below */
2248  }
2249  }
2250  }
2251 
2252  /*
2253  * Fast Track: if none of the arguments are polymorphic, return the
2254  * unmodified rettype. Not our job to resolve it if it's polymorphic.
2255  */
2256  if (n_poly_args == 0 && !have_poly_anycompatible)
2257  return rettype;
2258 
2259  /* Check matching of family-1 polymorphic arguments, if any */
2260  if (n_poly_args)
2261  {
2262  /* Get the element type based on the array type, if we have one */
2263  if (OidIsValid(array_typeid))
2264  {
2265  Oid array_typelem;
2266 
2267  if (array_typeid == ANYARRAYOID)
2268  {
2269  /*
2270  * Special case for matching ANYARRAY input to an ANYARRAY
2271  * argument: allow it iff no other arguments are family-1
2272  * polymorphics (otherwise we couldn't be sure whether the
2273  * array element type matches up) and the result type doesn't
2274  * require us to infer a specific element type.
2275  */
2276  if (n_poly_args != 1 ||
2277  (rettype != ANYARRAYOID &&
2278  IsPolymorphicTypeFamily1(rettype)))
2279  ereport(ERROR,
2280  (errcode(ERRCODE_DATATYPE_MISMATCH),
2281  errmsg("cannot determine element type of \"anyarray\" argument")));
2282  array_typelem = ANYELEMENTOID;
2283  }
2284  else
2285  {
2286  array_typelem = get_element_type(array_typeid);
2287  if (!OidIsValid(array_typelem))
2288  ereport(ERROR,
2289  (errcode(ERRCODE_DATATYPE_MISMATCH),
2290  errmsg("argument declared %s is not an array but type %s",
2291  "anyarray", format_type_be(array_typeid))));
2292  }
2293 
2294  if (!OidIsValid(elem_typeid))
2295  {
2296  /*
2297  * if we don't have an element type yet, use the one we just
2298  * got
2299  */
2300  elem_typeid = array_typelem;
2301  }
2302  else if (array_typelem != elem_typeid)
2303  {
2304  /* otherwise, they better match */
2305  ereport(ERROR,
2306  (errcode(ERRCODE_DATATYPE_MISMATCH),
2307  errmsg("argument declared %s is not consistent with argument declared %s",
2308  "anyarray", "anyelement"),
2309  errdetail("%s versus %s",
2310  format_type_be(array_typeid),
2311  format_type_be(elem_typeid))));
2312  }
2313  }
2314 
2315  /* Deduce range type from multirange type, or vice versa */
2316  if (OidIsValid(multirange_typeid))
2317  {
2318  Oid multirange_typelem;
2319 
2320  multirange_typelem = get_multirange_range(multirange_typeid);
2321  if (!OidIsValid(multirange_typelem))
2322  ereport(ERROR,
2323  (errcode(ERRCODE_DATATYPE_MISMATCH),
2324  errmsg("argument declared %s is not a multirange type but type %s",
2325  "anymultirange",
2326  format_type_be(multirange_typeid))));
2327 
2328  if (!OidIsValid(range_typeid))
2329  {
2330  /* if we don't have a range type yet, use the one we just got */
2331  range_typeid = multirange_typelem;
2332  }
2333  else if (multirange_typelem != range_typeid)
2334  {
2335  /* otherwise, they better match */
2336  ereport(ERROR,
2337  (errcode(ERRCODE_DATATYPE_MISMATCH),
2338  errmsg("argument declared %s is not consistent with argument declared %s",
2339  "anymultirange", "anyrange"),
2340  errdetail("%s versus %s",
2341  format_type_be(multirange_typeid),
2342  format_type_be(range_typeid))));
2343  }
2344  }
2345  else if (have_anymultirange && OidIsValid(range_typeid))
2346  {
2347  multirange_typeid = get_range_multirange(range_typeid);
2348  /* We'll complain below if that didn't work */
2349  }
2350 
2351  /* Get the element type based on the range type, if we have one */
2352  if (OidIsValid(range_typeid))
2353  {
2354  Oid range_typelem;
2355 
2356  range_typelem = get_range_subtype(range_typeid);
2357  if (!OidIsValid(range_typelem))
2358  ereport(ERROR,
2359  (errcode(ERRCODE_DATATYPE_MISMATCH),
2360  errmsg("argument declared %s is not a range type but type %s",
2361  "anyrange",
2362  format_type_be(range_typeid))));
2363 
2364  if (!OidIsValid(elem_typeid))
2365  {
2366  /*
2367  * if we don't have an element type yet, use the one we just
2368  * got
2369  */
2370  elem_typeid = range_typelem;
2371  }
2372  else if (range_typelem != elem_typeid)
2373  {
2374  /* otherwise, they better match */
2375  ereport(ERROR,
2376  (errcode(ERRCODE_DATATYPE_MISMATCH),
2377  errmsg("argument declared %s is not consistent with argument declared %s",
2378  "anyrange", "anyelement"),
2379  errdetail("%s versus %s",
2380  format_type_be(range_typeid),
2381  format_type_be(elem_typeid))));
2382  }
2383  }
2384 
2385  if (!OidIsValid(elem_typeid))
2386  {
2387  if (allow_poly)
2388  {
2389  elem_typeid = ANYELEMENTOID;
2390  array_typeid = ANYARRAYOID;
2391  range_typeid = ANYRANGEOID;
2392  multirange_typeid = ANYMULTIRANGEOID;
2393  }
2394  else
2395  {
2396  /*
2397  * Only way to get here is if all the family-1 polymorphic
2398  * arguments have UNKNOWN inputs.
2399  */
2400  ereport(ERROR,
2401  (errcode(ERRCODE_DATATYPE_MISMATCH),
2402  errmsg("could not determine polymorphic type because input has type %s",
2403  "unknown")));
2404  }
2405  }
2406 
2407  if (have_anynonarray && elem_typeid != ANYELEMENTOID)
2408  {
2409  /*
2410  * require the element type to not be an array or domain over
2411  * array
2412  */
2413  if (type_is_array_domain(elem_typeid))
2414  ereport(ERROR,
2415  (errcode(ERRCODE_DATATYPE_MISMATCH),
2416  errmsg("type matched to anynonarray is an array type: %s",
2417  format_type_be(elem_typeid))));
2418  }
2419 
2420  if (have_anyenum && elem_typeid != ANYELEMENTOID)
2421  {
2422  /* require the element type to be an enum */
2423  if (!type_is_enum(elem_typeid))
2424  ereport(ERROR,
2425  (errcode(ERRCODE_DATATYPE_MISMATCH),
2426  errmsg("type matched to anyenum is not an enum type: %s",
2427  format_type_be(elem_typeid))));
2428  }
2429  }
2430 
2431  /* Check matching of family-2 polymorphic arguments, if any */
2432  if (have_poly_anycompatible)
2433  {
2434  /* Deduce range type from multirange type, or vice versa */
2435  if (OidIsValid(anycompatible_multirange_typeid))
2436  {
2437  if (OidIsValid(anycompatible_range_typeid))
2438  {
2439  if (anycompatible_multirange_typelem !=
2440  anycompatible_range_typeid)
2441  ereport(ERROR,
2442  (errcode(ERRCODE_DATATYPE_MISMATCH),
2443  errmsg("argument declared %s is not consistent with argument declared %s",
2444  "anycompatiblemultirange",
2445  "anycompatiblerange"),
2446  errdetail("%s versus %s",
2447  format_type_be(anycompatible_multirange_typeid),
2448  format_type_be(anycompatible_range_typeid))));
2449  }
2450  else
2451  {
2452  anycompatible_range_typeid = anycompatible_multirange_typelem;
2453  anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
2454  if (!OidIsValid(anycompatible_range_typelem))
2455  ereport(ERROR,
2456  (errcode(ERRCODE_DATATYPE_MISMATCH),
2457  errmsg("argument declared %s is not a multirange type but type %s",
2458  "anycompatiblemultirange",
2459  format_type_be(anycompatible_multirange_typeid))));
2460  /* this enables element type matching check below */
2461  have_anycompatible_range = true;
2462  /* collect the subtype for common-supertype choice */
2463  anycompatible_actual_types[n_anycompatible_args++] =
2464  anycompatible_range_typelem;
2465  }
2466  }
2467  else if (have_anycompatible_multirange &&
2468  OidIsValid(anycompatible_range_typeid))
2469  {
2470  anycompatible_multirange_typeid = get_range_multirange(anycompatible_range_typeid);
2471  /* We'll complain below if that didn't work */
2472  }
2473 
2474  if (n_anycompatible_args > 0)
2475  {
2476  anycompatible_typeid =
2477  select_common_type_from_oids(n_anycompatible_args,
2478  anycompatible_actual_types,
2479  false);
2480 
2481  if (have_anycompatible_array)
2482  {
2483  anycompatible_array_typeid = get_array_type(anycompatible_typeid);
2484  if (!OidIsValid(anycompatible_array_typeid))
2485  ereport(ERROR,
2486  (errcode(ERRCODE_UNDEFINED_OBJECT),
2487  errmsg("could not find array type for data type %s",
2488  format_type_be(anycompatible_typeid))));
2489  }
2490 
2491  if (have_anycompatible_range)
2492  {
2493  /* we can't infer a range type from the others */
2494  if (!OidIsValid(anycompatible_range_typeid))
2495  ereport(ERROR,
2496  (errcode(ERRCODE_DATATYPE_MISMATCH),
2497  errmsg("could not determine polymorphic type %s because input has type %s",
2498  "anycompatiblerange", "unknown")));
2499 
2500  /*
2501  * the anycompatible type must exactly match the range element
2502  * type
2503  */
2504  if (anycompatible_range_typelem != anycompatible_typeid)
2505  ereport(ERROR,
2506  (errcode(ERRCODE_DATATYPE_MISMATCH),
2507  errmsg("anycompatiblerange type %s does not match anycompatible type %s",
2508  format_type_be(anycompatible_range_typeid),
2509  format_type_be(anycompatible_typeid))));
2510  }
2511 
2512  if (have_anycompatible_multirange)
2513  {
2514  /* we can't infer a multirange type from the others */
2515  if (!OidIsValid(anycompatible_multirange_typeid))
2516  ereport(ERROR,
2517  (errcode(ERRCODE_DATATYPE_MISMATCH),
2518  errmsg("could not determine polymorphic type %s because input has type %s",
2519  "anycompatiblemultirange", "unknown")));
2520 
2521  /*
2522  * the anycompatible type must exactly match the multirange
2523  * element type
2524  */
2525  if (anycompatible_range_typelem != anycompatible_typeid)
2526  ereport(ERROR,
2527  (errcode(ERRCODE_DATATYPE_MISMATCH),
2528  errmsg("anycompatiblemultirange type %s does not match anycompatible type %s",
2529  format_type_be(anycompatible_multirange_typeid),
2530  format_type_be(anycompatible_typeid))));
2531  }
2532 
2533  if (have_anycompatible_nonarray)
2534  {
2535  /*
2536  * require the element type to not be an array or domain over
2537  * array
2538  */
2539  if (type_is_array_domain(anycompatible_typeid))
2540  ereport(ERROR,
2541  (errcode(ERRCODE_DATATYPE_MISMATCH),
2542  errmsg("type matched to anycompatiblenonarray is an array type: %s",
2543  format_type_be(anycompatible_typeid))));
2544  }
2545  }
2546  else
2547  {
2548  if (allow_poly)
2549  {
2550  anycompatible_typeid = ANYCOMPATIBLEOID;
2551  anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
2552  anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
2553  anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
2554  }
2555  else
2556  {
2557  /*
2558  * Only way to get here is if all the family-2 polymorphic
2559  * arguments have UNKNOWN inputs. Resolve to TEXT as
2560  * select_common_type() would do. That doesn't license us to
2561  * use TEXTRANGE or TEXTMULTIRANGE, though.
2562  */
2563  anycompatible_typeid = TEXTOID;
2564  anycompatible_array_typeid = TEXTARRAYOID;
2565  if (have_anycompatible_range)
2566  ereport(ERROR,
2567  (errcode(ERRCODE_DATATYPE_MISMATCH),
2568  errmsg("could not determine polymorphic type %s because input has type %s",
2569  "anycompatiblerange", "unknown")));
2570  if (have_anycompatible_multirange)
2571  ereport(ERROR,
2572  (errcode(ERRCODE_DATATYPE_MISMATCH),
2573  errmsg("could not determine polymorphic type %s because input has type %s",
2574  "anycompatiblemultirange", "unknown")));
2575  }
2576  }
2577 
2578  /* replace family-2 polymorphic types by selected types */
2579  for (int j = 0; j < nargs; j++)
2580  {
2581  Oid decl_type = declared_arg_types[j];
2582 
2583  if (decl_type == ANYCOMPATIBLEOID ||
2584  decl_type == ANYCOMPATIBLENONARRAYOID)
2585  declared_arg_types[j] = anycompatible_typeid;
2586  else if (decl_type == ANYCOMPATIBLEARRAYOID)
2587  declared_arg_types[j] = anycompatible_array_typeid;
2588  else if (decl_type == ANYCOMPATIBLERANGEOID)
2589  declared_arg_types[j] = anycompatible_range_typeid;
2590  else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2591  declared_arg_types[j] = anycompatible_multirange_typeid;
2592  }
2593  }
2594 
2595  /*
2596  * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
2597  * re-scan to assign correct types to them.
2598  *
2599  * Note: we don't have to consider unknown inputs that were matched to
2600  * family-2 polymorphic arguments, because we forcibly updated their
2601  * declared_arg_types[] positions just above.
2602  */
2603  if (have_poly_unknowns)
2604  {
2605  for (int j = 0; j < nargs; j++)
2606  {
2607  Oid decl_type = declared_arg_types[j];
2608  Oid actual_type = actual_arg_types[j];
2609 
2610  if (actual_type != UNKNOWNOID)
2611  continue;
2612 
2613  if (decl_type == ANYELEMENTOID ||
2614  decl_type == ANYNONARRAYOID ||
2615  decl_type == ANYENUMOID)
2616  declared_arg_types[j] = elem_typeid;
2617  else if (decl_type == ANYARRAYOID)
2618  {
2619  if (!OidIsValid(array_typeid))
2620  {
2621  array_typeid = get_array_type(elem_typeid);
2622  if (!OidIsValid(array_typeid))
2623  ereport(ERROR,
2624  (errcode(ERRCODE_UNDEFINED_OBJECT),
2625  errmsg("could not find array type for data type %s",
2626  format_type_be(elem_typeid))));
2627  }
2628  declared_arg_types[j] = array_typeid;
2629  }
2630  else if (decl_type == ANYRANGEOID)
2631  {
2632  if (!OidIsValid(range_typeid))
2633  {
2634  /* we can't infer a range type from the others */
2635  ereport(ERROR,
2636  (errcode(ERRCODE_DATATYPE_MISMATCH),
2637  errmsg("could not determine polymorphic type %s because input has type %s",
2638  "anyrange", "unknown")));
2639  }
2640  declared_arg_types[j] = range_typeid;
2641  }
2642  else if (decl_type == ANYMULTIRANGEOID)
2643  {
2644  if (!OidIsValid(multirange_typeid))
2645  {
2646  /* we can't infer a multirange type from the others */
2647  ereport(ERROR,
2648  (errcode(ERRCODE_DATATYPE_MISMATCH),
2649  errmsg("could not determine polymorphic type %s because input has type %s",
2650  "anymultirange", "unknown")));
2651  }
2652  declared_arg_types[j] = multirange_typeid;
2653  }
2654  }
2655  }
2656 
2657  /* if we return ANYELEMENT use the appropriate argument type */
2658  if (rettype == ANYELEMENTOID ||
2659  rettype == ANYNONARRAYOID ||
2660  rettype == ANYENUMOID)
2661  return elem_typeid;
2662 
2663  /* if we return ANYARRAY use the appropriate argument type */
2664  if (rettype == ANYARRAYOID)
2665  {
2666  if (!OidIsValid(array_typeid))
2667  {
2668  array_typeid = get_array_type(elem_typeid);
2669  if (!OidIsValid(array_typeid))
2670  ereport(ERROR,
2671  (errcode(ERRCODE_UNDEFINED_OBJECT),
2672  errmsg("could not find array type for data type %s",
2673  format_type_be(elem_typeid))));
2674  }
2675  return array_typeid;
2676  }
2677 
2678  /* if we return ANYRANGE use the appropriate argument type */
2679  if (rettype == ANYRANGEOID)
2680  {
2681  /* this error is unreachable if the function signature is valid: */
2682  if (!OidIsValid(range_typeid))
2683  ereport(ERROR,
2684  (errcode(ERRCODE_DATATYPE_MISMATCH),
2685  errmsg_internal("could not determine polymorphic type %s because input has type %s",
2686  "anyrange", "unknown")));
2687  return range_typeid;
2688  }
2689 
2690  /* if we return ANYMULTIRANGE use the appropriate argument type */
2691  if (rettype == ANYMULTIRANGEOID)
2692  {
2693  /* this error is unreachable if the function signature is valid: */
2694  if (!OidIsValid(multirange_typeid))
2695  ereport(ERROR,
2696  (errcode(ERRCODE_DATATYPE_MISMATCH),
2697  errmsg_internal("could not determine polymorphic type %s because input has type %s",
2698  "anymultirange", "unknown")));
2699  return multirange_typeid;
2700  }
2701 
2702  /* if we return ANYCOMPATIBLE use the appropriate type */
2703  if (rettype == ANYCOMPATIBLEOID ||
2704  rettype == ANYCOMPATIBLENONARRAYOID)
2705  {
2706  /* this error is unreachable if the function signature is valid: */
2707  if (!OidIsValid(anycompatible_typeid))
2708  ereport(ERROR,
2709  (errcode(ERRCODE_DATATYPE_MISMATCH),
2710  errmsg_internal("could not identify anycompatible type")));
2711  return anycompatible_typeid;
2712  }
2713 
2714  /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
2715  if (rettype == ANYCOMPATIBLEARRAYOID)
2716  {
2717  /* this error is unreachable if the function signature is valid: */
2718  if (!OidIsValid(anycompatible_array_typeid))
2719  ereport(ERROR,
2720  (errcode(ERRCODE_DATATYPE_MISMATCH),
2721  errmsg_internal("could not identify anycompatiblearray type")));
2722  return anycompatible_array_typeid;
2723  }
2724 
2725  /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
2726  if (rettype == ANYCOMPATIBLERANGEOID)
2727  {
2728  /* this error is unreachable if the function signature is valid: */
2729  if (!OidIsValid(anycompatible_range_typeid))
2730  ereport(ERROR,
2731  (errcode(ERRCODE_DATATYPE_MISMATCH),
2732  errmsg_internal("could not identify anycompatiblerange type")));
2733  return anycompatible_range_typeid;
2734  }
2735 
2736  /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
2737  if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
2738  {
2739  /* this error is unreachable if the function signature is valid: */
2740  if (!OidIsValid(anycompatible_multirange_typeid))
2741  ereport(ERROR,
2742  (errcode(ERRCODE_DATATYPE_MISMATCH),
2743  errmsg_internal("could not identify anycompatiblemultirange type")));
2744  return anycompatible_multirange_typeid;
2745  }
2746 
2747  /* we don't return a generic type; send back the original return type */
2748  return rettype;
2749 }
2750 
2751 /*
2752  * check_valid_polymorphic_signature()
2753  * Is a proposed function signature valid per polymorphism rules?
2754  *
2755  * Returns NULL if the signature is valid (either ret_type is not polymorphic,
2756  * or it can be deduced from the given declared argument types). Otherwise,
2757  * returns a palloc'd, already translated errdetail string saying why not.
2758  */
2759 char *
2761  const Oid *declared_arg_types,
2762  int nargs)
2763 {
2764  if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
2765  {
2766  /*
2767  * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
2768  * input, else we can't tell which of several range types with the
2769  * same element type to use.
2770  */
2771  for (int i = 0; i < nargs; i++)
2772  {
2773  if (declared_arg_types[i] == ANYRANGEOID ||
2774  declared_arg_types[i] == ANYMULTIRANGEOID)
2775  return NULL; /* OK */
2776  }
2777  return psprintf(_("A result of type %s requires at least one input of type anyrange or anymultirange."),
2778  format_type_be(ret_type));
2779  }
2780  else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
2781  {
2782  /*
2783  * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
2784  * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
2785  * tell which of several range types with the same element type to
2786  * use.
2787  */
2788  for (int i = 0; i < nargs; i++)
2789  {
2790  if (declared_arg_types[i] == ANYCOMPATIBLERANGEOID ||
2791  declared_arg_types[i] == ANYCOMPATIBLEMULTIRANGEOID)
2792  return NULL; /* OK */
2793  }
2794  return psprintf(_("A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
2795  format_type_be(ret_type));
2796  }
2797  else if (IsPolymorphicTypeFamily1(ret_type))
2798  {
2799  /* Otherwise, any family-1 type can be deduced from any other */
2800  for (int i = 0; i < nargs; i++)
2801  {
2802  if (IsPolymorphicTypeFamily1(declared_arg_types[i]))
2803  return NULL; /* OK */
2804  }
2805  /* Keep this list in sync with IsPolymorphicTypeFamily1! */
2806  return psprintf(_("A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
2807  format_type_be(ret_type));
2808  }
2809  else if (IsPolymorphicTypeFamily2(ret_type))
2810  {
2811  /* Otherwise, any family-2 type can be deduced from any other */
2812  for (int i = 0; i < nargs; i++)
2813  {
2814  if (IsPolymorphicTypeFamily2(declared_arg_types[i]))
2815  return NULL; /* OK */
2816  }
2817  /* Keep this list in sync with IsPolymorphicTypeFamily2! */
2818  return psprintf(_("A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, anycompatiblerange, or anycompatiblemultirange."),
2819  format_type_be(ret_type));
2820  }
2821  else
2822  return NULL; /* OK, ret_type is not polymorphic */
2823 }
2824 
2825 /*
2826  * check_valid_internal_signature()
2827  * Is a proposed function signature valid per INTERNAL safety rules?
2828  *
2829  * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
2830  * none of the declared arg types are. (It's unsafe to create such a function
2831  * since it would allow invocation of INTERNAL-consuming functions directly
2832  * from SQL.) It's overkill to return the error detail message, since there
2833  * is only one possibility, but we do it like this to keep the API similar to
2834  * check_valid_polymorphic_signature().
2835  */
2836 char *
2838  const Oid *declared_arg_types,
2839  int nargs)
2840 {
2841  if (ret_type == INTERNALOID)
2842  {
2843  for (int i = 0; i < nargs; i++)
2844  {
2845  if (declared_arg_types[i] == ret_type)
2846  return NULL; /* OK */
2847  }
2848  return pstrdup(_("A result of type internal requires at least one input of type internal."));
2849  }
2850  else
2851  return NULL; /* OK, ret_type is not INTERNAL */
2852 }
2853 
2854 
2855 /* TypeCategory()
2856  * Assign a category to the specified type OID.
2857  *
2858  * NB: this must not return TYPCATEGORY_INVALID.
2859  */
2862 {
2863  char typcategory;
2864  bool typispreferred;
2865 
2866  get_type_category_preferred(type, &typcategory, &typispreferred);
2867  Assert(typcategory != TYPCATEGORY_INVALID);
2868  return (TYPCATEGORY) typcategory;
2869 }
2870 
2871 
2872 /* IsPreferredType()
2873  * Check if this type is a preferred type for the given category.
2874  *
2875  * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
2876  * types of any category; otherwise, only for preferred types of that
2877  * category.
2878  */
2879 bool
2881 {
2882  char typcategory;
2883  bool typispreferred;
2884 
2885  get_type_category_preferred(type, &typcategory, &typispreferred);
2886  if (category == typcategory || category == TYPCATEGORY_INVALID)
2887  return typispreferred;
2888  else
2889  return false;
2890 }
2891 
2892 
2893 /* IsBinaryCoercible()
2894  * Check if srctype is binary-coercible to targettype.
2895  *
2896  * This notion allows us to cheat and directly exchange values without
2897  * going through the trouble of calling a conversion function. Note that
2898  * in general, this should only be an implementation shortcut. Before 7.4,
2899  * this was also used as a heuristic for resolving overloaded functions and
2900  * operators, but that's basically a bad idea.
2901  *
2902  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
2903  * We consider two types binary-coercible if there is an implicitly
2904  * invokable, no-function-needed pg_cast entry. Also, a domain is always
2905  * binary-coercible to its base type, though *not* vice versa (in the other
2906  * direction, one must apply domain constraint checks before accepting the
2907  * value as legitimate). We also need to special-case various polymorphic
2908  * types.
2909  *
2910  * This function replaces IsBinaryCompatible(), which was an inherently
2911  * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
2912  * the order of the operands is now significant.
2913  */
2914 bool
2915 IsBinaryCoercible(Oid srctype, Oid targettype)
2916 {
2917  HeapTuple tuple;
2918  Form_pg_cast castForm;
2919  bool result;
2920 
2921  /* Fast path if same type */
2922  if (srctype == targettype)
2923  return true;
2924 
2925  /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
2926  if (targettype == ANYOID || targettype == ANYELEMENTOID ||
2927  targettype == ANYCOMPATIBLEOID)
2928  return true;
2929 
2930  /* If srctype is a domain, reduce to its base type */
2931  if (OidIsValid(srctype))
2932  srctype = getBaseType(srctype);
2933 
2934  /* Somewhat-fast path for domain -> base type case */
2935  if (srctype == targettype)
2936  return true;
2937 
2938  /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
2939  if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
2940  if (type_is_array(srctype))
2941  return true;
2942 
2943  /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
2944  if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
2945  if (!type_is_array(srctype))
2946  return true;
2947 
2948  /* Also accept any enum type as coercible to ANYENUM */
2949  if (targettype == ANYENUMOID)
2950  if (type_is_enum(srctype))
2951  return true;
2952 
2953  /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
2954  if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
2955  if (type_is_range(srctype))
2956  return true;
2957 
2958  /* Also, any multirange type is coercible to ANY[COMPATIBLE]MULTIRANGE */
2959  if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
2960  if (type_is_multirange(srctype))
2961  return true;
2962 
2963  /* Also accept any composite type as coercible to RECORD */
2964  if (targettype == RECORDOID)
2965  if (ISCOMPLEX(srctype))
2966  return true;
2967 
2968  /* Also accept any composite array type as coercible to RECORD[] */
2969  if (targettype == RECORDARRAYOID)
2970  if (is_complex_array(srctype))
2971  return true;
2972 
2973  /* Else look in pg_cast */
2975  ObjectIdGetDatum(srctype),
2976  ObjectIdGetDatum(targettype));
2977  if (!HeapTupleIsValid(tuple))
2978  return false; /* no cast */
2979  castForm = (Form_pg_cast) GETSTRUCT(tuple);
2980 
2981  result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2982  castForm->castcontext == COERCION_CODE_IMPLICIT);
2983 
2984  ReleaseSysCache(tuple);
2985 
2986  return result;
2987 }
2988 
2989 
2990 /*
2991  * find_coercion_pathway
2992  * Look for a coercion pathway between two types.
2993  *
2994  * Currently, this deals only with scalar-type cases; it does not consider
2995  * polymorphic types nor casts between composite types. (Perhaps fold
2996  * those in someday?)
2997  *
2998  * ccontext determines the set of available casts.
2999  *
3000  * The possible result codes are:
3001  * COERCION_PATH_NONE: failed to find any coercion pathway
3002  * *funcid is set to InvalidOid
3003  * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
3004  * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
3005  * *funcid is set to InvalidOid
3006  * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
3007  * *funcid is set to InvalidOid
3008  * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
3009  * *funcid is set to InvalidOid
3010  *
3011  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
3012  * needed to do the coercion; if the target is a domain then we may need to
3013  * apply domain constraint checking. If you want to check for a zero-effort
3014  * conversion then use IsBinaryCoercible().
3015  */
3017 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
3018  CoercionContext ccontext,
3019  Oid *funcid)
3020 {
3022  HeapTuple tuple;
3023 
3024  *funcid = InvalidOid;
3025 
3026  /* Perhaps the types are domains; if so, look at their base types */
3027  if (OidIsValid(sourceTypeId))
3028  sourceTypeId = getBaseType(sourceTypeId);
3029  if (OidIsValid(targetTypeId))
3030  targetTypeId = getBaseType(targetTypeId);
3031 
3032  /* Domains are always coercible to and from their base type */
3033  if (sourceTypeId == targetTypeId)
3035 
3036  /* Look in pg_cast */
3038  ObjectIdGetDatum(sourceTypeId),
3039  ObjectIdGetDatum(targetTypeId));
3040 
3041  if (HeapTupleIsValid(tuple))
3042  {
3043  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3044  CoercionContext castcontext;
3045 
3046  /* convert char value for castcontext to CoercionContext enum */
3047  switch (castForm->castcontext)
3048  {
3049  case COERCION_CODE_IMPLICIT:
3050  castcontext = COERCION_IMPLICIT;
3051  break;
3052  case COERCION_CODE_ASSIGNMENT:
3053  castcontext = COERCION_ASSIGNMENT;
3054  break;
3055  case COERCION_CODE_EXPLICIT:
3056  castcontext = COERCION_EXPLICIT;
3057  break;
3058  default:
3059  elog(ERROR, "unrecognized castcontext: %d",
3060  (int) castForm->castcontext);
3061  castcontext = 0; /* keep compiler quiet */
3062  break;
3063  }
3064 
3065  /* Rely on ordering of enum for correct behavior here */
3066  if (ccontext >= castcontext)
3067  {
3068  switch (castForm->castmethod)
3069  {
3070  case COERCION_METHOD_FUNCTION:
3071  result = COERCION_PATH_FUNC;
3072  *funcid = castForm->castfunc;
3073  break;
3074  case COERCION_METHOD_INOUT:
3075  result = COERCION_PATH_COERCEVIAIO;
3076  break;
3077  case COERCION_METHOD_BINARY:
3078  result = COERCION_PATH_RELABELTYPE;
3079  break;
3080  default:
3081  elog(ERROR, "unrecognized castmethod: %d",
3082  (int) castForm->castmethod);
3083  break;
3084  }
3085  }
3086 
3087  ReleaseSysCache(tuple);
3088  }
3089  else
3090  {
3091  /*
3092  * If there's no pg_cast entry, perhaps we are dealing with a pair of
3093  * array types. If so, and if their element types have a conversion
3094  * pathway, report that we can coerce with an ArrayCoerceExpr.
3095  *
3096  * Hack: disallow coercions to oidvector and int2vector, which
3097  * otherwise tend to capture coercions that should go to "real" array
3098  * types. We want those types to be considered "real" arrays for many
3099  * purposes, but not this one. (Also, ArrayCoerceExpr isn't
3100  * guaranteed to produce an output that meets the restrictions of
3101  * these datatypes, such as being 1-dimensional.)
3102  */
3103  if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
3104  {
3105  Oid targetElem;
3106  Oid sourceElem;
3107 
3108  if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
3109  (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
3110  {
3111  CoercionPathType elempathtype;
3112  Oid elemfuncid;
3113 
3114  elempathtype = find_coercion_pathway(targetElem,
3115  sourceElem,
3116  ccontext,
3117  &elemfuncid);
3118  if (elempathtype != COERCION_PATH_NONE)
3119  {
3120  result = COERCION_PATH_ARRAYCOERCE;
3121  }
3122  }
3123  }
3124 
3125  /*
3126  * If we still haven't found a possibility, consider automatic casting
3127  * using I/O functions. We allow assignment casts to string types and
3128  * explicit casts from string types to be handled this way. (The
3129  * CoerceViaIO mechanism is a lot more general than that, but this is
3130  * all we want to allow in the absence of a pg_cast entry.) It would
3131  * probably be better to insist on explicit casts in both directions,
3132  * but this is a compromise to preserve something of the pre-8.3
3133  * behavior that many types had implicit (yipes!) casts to text.
3134  */
3135  if (result == COERCION_PATH_NONE)
3136  {
3137  if (ccontext >= COERCION_ASSIGNMENT &&
3138  TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
3139  result = COERCION_PATH_COERCEVIAIO;
3140  else if (ccontext >= COERCION_EXPLICIT &&
3141  TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
3142  result = COERCION_PATH_COERCEVIAIO;
3143  }
3144  }
3145 
3146  /*
3147  * When parsing PL/pgSQL assignments, allow an I/O cast to be used
3148  * whenever no normal coercion is available.
3149  */
3150  if (result == COERCION_PATH_NONE &&
3151  ccontext == COERCION_PLPGSQL)
3152  result = COERCION_PATH_COERCEVIAIO;
3153 
3154  return result;
3155 }
3156 
3157 
3158 /*
3159  * find_typmod_coercion_function -- does the given type need length coercion?
3160  *
3161  * If the target type possesses a pg_cast function from itself to itself,
3162  * it must need length coercion.
3163  *
3164  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
3165  *
3166  * If the given type is a varlena array type, we do not look for a coercion
3167  * function associated directly with the array type, but instead look for
3168  * one associated with the element type. An ArrayCoerceExpr node must be
3169  * used to apply such a function. (Note: currently, it's pointless to
3170  * return the funcid in this case, because it'll just get looked up again
3171  * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
3172  *
3173  * We use the same result enum as find_coercion_pathway, but the only possible
3174  * result codes are:
3175  * COERCION_PATH_NONE: no length coercion needed
3176  * COERCION_PATH_FUNC: apply the function returned in *funcid
3177  * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
3178  */
3181  Oid *funcid)
3182 {
3183  CoercionPathType result;
3184  Type targetType;
3185  Form_pg_type typeForm;
3186  HeapTuple tuple;
3187 
3188  *funcid = InvalidOid;
3189  result = COERCION_PATH_FUNC;
3190 
3191  targetType = typeidType(typeId);
3192  typeForm = (Form_pg_type) GETSTRUCT(targetType);
3193 
3194  /* Check for a "true" array type */
3195  if (IsTrueArrayType(typeForm))
3196  {
3197  /* Yes, switch our attention to the element type */
3198  typeId = typeForm->typelem;
3199  result = COERCION_PATH_ARRAYCOERCE;
3200  }
3201  ReleaseSysCache(targetType);
3202 
3203  /* Look in pg_cast */
3205  ObjectIdGetDatum(typeId),
3206  ObjectIdGetDatum(typeId));
3207 
3208  if (HeapTupleIsValid(tuple))
3209  {
3210  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3211 
3212  *funcid = castForm->castfunc;
3213  ReleaseSysCache(tuple);
3214  }
3215 
3216  if (!OidIsValid(*funcid))
3217  result = COERCION_PATH_NONE;
3218 
3219  return result;
3220 }
3221 
3222 /*
3223  * is_complex_array
3224  * Is this type an array of composite?
3225  *
3226  * Note: this will not return true for record[]; check for RECORDARRAYOID
3227  * separately if needed.
3228  */
3229 static bool
3231 {
3232  Oid elemtype = get_element_type(typid);
3233 
3234  return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
3235 }
3236 
3237 
3238 /*
3239  * Check whether reltypeId is the row type of a typed table of type
3240  * reloftypeId, or is a domain over such a row type. (This is conceptually
3241  * similar to the subtype relationship checked by typeInheritsFrom().)
3242  */
3243 static bool
3244 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
3245 {
3246  Oid relid = typeOrDomainTypeRelid(reltypeId);
3247  bool result = false;
3248 
3249  if (relid)
3250  {
3251  HeapTuple tp;
3252  Form_pg_class reltup;
3253 
3254  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3255  if (!HeapTupleIsValid(tp))
3256  elog(ERROR, "cache lookup failed for relation %u", relid);
3257 
3258  reltup = (Form_pg_class) GETSTRUCT(tp);
3259  if (reltup->reloftype == reloftypeId)
3260  result = true;
3261 
3262  ReleaseSysCache(tp);
3263  }
3264 
3265  return result;
3266 }
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:1068
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:1824
int32 resulttypmod
Definition: primnodes.h:1307
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:881
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:1309
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:1019
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:1084
#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:1085
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:207
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:880
Expr * elemexpr
Definition: primnodes.h:905
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:909
int location
Definition: primnodes.h:226
uintptr_t Datum
Definition: postgres.h:411
CoercionForm convertformat
Definition: primnodes.h:932
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:885
#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:1069
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * arg
Definition: primnodes.h:946
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:884
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:907
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:948
CoercionForm row_format
Definition: primnodes.h:1083
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:865
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)