1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_coerce.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_relation.h"
25 #include "parser/parse_type.h"
26 #include "utils/builtins.h"
27 #include "utils/fmgroids.h"
28 #include "utils/lsyscache.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
33 static Node
*coerce_type_typmod(Node
*node
,
34 Oid targetTypeId
, int32 targetTypMod
,
35 CoercionForm cformat
, int location
,
36 bool isExplicit
, bool hideInputCoercion
);
37 static void hide_coercion_node(Node
*node
);
38 static Node
*build_coercion_expression(Node
*node
,
39 CoercionPathType pathtype
,
41 Oid targetTypeId
, int32 targetTypMod
,
42 CoercionForm cformat
, int location
,
44 static Node
*coerce_record_to_complex(ParseState
*pstate
, Node
*node
,
46 CoercionContext ccontext
,
49 static bool is_complex_array(Oid typid
);
53 * coerce_to_target_type()
54 * Convert an expression to a target type and typmod.
56 * This is the general-purpose entry point for arbitrary type coercion
57 * operations. Direct use of the component operations can_coerce_type,
58 * coerce_type, and coerce_type_typmod should be restricted to special
59 * cases (eg, when the conversion is expected to succeed).
61 * Returns the possibly-transformed expression tree, or NULL if the type
62 * conversion is not possible. (We do this, rather than ereport'ing directly,
63 * so that callers can generate custom error messages indicating context.)
65 * pstate - parse state (can be NULL, see coerce_type)
66 * expr - input expression tree (already transformed by transformExpr)
67 * exprtype - result type of expr
68 * targettype - desired result type
69 * targettypmod - desired result typmod
70 * ccontext, cformat - context indicators to control coercions
71 * location - parse location of the coercion request, or -1 if unknown/implicit
74 coerce_to_target_type(ParseState
*pstate
, Node
*expr
, Oid exprtype
,
75 Oid targettype
, int32 targettypmod
,
76 CoercionContext ccontext
,
82 if (!can_coerce_type(1, &exprtype
, &targettype
, ccontext
))
85 result
= coerce_type(pstate
, expr
, exprtype
,
86 targettype
, targettypmod
,
87 ccontext
, cformat
, location
);
90 * If the target is a fixed-length type, it may need a length coercion as
91 * well as a type coercion. If we find ourselves adding both, force the
92 * inner coercion node to implicit display form.
94 result
= coerce_type_typmod(result
,
95 targettype
, targettypmod
,
97 (cformat
!= COERCE_IMPLICIT_CAST
),
98 (result
!= expr
&& !IsA(result
, Const
)));
106 * Convert an expression to a different type.
108 * The caller should already have determined that the coercion is possible;
109 * see can_coerce_type.
111 * Normally, no coercion to a typmod (length) is performed here. The caller
112 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
113 * (But if the target type is a domain, it may internally contain a
114 * typmod constraint, which will be applied inside coerce_to_domain.)
115 * In some cases pg_cast specifies a type coercion function that also
116 * applies length conversion, and in those cases only, the result will
117 * already be properly coerced to the specified typmod.
119 * pstate is only used in the case that we are able to resolve the type of
120 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
121 * caller does not want type information updated for Params.
124 coerce_type(ParseState
*pstate
, Node
*node
,
125 Oid inputTypeId
, Oid targetTypeId
, int32 targetTypeMod
,
126 CoercionContext ccontext
, CoercionForm cformat
, int location
)
129 CoercionPathType pathtype
;
132 if (targetTypeId
== inputTypeId
||
135 /* no conversion needed */
138 if (targetTypeId
== ANYOID
||
139 targetTypeId
== ANYELEMENTOID
||
140 targetTypeId
== ANYNONARRAYOID
||
141 (targetTypeId
== ANYARRAYOID
&& inputTypeId
!= UNKNOWNOID
) ||
142 (targetTypeId
== ANYENUMOID
&& inputTypeId
!= UNKNOWNOID
))
145 * Assume can_coerce_type verified that implicit coercion is okay.
147 * Note: by returning the unmodified node here, we are saying that
148 * it's OK to treat an UNKNOWN constant as a valid input for a
149 * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
150 * all right, since an UNKNOWN value is still a perfectly valid Datum.
151 * However an UNKNOWN value is definitely *not* an array, and so we
152 * mustn't accept it for ANYARRAY. (Instead, we will call anyarray_in
153 * below, which will produce an error.) Likewise, UNKNOWN input is no
156 * NB: we do NOT want a RelabelType here.
160 if (inputTypeId
== UNKNOWNOID
&& IsA(node
, Const
))
163 * Input is a string constant with previously undetermined type. Apply
164 * the target type's typinput function to it to produce a constant of
167 * NOTE: this case cannot be folded together with the other
168 * constant-input case, since the typinput function does not
169 * necessarily behave the same as a type conversion function. For
170 * example, int4's typinput function will reject "1.2", whereas
171 * float-to-int type conversion will round to integer.
173 * XXX if the typinput function is not immutable, we really ought to
174 * postpone evaluation of the function call until runtime. But there
175 * is no way to represent a typinput function call as an expression
176 * tree, because C-string values are not Datums. (XXX This *is*
177 * possible as of 7.3, do we want to do it?)
179 Const
*con
= (Const
*) node
;
180 Const
*newcon
= makeNode(Const
);
185 ParseCallbackState pcbstate
;
188 * If the target type is a domain, we want to call its base type's
189 * input routine, not domain_in(). This is to avoid premature failure
190 * when the domain applies a typmod: existing input routines follow
191 * implicit-coercion semantics for length checks, which is not always
192 * what we want here. The needed check will be applied properly
193 * inside coerce_to_domain().
195 baseTypeMod
= targetTypeMod
;
196 baseTypeId
= getBaseTypeAndTypmod(targetTypeId
, &baseTypeMod
);
199 * For most types we pass typmod -1 to the input routine, because
200 * existing input routines follow implicit-coercion semantics for
201 * length checks, which is not always what we want here. Any length
202 * constraint will be applied later by our caller. An exception
203 * however is the INTERVAL type, for which we *must* pass the typmod
204 * or it won't be able to obey the bizarre SQL-spec input rules.
205 * (Ugly as sin, but so is this part of the spec...)
207 if (baseTypeId
== INTERVALOID
)
208 inputTypeMod
= baseTypeMod
;
212 targetType
= typeidType(baseTypeId
);
214 newcon
->consttype
= baseTypeId
;
215 newcon
->consttypmod
= inputTypeMod
;
216 newcon
->constlen
= typeLen(targetType
);
217 newcon
->constbyval
= typeByVal(targetType
);
218 newcon
->constisnull
= con
->constisnull
;
219 /* Use the leftmost of the constant's and coercion's locations */
221 newcon
->location
= con
->location
;
222 else if (con
->location
>= 0 && con
->location
< location
)
223 newcon
->location
= con
->location
;
225 newcon
->location
= location
;
228 * Set up to point at the constant's text if the input routine
231 setup_parser_errposition_callback(&pcbstate
, pstate
, con
->location
);
234 * We assume here that UNKNOWN's internal representation is the same
237 if (!con
->constisnull
)
238 newcon
->constvalue
= stringTypeDatum(targetType
,
239 DatumGetCString(con
->constvalue
),
242 newcon
->constvalue
= stringTypeDatum(targetType
,
246 cancel_parser_errposition_callback(&pcbstate
);
248 result
= (Node
*) newcon
;
250 /* If target is a domain, apply constraints. */
251 if (baseTypeId
!= targetTypeId
)
252 result
= coerce_to_domain(result
,
253 baseTypeId
, baseTypeMod
,
255 cformat
, location
, false, false);
257 ReleaseSysCache(targetType
);
261 if (inputTypeId
== UNKNOWNOID
&& IsA(node
, Param
) &&
262 ((Param
*) node
)->paramkind
== PARAM_EXTERN
&&
263 pstate
!= NULL
&& pstate
->p_variableparams
)
266 * Input is a Param of previously undetermined type, and we want to
267 * update our knowledge of the Param's type. Find the topmost
268 * ParseState and update the state.
270 Param
*param
= (Param
*) node
;
271 int paramno
= param
->paramid
;
272 ParseState
*toppstate
;
275 while (toppstate
->parentParseState
!= NULL
)
276 toppstate
= toppstate
->parentParseState
;
278 if (paramno
<= 0 || /* shouldn't happen, but... */
279 paramno
> toppstate
->p_numparams
)
281 (errcode(ERRCODE_UNDEFINED_PARAMETER
),
282 errmsg("there is no parameter $%d", paramno
),
283 parser_errposition(pstate
, param
->location
)));
285 if (toppstate
->p_paramtypes
[paramno
- 1] == UNKNOWNOID
)
287 /* We've successfully resolved the type */
288 toppstate
->p_paramtypes
[paramno
- 1] = targetTypeId
;
290 else if (toppstate
->p_paramtypes
[paramno
- 1] == targetTypeId
)
292 /* We previously resolved the type, and it matches */
298 (errcode(ERRCODE_AMBIGUOUS_PARAMETER
),
299 errmsg("inconsistent types deduced for parameter $%d",
301 errdetail("%s versus %s",
302 format_type_be(toppstate
->p_paramtypes
[paramno
- 1]),
303 format_type_be(targetTypeId
)),
304 parser_errposition(pstate
, param
->location
)));
307 param
->paramtype
= targetTypeId
;
310 * Note: it is tempting here to set the Param's paramtypmod to
311 * targetTypeMod, but that is probably unwise because we have no
312 * infrastructure that enforces that the value delivered for a Param
313 * will match any particular typmod. Leaving it -1 ensures that a
314 * run-time length check/coercion will occur if needed.
316 param
->paramtypmod
= -1;
318 /* Use the leftmost of the param's and coercion's locations */
320 (param
->location
< 0 || location
< param
->location
))
321 param
->location
= location
;
323 return (Node
*) param
;
325 pathtype
= find_coercion_pathway(targetTypeId
, inputTypeId
, ccontext
,
327 if (pathtype
!= COERCION_PATH_NONE
)
329 if (pathtype
!= COERCION_PATH_RELABELTYPE
)
332 * Generate an expression tree representing run-time application
333 * of the conversion function. If we are dealing with a domain
334 * target type, the conversion function will yield the base type,
335 * and we need to extract the correct typmod to use from the
336 * domain's typtypmod.
341 baseTypeMod
= targetTypeMod
;
342 baseTypeId
= getBaseTypeAndTypmod(targetTypeId
, &baseTypeMod
);
344 result
= build_coercion_expression(node
, pathtype
, funcId
,
345 baseTypeId
, baseTypeMod
,
347 (cformat
!= COERCE_IMPLICIT_CAST
));
350 * If domain, coerce to the domain type and relabel with domain
351 * type ID. We can skip the internal length-coercion step if the
352 * selected coercion function was a type-and-length coercion.
354 if (targetTypeId
!= baseTypeId
)
355 result
= coerce_to_domain(result
, baseTypeId
, baseTypeMod
,
357 cformat
, location
, true,
358 exprIsLengthCoercion(result
,
364 * We don't need to do a physical conversion, but we do need to
365 * attach a RelabelType node so that the expression will be seen
366 * to have the intended type when inspected by higher-level code.
368 * Also, domains may have value restrictions beyond the base type
369 * that must be accounted for. If the destination is a domain
370 * then we won't need a RelabelType node.
372 result
= coerce_to_domain(node
, InvalidOid
, -1, targetTypeId
,
373 cformat
, location
, false, false);
377 * XXX could we label result with exprTypmod(node) instead of
378 * default -1 typmod, to save a possible length-coercion
379 * later? Would work if both types have same interpretation of
380 * typmod, which is likely but not certain.
382 RelabelType
*r
= makeRelabelType((Expr
*) result
,
386 r
->location
= location
;
392 if (inputTypeId
== RECORDOID
&&
393 ISCOMPLEX(targetTypeId
))
395 /* Coerce a RECORD to a specific complex type */
396 return coerce_record_to_complex(pstate
, node
, targetTypeId
,
397 ccontext
, cformat
, location
);
399 if (targetTypeId
== RECORDOID
&&
400 ISCOMPLEX(inputTypeId
))
402 /* Coerce a specific complex type to RECORD */
403 /* NB: we do NOT want a RelabelType here */
407 if (inputTypeId
== RECORDARRAYOID
&&
408 is_complex_array(targetTypeId
))
410 /* Coerce record[] to a specific complex array type */
411 /* not implemented yet ... */
414 if (targetTypeId
== RECORDARRAYOID
&&
415 is_complex_array(inputTypeId
))
417 /* Coerce a specific complex array type to record[] */
418 /* NB: we do NOT want a RelabelType here */
421 if (typeInheritsFrom(inputTypeId
, targetTypeId
))
424 * Input class type is a subclass of target, so generate an
425 * appropriate runtime conversion (removing unneeded columns and
426 * possibly rearranging the ones that are wanted).
428 ConvertRowtypeExpr
*r
= makeNode(ConvertRowtypeExpr
);
430 r
->arg
= (Expr
*) node
;
431 r
->resulttype
= targetTypeId
;
432 r
->convertformat
= cformat
;
433 r
->location
= location
;
436 /* If we get here, caller blew it */
437 elog(ERROR
, "failed to find conversion function from %s to %s",
438 format_type_be(inputTypeId
), format_type_be(targetTypeId
));
439 return NULL
; /* keep compiler quiet */
445 * Can input_typeids be coerced to target_typeids?
447 * We must be told the context (CAST construct, assignment, implicit coercion)
448 * as this determines the set of available casts.
451 can_coerce_type(int nargs
, Oid
*input_typeids
, Oid
*target_typeids
,
452 CoercionContext ccontext
)
454 bool have_generics
= false;
457 /* run through argument list... */
458 for (i
= 0; i
< nargs
; i
++)
460 Oid inputTypeId
= input_typeids
[i
];
461 Oid targetTypeId
= target_typeids
[i
];
462 CoercionPathType pathtype
;
465 /* no problem if same type */
466 if (inputTypeId
== targetTypeId
)
469 /* accept if target is ANY */
470 if (targetTypeId
== ANYOID
)
473 /* accept if target is polymorphic, for now */
474 if (IsPolymorphicType(targetTypeId
))
476 have_generics
= true; /* do more checking later */
481 * If input is an untyped string constant, assume we can convert it to
484 if (inputTypeId
== UNKNOWNOID
)
488 * If pg_cast shows that we can coerce, accept. This test now covers
489 * both binary-compatible and coercion-function cases.
491 pathtype
= find_coercion_pathway(targetTypeId
, inputTypeId
, ccontext
,
493 if (pathtype
!= COERCION_PATH_NONE
)
497 * If input is RECORD and target is a composite type, assume we can
498 * coerce (may need tighter checking here)
500 if (inputTypeId
== RECORDOID
&&
501 ISCOMPLEX(targetTypeId
))
505 * If input is a composite type and target is RECORD, accept
507 if (targetTypeId
== RECORDOID
&&
508 ISCOMPLEX(inputTypeId
))
511 #ifdef NOT_USED /* not implemented yet */
513 * If input is record[] and target is a composite array type,
514 * assume we can coerce (may need tighter checking here)
516 if (inputTypeId
== RECORDARRAYOID
&&
517 is_complex_array(targetTypeId
))
522 * If input is a composite array type and target is record[], accept
524 if (targetTypeId
== RECORDARRAYOID
&&
525 is_complex_array(inputTypeId
))
529 * If input is a class type that inherits from target, accept
531 if (typeInheritsFrom(inputTypeId
, targetTypeId
))
535 * Else, cannot coerce at this argument position
540 /* If we found any generic argument types, cross-check them */
543 if (!check_generic_type_consistency(input_typeids
, target_typeids
,
553 * Create an expression tree to represent coercion to a domain type.
555 * 'arg': input expression
556 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
557 * has not bothered to look this up)
558 * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
559 * has not bothered to look this up)
560 * 'typeId': target type to coerce to
561 * 'cformat': coercion format
562 * 'location': coercion request location
563 * 'hideInputCoercion': if true, hide the input coercion under this one.
564 * 'lengthCoercionDone': if true, caller already accounted for length,
565 * ie the input is already of baseTypMod as well as baseTypeId.
567 * If the target type isn't a domain, the given 'arg' is returned as-is.
570 coerce_to_domain(Node
*arg
, Oid baseTypeId
, int32 baseTypeMod
, Oid typeId
,
571 CoercionForm cformat
, int location
,
572 bool hideInputCoercion
,
573 bool lengthCoercionDone
)
575 CoerceToDomain
*result
;
577 /* Get the base type if it hasn't been supplied */
578 if (baseTypeId
== InvalidOid
)
579 baseTypeId
= getBaseTypeAndTypmod(typeId
, &baseTypeMod
);
581 /* If it isn't a domain, return the node as it was passed in */
582 if (baseTypeId
== typeId
)
585 /* Suppress display of nested coercion steps */
586 if (hideInputCoercion
)
587 hide_coercion_node(arg
);
590 * If the domain applies a typmod to its base type, build the appropriate
591 * coercion step. Mark it implicit for display purposes, because we don't
592 * want it shown separately by ruleutils.c; but the isExplicit flag passed
593 * to the conversion function depends on the manner in which the domain
594 * coercion is invoked, so that the semantics of implicit and explicit
595 * coercion differ. (Is that really the behavior we want?)
597 * NOTE: because we apply this as part of the fixed expression structure,
598 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
599 * would be safe to do anyway, without lots of knowledge about what the
600 * base type thinks the typmod means.
602 if (!lengthCoercionDone
)
604 if (baseTypeMod
>= 0)
605 arg
= coerce_type_typmod(arg
, baseTypeId
, baseTypeMod
,
606 COERCE_IMPLICIT_CAST
, location
,
607 (cformat
!= COERCE_IMPLICIT_CAST
),
612 * Now build the domain coercion node. This represents run-time checking
613 * of any constraints currently attached to the domain. This also ensures
614 * that the expression is properly labeled as to result type.
616 result
= makeNode(CoerceToDomain
);
617 result
->arg
= (Expr
*) arg
;
618 result
->resulttype
= typeId
;
619 result
->resulttypmod
= -1; /* currently, always -1 for domains */
620 result
->coercionformat
= cformat
;
621 result
->location
= location
;
623 return (Node
*) result
;
628 * coerce_type_typmod()
629 * Force a value to a particular typmod, if meaningful and possible.
631 * This is applied to values that are going to be stored in a relation
632 * (where we have an atttypmod for the column) as well as values being
633 * explicitly CASTed (where the typmod comes from the target type spec).
635 * The caller must have already ensured that the value is of the correct
636 * type, typically by applying coerce_type.
638 * cformat determines the display properties of the generated node (if any),
639 * while isExplicit may affect semantics. If hideInputCoercion is true
640 * *and* we generate a node, the input node is forced to IMPLICIT display
641 * form, so that only the typmod coercion node will be visible when
642 * displaying the expression.
644 * NOTE: this does not need to work on domain types, because any typmod
645 * coercion for a domain is considered to be part of the type coercion
646 * needed to produce the domain value in the first place. So, no getBaseType.
649 coerce_type_typmod(Node
*node
, Oid targetTypeId
, int32 targetTypMod
,
650 CoercionForm cformat
, int location
,
651 bool isExplicit
, bool hideInputCoercion
)
653 CoercionPathType pathtype
;
657 * A negative typmod is assumed to mean that no coercion is wanted. Also,
658 * skip coercion if already done.
660 if (targetTypMod
< 0 || targetTypMod
== exprTypmod(node
))
663 pathtype
= find_typmod_coercion_function(targetTypeId
, &funcId
);
665 if (pathtype
!= COERCION_PATH_NONE
)
667 /* Suppress display of nested coercion steps */
668 if (hideInputCoercion
)
669 hide_coercion_node(node
);
671 node
= build_coercion_expression(node
, pathtype
, funcId
,
672 targetTypeId
, targetTypMod
,
681 * Mark a coercion node as IMPLICIT so it will never be displayed by
682 * ruleutils.c. We use this when we generate a nest of coercion nodes
683 * to implement what is logically one conversion; the inner nodes are
684 * forced to IMPLICIT_CAST format. This does not change their semantics,
685 * only display behavior.
687 * It is caller error to call this on something that doesn't have a
688 * CoercionForm field.
691 hide_coercion_node(Node
*node
)
693 if (IsA(node
, FuncExpr
))
694 ((FuncExpr
*) node
)->funcformat
= COERCE_IMPLICIT_CAST
;
695 else if (IsA(node
, RelabelType
))
696 ((RelabelType
*) node
)->relabelformat
= COERCE_IMPLICIT_CAST
;
697 else if (IsA(node
, CoerceViaIO
))
698 ((CoerceViaIO
*) node
)->coerceformat
= COERCE_IMPLICIT_CAST
;
699 else if (IsA(node
, ArrayCoerceExpr
))
700 ((ArrayCoerceExpr
*) node
)->coerceformat
= COERCE_IMPLICIT_CAST
;
701 else if (IsA(node
, ConvertRowtypeExpr
))
702 ((ConvertRowtypeExpr
*) node
)->convertformat
= COERCE_IMPLICIT_CAST
;
703 else if (IsA(node
, RowExpr
))
704 ((RowExpr
*) node
)->row_format
= COERCE_IMPLICIT_CAST
;
705 else if (IsA(node
, CoerceToDomain
))
706 ((CoerceToDomain
*) node
)->coercionformat
= COERCE_IMPLICIT_CAST
;
708 elog(ERROR
, "unsupported node type: %d", (int) nodeTag(node
));
712 * build_coercion_expression()
713 * Construct an expression tree for applying a pg_cast entry.
715 * This is used for both type-coercion and length-coercion operations,
716 * since there is no difference in terms of the calling convention.
719 build_coercion_expression(Node
*node
,
720 CoercionPathType pathtype
,
722 Oid targetTypeId
, int32 targetTypMod
,
723 CoercionForm cformat
, int location
,
728 if (OidIsValid(funcId
))
731 Form_pg_proc procstruct
;
733 tp
= SearchSysCache(PROCOID
,
734 ObjectIdGetDatum(funcId
),
736 if (!HeapTupleIsValid(tp
))
737 elog(ERROR
, "cache lookup failed for function %u", funcId
);
738 procstruct
= (Form_pg_proc
) GETSTRUCT(tp
);
741 * These Asserts essentially check that function is a legal coercion
742 * function. We can't make the seemingly obvious tests on prorettype
743 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
744 * various binary-compatibility cases.
746 /* Assert(targetTypeId == procstruct->prorettype); */
747 Assert(!procstruct
->proretset
);
748 Assert(!procstruct
->proisagg
);
749 nargs
= procstruct
->pronargs
;
750 Assert(nargs
>= 1 && nargs
<= 3);
751 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
752 Assert(nargs
< 2 || procstruct
->proargtypes
.values
[1] == INT4OID
);
753 Assert(nargs
< 3 || procstruct
->proargtypes
.values
[2] == BOOLOID
);
758 if (pathtype
== COERCION_PATH_FUNC
)
760 /* We build an ordinary FuncExpr with special arguments */
765 Assert(OidIsValid(funcId
));
767 args
= list_make1(node
);
771 /* Pass target typmod as an int4 constant */
772 cons
= makeConst(INT4OID
,
775 Int32GetDatum(targetTypMod
),
779 args
= lappend(args
, cons
);
784 /* Pass it a boolean isExplicit parameter, too */
785 cons
= makeConst(BOOLOID
,
788 BoolGetDatum(isExplicit
),
792 args
= lappend(args
, cons
);
795 fexpr
= makeFuncExpr(funcId
, targetTypeId
, args
, cformat
);
796 fexpr
->location
= location
;
797 return (Node
*) fexpr
;
799 else if (pathtype
== COERCION_PATH_ARRAYCOERCE
)
801 /* We need to build an ArrayCoerceExpr */
802 ArrayCoerceExpr
*acoerce
= makeNode(ArrayCoerceExpr
);
804 acoerce
->arg
= (Expr
*) node
;
805 acoerce
->elemfuncid
= funcId
;
806 acoerce
->resulttype
= targetTypeId
;
809 * Label the output as having a particular typmod only if we are
810 * really invoking a length-coercion function, ie one with more than
813 acoerce
->resulttypmod
= (nargs
>= 2) ? targetTypMod
: -1;
814 acoerce
->isExplicit
= isExplicit
;
815 acoerce
->coerceformat
= cformat
;
816 acoerce
->location
= location
;
818 return (Node
*) acoerce
;
820 else if (pathtype
== COERCION_PATH_COERCEVIAIO
)
822 /* We need to build a CoerceViaIO node */
823 CoerceViaIO
*iocoerce
= makeNode(CoerceViaIO
);
825 Assert(!OidIsValid(funcId
));
827 iocoerce
->arg
= (Expr
*) node
;
828 iocoerce
->resulttype
= targetTypeId
;
829 iocoerce
->coerceformat
= cformat
;
830 iocoerce
->location
= location
;
832 return (Node
*) iocoerce
;
836 elog(ERROR
, "unsupported pathtype %d in build_coercion_expression",
838 return NULL
; /* keep compiler quiet */
844 * coerce_record_to_complex
845 * Coerce a RECORD to a specific composite type.
847 * Currently we only support this for inputs that are RowExprs or whole-row
851 coerce_record_to_complex(ParseState
*pstate
, Node
*node
,
853 CoercionContext ccontext
,
854 CoercionForm cformat
,
865 if (node
&& IsA(node
, RowExpr
))
868 * Since the RowExpr must be of type RECORD, we needn't worry about it
869 * containing any dropped columns.
871 args
= ((RowExpr
*) node
)->args
;
873 else if (node
&& IsA(node
, Var
) &&
874 ((Var
*) node
)->varattno
== InvalidAttrNumber
)
876 int rtindex
= ((Var
*) node
)->varno
;
877 int sublevels_up
= ((Var
*) node
)->varlevelsup
;
878 int vlocation
= ((Var
*) node
)->location
;
881 rte
= GetRTEByRangeTablePosn(pstate
, rtindex
, sublevels_up
);
882 expandRTE(rte
, rtindex
, sublevels_up
, vlocation
, false,
887 (errcode(ERRCODE_CANNOT_COERCE
),
888 errmsg("cannot cast type %s to %s",
889 format_type_be(RECORDOID
),
890 format_type_be(targetTypeId
)),
891 parser_coercion_errposition(pstate
, location
, node
)));
893 tupdesc
= lookup_rowtype_tupdesc(targetTypeId
, -1);
896 arg
= list_head(args
);
897 for (i
= 0; i
< tupdesc
->natts
; i
++)
903 /* Fill in NULLs for dropped columns in rowtype */
904 if (tupdesc
->attrs
[i
]->attisdropped
)
907 * can't use atttypid here, but it doesn't really matter what type
908 * the Const claims to be.
910 newargs
= lappend(newargs
, makeNullConst(INT4OID
, -1));
916 (errcode(ERRCODE_CANNOT_COERCE
),
917 errmsg("cannot cast type %s to %s",
918 format_type_be(RECORDOID
),
919 format_type_be(targetTypeId
)),
920 errdetail("Input has too few columns."),
921 parser_coercion_errposition(pstate
, location
, node
)));
922 expr
= (Node
*) lfirst(arg
);
923 exprtype
= exprType(expr
);
925 cexpr
= coerce_to_target_type(pstate
,
927 tupdesc
->attrs
[i
]->atttypid
,
928 tupdesc
->attrs
[i
]->atttypmod
,
930 COERCE_IMPLICIT_CAST
,
934 (errcode(ERRCODE_CANNOT_COERCE
),
935 errmsg("cannot cast type %s to %s",
936 format_type_be(RECORDOID
),
937 format_type_be(targetTypeId
)),
938 errdetail("Cannot cast type %s to %s in column %d.",
939 format_type_be(exprtype
),
940 format_type_be(tupdesc
->attrs
[i
]->atttypid
),
942 parser_coercion_errposition(pstate
, location
, expr
)));
943 newargs
= lappend(newargs
, cexpr
);
949 (errcode(ERRCODE_CANNOT_COERCE
),
950 errmsg("cannot cast type %s to %s",
951 format_type_be(RECORDOID
),
952 format_type_be(targetTypeId
)),
953 errdetail("Input has too many columns."),
954 parser_coercion_errposition(pstate
, location
, node
)));
956 ReleaseTupleDesc(tupdesc
);
958 rowexpr
= makeNode(RowExpr
);
959 rowexpr
->args
= newargs
;
960 rowexpr
->row_typeid
= targetTypeId
;
961 rowexpr
->row_format
= cformat
;
962 rowexpr
->colnames
= NIL
; /* not needed for named target type */
963 rowexpr
->location
= location
;
964 return (Node
*) rowexpr
;
968 * coerce_to_boolean()
969 * Coerce an argument of a construct that requires boolean input
970 * (AND, OR, NOT, etc). Also check that input is not a set.
972 * Returns the possibly-transformed node tree.
974 * As with coerce_type, pstate may be NULL if no special unknown-Param
975 * processing is wanted.
978 coerce_to_boolean(ParseState
*pstate
, Node
*node
,
979 const char *constructName
)
981 Oid inputTypeId
= exprType(node
);
983 if (inputTypeId
!= BOOLOID
)
987 newnode
= coerce_to_target_type(pstate
, node
, inputTypeId
,
990 COERCE_IMPLICIT_CAST
,
994 (errcode(ERRCODE_DATATYPE_MISMATCH
),
995 /* translator: first %s is name of a SQL construct, eg WHERE */
996 errmsg("argument of %s must be type boolean, not type %s",
997 constructName
, format_type_be(inputTypeId
)),
998 parser_errposition(pstate
, exprLocation(node
))));
1002 if (expression_returns_set(node
))
1004 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1005 /* translator: %s is name of a SQL construct, eg WHERE */
1006 errmsg("argument of %s must not return a set",
1008 parser_errposition(pstate
, exprLocation(node
))));
1014 * coerce_to_specific_type()
1015 * Coerce an argument of a construct that requires a specific data type.
1016 * Also check that input is not a set.
1018 * Returns the possibly-transformed node tree.
1020 * As with coerce_type, pstate may be NULL if no special unknown-Param
1021 * processing is wanted.
1024 coerce_to_specific_type(ParseState
*pstate
, Node
*node
,
1026 const char *constructName
)
1028 Oid inputTypeId
= exprType(node
);
1030 if (inputTypeId
!= targetTypeId
)
1034 newnode
= coerce_to_target_type(pstate
, node
, inputTypeId
,
1036 COERCION_ASSIGNMENT
,
1037 COERCE_IMPLICIT_CAST
,
1039 if (newnode
== NULL
)
1041 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1042 /* translator: first %s is name of a SQL construct, eg LIMIT */
1043 errmsg("argument of %s must be type %s, not type %s",
1045 format_type_be(targetTypeId
),
1046 format_type_be(inputTypeId
)),
1047 parser_errposition(pstate
, exprLocation(node
))));
1051 if (expression_returns_set(node
))
1053 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1054 /* translator: %s is name of a SQL construct, eg LIMIT */
1055 errmsg("argument of %s must not return a set",
1057 parser_errposition(pstate
, exprLocation(node
))));
1064 * parser_coercion_errposition - report coercion error location, if possible
1066 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1067 * but there may be no such location in the case of an implicit coercion.
1068 * In that case point at the input expression.
1070 * XXX possibly this is more generally useful than coercion errors;
1071 * if so, should rename and place with parser_errposition.
1074 parser_coercion_errposition(ParseState
*pstate
,
1075 int coerce_location
,
1078 if (coerce_location
>= 0)
1079 return parser_errposition(pstate
, coerce_location
);
1081 return parser_errposition(pstate
, exprLocation(input_expr
));
1086 * select_common_type()
1087 * Determine the common supertype of a list of input expressions.
1088 * This is used for determining the output type of CASE, UNION,
1089 * and similar constructs.
1091 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1092 * in the list will be preferred if there is doubt.
1093 * 'context' is a phrase to use in the error message if we fail to select
1094 * a usable type. Pass NULL to have the routine return InvalidOid
1095 * rather than throwing an error on failure.
1096 * 'which_expr': if not NULL, receives a pointer to the particular input
1097 * expression from which the result type was taken.
1100 select_common_type(ParseState
*pstate
, List
*exprs
, const char *context
,
1105 TYPCATEGORY pcategory
;
1109 Assert(exprs
!= NIL
);
1110 pexpr
= (Node
*) linitial(exprs
);
1111 lc
= lnext(list_head(exprs
));
1112 ptype
= exprType(pexpr
);
1115 * If all input types are valid and exactly the same, just pick that type.
1116 * This is the only way that we will resolve the result as being a domain
1117 * type; otherwise domains are smashed to their base types for comparison.
1119 if (ptype
!= UNKNOWNOID
)
1121 for_each_cell(lc
, lc
)
1123 Node
*nexpr
= (Node
*) lfirst(lc
);
1124 Oid ntype
= exprType(nexpr
);
1129 if (lc
== NULL
) /* got to the end of the list? */
1132 *which_expr
= pexpr
;
1138 * Nope, so set up for the full algorithm. Note that at this point,
1139 * lc points to the first list item with type different from pexpr's;
1140 * we need not re-examine any items the previous loop advanced over.
1142 ptype
= getBaseType(ptype
);
1143 get_type_category_preferred(ptype
, &pcategory
, &pispreferred
);
1145 for_each_cell(lc
, lc
)
1147 Node
*nexpr
= (Node
*) lfirst(lc
);
1148 Oid ntype
= getBaseType(exprType(nexpr
));
1150 /* move on to next one if no new information... */
1151 if (ntype
!= UNKNOWNOID
&& ntype
!= ptype
)
1153 TYPCATEGORY ncategory
;
1156 get_type_category_preferred(ntype
, &ncategory
, &nispreferred
);
1157 if (ptype
== UNKNOWNOID
)
1159 /* so far, only unknowns so take anything... */
1162 pcategory
= ncategory
;
1163 pispreferred
= nispreferred
;
1165 else if (ncategory
!= pcategory
)
1168 * both types in different categories? then not much hope...
1170 if (context
== NULL
)
1173 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1175 translator: first %s is name of a SQL construct, eg CASE */
1176 errmsg("%s types %s and %s cannot be matched",
1178 format_type_be(ptype
),
1179 format_type_be(ntype
)),
1180 parser_errposition(pstate
, exprLocation(nexpr
))));
1182 else if (!pispreferred
&&
1183 can_coerce_type(1, &ptype
, &ntype
, COERCION_IMPLICIT
) &&
1184 !can_coerce_type(1, &ntype
, &ptype
, COERCION_IMPLICIT
))
1187 * take new type if can coerce to it implicitly but not the
1188 * other way; but if we have a preferred type, stay on it.
1192 pcategory
= ncategory
;
1193 pispreferred
= nispreferred
;
1199 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1200 * then resolve as type TEXT. This situation comes up with constructs
1201 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1202 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1203 * output type as UNKNOWN, but that really doesn't work, because we'd
1204 * probably end up needing a runtime coercion from UNKNOWN to something
1205 * else, and we usually won't have it. We need to coerce the unknown
1206 * literals while they are still literals, so a decision has to be made
1209 if (ptype
== UNKNOWNOID
)
1213 *which_expr
= pexpr
;
1218 * coerce_to_common_type()
1219 * Coerce an expression to the given type.
1221 * This is used following select_common_type() to coerce the individual
1222 * expressions to the desired type. 'context' is a phrase to use in the
1223 * error message if we fail to coerce.
1225 * As with coerce_type, pstate may be NULL if no special unknown-Param
1226 * processing is wanted.
1229 coerce_to_common_type(ParseState
*pstate
, Node
*node
,
1230 Oid targetTypeId
, const char *context
)
1232 Oid inputTypeId
= exprType(node
);
1234 if (inputTypeId
== targetTypeId
)
1235 return node
; /* no work */
1236 if (can_coerce_type(1, &inputTypeId
, &targetTypeId
, COERCION_IMPLICIT
))
1237 node
= coerce_type(pstate
, node
, inputTypeId
, targetTypeId
, -1,
1238 COERCION_IMPLICIT
, COERCE_IMPLICIT_CAST
, -1);
1241 (errcode(ERRCODE_CANNOT_COERCE
),
1242 /* translator: first %s is name of a SQL construct, eg CASE */
1243 errmsg("%s could not convert type %s to %s",
1245 format_type_be(inputTypeId
),
1246 format_type_be(targetTypeId
)),
1247 parser_errposition(pstate
, exprLocation(node
))));
1252 * check_generic_type_consistency()
1253 * Are the actual arguments potentially compatible with a
1254 * polymorphic function?
1256 * The argument consistency rules are:
1258 * 1) All arguments declared ANYARRAY must have matching datatypes,
1259 * and must in fact be varlena arrays.
1260 * 2) All arguments declared ANYELEMENT must have matching datatypes.
1261 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1262 * the actual ANYELEMENT datatype is in fact the element type for
1263 * the actual ANYARRAY datatype.
1264 * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1265 * (alone or in combination with plain ANYELEMENT), we add the extra
1266 * condition that the ANYELEMENT type must be an enum.
1267 * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1268 * we add the extra condition that the ANYELEMENT type must not be an array.
1269 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1270 * is an extra restriction if not.)
1272 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1273 * argument, assume it is okay.
1275 * If an input is of type ANYARRAY (ie, we know it's an array, but not
1276 * what element type), we will accept it as a match to an argument declared
1277 * ANYARRAY, so long as we don't have to determine an element type ---
1278 * that is, so long as there is no use of ANYELEMENT. This is mostly for
1279 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1281 * We do not ereport here, but just return FALSE if a rule is violated.
1284 check_generic_type_consistency(Oid
*actual_arg_types
,
1285 Oid
*declared_arg_types
,
1289 Oid elem_typeid
= InvalidOid
;
1290 Oid array_typeid
= InvalidOid
;
1292 bool have_anyelement
= false;
1293 bool have_anynonarray
= false;
1294 bool have_anyenum
= false;
1297 * Loop through the arguments to see if we have any that are polymorphic.
1298 * If so, require the actual types to be consistent.
1300 for (j
= 0; j
< nargs
; j
++)
1302 Oid decl_type
= declared_arg_types
[j
];
1303 Oid actual_type
= actual_arg_types
[j
];
1305 if (decl_type
== ANYELEMENTOID
||
1306 decl_type
== ANYNONARRAYOID
||
1307 decl_type
== ANYENUMOID
)
1309 have_anyelement
= true;
1310 if (decl_type
== ANYNONARRAYOID
)
1311 have_anynonarray
= true;
1312 else if (decl_type
== ANYENUMOID
)
1313 have_anyenum
= true;
1314 if (actual_type
== UNKNOWNOID
)
1316 if (OidIsValid(elem_typeid
) && actual_type
!= elem_typeid
)
1318 elem_typeid
= actual_type
;
1320 else if (decl_type
== ANYARRAYOID
)
1322 if (actual_type
== UNKNOWNOID
)
1324 if (OidIsValid(array_typeid
) && actual_type
!= array_typeid
)
1326 array_typeid
= actual_type
;
1330 /* Get the element type based on the array type, if we have one */
1331 if (OidIsValid(array_typeid
))
1333 if (array_typeid
== ANYARRAYOID
)
1335 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1336 if (have_anyelement
)
1341 array_typelem
= get_element_type(array_typeid
);
1342 if (!OidIsValid(array_typelem
))
1343 return false; /* should be an array, but isn't */
1345 if (!OidIsValid(elem_typeid
))
1348 * if we don't have an element type yet, use the one we just got
1350 elem_typeid
= array_typelem
;
1352 else if (array_typelem
!= elem_typeid
)
1354 /* otherwise, they better match */
1359 if (have_anynonarray
)
1361 /* require the element type to not be an array */
1362 if (type_is_array(elem_typeid
))
1368 /* require the element type to be an enum */
1369 if (!type_is_enum(elem_typeid
))
1378 * enforce_generic_type_consistency()
1379 * Make sure a polymorphic function is legally callable, and
1380 * deduce actual argument and result types.
1382 * If any polymorphic pseudotype is used in a function's arguments or
1383 * return type, we make sure the actual data types are consistent with
1384 * each other. The argument consistency rules are shown above for
1385 * check_generic_type_consistency().
1387 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1388 * argument, we attempt to deduce the actual type it should have. If
1389 * successful, we alter that position of declared_arg_types[] so that
1390 * make_fn_arguments will coerce the literal to the right thing.
1392 * Rules are applied to the function's return type (possibly altering it)
1393 * if it is declared as a polymorphic type:
1395 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1396 * argument's actual type as the function's return type.
1397 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1398 * is ANYELEMENT, use the actual type of the argument to determine
1399 * the function's return type, i.e. the element type's corresponding
1401 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1402 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1403 * and is therefore not expected here.
1404 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1405 * argument's actual type as the function's return type.
1406 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1407 * argument is ANYARRAY, use the actual type of the argument to determine
1408 * the function's return type, i.e. the array type's corresponding
1410 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1411 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1412 * and is therefore not expected here.
1413 * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1414 * (alone or in combination with plain ANYELEMENT), we add the extra
1415 * condition that the ANYELEMENT type must be an enum.
1416 * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1417 * we add the extra condition that the ANYELEMENT type must not be an array.
1418 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1419 * is an extra restriction if not.)
1421 * When allow_poly is false, we are not expecting any of the actual_arg_types
1422 * to be polymorphic, and we should not return a polymorphic result type
1423 * either. When allow_poly is true, it is okay to have polymorphic "actual"
1424 * arg types, and we can return ANYARRAY or ANYELEMENT as the result. (This
1425 * case is currently used only to check compatibility of an aggregate's
1426 * declaration with the underlying transfn.)
1429 enforce_generic_type_consistency(Oid
*actual_arg_types
,
1430 Oid
*declared_arg_types
,
1436 bool have_generics
= false;
1437 bool have_unknowns
= false;
1438 Oid elem_typeid
= InvalidOid
;
1439 Oid array_typeid
= InvalidOid
;
1441 bool have_anynonarray
= (rettype
== ANYNONARRAYOID
);
1442 bool have_anyenum
= (rettype
== ANYENUMOID
);
1445 * Loop through the arguments to see if we have any that are polymorphic.
1446 * If so, require the actual types to be consistent.
1448 for (j
= 0; j
< nargs
; j
++)
1450 Oid decl_type
= declared_arg_types
[j
];
1451 Oid actual_type
= actual_arg_types
[j
];
1453 if (decl_type
== ANYELEMENTOID
||
1454 decl_type
== ANYNONARRAYOID
||
1455 decl_type
== ANYENUMOID
)
1457 have_generics
= true;
1458 if (decl_type
== ANYNONARRAYOID
)
1459 have_anynonarray
= true;
1460 else if (decl_type
== ANYENUMOID
)
1461 have_anyenum
= true;
1462 if (actual_type
== UNKNOWNOID
)
1464 have_unknowns
= true;
1467 if (allow_poly
&& decl_type
== actual_type
)
1468 continue; /* no new information here */
1469 if (OidIsValid(elem_typeid
) && actual_type
!= elem_typeid
)
1471 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1472 errmsg("arguments declared \"anyelement\" are not all alike"),
1473 errdetail("%s versus %s",
1474 format_type_be(elem_typeid
),
1475 format_type_be(actual_type
))));
1476 elem_typeid
= actual_type
;
1478 else if (decl_type
== ANYARRAYOID
)
1480 have_generics
= true;
1481 if (actual_type
== UNKNOWNOID
)
1483 have_unknowns
= true;
1486 if (allow_poly
&& decl_type
== actual_type
)
1487 continue; /* no new information here */
1488 if (OidIsValid(array_typeid
) && actual_type
!= array_typeid
)
1490 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1491 errmsg("arguments declared \"anyarray\" are not all alike"),
1492 errdetail("%s versus %s",
1493 format_type_be(array_typeid
),
1494 format_type_be(actual_type
))));
1495 array_typeid
= actual_type
;
1500 * Fast Track: if none of the arguments are polymorphic, return the
1501 * unmodified rettype. We assume it can't be polymorphic either.
1506 /* Get the element type based on the array type, if we have one */
1507 if (OidIsValid(array_typeid
))
1509 array_typelem
= get_element_type(array_typeid
);
1510 if (!OidIsValid(array_typelem
))
1512 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1513 errmsg("argument declared \"anyarray\" is not an array but type %s",
1514 format_type_be(array_typeid
))));
1516 if (!OidIsValid(elem_typeid
))
1519 * if we don't have an element type yet, use the one we just got
1521 elem_typeid
= array_typelem
;
1523 else if (array_typelem
!= elem_typeid
)
1525 /* otherwise, they better match */
1527 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1528 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1529 errdetail("%s versus %s",
1530 format_type_be(array_typeid
),
1531 format_type_be(elem_typeid
))));
1534 else if (!OidIsValid(elem_typeid
))
1538 array_typeid
= ANYARRAYOID
;
1539 elem_typeid
= ANYELEMENTOID
;
1543 /* Only way to get here is if all the generic args are UNKNOWN */
1545 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1546 errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1550 if (have_anynonarray
&& elem_typeid
!= ANYELEMENTOID
)
1552 /* require the element type to not be an array */
1553 if (type_is_array(elem_typeid
))
1555 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1556 errmsg("type matched to anynonarray is an array type: %s",
1557 format_type_be(elem_typeid
))));
1560 if (have_anyenum
&& elem_typeid
!= ANYELEMENTOID
)
1562 /* require the element type to be an enum */
1563 if (!type_is_enum(elem_typeid
))
1565 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1566 errmsg("type matched to anyenum is not an enum type: %s",
1567 format_type_be(elem_typeid
))));
1571 * If we had any unknown inputs, re-scan to assign correct types
1575 for (j
= 0; j
< nargs
; j
++)
1577 Oid decl_type
= declared_arg_types
[j
];
1578 Oid actual_type
= actual_arg_types
[j
];
1580 if (actual_type
!= UNKNOWNOID
)
1583 if (decl_type
== ANYELEMENTOID
||
1584 decl_type
== ANYNONARRAYOID
||
1585 decl_type
== ANYENUMOID
)
1586 declared_arg_types
[j
] = elem_typeid
;
1587 else if (decl_type
== ANYARRAYOID
)
1589 if (!OidIsValid(array_typeid
))
1591 array_typeid
= get_array_type(elem_typeid
);
1592 if (!OidIsValid(array_typeid
))
1594 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1595 errmsg("could not find array type for data type %s",
1596 format_type_be(elem_typeid
))));
1598 declared_arg_types
[j
] = array_typeid
;
1603 /* if we return ANYARRAY use the appropriate argument type */
1604 if (rettype
== ANYARRAYOID
)
1606 if (!OidIsValid(array_typeid
))
1608 array_typeid
= get_array_type(elem_typeid
);
1609 if (!OidIsValid(array_typeid
))
1611 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1612 errmsg("could not find array type for data type %s",
1613 format_type_be(elem_typeid
))));
1615 return array_typeid
;
1618 /* if we return ANYELEMENT use the appropriate argument type */
1619 if (rettype
== ANYELEMENTOID
||
1620 rettype
== ANYNONARRAYOID
||
1621 rettype
== ANYENUMOID
)
1624 /* we don't return a generic type; send back the original return type */
1629 * resolve_generic_type()
1630 * Deduce an individual actual datatype on the assumption that
1631 * the rules for polymorphic types are being followed.
1633 * declared_type is the declared datatype we want to resolve.
1634 * context_actual_type is the actual input datatype to some argument
1635 * that has declared datatype context_declared_type.
1637 * If declared_type isn't polymorphic, we just return it. Otherwise,
1638 * context_declared_type must be polymorphic, and we deduce the correct
1639 * return type based on the relationship of the two polymorphic types.
1642 resolve_generic_type(Oid declared_type
,
1643 Oid context_actual_type
,
1644 Oid context_declared_type
)
1646 if (declared_type
== ANYARRAYOID
)
1648 if (context_declared_type
== ANYARRAYOID
)
1650 /* Use actual type, but it must be an array */
1651 Oid array_typelem
= get_element_type(context_actual_type
);
1653 if (!OidIsValid(array_typelem
))
1655 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1656 errmsg("argument declared \"anyarray\" is not an array but type %s",
1657 format_type_be(context_actual_type
))));
1658 return context_actual_type
;
1660 else if (context_declared_type
== ANYELEMENTOID
||
1661 context_declared_type
== ANYNONARRAYOID
||
1662 context_declared_type
== ANYENUMOID
)
1664 /* Use the array type corresponding to actual type */
1665 Oid array_typeid
= get_array_type(context_actual_type
);
1667 if (!OidIsValid(array_typeid
))
1669 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1670 errmsg("could not find array type for data type %s",
1671 format_type_be(context_actual_type
))));
1672 return array_typeid
;
1675 else if (declared_type
== ANYELEMENTOID
||
1676 declared_type
== ANYNONARRAYOID
||
1677 declared_type
== ANYENUMOID
)
1679 if (context_declared_type
== ANYARRAYOID
)
1681 /* Use the element type corresponding to actual type */
1682 Oid array_typelem
= get_element_type(context_actual_type
);
1684 if (!OidIsValid(array_typelem
))
1686 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1687 errmsg("argument declared \"anyarray\" is not an array but type %s",
1688 format_type_be(context_actual_type
))));
1689 return array_typelem
;
1691 else if (context_declared_type
== ANYELEMENTOID
||
1692 context_declared_type
== ANYNONARRAYOID
||
1693 context_declared_type
== ANYENUMOID
)
1695 /* Use the actual type; it doesn't matter if array or not */
1696 return context_actual_type
;
1701 /* declared_type isn't polymorphic, so return it as-is */
1702 return declared_type
;
1704 /* If we get here, declared_type is polymorphic and context isn't */
1705 /* NB: this is a calling-code logic error, not a user error */
1706 elog(ERROR
, "could not determine polymorphic type because context isn't polymorphic");
1707 return InvalidOid
; /* keep compiler quiet */
1712 * Assign a category to the specified type OID.
1714 * NB: this must not return TYPCATEGORY_INVALID.
1717 TypeCategory(Oid type
)
1720 bool typispreferred
;
1722 get_type_category_preferred(type
, &typcategory
, &typispreferred
);
1723 Assert(typcategory
!= TYPCATEGORY_INVALID
);
1724 return (TYPCATEGORY
) typcategory
;
1728 /* IsPreferredType()
1729 * Check if this type is a preferred type for the given category.
1731 * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1732 * types of any category; otherwise, only for preferred types of that
1736 IsPreferredType(TYPCATEGORY category
, Oid type
)
1739 bool typispreferred
;
1741 get_type_category_preferred(type
, &typcategory
, &typispreferred
);
1742 if (category
== typcategory
|| category
== TYPCATEGORY_INVALID
)
1743 return typispreferred
;
1749 /* IsBinaryCoercible()
1750 * Check if srctype is binary-coercible to targettype.
1752 * This notion allows us to cheat and directly exchange values without
1753 * going through the trouble of calling a conversion function. Note that
1754 * in general, this should only be an implementation shortcut. Before 7.4,
1755 * this was also used as a heuristic for resolving overloaded functions and
1756 * operators, but that's basically a bad idea.
1758 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1759 * We consider two types binary-coercible if there is an implicitly
1760 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1761 * binary-coercible to its base type, though *not* vice versa (in the other
1762 * direction, one must apply domain constraint checks before accepting the
1763 * value as legitimate). We also need to special-case various polymorphic
1766 * This function replaces IsBinaryCompatible(), which was an inherently
1767 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1768 * the order of the operands is now significant.
1771 IsBinaryCoercible(Oid srctype
, Oid targettype
)
1774 Form_pg_cast castForm
;
1777 /* Fast path if same type */
1778 if (srctype
== targettype
)
1781 /* If srctype is a domain, reduce to its base type */
1782 if (OidIsValid(srctype
))
1783 srctype
= getBaseType(srctype
);
1785 /* Somewhat-fast path for domain -> base type case */
1786 if (srctype
== targettype
)
1789 /* Also accept any array type as coercible to ANYARRAY */
1790 if (targettype
== ANYARRAYOID
)
1791 if (type_is_array(srctype
))
1794 /* Also accept any non-array type as coercible to ANYNONARRAY */
1795 if (targettype
== ANYNONARRAYOID
)
1796 if (!type_is_array(srctype
))
1799 /* Also accept any enum type as coercible to ANYENUM */
1800 if (targettype
== ANYENUMOID
)
1801 if (type_is_enum(srctype
))
1804 /* Also accept any composite type as coercible to RECORD */
1805 if (targettype
== RECORDOID
)
1806 if (ISCOMPLEX(srctype
))
1809 /* Also accept any composite array type as coercible to RECORD[] */
1810 if (targettype
== RECORDARRAYOID
)
1811 if (is_complex_array(srctype
))
1814 /* Else look in pg_cast */
1815 tuple
= SearchSysCache(CASTSOURCETARGET
,
1816 ObjectIdGetDatum(srctype
),
1817 ObjectIdGetDatum(targettype
),
1819 if (!HeapTupleIsValid(tuple
))
1820 return false; /* no cast */
1821 castForm
= (Form_pg_cast
) GETSTRUCT(tuple
);
1823 result
= (castForm
->castfunc
== InvalidOid
&&
1824 castForm
->castcontext
== COERCION_CODE_IMPLICIT
);
1826 ReleaseSysCache(tuple
);
1833 * find_coercion_pathway
1834 * Look for a coercion pathway between two types.
1836 * Currently, this deals only with scalar-type cases; it does not consider
1837 * polymorphic types nor casts between composite types. (Perhaps fold
1838 * those in someday?)
1840 * ccontext determines the set of available casts.
1842 * The possible result codes are:
1843 * COERCION_PATH_NONE: failed to find any coercion pathway
1844 * *funcid is set to InvalidOid
1845 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1846 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1847 * *funcid is set to InvalidOid
1848 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1849 * *funcid is set to the element cast function, or InvalidOid
1850 * if the array elements are binary-compatible
1851 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1852 * *funcid is set to InvalidOid
1854 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1855 * needed to do the coercion; if the target is a domain then we may need to
1856 * apply domain constraint checking. If you want to check for a zero-effort
1857 * conversion then use IsBinaryCoercible().
1860 find_coercion_pathway(Oid targetTypeId
, Oid sourceTypeId
,
1861 CoercionContext ccontext
,
1864 CoercionPathType result
= COERCION_PATH_NONE
;
1867 *funcid
= InvalidOid
;
1869 /* Perhaps the types are domains; if so, look at their base types */
1870 if (OidIsValid(sourceTypeId
))
1871 sourceTypeId
= getBaseType(sourceTypeId
);
1872 if (OidIsValid(targetTypeId
))
1873 targetTypeId
= getBaseType(targetTypeId
);
1875 /* Domains are always coercible to and from their base type */
1876 if (sourceTypeId
== targetTypeId
)
1877 return COERCION_PATH_RELABELTYPE
;
1879 /* Look in pg_cast */
1880 tuple
= SearchSysCache(CASTSOURCETARGET
,
1881 ObjectIdGetDatum(sourceTypeId
),
1882 ObjectIdGetDatum(targetTypeId
),
1885 if (HeapTupleIsValid(tuple
))
1887 Form_pg_cast castForm
= (Form_pg_cast
) GETSTRUCT(tuple
);
1888 CoercionContext castcontext
;
1890 /* convert char value for castcontext to CoercionContext enum */
1891 switch (castForm
->castcontext
)
1893 case COERCION_CODE_IMPLICIT
:
1894 castcontext
= COERCION_IMPLICIT
;
1896 case COERCION_CODE_ASSIGNMENT
:
1897 castcontext
= COERCION_ASSIGNMENT
;
1899 case COERCION_CODE_EXPLICIT
:
1900 castcontext
= COERCION_EXPLICIT
;
1903 elog(ERROR
, "unrecognized castcontext: %d",
1904 (int) castForm
->castcontext
);
1905 castcontext
= 0; /* keep compiler quiet */
1909 /* Rely on ordering of enum for correct behavior here */
1910 if (ccontext
>= castcontext
)
1912 switch (castForm
->castmethod
)
1914 case COERCION_METHOD_FUNCTION
:
1915 result
= COERCION_PATH_FUNC
;
1916 *funcid
= castForm
->castfunc
;
1918 case COERCION_METHOD_INOUT
:
1919 result
= COERCION_PATH_COERCEVIAIO
;
1921 case COERCION_METHOD_BINARY
:
1922 result
= COERCION_PATH_RELABELTYPE
;
1925 elog(ERROR
, "unrecognized castmethod: %d",
1926 (int) castForm
->castmethod
);
1931 ReleaseSysCache(tuple
);
1936 * If there's no pg_cast entry, perhaps we are dealing with a pair of
1937 * array types. If so, and if the element types have a suitable cast,
1938 * report that we can coerce with an ArrayCoerceExpr.
1940 * Hack: disallow coercions to oidvector and int2vector, which
1941 * otherwise tend to capture coercions that should go to "real" array
1942 * types. We want those types to be considered "real" arrays for many
1943 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
1944 * guaranteed to produce an output that meets the restrictions of
1945 * these datatypes, such as being 1-dimensional.)
1947 if (targetTypeId
!= OIDVECTOROID
&& targetTypeId
!= INT2VECTOROID
)
1952 if ((targetElem
= get_element_type(targetTypeId
)) != InvalidOid
&&
1953 (sourceElem
= get_element_type(sourceTypeId
)) != InvalidOid
)
1955 CoercionPathType elempathtype
;
1958 elempathtype
= find_coercion_pathway(targetElem
,
1962 if (elempathtype
!= COERCION_PATH_NONE
&&
1963 elempathtype
!= COERCION_PATH_ARRAYCOERCE
)
1965 *funcid
= elemfuncid
;
1966 if (elempathtype
== COERCION_PATH_COERCEVIAIO
)
1967 result
= COERCION_PATH_COERCEVIAIO
;
1969 result
= COERCION_PATH_ARRAYCOERCE
;
1975 * If we still haven't found a possibility, consider automatic casting
1976 * using I/O functions. We allow assignment casts to string types
1977 * and explicit casts from string types to be handled this way. (The
1978 * CoerceViaIO mechanism is a lot more general than that, but this is
1979 * all we want to allow in the absence of a pg_cast entry.) It would
1980 * probably be better to insist on explicit casts in both directions,
1981 * but this is a compromise to preserve something of the pre-8.3
1982 * behavior that many types had implicit (yipes!) casts to text.
1984 if (result
== COERCION_PATH_NONE
)
1986 if (ccontext
>= COERCION_ASSIGNMENT
&&
1987 TypeCategory(targetTypeId
) == TYPCATEGORY_STRING
)
1988 result
= COERCION_PATH_COERCEVIAIO
;
1989 else if (ccontext
>= COERCION_EXPLICIT
&&
1990 TypeCategory(sourceTypeId
) == TYPCATEGORY_STRING
)
1991 result
= COERCION_PATH_COERCEVIAIO
;
2000 * find_typmod_coercion_function -- does the given type need length coercion?
2002 * If the target type possesses a pg_cast function from itself to itself,
2003 * it must need length coercion.
2005 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2007 * If the given type is a varlena array type, we do not look for a coercion
2008 * function associated directly with the array type, but instead look for
2009 * one associated with the element type. An ArrayCoerceExpr node must be
2010 * used to apply such a function.
2012 * We use the same result enum as find_coercion_pathway, but the only possible
2014 * COERCION_PATH_NONE: no length coercion needed
2015 * COERCION_PATH_FUNC: apply the function returned in *funcid
2016 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2019 find_typmod_coercion_function(Oid typeId
,
2022 CoercionPathType result
;
2024 Form_pg_type typeForm
;
2027 *funcid
= InvalidOid
;
2028 result
= COERCION_PATH_FUNC
;
2030 targetType
= typeidType(typeId
);
2031 typeForm
= (Form_pg_type
) GETSTRUCT(targetType
);
2033 /* Check for a varlena array type (and not a domain) */
2034 if (typeForm
->typelem
!= InvalidOid
&&
2035 typeForm
->typlen
== -1 &&
2036 typeForm
->typtype
!= TYPTYPE_DOMAIN
)
2038 /* Yes, switch our attention to the element type */
2039 typeId
= typeForm
->typelem
;
2040 result
= COERCION_PATH_ARRAYCOERCE
;
2042 ReleaseSysCache(targetType
);
2044 /* Look in pg_cast */
2045 tuple
= SearchSysCache(CASTSOURCETARGET
,
2046 ObjectIdGetDatum(typeId
),
2047 ObjectIdGetDatum(typeId
),
2050 if (HeapTupleIsValid(tuple
))
2052 Form_pg_cast castForm
= (Form_pg_cast
) GETSTRUCT(tuple
);
2054 *funcid
= castForm
->castfunc
;
2055 ReleaseSysCache(tuple
);
2058 if (!OidIsValid(*funcid
))
2059 result
= COERCION_PATH_NONE
;
2066 * Is this type an array of composite?
2068 * Note: this will not return true for record[]; check for RECORDARRAYOID
2069 * separately if needed.
2072 is_complex_array(Oid typid
)
2074 Oid elemtype
= get_element_type(typid
);
2076 return (OidIsValid(elemtype
) && ISCOMPLEX(elemtype
));