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