PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2017, 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 "access/htup_details.h"
18 #include "catalog/pg_cast.h"
19 #include "catalog/pg_class.h"
20 #include "catalog/pg_inherits_fn.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "nodes/makefuncs.h"
24 #include "nodes/nodeFuncs.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/datum.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  CoercionForm cformat, int location,
38  bool isExplicit, bool hideInputCoercion);
39 static void hide_coercion_node(Node *node);
40 static Node *build_coercion_expression(Node *node,
41  CoercionPathType pathtype,
42  Oid funcId,
43  Oid targetTypeId, int32 targetTypMod,
44  CoercionForm cformat, int location,
45  bool isExplicit);
46 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
47  Oid targetTypeId,
48  CoercionContext ccontext,
49  CoercionForm cformat,
50  int location);
51 static bool is_complex_array(Oid typid);
52 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
53 
54 
55 /*
56  * coerce_to_target_type()
57  * Convert an expression to a target type and typmod.
58  *
59  * This is the general-purpose entry point for arbitrary type coercion
60  * operations. Direct use of the component operations can_coerce_type,
61  * coerce_type, and coerce_type_typmod should be restricted to special
62  * cases (eg, when the conversion is expected to succeed).
63  *
64  * Returns the possibly-transformed expression tree, or NULL if the type
65  * conversion is not possible. (We do this, rather than ereport'ing directly,
66  * so that callers can generate custom error messages indicating context.)
67  *
68  * pstate - parse state (can be NULL, see coerce_type)
69  * expr - input expression tree (already transformed by transformExpr)
70  * exprtype - result type of expr
71  * targettype - desired result type
72  * targettypmod - desired result typmod
73  * ccontext, cformat - context indicators to control coercions
74  * location - parse location of the coercion request, or -1 if unknown/implicit
75  */
76 Node *
77 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
78  Oid targettype, int32 targettypmod,
79  CoercionContext ccontext,
80  CoercionForm cformat,
81  int location)
82 {
83  Node *result;
84  Node *origexpr;
85 
86  if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
87  return NULL;
88 
89  /*
90  * If the input has a CollateExpr at the top, strip it off, perform the
91  * coercion, and put a new one back on. This is annoying since it
92  * duplicates logic in coerce_type, but if we don't do this then it's too
93  * hard to tell whether coerce_type actually changed anything, and we
94  * *must* know that to avoid possibly calling hide_coercion_node on
95  * something that wasn't generated by coerce_type. Note that if there are
96  * multiple stacked CollateExprs, we just discard all but the topmost.
97  */
98  origexpr = expr;
99  while (expr && IsA(expr, CollateExpr))
100  expr = (Node *) ((CollateExpr *) expr)->arg;
101 
102  result = coerce_type(pstate, expr, exprtype,
103  targettype, targettypmod,
104  ccontext, cformat, location);
105 
106  /*
107  * If the target is a fixed-length type, it may need a length coercion as
108  * well as a type coercion. If we find ourselves adding both, force the
109  * inner coercion node to implicit display form.
110  */
111  result = coerce_type_typmod(result,
112  targettype, targettypmod,
113  cformat, location,
114  (cformat != COERCE_IMPLICIT_CAST),
115  (result != expr && !IsA(result, Const)));
116 
117  if (expr != origexpr)
118  {
119  /* Reinstall top CollateExpr */
120  CollateExpr *coll = (CollateExpr *) origexpr;
121  CollateExpr *newcoll = makeNode(CollateExpr);
122 
123  newcoll->arg = (Expr *) result;
124  newcoll->collOid = coll->collOid;
125  newcoll->location = coll->location;
126  result = (Node *) newcoll;
127  }
128 
129  return result;
130 }
131 
132 
133 /*
134  * coerce_type()
135  * Convert an expression to a different type.
136  *
137  * The caller should already have determined that the coercion is possible;
138  * see can_coerce_type.
139  *
140  * Normally, no coercion to a typmod (length) is performed here. The caller
141  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
142  * (But if the target type is a domain, it may internally contain a
143  * typmod constraint, which will be applied inside coerce_to_domain.)
144  * In some cases pg_cast specifies a type coercion function that also
145  * applies length conversion, and in those cases only, the result will
146  * already be properly coerced to the specified typmod.
147  *
148  * pstate is only used in the case that we are able to resolve the type of
149  * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
150  * caller does not want type information updated for Params.
151  *
152  * Note: this function must not modify the given expression tree, only add
153  * decoration on top of it. See transformSetOperationTree, for example.
154  */
155 Node *
156 coerce_type(ParseState *pstate, Node *node,
157  Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
158  CoercionContext ccontext, CoercionForm cformat, int location)
159 {
160  Node *result;
161  CoercionPathType pathtype;
162  Oid funcId;
163 
164  if (targetTypeId == inputTypeId ||
165  node == NULL)
166  {
167  /* no conversion needed */
168  return node;
169  }
170  if (targetTypeId == ANYOID ||
171  targetTypeId == ANYELEMENTOID ||
172  targetTypeId == ANYNONARRAYOID)
173  {
174  /*
175  * Assume can_coerce_type verified that implicit coercion is okay.
176  *
177  * Note: by returning the unmodified node here, we are saying that
178  * it's OK to treat an UNKNOWN constant as a valid input for a
179  * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
180  * all right, since an UNKNOWN value is still a perfectly valid Datum.
181  *
182  * NB: we do NOT want a RelabelType here: the exposed type of the
183  * function argument must be its actual type, not the polymorphic
184  * pseudotype.
185  */
186  return node;
187  }
188  if (targetTypeId == ANYARRAYOID ||
189  targetTypeId == ANYENUMOID ||
190  targetTypeId == ANYRANGEOID)
191  {
192  /*
193  * Assume can_coerce_type verified that implicit coercion is okay.
194  *
195  * These cases are unlike the ones above because the exposed type of
196  * the argument must be an actual array, enum, or range type. In
197  * particular the argument must *not* be an UNKNOWN constant. If it
198  * is, we just fall through; below, we'll call anyarray_in,
199  * anyenum_in, or anyrange_in, which will produce an error. Also, if
200  * what we have is a domain over array, enum, or range, we have to
201  * relabel it to its base type.
202  *
203  * Note: currently, we can't actually see a domain-over-enum here,
204  * since the other functions in this file will not match such a
205  * parameter to ANYENUM. But that should get changed eventually.
206  */
207  if (inputTypeId != UNKNOWNOID)
208  {
209  Oid baseTypeId = getBaseType(inputTypeId);
210 
211  if (baseTypeId != inputTypeId)
212  {
213  RelabelType *r = makeRelabelType((Expr *) node,
214  baseTypeId, -1,
215  InvalidOid,
216  cformat);
217 
218  r->location = location;
219  return (Node *) r;
220  }
221  /* Not a domain type, so return it as-is */
222  return node;
223  }
224  }
225  if (inputTypeId == UNKNOWNOID && IsA(node, Const))
226  {
227  /*
228  * Input is a string constant with previously undetermined type. Apply
229  * the target type's typinput function to it to produce a constant of
230  * the target type.
231  *
232  * NOTE: this case cannot be folded together with the other
233  * constant-input case, since the typinput function does not
234  * necessarily behave the same as a type conversion function. For
235  * example, int4's typinput function will reject "1.2", whereas
236  * float-to-int type conversion will round to integer.
237  *
238  * XXX if the typinput function is not immutable, we really ought to
239  * postpone evaluation of the function call until runtime. But there
240  * is no way to represent a typinput function call as an expression
241  * tree, because C-string values are not Datums. (XXX This *is*
242  * possible as of 7.3, do we want to do it?)
243  */
244  Const *con = (Const *) node;
245  Const *newcon = makeNode(Const);
246  Oid baseTypeId;
247  int32 baseTypeMod;
248  int32 inputTypeMod;
249  Type baseType;
250  ParseCallbackState pcbstate;
251 
252  /*
253  * If the target type is a domain, we want to call its base type's
254  * input routine, not domain_in(). This is to avoid premature failure
255  * when the domain applies a typmod: existing input routines follow
256  * implicit-coercion semantics for length checks, which is not always
257  * what we want here. The needed check will be applied properly
258  * inside coerce_to_domain().
259  */
260  baseTypeMod = targetTypeMod;
261  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
262 
263  /*
264  * For most types we pass typmod -1 to the input routine, because
265  * existing input routines follow implicit-coercion semantics for
266  * length checks, which is not always what we want here. Any length
267  * constraint will be applied later by our caller. An exception
268  * however is the INTERVAL type, for which we *must* pass the typmod
269  * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
270  * as sin, but so is this part of the spec...)
271  */
272  if (baseTypeId == INTERVALOID)
273  inputTypeMod = baseTypeMod;
274  else
275  inputTypeMod = -1;
276 
277  baseType = typeidType(baseTypeId);
278 
279  newcon->consttype = baseTypeId;
280  newcon->consttypmod = inputTypeMod;
281  newcon->constcollid = typeTypeCollation(baseType);
282  newcon->constlen = typeLen(baseType);
283  newcon->constbyval = typeByVal(baseType);
284  newcon->constisnull = con->constisnull;
285 
286  /*
287  * We use the original literal's location regardless of the position
288  * of the coercion. This is a change from pre-9.2 behavior, meant to
289  * simplify life for pg_stat_statements.
290  */
291  newcon->location = con->location;
292 
293  /*
294  * Set up to point at the constant's text if the input routine throws
295  * an error.
296  */
297  setup_parser_errposition_callback(&pcbstate, pstate, con->location);
298 
299  /*
300  * We assume here that UNKNOWN's internal representation is the same
301  * as CSTRING.
302  */
303  if (!con->constisnull)
304  newcon->constvalue = stringTypeDatum(baseType,
306  inputTypeMod);
307  else
308  newcon->constvalue = stringTypeDatum(baseType,
309  NULL,
310  inputTypeMod);
311 
312  /*
313  * If it's a varlena value, force it to be in non-expanded
314  * (non-toasted) format; this avoids any possible dependency on
315  * external values and improves consistency of representation.
316  */
317  if (!con->constisnull && newcon->constlen == -1)
318  newcon->constvalue =
320 
321 #ifdef RANDOMIZE_ALLOCATED_MEMORY
322 
323  /*
324  * For pass-by-reference data types, repeat the conversion to see if
325  * the input function leaves any uninitialized bytes in the result. We
326  * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
327  * enabled, so we don't bother testing otherwise. The reason we don't
328  * want any instability in the input function is that comparison of
329  * Const nodes relies on bytewise comparison of the datums, so if the
330  * input function leaves garbage then subexpressions that should be
331  * identical may not get recognized as such. See pgsql-hackers
332  * discussion of 2008-04-04.
333  */
334  if (!con->constisnull && !newcon->constbyval)
335  {
336  Datum val2;
337 
338  val2 = stringTypeDatum(baseType,
340  inputTypeMod);
341  if (newcon->constlen == -1)
342  val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
343  if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
344  elog(WARNING, "type %s has unstable input conversion for \"%s\"",
345  typeTypeName(baseType), DatumGetCString(con->constvalue));
346  }
347 #endif
348 
350 
351  result = (Node *) newcon;
352 
353  /* If target is a domain, apply constraints. */
354  if (baseTypeId != targetTypeId)
355  result = coerce_to_domain(result,
356  baseTypeId, baseTypeMod,
357  targetTypeId,
358  cformat, location, false, false);
359 
360  ReleaseSysCache(baseType);
361 
362  return result;
363  }
364  if (IsA(node, Param) &&
365  pstate != NULL && pstate->p_coerce_param_hook != NULL)
366  {
367  /*
368  * Allow the CoerceParamHook to decide what happens. It can return a
369  * transformed node (very possibly the same Param node), or return
370  * NULL to indicate we should proceed with normal coercion.
371  */
372  result = (*pstate->p_coerce_param_hook) (pstate,
373  (Param *) node,
374  targetTypeId,
375  targetTypeMod,
376  location);
377  if (result)
378  return result;
379  }
380  if (IsA(node, CollateExpr))
381  {
382  /*
383  * If we have a COLLATE clause, we have to push the coercion
384  * underneath the COLLATE. This is really ugly, but there is little
385  * choice because the above hacks on Consts and Params wouldn't happen
386  * otherwise. This kluge has consequences in coerce_to_target_type.
387  */
388  CollateExpr *coll = (CollateExpr *) node;
389  CollateExpr *newcoll = makeNode(CollateExpr);
390 
391  newcoll->arg = (Expr *)
392  coerce_type(pstate, (Node *) coll->arg,
393  inputTypeId, targetTypeId, targetTypeMod,
394  ccontext, cformat, location);
395  newcoll->collOid = coll->collOid;
396  newcoll->location = coll->location;
397  return (Node *) newcoll;
398  }
399  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
400  &funcId);
401  if (pathtype != COERCION_PATH_NONE)
402  {
403  if (pathtype != COERCION_PATH_RELABELTYPE)
404  {
405  /*
406  * Generate an expression tree representing run-time application
407  * of the conversion function. If we are dealing with a domain
408  * target type, the conversion function will yield the base type,
409  * and we need to extract the correct typmod to use from the
410  * domain's typtypmod.
411  */
412  Oid baseTypeId;
413  int32 baseTypeMod;
414 
415  baseTypeMod = targetTypeMod;
416  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
417 
418  result = build_coercion_expression(node, pathtype, funcId,
419  baseTypeId, baseTypeMod,
420  cformat, location,
421  (cformat != COERCE_IMPLICIT_CAST));
422 
423  /*
424  * If domain, coerce to the domain type and relabel with domain
425  * type ID. We can skip the internal length-coercion step if the
426  * selected coercion function was a type-and-length coercion.
427  */
428  if (targetTypeId != baseTypeId)
429  result = coerce_to_domain(result, baseTypeId, baseTypeMod,
430  targetTypeId,
431  cformat, location, true,
432  exprIsLengthCoercion(result,
433  NULL));
434  }
435  else
436  {
437  /*
438  * We don't need to do a physical conversion, but we do need to
439  * attach a RelabelType node so that the expression will be seen
440  * to have the intended type when inspected by higher-level code.
441  *
442  * Also, domains may have value restrictions beyond the base type
443  * that must be accounted for. If the destination is a domain
444  * then we won't need a RelabelType node.
445  */
446  result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
447  cformat, location, false, false);
448  if (result == node)
449  {
450  /*
451  * XXX could we label result with exprTypmod(node) instead of
452  * default -1 typmod, to save a possible length-coercion
453  * later? Would work if both types have same interpretation of
454  * typmod, which is likely but not certain.
455  */
456  RelabelType *r = makeRelabelType((Expr *) result,
457  targetTypeId, -1,
458  InvalidOid,
459  cformat);
460 
461  r->location = location;
462  result = (Node *) r;
463  }
464  }
465  return result;
466  }
467  if (inputTypeId == RECORDOID &&
468  ISCOMPLEX(targetTypeId))
469  {
470  /* Coerce a RECORD to a specific complex type */
471  return coerce_record_to_complex(pstate, node, targetTypeId,
472  ccontext, cformat, location);
473  }
474  if (targetTypeId == RECORDOID &&
475  ISCOMPLEX(inputTypeId))
476  {
477  /* Coerce a specific complex type to RECORD */
478  /* NB: we do NOT want a RelabelType here */
479  return node;
480  }
481 #ifdef NOT_USED
482  if (inputTypeId == RECORDARRAYOID &&
483  is_complex_array(targetTypeId))
484  {
485  /* Coerce record[] to a specific complex array type */
486  /* not implemented yet ... */
487  }
488 #endif
489  if (targetTypeId == RECORDARRAYOID &&
490  is_complex_array(inputTypeId))
491  {
492  /* Coerce a specific complex array type to record[] */
493  /* NB: we do NOT want a RelabelType here */
494  return node;
495  }
496  if (typeInheritsFrom(inputTypeId, targetTypeId)
497  || typeIsOfTypedTable(inputTypeId, targetTypeId))
498  {
499  /*
500  * Input class type is a subclass of target, so generate an
501  * appropriate runtime conversion (removing unneeded columns and
502  * possibly rearranging the ones that are wanted).
503  */
505 
506  r->arg = (Expr *) node;
507  r->resulttype = targetTypeId;
508  r->convertformat = cformat;
509  r->location = location;
510  return (Node *) r;
511  }
512  /* If we get here, caller blew it */
513  elog(ERROR, "failed to find conversion function from %s to %s",
514  format_type_be(inputTypeId), format_type_be(targetTypeId));
515  return NULL; /* keep compiler quiet */
516 }
517 
518 
519 /*
520  * can_coerce_type()
521  * Can input_typeids be coerced to target_typeids?
522  *
523  * We must be told the context (CAST construct, assignment, implicit coercion)
524  * as this determines the set of available casts.
525  */
526 bool
527 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
528  CoercionContext ccontext)
529 {
530  bool have_generics = false;
531  int i;
532 
533  /* run through argument list... */
534  for (i = 0; i < nargs; i++)
535  {
536  Oid inputTypeId = input_typeids[i];
537  Oid targetTypeId = target_typeids[i];
538  CoercionPathType pathtype;
539  Oid funcId;
540 
541  /* no problem if same type */
542  if (inputTypeId == targetTypeId)
543  continue;
544 
545  /* accept if target is ANY */
546  if (targetTypeId == ANYOID)
547  continue;
548 
549  /* accept if target is polymorphic, for now */
550  if (IsPolymorphicType(targetTypeId))
551  {
552  have_generics = true; /* do more checking later */
553  continue;
554  }
555 
556  /*
557  * If input is an untyped string constant, assume we can convert it to
558  * anything.
559  */
560  if (inputTypeId == UNKNOWNOID)
561  continue;
562 
563  /*
564  * If pg_cast shows that we can coerce, accept. This test now covers
565  * both binary-compatible and coercion-function cases.
566  */
567  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
568  &funcId);
569  if (pathtype != COERCION_PATH_NONE)
570  continue;
571 
572  /*
573  * If input is RECORD and target is a composite type, assume we can
574  * coerce (may need tighter checking here)
575  */
576  if (inputTypeId == RECORDOID &&
577  ISCOMPLEX(targetTypeId))
578  continue;
579 
580  /*
581  * If input is a composite type and target is RECORD, accept
582  */
583  if (targetTypeId == RECORDOID &&
584  ISCOMPLEX(inputTypeId))
585  continue;
586 
587 #ifdef NOT_USED /* not implemented yet */
588 
589  /*
590  * If input is record[] and target is a composite array type, assume
591  * we can coerce (may need tighter checking here)
592  */
593  if (inputTypeId == RECORDARRAYOID &&
594  is_complex_array(targetTypeId))
595  continue;
596 #endif
597 
598  /*
599  * If input is a composite array type and target is record[], accept
600  */
601  if (targetTypeId == RECORDARRAYOID &&
602  is_complex_array(inputTypeId))
603  continue;
604 
605  /*
606  * If input is a class type that inherits from target, accept
607  */
608  if (typeInheritsFrom(inputTypeId, targetTypeId)
609  || typeIsOfTypedTable(inputTypeId, targetTypeId))
610  continue;
611 
612  /*
613  * Else, cannot coerce at this argument position
614  */
615  return false;
616  }
617 
618  /* If we found any generic argument types, cross-check them */
619  if (have_generics)
620  {
621  if (!check_generic_type_consistency(input_typeids, target_typeids,
622  nargs))
623  return false;
624  }
625 
626  return true;
627 }
628 
629 
630 /*
631  * Create an expression tree to represent coercion to a domain type.
632  *
633  * 'arg': input expression
634  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
635  * has not bothered to look this up)
636  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
637  * has not bothered to look this up)
638  * 'typeId': target type to coerce to
639  * 'cformat': coercion format
640  * 'location': coercion request location
641  * 'hideInputCoercion': if true, hide the input coercion under this one.
642  * 'lengthCoercionDone': if true, caller already accounted for length,
643  * ie the input is already of baseTypMod as well as baseTypeId.
644  *
645  * If the target type isn't a domain, the given 'arg' is returned as-is.
646  */
647 Node *
648 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
649  CoercionForm cformat, int location,
650  bool hideInputCoercion,
651  bool lengthCoercionDone)
652 {
654 
655  /* Get the base type if it hasn't been supplied */
656  if (baseTypeId == InvalidOid)
657  baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
658 
659  /* If it isn't a domain, return the node as it was passed in */
660  if (baseTypeId == typeId)
661  return arg;
662 
663  /* Suppress display of nested coercion steps */
664  if (hideInputCoercion)
665  hide_coercion_node(arg);
666 
667  /*
668  * If the domain applies a typmod to its base type, build the appropriate
669  * coercion step. Mark it implicit for display purposes, because we don't
670  * want it shown separately by ruleutils.c; but the isExplicit flag passed
671  * to the conversion function depends on the manner in which the domain
672  * coercion is invoked, so that the semantics of implicit and explicit
673  * coercion differ. (Is that really the behavior we want?)
674  *
675  * NOTE: because we apply this as part of the fixed expression structure,
676  * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
677  * would be safe to do anyway, without lots of knowledge about what the
678  * base type thinks the typmod means.
679  */
680  if (!lengthCoercionDone)
681  {
682  if (baseTypeMod >= 0)
683  arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
684  COERCE_IMPLICIT_CAST, location,
685  (cformat != COERCE_IMPLICIT_CAST),
686  false);
687  }
688 
689  /*
690  * Now build the domain coercion node. This represents run-time checking
691  * of any constraints currently attached to the domain. This also ensures
692  * that the expression is properly labeled as to result type.
693  */
694  result = makeNode(CoerceToDomain);
695  result->arg = (Expr *) arg;
696  result->resulttype = typeId;
697  result->resulttypmod = -1; /* currently, always -1 for domains */
698  /* resultcollid will be set by parse_collate.c */
699  result->coercionformat = cformat;
700  result->location = location;
701 
702  return (Node *) result;
703 }
704 
705 
706 /*
707  * coerce_type_typmod()
708  * Force a value to a particular typmod, if meaningful and possible.
709  *
710  * This is applied to values that are going to be stored in a relation
711  * (where we have an atttypmod for the column) as well as values being
712  * explicitly CASTed (where the typmod comes from the target type spec).
713  *
714  * The caller must have already ensured that the value is of the correct
715  * type, typically by applying coerce_type.
716  *
717  * cformat determines the display properties of the generated node (if any),
718  * while isExplicit may affect semantics. If hideInputCoercion is true
719  * *and* we generate a node, the input node is forced to IMPLICIT display
720  * form, so that only the typmod coercion node will be visible when
721  * displaying the expression.
722  *
723  * NOTE: this does not need to work on domain types, because any typmod
724  * coercion for a domain is considered to be part of the type coercion
725  * needed to produce the domain value in the first place. So, no getBaseType.
726  */
727 static Node *
728 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
729  CoercionForm cformat, int location,
730  bool isExplicit, bool hideInputCoercion)
731 {
732  CoercionPathType pathtype;
733  Oid funcId;
734 
735  /*
736  * A negative typmod is assumed to mean that no coercion is wanted. Also,
737  * skip coercion if already done.
738  */
739  if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
740  return node;
741 
742  pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
743 
744  if (pathtype != COERCION_PATH_NONE)
745  {
746  /* Suppress display of nested coercion steps */
747  if (hideInputCoercion)
748  hide_coercion_node(node);
749 
750  node = build_coercion_expression(node, pathtype, funcId,
751  targetTypeId, targetTypMod,
752  cformat, location,
753  isExplicit);
754  }
755 
756  return node;
757 }
758 
759 /*
760  * Mark a coercion node as IMPLICIT so it will never be displayed by
761  * ruleutils.c. We use this when we generate a nest of coercion nodes
762  * to implement what is logically one conversion; the inner nodes are
763  * forced to IMPLICIT_CAST format. This does not change their semantics,
764  * only display behavior.
765  *
766  * It is caller error to call this on something that doesn't have a
767  * CoercionForm field.
768  */
769 static void
771 {
772  if (IsA(node, FuncExpr))
773  ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
774  else if (IsA(node, RelabelType))
775  ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
776  else if (IsA(node, CoerceViaIO))
777  ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
778  else if (IsA(node, ArrayCoerceExpr))
779  ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
780  else if (IsA(node, ConvertRowtypeExpr))
781  ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
782  else if (IsA(node, RowExpr))
783  ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
784  else if (IsA(node, CoerceToDomain))
785  ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
786  else
787  elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
788 }
789 
790 /*
791  * build_coercion_expression()
792  * Construct an expression tree for applying a pg_cast entry.
793  *
794  * This is used for both type-coercion and length-coercion operations,
795  * since there is no difference in terms of the calling convention.
796  */
797 static Node *
799  CoercionPathType pathtype,
800  Oid funcId,
801  Oid targetTypeId, int32 targetTypMod,
802  CoercionForm cformat, int location,
803  bool isExplicit)
804 {
805  int nargs = 0;
806 
807  if (OidIsValid(funcId))
808  {
809  HeapTuple tp;
810  Form_pg_proc procstruct;
811 
813  if (!HeapTupleIsValid(tp))
814  elog(ERROR, "cache lookup failed for function %u", funcId);
815  procstruct = (Form_pg_proc) GETSTRUCT(tp);
816 
817  /*
818  * These Asserts essentially check that function is a legal coercion
819  * function. We can't make the seemingly obvious tests on prorettype
820  * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
821  * various binary-compatibility cases.
822  */
823  /* Assert(targetTypeId == procstruct->prorettype); */
824  Assert(!procstruct->proretset);
825  Assert(!procstruct->proisagg);
826  Assert(!procstruct->proiswindow);
827  nargs = procstruct->pronargs;
828  Assert(nargs >= 1 && nargs <= 3);
829  /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
830  Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
831  Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
832 
833  ReleaseSysCache(tp);
834  }
835 
836  if (pathtype == COERCION_PATH_FUNC)
837  {
838  /* We build an ordinary FuncExpr with special arguments */
839  FuncExpr *fexpr;
840  List *args;
841  Const *cons;
842 
843  Assert(OidIsValid(funcId));
844 
845  args = list_make1(node);
846 
847  if (nargs >= 2)
848  {
849  /* Pass target typmod as an int4 constant */
850  cons = makeConst(INT4OID,
851  -1,
852  InvalidOid,
853  sizeof(int32),
854  Int32GetDatum(targetTypMod),
855  false,
856  true);
857 
858  args = lappend(args, cons);
859  }
860 
861  if (nargs == 3)
862  {
863  /* Pass it a boolean isExplicit parameter, too */
864  cons = makeConst(BOOLOID,
865  -1,
866  InvalidOid,
867  sizeof(bool),
868  BoolGetDatum(isExplicit),
869  false,
870  true);
871 
872  args = lappend(args, cons);
873  }
874 
875  fexpr = makeFuncExpr(funcId, targetTypeId, args,
876  InvalidOid, InvalidOid, cformat);
877  fexpr->location = location;
878  return (Node *) fexpr;
879  }
880  else if (pathtype == COERCION_PATH_ARRAYCOERCE)
881  {
882  /* We need to build an ArrayCoerceExpr */
884 
885  acoerce->arg = (Expr *) node;
886  acoerce->elemfuncid = funcId;
887  acoerce->resulttype = targetTypeId;
888 
889  /*
890  * Label the output as having a particular typmod only if we are
891  * really invoking a length-coercion function, ie one with more than
892  * one argument.
893  */
894  acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
895  /* resultcollid will be set by parse_collate.c */
896  acoerce->isExplicit = isExplicit;
897  acoerce->coerceformat = cformat;
898  acoerce->location = location;
899 
900  return (Node *) acoerce;
901  }
902  else if (pathtype == COERCION_PATH_COERCEVIAIO)
903  {
904  /* We need to build a CoerceViaIO node */
905  CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
906 
907  Assert(!OidIsValid(funcId));
908 
909  iocoerce->arg = (Expr *) node;
910  iocoerce->resulttype = targetTypeId;
911  /* resultcollid will be set by parse_collate.c */
912  iocoerce->coerceformat = cformat;
913  iocoerce->location = location;
914 
915  return (Node *) iocoerce;
916  }
917  else
918  {
919  elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
920  (int) pathtype);
921  return NULL; /* keep compiler quiet */
922  }
923 }
924 
925 
926 /*
927  * coerce_record_to_complex
928  * Coerce a RECORD to a specific composite type.
929  *
930  * Currently we only support this for inputs that are RowExprs or whole-row
931  * Vars.
932  */
933 static Node *
935  Oid targetTypeId,
936  CoercionContext ccontext,
937  CoercionForm cformat,
938  int location)
939 {
940  RowExpr *rowexpr;
941  TupleDesc tupdesc;
942  List *args = NIL;
943  List *newargs;
944  int i;
945  int ucolno;
946  ListCell *arg;
947 
948  if (node && IsA(node, RowExpr))
949  {
950  /*
951  * Since the RowExpr must be of type RECORD, we needn't worry about it
952  * containing any dropped columns.
953  */
954  args = ((RowExpr *) node)->args;
955  }
956  else if (node && IsA(node, Var) &&
957  ((Var *) node)->varattno == InvalidAttrNumber)
958  {
959  int rtindex = ((Var *) node)->varno;
960  int sublevels_up = ((Var *) node)->varlevelsup;
961  int vlocation = ((Var *) node)->location;
962  RangeTblEntry *rte;
963 
964  rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
965  expandRTE(rte, rtindex, sublevels_up, vlocation, false,
966  NULL, &args);
967  }
968  else
969  ereport(ERROR,
970  (errcode(ERRCODE_CANNOT_COERCE),
971  errmsg("cannot cast type %s to %s",
973  format_type_be(targetTypeId)),
974  parser_coercion_errposition(pstate, location, node)));
975 
976  tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
977  newargs = NIL;
978  ucolno = 1;
979  arg = list_head(args);
980  for (i = 0; i < tupdesc->natts; i++)
981  {
982  Node *expr;
983  Node *cexpr;
984  Oid exprtype;
985 
986  /* Fill in NULLs for dropped columns in rowtype */
987  if (tupdesc->attrs[i]->attisdropped)
988  {
989  /*
990  * can't use atttypid here, but it doesn't really matter what type
991  * the Const claims to be.
992  */
993  newargs = lappend(newargs,
995  continue;
996  }
997 
998  if (arg == NULL)
999  ereport(ERROR,
1000  (errcode(ERRCODE_CANNOT_COERCE),
1001  errmsg("cannot cast type %s to %s",
1003  format_type_be(targetTypeId)),
1004  errdetail("Input has too few columns."),
1005  parser_coercion_errposition(pstate, location, node)));
1006  expr = (Node *) lfirst(arg);
1007  exprtype = exprType(expr);
1008 
1009  cexpr = coerce_to_target_type(pstate,
1010  expr, exprtype,
1011  tupdesc->attrs[i]->atttypid,
1012  tupdesc->attrs[i]->atttypmod,
1013  ccontext,
1015  -1);
1016  if (cexpr == NULL)
1017  ereport(ERROR,
1018  (errcode(ERRCODE_CANNOT_COERCE),
1019  errmsg("cannot cast type %s to %s",
1021  format_type_be(targetTypeId)),
1022  errdetail("Cannot cast type %s to %s in column %d.",
1023  format_type_be(exprtype),
1024  format_type_be(tupdesc->attrs[i]->atttypid),
1025  ucolno),
1026  parser_coercion_errposition(pstate, location, expr)));
1027  newargs = lappend(newargs, cexpr);
1028  ucolno++;
1029  arg = lnext(arg);
1030  }
1031  if (arg != NULL)
1032  ereport(ERROR,
1033  (errcode(ERRCODE_CANNOT_COERCE),
1034  errmsg("cannot cast type %s to %s",
1036  format_type_be(targetTypeId)),
1037  errdetail("Input has too many columns."),
1038  parser_coercion_errposition(pstate, location, node)));
1039 
1040  ReleaseTupleDesc(tupdesc);
1041 
1042  rowexpr = makeNode(RowExpr);
1043  rowexpr->args = newargs;
1044  rowexpr->row_typeid = targetTypeId;
1045  rowexpr->row_format = cformat;
1046  rowexpr->colnames = NIL; /* not needed for named target type */
1047  rowexpr->location = location;
1048  return (Node *) rowexpr;
1049 }
1050 
1051 /*
1052  * coerce_to_boolean()
1053  * Coerce an argument of a construct that requires boolean input
1054  * (AND, OR, NOT, etc). Also check that input is not a set.
1055  *
1056  * Returns the possibly-transformed node tree.
1057  *
1058  * As with coerce_type, pstate may be NULL if no special unknown-Param
1059  * processing is wanted.
1060  */
1061 Node *
1063  const char *constructName)
1064 {
1065  Oid inputTypeId = exprType(node);
1066 
1067  if (inputTypeId != BOOLOID)
1068  {
1069  Node *newnode;
1070 
1071  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1072  BOOLOID, -1,
1075  -1);
1076  if (newnode == NULL)
1077  ereport(ERROR,
1078  (errcode(ERRCODE_DATATYPE_MISMATCH),
1079  /* translator: first %s is name of a SQL construct, eg WHERE */
1080  errmsg("argument of %s must be type %s, not type %s",
1081  constructName, "boolean",
1082  format_type_be(inputTypeId)),
1083  parser_errposition(pstate, exprLocation(node))));
1084  node = newnode;
1085  }
1086 
1087  if (expression_returns_set(node))
1088  ereport(ERROR,
1089  (errcode(ERRCODE_DATATYPE_MISMATCH),
1090  /* translator: %s is name of a SQL construct, eg WHERE */
1091  errmsg("argument of %s must not return a set",
1092  constructName),
1093  parser_errposition(pstate, exprLocation(node))));
1094 
1095  return node;
1096 }
1097 
1098 /*
1099  * coerce_to_specific_type_typmod()
1100  * Coerce an argument of a construct that requires a specific data type,
1101  * with a specific typmod. Also check that input is not a set.
1102  *
1103  * Returns the possibly-transformed node tree.
1104  *
1105  * As with coerce_type, pstate may be NULL if no special unknown-Param
1106  * processing is wanted.
1107  */
1108 Node *
1110  Oid targetTypeId, int32 targetTypmod,
1111  const char *constructName)
1112 {
1113  Oid inputTypeId = exprType(node);
1114 
1115  if (inputTypeId != targetTypeId)
1116  {
1117  Node *newnode;
1118 
1119  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1120  targetTypeId, targetTypmod,
1123  -1);
1124  if (newnode == NULL)
1125  ereport(ERROR,
1126  (errcode(ERRCODE_DATATYPE_MISMATCH),
1127  /* translator: first %s is name of a SQL construct, eg LIMIT */
1128  errmsg("argument of %s must be type %s, not type %s",
1129  constructName,
1130  format_type_be(targetTypeId),
1131  format_type_be(inputTypeId)),
1132  parser_errposition(pstate, exprLocation(node))));
1133  node = newnode;
1134  }
1135 
1136  if (expression_returns_set(node))
1137  ereport(ERROR,
1138  (errcode(ERRCODE_DATATYPE_MISMATCH),
1139  /* translator: %s is name of a SQL construct, eg LIMIT */
1140  errmsg("argument of %s must not return a set",
1141  constructName),
1142  parser_errposition(pstate, exprLocation(node))));
1143 
1144  return node;
1145 }
1146 
1147 /*
1148  * coerce_to_specific_type()
1149  * Coerce an argument of a construct that requires a specific data type.
1150  * Also check that input is not a set.
1151  *
1152  * Returns the possibly-transformed node tree.
1153  *
1154  * As with coerce_type, pstate may be NULL if no special unknown-Param
1155  * processing is wanted.
1156  */
1157 Node *
1159  Oid targetTypeId,
1160  const char *constructName)
1161 {
1162  return coerce_to_specific_type_typmod(pstate, node,
1163  targetTypeId, -1,
1164  constructName);
1165 }
1166 
1167 /*
1168  * parser_coercion_errposition - report coercion error location, if possible
1169  *
1170  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1171  * but there may be no such location in the case of an implicit coercion.
1172  * In that case point at the input expression.
1173  *
1174  * XXX possibly this is more generally useful than coercion errors;
1175  * if so, should rename and place with parser_errposition.
1176  */
1177 int
1179  int coerce_location,
1180  Node *input_expr)
1181 {
1182  if (coerce_location >= 0)
1183  return parser_errposition(pstate, coerce_location);
1184  else
1185  return parser_errposition(pstate, exprLocation(input_expr));
1186 }
1187 
1188 
1189 /*
1190  * select_common_type()
1191  * Determine the common supertype of a list of input expressions.
1192  * This is used for determining the output type of CASE, UNION,
1193  * and similar constructs.
1194  *
1195  * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1196  * in the list will be preferred if there is doubt.
1197  * 'context' is a phrase to use in the error message if we fail to select
1198  * a usable type. Pass NULL to have the routine return InvalidOid
1199  * rather than throwing an error on failure.
1200  * 'which_expr': if not NULL, receives a pointer to the particular input
1201  * expression from which the result type was taken.
1202  */
1203 Oid
1204 select_common_type(ParseState *pstate, List *exprs, const char *context,
1205  Node **which_expr)
1206 {
1207  Node *pexpr;
1208  Oid ptype;
1209  TYPCATEGORY pcategory;
1210  bool pispreferred;
1211  ListCell *lc;
1212 
1213  Assert(exprs != NIL);
1214  pexpr = (Node *) linitial(exprs);
1215  lc = lnext(list_head(exprs));
1216  ptype = exprType(pexpr);
1217 
1218  /*
1219  * If all input types are valid and exactly the same, just pick that type.
1220  * This is the only way that we will resolve the result as being a domain
1221  * type; otherwise domains are smashed to their base types for comparison.
1222  */
1223  if (ptype != UNKNOWNOID)
1224  {
1225  for_each_cell(lc, lc)
1226  {
1227  Node *nexpr = (Node *) lfirst(lc);
1228  Oid ntype = exprType(nexpr);
1229 
1230  if (ntype != ptype)
1231  break;
1232  }
1233  if (lc == NULL) /* got to the end of the list? */
1234  {
1235  if (which_expr)
1236  *which_expr = pexpr;
1237  return ptype;
1238  }
1239  }
1240 
1241  /*
1242  * Nope, so set up for the full algorithm. Note that at this point, lc
1243  * points to the first list item with type different from pexpr's; we need
1244  * not re-examine any items the previous loop advanced over.
1245  */
1246  ptype = getBaseType(ptype);
1247  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1248 
1249  for_each_cell(lc, lc)
1250  {
1251  Node *nexpr = (Node *) lfirst(lc);
1252  Oid ntype = getBaseType(exprType(nexpr));
1253 
1254  /* move on to next one if no new information... */
1255  if (ntype != UNKNOWNOID && ntype != ptype)
1256  {
1257  TYPCATEGORY ncategory;
1258  bool nispreferred;
1259 
1260  get_type_category_preferred(ntype, &ncategory, &nispreferred);
1261  if (ptype == UNKNOWNOID)
1262  {
1263  /* so far, only unknowns so take anything... */
1264  pexpr = nexpr;
1265  ptype = ntype;
1266  pcategory = ncategory;
1267  pispreferred = nispreferred;
1268  }
1269  else if (ncategory != pcategory)
1270  {
1271  /*
1272  * both types in different categories? then not much hope...
1273  */
1274  if (context == NULL)
1275  return InvalidOid;
1276  ereport(ERROR,
1277  (errcode(ERRCODE_DATATYPE_MISMATCH),
1278  /*------
1279  translator: first %s is name of a SQL construct, eg CASE */
1280  errmsg("%s types %s and %s cannot be matched",
1281  context,
1282  format_type_be(ptype),
1283  format_type_be(ntype)),
1284  parser_errposition(pstate, exprLocation(nexpr))));
1285  }
1286  else if (!pispreferred &&
1287  can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1288  !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1289  {
1290  /*
1291  * take new type if can coerce to it implicitly but not the
1292  * other way; but if we have a preferred type, stay on it.
1293  */
1294  pexpr = nexpr;
1295  ptype = ntype;
1296  pcategory = ncategory;
1297  pispreferred = nispreferred;
1298  }
1299  }
1300  }
1301 
1302  /*
1303  * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1304  * then resolve as type TEXT. This situation comes up with constructs
1305  * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1306  * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1307  * output type as UNKNOWN, but that really doesn't work, because we'd
1308  * probably end up needing a runtime coercion from UNKNOWN to something
1309  * else, and we usually won't have it. We need to coerce the unknown
1310  * literals while they are still literals, so a decision has to be made
1311  * now.
1312  */
1313  if (ptype == UNKNOWNOID)
1314  ptype = TEXTOID;
1315 
1316  if (which_expr)
1317  *which_expr = pexpr;
1318  return ptype;
1319 }
1320 
1321 /*
1322  * coerce_to_common_type()
1323  * Coerce an expression to the given type.
1324  *
1325  * This is used following select_common_type() to coerce the individual
1326  * expressions to the desired type. 'context' is a phrase to use in the
1327  * error message if we fail to coerce.
1328  *
1329  * As with coerce_type, pstate may be NULL if no special unknown-Param
1330  * processing is wanted.
1331  */
1332 Node *
1334  Oid targetTypeId, const char *context)
1335 {
1336  Oid inputTypeId = exprType(node);
1337 
1338  if (inputTypeId == targetTypeId)
1339  return node; /* no work */
1340  if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1341  node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1343  else
1344  ereport(ERROR,
1345  (errcode(ERRCODE_CANNOT_COERCE),
1346  /* translator: first %s is name of a SQL construct, eg CASE */
1347  errmsg("%s could not convert type %s to %s",
1348  context,
1349  format_type_be(inputTypeId),
1350  format_type_be(targetTypeId)),
1351  parser_errposition(pstate, exprLocation(node))));
1352  return node;
1353 }
1354 
1355 /*
1356  * check_generic_type_consistency()
1357  * Are the actual arguments potentially compatible with a
1358  * polymorphic function?
1359  *
1360  * The argument consistency rules are:
1361  *
1362  * 1) All arguments declared ANYELEMENT must have the same datatype.
1363  * 2) All arguments declared ANYARRAY must have the same datatype,
1364  * which must be a varlena array type.
1365  * 3) All arguments declared ANYRANGE must have the same datatype,
1366  * which must be a range type.
1367  * 4) If there are arguments of both ANYELEMENT and ANYARRAY, make sure the
1368  * actual ANYELEMENT datatype is in fact the element type for the actual
1369  * ANYARRAY datatype.
1370  * 5) Similarly, if there are arguments of both ANYELEMENT and ANYRANGE,
1371  * make sure the actual ANYELEMENT datatype is in fact the subtype for
1372  * the actual ANYRANGE type.
1373  * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
1374  * (alone or in combination with plain ANYELEMENT), we add the extra
1375  * condition that the ANYELEMENT type must be an enum.
1376  * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1377  * we add the extra condition that the ANYELEMENT type must not be an array.
1378  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1379  * is an extra restriction if not.)
1380  *
1381  * Domains over arrays match ANYARRAY, and are immediately flattened to their
1382  * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1383  * argument is a domain over int4[] while another one is just int4[].) Also
1384  * notice that such a domain does *not* match ANYNONARRAY.
1385  *
1386  * Similarly, domains over ranges match ANYRANGE, and are immediately
1387  * flattened to their base type.
1388  *
1389  * Note that domains aren't currently considered to match ANYENUM,
1390  * even if their base type would match.
1391  *
1392  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1393  * argument, assume it is okay.
1394  *
1395  * If an input is of type ANYARRAY (ie, we know it's an array, but not
1396  * what element type), we will accept it as a match to an argument declared
1397  * ANYARRAY, so long as we don't have to determine an element type ---
1398  * that is, so long as there is no use of ANYELEMENT. This is mostly for
1399  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1400  *
1401  * We do not ereport here, but just return FALSE if a rule is violated.
1402  */
1403 bool
1405  Oid *declared_arg_types,
1406  int nargs)
1407 {
1408  int j;
1409  Oid elem_typeid = InvalidOid;
1410  Oid array_typeid = InvalidOid;
1411  Oid array_typelem;
1412  Oid range_typeid = InvalidOid;
1413  Oid range_typelem;
1414  bool have_anyelement = false;
1415  bool have_anynonarray = false;
1416  bool have_anyenum = false;
1417 
1418  /*
1419  * Loop through the arguments to see if we have any that are polymorphic.
1420  * If so, require the actual types to be consistent.
1421  */
1422  for (j = 0; j < nargs; j++)
1423  {
1424  Oid decl_type = declared_arg_types[j];
1425  Oid actual_type = actual_arg_types[j];
1426 
1427  if (decl_type == ANYELEMENTOID ||
1428  decl_type == ANYNONARRAYOID ||
1429  decl_type == ANYENUMOID)
1430  {
1431  have_anyelement = true;
1432  if (decl_type == ANYNONARRAYOID)
1433  have_anynonarray = true;
1434  else if (decl_type == ANYENUMOID)
1435  have_anyenum = true;
1436  if (actual_type == UNKNOWNOID)
1437  continue;
1438  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1439  return false;
1440  elem_typeid = actual_type;
1441  }
1442  else if (decl_type == ANYARRAYOID)
1443  {
1444  if (actual_type == UNKNOWNOID)
1445  continue;
1446  actual_type = getBaseType(actual_type); /* flatten domains */
1447  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1448  return false;
1449  array_typeid = actual_type;
1450  }
1451  else if (decl_type == ANYRANGEOID)
1452  {
1453  if (actual_type == UNKNOWNOID)
1454  continue;
1455  actual_type = getBaseType(actual_type); /* flatten domains */
1456  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1457  return false;
1458  range_typeid = actual_type;
1459  }
1460  }
1461 
1462  /* Get the element type based on the array type, if we have one */
1463  if (OidIsValid(array_typeid))
1464  {
1465  if (array_typeid == ANYARRAYOID)
1466  {
1467  /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1468  if (have_anyelement)
1469  return false;
1470  return true;
1471  }
1472 
1473  array_typelem = get_element_type(array_typeid);
1474  if (!OidIsValid(array_typelem))
1475  return false; /* should be an array, but isn't */
1476 
1477  if (!OidIsValid(elem_typeid))
1478  {
1479  /*
1480  * if we don't have an element type yet, use the one we just got
1481  */
1482  elem_typeid = array_typelem;
1483  }
1484  else if (array_typelem != elem_typeid)
1485  {
1486  /* otherwise, they better match */
1487  return false;
1488  }
1489  }
1490 
1491  /* Get the element type based on the range type, if we have one */
1492  if (OidIsValid(range_typeid))
1493  {
1494  range_typelem = get_range_subtype(range_typeid);
1495  if (!OidIsValid(range_typelem))
1496  return false; /* should be a range, but isn't */
1497 
1498  if (!OidIsValid(elem_typeid))
1499  {
1500  /*
1501  * if we don't have an element type yet, use the one we just got
1502  */
1503  elem_typeid = range_typelem;
1504  }
1505  else if (range_typelem != elem_typeid)
1506  {
1507  /* otherwise, they better match */
1508  return false;
1509  }
1510  }
1511 
1512  if (have_anynonarray)
1513  {
1514  /* require the element type to not be an array or domain over array */
1515  if (type_is_array_domain(elem_typeid))
1516  return false;
1517  }
1518 
1519  if (have_anyenum)
1520  {
1521  /* require the element type to be an enum */
1522  if (!type_is_enum(elem_typeid))
1523  return false;
1524  }
1525 
1526  /* Looks valid */
1527  return true;
1528 }
1529 
1530 /*
1531  * enforce_generic_type_consistency()
1532  * Make sure a polymorphic function is legally callable, and
1533  * deduce actual argument and result types.
1534  *
1535  * If any polymorphic pseudotype is used in a function's arguments or
1536  * return type, we make sure the actual data types are consistent with
1537  * each other. The argument consistency rules are shown above for
1538  * check_generic_type_consistency().
1539  *
1540  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1541  * argument, we attempt to deduce the actual type it should have. If
1542  * successful, we alter that position of declared_arg_types[] so that
1543  * make_fn_arguments will coerce the literal to the right thing.
1544  *
1545  * Rules are applied to the function's return type (possibly altering it)
1546  * if it is declared as a polymorphic type:
1547  *
1548  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1549  * argument's actual type as the function's return type.
1550  * 2) Similarly, if return type is ANYRANGE, and any argument is ANYRANGE,
1551  * use the argument's actual type as the function's return type.
1552  * 3) If return type is ANYARRAY, no argument is ANYARRAY, but any argument is
1553  * ANYELEMENT, use the actual type of the argument to determine the
1554  * function's return type, i.e. the element type's corresponding array
1555  * type. (Note: similar behavior does not exist for ANYRANGE, because it's
1556  * impossible to determine the range type from the subtype alone.)
1557  * 4) If return type is ANYARRAY, but no argument is ANYARRAY or ANYELEMENT,
1558  * generate an error. Similarly, if return type is ANYRANGE, but no
1559  * argument is ANYRANGE, generate an error. (These conditions are
1560  * prevented by CREATE FUNCTION and therefore are not expected here.)
1561  * 5) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1562  * argument's actual type as the function's return type.
1563  * 6) If return type is ANYELEMENT, no argument is ANYELEMENT, but any argument
1564  * is ANYARRAY or ANYRANGE, use the actual type of the argument to determine
1565  * the function's return type, i.e. the array type's corresponding element
1566  * type or the range type's corresponding subtype (or both, in which case
1567  * they must match).
1568  * 7) If return type is ANYELEMENT, no argument is ANYELEMENT, ANYARRAY, or
1569  * ANYRANGE, generate an error. (This condition is prevented by CREATE
1570  * FUNCTION and therefore is not expected here.)
1571  * 8) ANYENUM is treated the same as ANYELEMENT except that if it is used
1572  * (alone or in combination with plain ANYELEMENT), we add the extra
1573  * condition that the ANYELEMENT type must be an enum.
1574  * 9) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1575  * we add the extra condition that the ANYELEMENT type must not be an array.
1576  * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1577  * is an extra restriction if not.)
1578  *
1579  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
1580  * respectively, and are immediately flattened to their base type. (In
1581  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set it
1582  * to the base type not the domain type.)
1583  *
1584  * When allow_poly is false, we are not expecting any of the actual_arg_types
1585  * to be polymorphic, and we should not return a polymorphic result type
1586  * either. When allow_poly is true, it is okay to have polymorphic "actual"
1587  * arg types, and we can return ANYARRAY, ANYRANGE, or ANYELEMENT as the
1588  * result. (This case is currently used only to check compatibility of an
1589  * aggregate's declaration with the underlying transfn.)
1590  *
1591  * A special case is that we could see ANYARRAY as an actual_arg_type even
1592  * when allow_poly is false (this is possible only because pg_statistic has
1593  * columns shown as anyarray in the catalogs). We allow this to match a
1594  * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1595  * or result (since we can't determine a specific element type to match to
1596  * ANYELEMENT). Note this means that functions taking ANYARRAY had better
1597  * behave sanely if applied to the pg_statistic columns; they can't just
1598  * assume that successive inputs are of the same actual element type.
1599  */
1600 Oid
1602  Oid *declared_arg_types,
1603  int nargs,
1604  Oid rettype,
1605  bool allow_poly)
1606 {
1607  int j;
1608  bool have_generics = false;
1609  bool have_unknowns = false;
1610  Oid elem_typeid = InvalidOid;
1611  Oid array_typeid = InvalidOid;
1612  Oid range_typeid = InvalidOid;
1613  Oid array_typelem;
1614  Oid range_typelem;
1615  bool have_anyelement = (rettype == ANYELEMENTOID ||
1616  rettype == ANYNONARRAYOID ||
1617  rettype == ANYENUMOID);
1618  bool have_anynonarray = (rettype == ANYNONARRAYOID);
1619  bool have_anyenum = (rettype == ANYENUMOID);
1620 
1621  /*
1622  * Loop through the arguments to see if we have any that are polymorphic.
1623  * If so, require the actual types to be consistent.
1624  */
1625  for (j = 0; j < nargs; j++)
1626  {
1627  Oid decl_type = declared_arg_types[j];
1628  Oid actual_type = actual_arg_types[j];
1629 
1630  if (decl_type == ANYELEMENTOID ||
1631  decl_type == ANYNONARRAYOID ||
1632  decl_type == ANYENUMOID)
1633  {
1634  have_generics = have_anyelement = true;
1635  if (decl_type == ANYNONARRAYOID)
1636  have_anynonarray = true;
1637  else if (decl_type == ANYENUMOID)
1638  have_anyenum = true;
1639  if (actual_type == UNKNOWNOID)
1640  {
1641  have_unknowns = true;
1642  continue;
1643  }
1644  if (allow_poly && decl_type == actual_type)
1645  continue; /* no new information here */
1646  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1647  ereport(ERROR,
1648  (errcode(ERRCODE_DATATYPE_MISMATCH),
1649  errmsg("arguments declared \"anyelement\" are not all alike"),
1650  errdetail("%s versus %s",
1651  format_type_be(elem_typeid),
1652  format_type_be(actual_type))));
1653  elem_typeid = actual_type;
1654  }
1655  else if (decl_type == ANYARRAYOID)
1656  {
1657  have_generics = true;
1658  if (actual_type == UNKNOWNOID)
1659  {
1660  have_unknowns = true;
1661  continue;
1662  }
1663  if (allow_poly && decl_type == actual_type)
1664  continue; /* no new information here */
1665  actual_type = getBaseType(actual_type); /* flatten domains */
1666  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1667  ereport(ERROR,
1668  (errcode(ERRCODE_DATATYPE_MISMATCH),
1669  errmsg("arguments declared \"anyarray\" are not all alike"),
1670  errdetail("%s versus %s",
1671  format_type_be(array_typeid),
1672  format_type_be(actual_type))));
1673  array_typeid = actual_type;
1674  }
1675  else if (decl_type == ANYRANGEOID)
1676  {
1677  have_generics = true;
1678  if (actual_type == UNKNOWNOID)
1679  {
1680  have_unknowns = true;
1681  continue;
1682  }
1683  if (allow_poly && decl_type == actual_type)
1684  continue; /* no new information here */
1685  actual_type = getBaseType(actual_type); /* flatten domains */
1686  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1687  ereport(ERROR,
1688  (errcode(ERRCODE_DATATYPE_MISMATCH),
1689  errmsg("arguments declared \"anyrange\" are not all alike"),
1690  errdetail("%s versus %s",
1691  format_type_be(range_typeid),
1692  format_type_be(actual_type))));
1693  range_typeid = actual_type;
1694  }
1695  }
1696 
1697  /*
1698  * Fast Track: if none of the arguments are polymorphic, return the
1699  * unmodified rettype. We assume it can't be polymorphic either.
1700  */
1701  if (!have_generics)
1702  return rettype;
1703 
1704  /* Get the element type based on the array type, if we have one */
1705  if (OidIsValid(array_typeid))
1706  {
1707  if (array_typeid == ANYARRAYOID && !have_anyelement)
1708  {
1709  /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1710  array_typelem = ANYELEMENTOID;
1711  }
1712  else
1713  {
1714  array_typelem = get_element_type(array_typeid);
1715  if (!OidIsValid(array_typelem))
1716  ereport(ERROR,
1717  (errcode(ERRCODE_DATATYPE_MISMATCH),
1718  errmsg("argument declared %s is not an array but type %s",
1719  "anyarray", format_type_be(array_typeid))));
1720  }
1721 
1722  if (!OidIsValid(elem_typeid))
1723  {
1724  /*
1725  * if we don't have an element type yet, use the one we just got
1726  */
1727  elem_typeid = array_typelem;
1728  }
1729  else if (array_typelem != elem_typeid)
1730  {
1731  /* otherwise, they better match */
1732  ereport(ERROR,
1733  (errcode(ERRCODE_DATATYPE_MISMATCH),
1734  errmsg("argument declared %s is not consistent with argument declared %s",
1735  "anyarray", "anyelement"),
1736  errdetail("%s versus %s",
1737  format_type_be(array_typeid),
1738  format_type_be(elem_typeid))));
1739  }
1740  }
1741 
1742  /* Get the element type based on the range type, if we have one */
1743  if (OidIsValid(range_typeid))
1744  {
1745  if (range_typeid == ANYRANGEOID && !have_anyelement)
1746  {
1747  /* Special case for ANYRANGE input: okay iff no ANYELEMENT */
1748  range_typelem = ANYELEMENTOID;
1749  }
1750  else
1751  {
1752  range_typelem = get_range_subtype(range_typeid);
1753  if (!OidIsValid(range_typelem))
1754  ereport(ERROR,
1755  (errcode(ERRCODE_DATATYPE_MISMATCH),
1756  errmsg("argument declared %s is not a range type but type %s",
1757  "anyrange",
1758  format_type_be(range_typeid))));
1759  }
1760 
1761  if (!OidIsValid(elem_typeid))
1762  {
1763  /*
1764  * if we don't have an element type yet, use the one we just got
1765  */
1766  elem_typeid = range_typelem;
1767  }
1768  else if (range_typelem != elem_typeid)
1769  {
1770  /* otherwise, they better match */
1771  ereport(ERROR,
1772  (errcode(ERRCODE_DATATYPE_MISMATCH),
1773  errmsg("argument declared %s is not consistent with argument declared %s",
1774  "anyrange", "anyelement"),
1775  errdetail("%s versus %s",
1776  format_type_be(range_typeid),
1777  format_type_be(elem_typeid))));
1778  }
1779  }
1780 
1781  if (!OidIsValid(elem_typeid))
1782  {
1783  if (allow_poly)
1784  {
1785  elem_typeid = ANYELEMENTOID;
1786  array_typeid = ANYARRAYOID;
1787  range_typeid = ANYRANGEOID;
1788  }
1789  else
1790  {
1791  /* Only way to get here is if all the generic args are UNKNOWN */
1792  ereport(ERROR,
1793  (errcode(ERRCODE_DATATYPE_MISMATCH),
1794  errmsg("could not determine polymorphic type because input has type %s",
1795  "unknown")));
1796  }
1797  }
1798 
1799  if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1800  {
1801  /* require the element type to not be an array or domain over array */
1802  if (type_is_array_domain(elem_typeid))
1803  ereport(ERROR,
1804  (errcode(ERRCODE_DATATYPE_MISMATCH),
1805  errmsg("type matched to anynonarray is an array type: %s",
1806  format_type_be(elem_typeid))));
1807  }
1808 
1809  if (have_anyenum && elem_typeid != ANYELEMENTOID)
1810  {
1811  /* require the element type to be an enum */
1812  if (!type_is_enum(elem_typeid))
1813  ereport(ERROR,
1814  (errcode(ERRCODE_DATATYPE_MISMATCH),
1815  errmsg("type matched to anyenum is not an enum type: %s",
1816  format_type_be(elem_typeid))));
1817  }
1818 
1819  /*
1820  * If we had any unknown inputs, re-scan to assign correct types
1821  */
1822  if (have_unknowns)
1823  {
1824  for (j = 0; j < nargs; j++)
1825  {
1826  Oid decl_type = declared_arg_types[j];
1827  Oid actual_type = actual_arg_types[j];
1828 
1829  if (actual_type != UNKNOWNOID)
1830  continue;
1831 
1832  if (decl_type == ANYELEMENTOID ||
1833  decl_type == ANYNONARRAYOID ||
1834  decl_type == ANYENUMOID)
1835  declared_arg_types[j] = elem_typeid;
1836  else if (decl_type == ANYARRAYOID)
1837  {
1838  if (!OidIsValid(array_typeid))
1839  {
1840  array_typeid = get_array_type(elem_typeid);
1841  if (!OidIsValid(array_typeid))
1842  ereport(ERROR,
1843  (errcode(ERRCODE_UNDEFINED_OBJECT),
1844  errmsg("could not find array type for data type %s",
1845  format_type_be(elem_typeid))));
1846  }
1847  declared_arg_types[j] = array_typeid;
1848  }
1849  else if (decl_type == ANYRANGEOID)
1850  {
1851  if (!OidIsValid(range_typeid))
1852  {
1853  ereport(ERROR,
1854  (errcode(ERRCODE_UNDEFINED_OBJECT),
1855  errmsg("could not find range type for data type %s",
1856  format_type_be(elem_typeid))));
1857  }
1858  declared_arg_types[j] = range_typeid;
1859  }
1860  }
1861  }
1862 
1863  /* if we return ANYARRAY use the appropriate argument type */
1864  if (rettype == ANYARRAYOID)
1865  {
1866  if (!OidIsValid(array_typeid))
1867  {
1868  array_typeid = get_array_type(elem_typeid);
1869  if (!OidIsValid(array_typeid))
1870  ereport(ERROR,
1871  (errcode(ERRCODE_UNDEFINED_OBJECT),
1872  errmsg("could not find array type for data type %s",
1873  format_type_be(elem_typeid))));
1874  }
1875  return array_typeid;
1876  }
1877 
1878  /* if we return ANYRANGE use the appropriate argument type */
1879  if (rettype == ANYRANGEOID)
1880  {
1881  if (!OidIsValid(range_typeid))
1882  {
1883  ereport(ERROR,
1884  (errcode(ERRCODE_UNDEFINED_OBJECT),
1885  errmsg("could not find range type for data type %s",
1886  format_type_be(elem_typeid))));
1887  }
1888  return range_typeid;
1889  }
1890 
1891  /* if we return ANYELEMENT use the appropriate argument type */
1892  if (rettype == ANYELEMENTOID ||
1893  rettype == ANYNONARRAYOID ||
1894  rettype == ANYENUMOID)
1895  return elem_typeid;
1896 
1897  /* we don't return a generic type; send back the original return type */
1898  return rettype;
1899 }
1900 
1901 /*
1902  * resolve_generic_type()
1903  * Deduce an individual actual datatype on the assumption that
1904  * the rules for polymorphic types are being followed.
1905  *
1906  * declared_type is the declared datatype we want to resolve.
1907  * context_actual_type is the actual input datatype to some argument
1908  * that has declared datatype context_declared_type.
1909  *
1910  * If declared_type isn't polymorphic, we just return it. Otherwise,
1911  * context_declared_type must be polymorphic, and we deduce the correct
1912  * return type based on the relationship of the two polymorphic types.
1913  */
1914 Oid
1916  Oid context_actual_type,
1917  Oid context_declared_type)
1918 {
1919  if (declared_type == ANYARRAYOID)
1920  {
1921  if (context_declared_type == ANYARRAYOID)
1922  {
1923  /*
1924  * Use actual type, but it must be an array; or if it's a domain
1925  * over array, use the base array type.
1926  */
1927  Oid context_base_type = getBaseType(context_actual_type);
1928  Oid array_typelem = get_element_type(context_base_type);
1929 
1930  if (!OidIsValid(array_typelem))
1931  ereport(ERROR,
1932  (errcode(ERRCODE_DATATYPE_MISMATCH),
1933  errmsg("argument declared %s is not an array but type %s",
1934  "anyarray", format_type_be(context_base_type))));
1935  return context_base_type;
1936  }
1937  else if (context_declared_type == ANYELEMENTOID ||
1938  context_declared_type == ANYNONARRAYOID ||
1939  context_declared_type == ANYENUMOID ||
1940  context_declared_type == ANYRANGEOID)
1941  {
1942  /* Use the array type corresponding to actual type */
1943  Oid array_typeid = get_array_type(context_actual_type);
1944 
1945  if (!OidIsValid(array_typeid))
1946  ereport(ERROR,
1947  (errcode(ERRCODE_UNDEFINED_OBJECT),
1948  errmsg("could not find array type for data type %s",
1949  format_type_be(context_actual_type))));
1950  return array_typeid;
1951  }
1952  }
1953  else if (declared_type == ANYELEMENTOID ||
1954  declared_type == ANYNONARRAYOID ||
1955  declared_type == ANYENUMOID ||
1956  declared_type == ANYRANGEOID)
1957  {
1958  if (context_declared_type == ANYARRAYOID)
1959  {
1960  /* Use the element type corresponding to actual type */
1961  Oid context_base_type = getBaseType(context_actual_type);
1962  Oid array_typelem = get_element_type(context_base_type);
1963 
1964  if (!OidIsValid(array_typelem))
1965  ereport(ERROR,
1966  (errcode(ERRCODE_DATATYPE_MISMATCH),
1967  errmsg("argument declared %s is not an array but type %s",
1968  "anyarray", format_type_be(context_base_type))));
1969  return array_typelem;
1970  }
1971  else if (context_declared_type == ANYRANGEOID)
1972  {
1973  /* Use the element type corresponding to actual type */
1974  Oid context_base_type = getBaseType(context_actual_type);
1975  Oid range_typelem = get_range_subtype(context_base_type);
1976 
1977  if (!OidIsValid(range_typelem))
1978  ereport(ERROR,
1979  (errcode(ERRCODE_DATATYPE_MISMATCH),
1980  errmsg("argument declared %s is not a range type but type %s",
1981  "anyrange", format_type_be(context_base_type))));
1982  return range_typelem;
1983  }
1984  else if (context_declared_type == ANYELEMENTOID ||
1985  context_declared_type == ANYNONARRAYOID ||
1986  context_declared_type == ANYENUMOID)
1987  {
1988  /* Use the actual type; it doesn't matter if array or not */
1989  return context_actual_type;
1990  }
1991  }
1992  else
1993  {
1994  /* declared_type isn't polymorphic, so return it as-is */
1995  return declared_type;
1996  }
1997  /* If we get here, declared_type is polymorphic and context isn't */
1998  /* NB: this is a calling-code logic error, not a user error */
1999  elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
2000  return InvalidOid; /* keep compiler quiet */
2001 }
2002 
2003 
2004 /* TypeCategory()
2005  * Assign a category to the specified type OID.
2006  *
2007  * NB: this must not return TYPCATEGORY_INVALID.
2008  */
2011 {
2012  char typcategory;
2013  bool typispreferred;
2014 
2015  get_type_category_preferred(type, &typcategory, &typispreferred);
2016  Assert(typcategory != TYPCATEGORY_INVALID);
2017  return (TYPCATEGORY) typcategory;
2018 }
2019 
2020 
2021 /* IsPreferredType()
2022  * Check if this type is a preferred type for the given category.
2023  *
2024  * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
2025  * types of any category; otherwise, only for preferred types of that
2026  * category.
2027  */
2028 bool
2030 {
2031  char typcategory;
2032  bool typispreferred;
2033 
2034  get_type_category_preferred(type, &typcategory, &typispreferred);
2035  if (category == typcategory || category == TYPCATEGORY_INVALID)
2036  return typispreferred;
2037  else
2038  return false;
2039 }
2040 
2041 
2042 /* IsBinaryCoercible()
2043  * Check if srctype is binary-coercible to targettype.
2044  *
2045  * This notion allows us to cheat and directly exchange values without
2046  * going through the trouble of calling a conversion function. Note that
2047  * in general, this should only be an implementation shortcut. Before 7.4,
2048  * this was also used as a heuristic for resolving overloaded functions and
2049  * operators, but that's basically a bad idea.
2050  *
2051  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
2052  * We consider two types binary-coercible if there is an implicitly
2053  * invokable, no-function-needed pg_cast entry. Also, a domain is always
2054  * binary-coercible to its base type, though *not* vice versa (in the other
2055  * direction, one must apply domain constraint checks before accepting the
2056  * value as legitimate). We also need to special-case various polymorphic
2057  * types.
2058  *
2059  * This function replaces IsBinaryCompatible(), which was an inherently
2060  * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
2061  * the order of the operands is now significant.
2062  */
2063 bool
2064 IsBinaryCoercible(Oid srctype, Oid targettype)
2065 {
2066  HeapTuple tuple;
2067  Form_pg_cast castForm;
2068  bool result;
2069 
2070  /* Fast path if same type */
2071  if (srctype == targettype)
2072  return true;
2073 
2074  /* Anything is coercible to ANY or ANYELEMENT */
2075  if (targettype == ANYOID || targettype == ANYELEMENTOID)
2076  return true;
2077 
2078  /* If srctype is a domain, reduce to its base type */
2079  if (OidIsValid(srctype))
2080  srctype = getBaseType(srctype);
2081 
2082  /* Somewhat-fast path for domain -> base type case */
2083  if (srctype == targettype)
2084  return true;
2085 
2086  /* Also accept any array type as coercible to ANYARRAY */
2087  if (targettype == ANYARRAYOID)
2088  if (type_is_array(srctype))
2089  return true;
2090 
2091  /* Also accept any non-array type as coercible to ANYNONARRAY */
2092  if (targettype == ANYNONARRAYOID)
2093  if (!type_is_array(srctype))
2094  return true;
2095 
2096  /* Also accept any enum type as coercible to ANYENUM */
2097  if (targettype == ANYENUMOID)
2098  if (type_is_enum(srctype))
2099  return true;
2100 
2101  /* Also accept any range type as coercible to ANYRANGE */
2102  if (targettype == ANYRANGEOID)
2103  if (type_is_range(srctype))
2104  return true;
2105 
2106  /* Also accept any composite type as coercible to RECORD */
2107  if (targettype == RECORDOID)
2108  if (ISCOMPLEX(srctype))
2109  return true;
2110 
2111  /* Also accept any composite array type as coercible to RECORD[] */
2112  if (targettype == RECORDARRAYOID)
2113  if (is_complex_array(srctype))
2114  return true;
2115 
2116  /* Else look in pg_cast */
2118  ObjectIdGetDatum(srctype),
2119  ObjectIdGetDatum(targettype));
2120  if (!HeapTupleIsValid(tuple))
2121  return false; /* no cast */
2122  castForm = (Form_pg_cast) GETSTRUCT(tuple);
2123 
2124  result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2125  castForm->castcontext == COERCION_CODE_IMPLICIT);
2126 
2127  ReleaseSysCache(tuple);
2128 
2129  return result;
2130 }
2131 
2132 
2133 /*
2134  * find_coercion_pathway
2135  * Look for a coercion pathway between two types.
2136  *
2137  * Currently, this deals only with scalar-type cases; it does not consider
2138  * polymorphic types nor casts between composite types. (Perhaps fold
2139  * those in someday?)
2140  *
2141  * ccontext determines the set of available casts.
2142  *
2143  * The possible result codes are:
2144  * COERCION_PATH_NONE: failed to find any coercion pathway
2145  * *funcid is set to InvalidOid
2146  * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
2147  * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
2148  * *funcid is set to InvalidOid
2149  * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
2150  * *funcid is set to the element cast function, or InvalidOid
2151  * if the array elements are binary-compatible
2152  * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
2153  * *funcid is set to InvalidOid
2154  *
2155  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
2156  * needed to do the coercion; if the target is a domain then we may need to
2157  * apply domain constraint checking. If you want to check for a zero-effort
2158  * conversion then use IsBinaryCoercible().
2159  */
2161 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
2162  CoercionContext ccontext,
2163  Oid *funcid)
2164 {
2166  HeapTuple tuple;
2167 
2168  *funcid = InvalidOid;
2169 
2170  /* Perhaps the types are domains; if so, look at their base types */
2171  if (OidIsValid(sourceTypeId))
2172  sourceTypeId = getBaseType(sourceTypeId);
2173  if (OidIsValid(targetTypeId))
2174  targetTypeId = getBaseType(targetTypeId);
2175 
2176  /* Domains are always coercible to and from their base type */
2177  if (sourceTypeId == targetTypeId)
2179 
2180  /* Look in pg_cast */
2182  ObjectIdGetDatum(sourceTypeId),
2183  ObjectIdGetDatum(targetTypeId));
2184 
2185  if (HeapTupleIsValid(tuple))
2186  {
2187  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2188  CoercionContext castcontext;
2189 
2190  /* convert char value for castcontext to CoercionContext enum */
2191  switch (castForm->castcontext)
2192  {
2194  castcontext = COERCION_IMPLICIT;
2195  break;
2197  castcontext = COERCION_ASSIGNMENT;
2198  break;
2200  castcontext = COERCION_EXPLICIT;
2201  break;
2202  default:
2203  elog(ERROR, "unrecognized castcontext: %d",
2204  (int) castForm->castcontext);
2205  castcontext = 0; /* keep compiler quiet */
2206  break;
2207  }
2208 
2209  /* Rely on ordering of enum for correct behavior here */
2210  if (ccontext >= castcontext)
2211  {
2212  switch (castForm->castmethod)
2213  {
2215  result = COERCION_PATH_FUNC;
2216  *funcid = castForm->castfunc;
2217  break;
2218  case COERCION_METHOD_INOUT:
2219  result = COERCION_PATH_COERCEVIAIO;
2220  break;
2222  result = COERCION_PATH_RELABELTYPE;
2223  break;
2224  default:
2225  elog(ERROR, "unrecognized castmethod: %d",
2226  (int) castForm->castmethod);
2227  break;
2228  }
2229  }
2230 
2231  ReleaseSysCache(tuple);
2232  }
2233  else
2234  {
2235  /*
2236  * If there's no pg_cast entry, perhaps we are dealing with a pair of
2237  * array types. If so, and if the element types have a suitable cast,
2238  * report that we can coerce with an ArrayCoerceExpr.
2239  *
2240  * Note that the source type can be a domain over array, but not the
2241  * target, because ArrayCoerceExpr won't check domain constraints.
2242  *
2243  * Hack: disallow coercions to oidvector and int2vector, which
2244  * otherwise tend to capture coercions that should go to "real" array
2245  * types. We want those types to be considered "real" arrays for many
2246  * purposes, but not this one. (Also, ArrayCoerceExpr isn't
2247  * guaranteed to produce an output that meets the restrictions of
2248  * these datatypes, such as being 1-dimensional.)
2249  */
2250  if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
2251  {
2252  Oid targetElem;
2253  Oid sourceElem;
2254 
2255  if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
2256  (sourceElem = get_base_element_type(sourceTypeId)) != InvalidOid)
2257  {
2258  CoercionPathType elempathtype;
2259  Oid elemfuncid;
2260 
2261  elempathtype = find_coercion_pathway(targetElem,
2262  sourceElem,
2263  ccontext,
2264  &elemfuncid);
2265  if (elempathtype != COERCION_PATH_NONE &&
2266  elempathtype != COERCION_PATH_ARRAYCOERCE)
2267  {
2268  *funcid = elemfuncid;
2269  if (elempathtype == COERCION_PATH_COERCEVIAIO)
2270  result = COERCION_PATH_COERCEVIAIO;
2271  else
2272  result = COERCION_PATH_ARRAYCOERCE;
2273  }
2274  }
2275  }
2276 
2277  /*
2278  * If we still haven't found a possibility, consider automatic casting
2279  * using I/O functions. We allow assignment casts to string types and
2280  * explicit casts from string types to be handled this way. (The
2281  * CoerceViaIO mechanism is a lot more general than that, but this is
2282  * all we want to allow in the absence of a pg_cast entry.) It would
2283  * probably be better to insist on explicit casts in both directions,
2284  * but this is a compromise to preserve something of the pre-8.3
2285  * behavior that many types had implicit (yipes!) casts to text.
2286  */
2287  if (result == COERCION_PATH_NONE)
2288  {
2289  if (ccontext >= COERCION_ASSIGNMENT &&
2290  TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2291  result = COERCION_PATH_COERCEVIAIO;
2292  else if (ccontext >= COERCION_EXPLICIT &&
2293  TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2294  result = COERCION_PATH_COERCEVIAIO;
2295  }
2296  }
2297 
2298  return result;
2299 }
2300 
2301 
2302 /*
2303  * find_typmod_coercion_function -- does the given type need length coercion?
2304  *
2305  * If the target type possesses a pg_cast function from itself to itself,
2306  * it must need length coercion.
2307  *
2308  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2309  *
2310  * If the given type is a varlena array type, we do not look for a coercion
2311  * function associated directly with the array type, but instead look for
2312  * one associated with the element type. An ArrayCoerceExpr node must be
2313  * used to apply such a function.
2314  *
2315  * We use the same result enum as find_coercion_pathway, but the only possible
2316  * result codes are:
2317  * COERCION_PATH_NONE: no length coercion needed
2318  * COERCION_PATH_FUNC: apply the function returned in *funcid
2319  * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2320  */
2323  Oid *funcid)
2324 {
2326  Type targetType;
2327  Form_pg_type typeForm;
2328  HeapTuple tuple;
2329 
2330  *funcid = InvalidOid;
2331  result = COERCION_PATH_FUNC;
2332 
2333  targetType = typeidType(typeId);
2334  typeForm = (Form_pg_type) GETSTRUCT(targetType);
2335 
2336  /* Check for a varlena array type */
2337  if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
2338  {
2339  /* Yes, switch our attention to the element type */
2340  typeId = typeForm->typelem;
2341  result = COERCION_PATH_ARRAYCOERCE;
2342  }
2343  ReleaseSysCache(targetType);
2344 
2345  /* Look in pg_cast */
2347  ObjectIdGetDatum(typeId),
2348  ObjectIdGetDatum(typeId));
2349 
2350  if (HeapTupleIsValid(tuple))
2351  {
2352  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2353 
2354  *funcid = castForm->castfunc;
2355  ReleaseSysCache(tuple);
2356  }
2357 
2358  if (!OidIsValid(*funcid))
2359  result = COERCION_PATH_NONE;
2360 
2361  return result;
2362 }
2363 
2364 /*
2365  * is_complex_array
2366  * Is this type an array of composite?
2367  *
2368  * Note: this will not return true for record[]; check for RECORDARRAYOID
2369  * separately if needed.
2370  */
2371 static bool
2373 {
2374  Oid elemtype = get_element_type(typid);
2375 
2376  return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2377 }
2378 
2379 
2380 /*
2381  * Check whether reltypeId is the row type of a typed table of type
2382  * reloftypeId. (This is conceptually similar to the subtype
2383  * relationship checked by typeInheritsFrom().)
2384  */
2385 static bool
2386 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
2387 {
2388  Oid relid = typeidTypeRelid(reltypeId);
2389  bool result = false;
2390 
2391  if (relid)
2392  {
2393  HeapTuple tp;
2394  Form_pg_class reltup;
2395 
2396  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2397  if (!HeapTupleIsValid(tp))
2398  elog(ERROR, "cache lookup failed for relation %u", relid);
2399 
2400  reltup = (Form_pg_class) GETSTRUCT(tp);
2401  if (reltup->reloftype == reloftypeId)
2402  result = true;
2403 
2404  ReleaseSysCache(tp);
2405  }
2406 
2407  return result;
2408 }
Datum constvalue
Definition: primnodes.h:196
#define RECORDARRAYOID
Definition: pg_type.h:682
static Node * coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod, CoercionForm cformat, int location, bool isExplicit, bool hideInputCoercion)
Definition: parse_coerce.c:728
#define ANYNONARRAYOID
Definition: pg_type.h:704
#define NIL
Definition: pg_list.h:69
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2288
List * args
Definition: primnodes.h:985
Oid typeTypeCollation(Type typ)
Definition: parse_type.c:621
#define INT2VECTOROID
Definition: pg_type.h:312
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define type_is_array_domain(typid)
Definition: lsyscache.h:182
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid resolve_generic_type(Oid declared_type, Oid context_actual_type, Oid context_declared_type)
bool constbyval
Definition: primnodes.h:199
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1214
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1257
int32 resulttypmod
Definition: primnodes.h:1221
#define TEXTOID
Definition: pg_type.h:324
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
int16 typeLen(Type t)
Definition: parse_type.c:580
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2484
#define PointerGetDatum(X)
Definition: postgres.h:562
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2512
#define ANYELEMENTOID
Definition: pg_type.h:702
Oid resulttype
Definition: primnodes.h:811
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:670
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:219
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static Node * build_coercion_expression(Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionForm cformat, int location, bool isExplicit)
Definition: parse_coerce.c:798
CoerceParamHook p_coerce_param_hook
Definition: parse_node.h:209
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:509
CoercionForm coercionformat
Definition: primnodes.h:1223
int errcode(int sqlerrcode)
Definition: elog.c:575
bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
Definition: nodeFuncs.c:513
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
bool type_is_range(Oid typid)
Definition: lsyscache.c:2424
return result
Definition: formatting.c:1632
Oid typeidTypeRelid(Oid type_id)
Definition: parse_type.c:646
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:296
#define OidIsValid(objectId)
Definition: c.h:538
CoercionContext
Definition: primnodes.h:419
int natts
Definition: tupdesc.h:73
bool IsPreferredType(TYPCATEGORY category, Oid type)
CoercionPathType
Definition: parse_coerce.h:24
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
signed int int32
Definition: c.h:256
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
static void hide_coercion_node(Node *node)
Definition: parse_coerce.c:770
#define list_make1(x1)
Definition: pg_list.h:139
int constlen
Definition: primnodes.h:195
Oid consttype
Definition: primnodes.h:192
char TYPCATEGORY
Definition: parse_coerce.h:21
#define OIDVECTOROID
Definition: pg_type.h:344
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
bool typeByVal(Type t)
Definition: parse_type.c:590
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
List * colnames
Definition: primnodes.h:998
#define TYPCATEGORY_INVALID
Definition: pg_type.h:727
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
#define DatumGetCString(X)
Definition: postgres.h:572
#define ANYRANGEOID
Definition: pg_type.h:714
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:77
char * typeTypeName(Type t)
Definition: parse_type.c:600
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionForm cformat, int location, bool hideInputCoercion, bool lengthCoercionDone)
Definition: parse_coerce.c:648
Datum stringTypeDatum(Type tp, char *string, int32 atttypmod)
Definition: parse_type.c:635
Oid constcollid
Definition: primnodes.h:194
int location
Definition: primnodes.h:999
#define ANYENUMOID
Definition: pg_type.h:706
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define INTERVALOID
Definition: pg_type.h:529
#define ANYOID
Definition: pg_type.h:686
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define RECORDOID
Definition: pg_type.h:680
Expr * arg
Definition: primnodes.h:810
FormData_pg_cast * Form_pg_cast
Definition: pg_cast.h:42
bool check_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs)
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
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:128
#define WARNING
Definition: elog.h:40
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
CoercionForm coerceformat
Definition: primnodes.h:839
int location
Definition: primnodes.h:203
#define ANYARRAYOID
Definition: pg_type.h:688
uintptr_t Datum
Definition: postgres.h:372
CoercionForm convertformat
Definition: primnodes.h:861
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define TYPCATEGORY_STRING
Definition: pg_type.h:738
#define makeNode(_type_)
Definition: nodes.h:557
int location
Definition: primnodes.h:815
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
Definition: pg_inherits.c:282
#define ISCOMPLEX(typeid)
Definition: parse_type.h:53
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
bool type_is_enum(Oid typid)
Definition: lsyscache.c:2414
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Oid row_typeid
Definition: primnodes.h:986
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * arg
Definition: primnodes.h:875
#define type_is_array(typid)
Definition: lsyscache.h:180
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
#define BOOLOID
Definition: pg_type.h:288
#define UNKNOWNOID
Definition: pg_type.h:431
#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:934
#define nodeTag(nodeptr)
Definition: nodes.h:514
int32 consttypmod
Definition: primnodes.h:193
CoercionForm coerceformat
Definition: primnodes.h:814
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2557
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:527
#define Int32GetDatum(X)
Definition: postgres.h:485
int errmsg(const char *fmt,...)
Definition: elog.c:797
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int parser_coercion_errposition(ParseState *pstate, int coerce_location, Node *input_expr)
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:205
int location
Definition: primnodes.h:457
int32 resulttypmod
Definition: primnodes.h:836
#define elog
Definition: elog.h:219
static bool is_complex_array(Oid typid)
Type typeidType(Oid id)
Definition: parse_type.c:559
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:107
int location
Definition: primnodes.h:877
CoercionForm row_format
Definition: primnodes.h:997
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2271
CoercionForm
Definition: primnodes.h:435
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2436
Definition: pg_list.h:45
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
Oid get_range_subtype(Oid rangeOid)
Definition: lsyscache.c:3074
int location
Definition: primnodes.h:795
bool constisnull
Definition: primnodes.h:197
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:158