1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.119 2004/06/16 01:26:44 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "nodes/makefuncs.h"
20 #include "nodes/params.h"
21 #include "optimizer/clauses.h"
22 #include "parser/parsetree.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_expr.h"
25 #include "parser/parse_func.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/fmgroids.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/typcache.h"
35 static Node *coerce_type_typmod(Node *node,
36 Oid targetTypeId, int32 targetTypMod,
37 CoercionForm cformat, bool isExplicit,
38 bool hideInputCoercion);
39 static void hide_coercion_node(Node *node);
40 static Node *build_coercion_expression(Node *node, Oid funcId,
41 Oid targetTypeId, int32 targetTypMod,
42 CoercionForm cformat, bool isExplicit);
43 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
45 CoercionContext ccontext,
46 CoercionForm cformat);
50 * coerce_to_target_type()
51 * Convert an expression to a target type and typmod.
53 * This is the general-purpose entry point for arbitrary type coercion
54 * operations. Direct use of the component operations can_coerce_type,
55 * coerce_type, and coerce_type_typmod should be restricted to special
56 * cases (eg, when the conversion is expected to succeed).
58 * Returns the possibly-transformed expression tree, or NULL if the type
59 * conversion is not possible. (We do this, rather than ereport'ing directly,
60 * so that callers can generate custom error messages indicating context.)
62 * pstate - parse state (can be NULL, see coerce_type)
63 * expr - input expression tree (already transformed by transformExpr)
64 * exprtype - result type of expr
65 * targettype - desired result type
66 * targettypmod - desired result typmod
67 * ccontext, cformat - context indicators to control coercions
70 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
71 Oid targettype, int32 targettypmod,
72 CoercionContext ccontext,
77 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
80 result = coerce_type(pstate, expr, exprtype,
81 targettype, targettypmod,
85 * If the target is a fixed-length type, it may need a length coercion
86 * as well as a type coercion. If we find ourselves adding both,
87 * force the inner coercion node to implicit display form.
89 result = coerce_type_typmod(result,
90 targettype, targettypmod,
92 (cformat != COERCE_IMPLICIT_CAST),
93 (result != expr && !IsA(result, Const)));
101 * Convert an expression to a different type.
103 * The caller should already have determined that the coercion is possible;
104 * see can_coerce_type.
106 * Normally, no coercion to a typmod (length) is performed here. The caller
107 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
108 * (But if the target type is a domain, it may internally contain a
109 * typmod constraint, which will be applied inside coerce_to_domain.)
110 * In some cases pg_cast specifies a type coercion function that also
111 * applies length conversion, and in those cases only, the result will
112 * already be properly coerced to the specified typmod.
114 * pstate is only used in the case that we are able to resolve the type of
115 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
116 * caller does not want type information updated for Params.
119 coerce_type(ParseState *pstate, Node *node,
120 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
121 CoercionContext ccontext, CoercionForm cformat)
126 if (targetTypeId == inputTypeId ||
129 /* no conversion needed */
132 if (targetTypeId == ANYOID ||
133 targetTypeId == ANYARRAYOID ||
134 targetTypeId == ANYELEMENTOID)
136 /* assume can_coerce_type verified that implicit coercion is okay */
137 /* NB: we do NOT want a RelabelType here */
140 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
143 * Input is a string constant with previously undetermined type.
144 * Apply the target type's typinput function to it to produce a
145 * constant of the target type.
147 * NOTE: this case cannot be folded together with the other
148 * constant-input case, since the typinput function does not
149 * necessarily behave the same as a type conversion function. For
150 * example, int4's typinput function will reject "1.2", whereas
151 * float-to-int type conversion will round to integer.
153 * XXX if the typinput function is not immutable, we really ought to
154 * postpone evaluation of the function call until runtime. But
155 * there is no way to represent a typinput function call as an
156 * expression tree, because C-string values are not Datums. (XXX
157 * This *is* possible as of 7.3, do we want to do it?)
159 Const *con = (Const *) node;
160 Const *newcon = makeNode(Const);
161 Type targetType = typeidType(targetTypeId);
162 char targetTyptype = typeTypType(targetType);
164 newcon->consttype = targetTypeId;
165 newcon->constlen = typeLen(targetType);
166 newcon->constbyval = typeByVal(targetType);
167 newcon->constisnull = con->constisnull;
169 if (!con->constisnull)
171 char *val = DatumGetCString(DirectFunctionCall1(unknownout,
175 * We pass typmod -1 to the input routine, primarily because
176 * existing input routines follow implicit-coercion semantics
177 * for length checks, which is not always what we want here.
178 * Any length constraint will be applied later by our caller.
180 * Note that we call stringTypeDatum using the domain's pg_type
181 * row, if it's a domain. This works because the domain row
182 * has the same typinput and typelem as the base type ---
185 newcon->constvalue = stringTypeDatum(targetType, val, -1);
189 result = (Node *) newcon;
191 /* If target is a domain, apply constraints. */
192 if (targetTyptype == 'd')
193 result = coerce_to_domain(result, InvalidOid, targetTypeId,
196 ReleaseSysCache(targetType);
200 if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
201 ((Param *) node)->paramkind == PARAM_NUM &&
202 pstate != NULL && pstate->p_variableparams)
205 * Input is a Param of previously undetermined type, and we want
206 * to update our knowledge of the Param's type. Find the topmost
207 * ParseState and update the state.
209 Param *param = (Param *) node;
210 int paramno = param->paramid;
211 ParseState *toppstate;
214 while (toppstate->parentParseState != NULL)
215 toppstate = toppstate->parentParseState;
217 if (paramno <= 0 || /* shouldn't happen, but... */
218 paramno > toppstate->p_numparams)
220 (errcode(ERRCODE_UNDEFINED_PARAMETER),
221 errmsg("there is no parameter $%d", paramno)));
223 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
225 /* We've successfully resolved the type */
226 toppstate->p_paramtypes[paramno - 1] = targetTypeId;
228 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
230 /* We previously resolved the type, and it matches */
236 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
237 errmsg("inconsistent types deduced for parameter $%d",
239 errdetail("%s versus %s",
240 format_type_be(toppstate->p_paramtypes[paramno - 1]),
241 format_type_be(targetTypeId))));
244 param->paramtype = targetTypeId;
245 return (Node *) param;
247 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
250 if (OidIsValid(funcId))
253 * Generate an expression tree representing run-time
254 * application of the conversion function. If we are dealing
255 * with a domain target type, the conversion function will
256 * yield the base type (and we assume targetTypeMod must be -1).
258 Oid baseTypeId = getBaseType(targetTypeId);
260 result = build_coercion_expression(node, funcId,
261 baseTypeId, targetTypeMod,
263 (cformat != COERCE_IMPLICIT_CAST));
266 * If domain, coerce to the domain type and relabel with
269 if (targetTypeId != baseTypeId)
270 result = coerce_to_domain(result, baseTypeId, targetTypeId,
276 * We don't need to do a physical conversion, but we do need
277 * to attach a RelabelType node so that the expression will be
278 * seen to have the intended type when inspected by
281 * Also, domains may have value restrictions beyond the base type
282 * that must be accounted for. If the destination is a domain
283 * then we won't need a RelabelType node.
285 result = coerce_to_domain(node, InvalidOid, targetTypeId,
290 * XXX could we label result with exprTypmod(node) instead
291 * of default -1 typmod, to save a possible
292 * length-coercion later? Would work if both types have
293 * same interpretation of typmod, which is likely but not
296 result = (Node *) makeRelabelType((Expr *) result,
303 if (inputTypeId == RECORDOID &&
304 ISCOMPLEX(targetTypeId))
306 /* Coerce a RECORD to a specific complex type */
307 return coerce_record_to_complex(pstate, node, targetTypeId,
310 if (typeInheritsFrom(inputTypeId, targetTypeId))
313 * Input class type is a subclass of target, so nothing to do ---
314 * except relabel the type. This is binary compatibility for
317 return (Node *) makeRelabelType((Expr *) node,
321 /* If we get here, caller blew it */
322 elog(ERROR, "failed to find conversion function from %s to %s",
323 format_type_be(inputTypeId), format_type_be(targetTypeId));
324 return NULL; /* keep compiler quiet */
330 * Can input_typeids be coerced to target_typeids?
332 * We must be told the context (CAST construct, assignment, implicit coercion)
333 * as this determines the set of available casts.
336 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
337 CoercionContext ccontext)
339 bool have_generics = false;
342 /* run through argument list... */
343 for (i = 0; i < nargs; i++)
345 Oid inputTypeId = input_typeids[i];
346 Oid targetTypeId = target_typeids[i];
349 /* no problem if same type */
350 if (inputTypeId == targetTypeId)
353 /* don't choke on references to no-longer-existing types */
354 if (!typeidIsValid(inputTypeId))
356 if (!typeidIsValid(targetTypeId))
359 /* accept if target is ANY */
360 if (targetTypeId == ANYOID)
363 /* accept if target is ANYARRAY or ANYELEMENT, for now */
364 if (targetTypeId == ANYARRAYOID ||
365 targetTypeId == ANYELEMENTOID)
367 have_generics = true; /* do more checking later */
372 * If input is an untyped string constant, assume we can convert
375 if (inputTypeId == UNKNOWNOID)
379 * If pg_cast shows that we can coerce, accept. This test now
380 * covers both binary-compatible and coercion-function cases.
382 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
387 * If input is RECORD and target is a composite type, assume
388 * we can coerce (may need tighter checking here)
390 if (inputTypeId == RECORDOID &&
391 ISCOMPLEX(targetTypeId))
395 * If input is a class type that inherits from target, accept
397 if (typeInheritsFrom(inputTypeId, targetTypeId))
401 * Else, cannot coerce at this argument position
406 /* If we found any generic argument types, cross-check them */
409 if (!check_generic_type_consistency(input_typeids, target_typeids,
419 * Create an expression tree to represent coercion to a domain type.
421 * 'arg': input expression
422 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
423 * has not bothered to look this up)
424 * 'typeId': target type to coerce to
425 * 'cformat': coercion format
426 * 'hideInputCoercion': if true, hide the input coercion under this one.
428 * If the target type isn't a domain, the given 'arg' is returned as-is.
431 coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId,
432 CoercionForm cformat, bool hideInputCoercion)
434 CoerceToDomain *result;
437 /* Get the base type if it hasn't been supplied */
438 if (baseTypeId == InvalidOid)
439 baseTypeId = getBaseType(typeId);
441 /* If it isn't a domain, return the node as it was passed in */
442 if (baseTypeId == typeId)
445 /* Suppress display of nested coercion steps */
446 if (hideInputCoercion)
447 hide_coercion_node(arg);
450 * If the domain applies a typmod to its base type, build the
451 * appropriate coercion step. Mark it implicit for display purposes,
452 * because we don't want it shown separately by ruleutils.c; but the
453 * isExplicit flag passed to the conversion function depends on the
454 * manner in which the domain coercion is invoked, so that the
455 * semantics of implicit and explicit coercion differ. (Is that
456 * really the behavior we want?)
458 * NOTE: because we apply this as part of the fixed expression structure,
459 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that
460 * that would be safe to do anyway, without lots of knowledge about
461 * what the base type thinks the typmod means.
463 typmod = get_typtypmod(typeId);
465 arg = coerce_type_typmod(arg, baseTypeId, typmod,
466 COERCE_IMPLICIT_CAST,
467 (cformat != COERCE_IMPLICIT_CAST),
471 * Now build the domain coercion node. This represents run-time
472 * checking of any constraints currently attached to the domain. This
473 * also ensures that the expression is properly labeled as to result
476 result = makeNode(CoerceToDomain);
477 result->arg = (Expr *) arg;
478 result->resulttype = typeId;
479 result->resulttypmod = -1; /* currently, always -1 for domains */
480 result->coercionformat = cformat;
482 return (Node *) result;
487 * coerce_type_typmod()
488 * Force a value to a particular typmod, if meaningful and possible.
490 * This is applied to values that are going to be stored in a relation
491 * (where we have an atttypmod for the column) as well as values being
492 * explicitly CASTed (where the typmod comes from the target type spec).
494 * The caller must have already ensured that the value is of the correct
495 * type, typically by applying coerce_type.
497 * cformat determines the display properties of the generated node (if any),
498 * while isExplicit may affect semantics. If hideInputCoercion is true
499 * *and* we generate a node, the input node is forced to IMPLICIT display
500 * form, so that only the typmod coercion node will be visible when
501 * displaying the expression.
503 * NOTE: this does not need to work on domain types, because any typmod
504 * coercion for a domain is considered to be part of the type coercion
505 * needed to produce the domain value in the first place. So, no getBaseType.
508 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
509 CoercionForm cformat, bool isExplicit,
510 bool hideInputCoercion)
515 * A negative typmod is assumed to mean that no coercion is wanted.
516 * Also, skip coercion if already done.
518 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
521 funcId = find_typmod_coercion_function(targetTypeId);
523 if (OidIsValid(funcId))
525 /* Suppress display of nested coercion steps */
526 if (hideInputCoercion)
527 hide_coercion_node(node);
529 node = build_coercion_expression(node, funcId,
530 targetTypeId, targetTypMod,
531 cformat, isExplicit);
538 * Mark a coercion node as IMPLICIT so it will never be displayed by
539 * ruleutils.c. We use this when we generate a nest of coercion nodes
540 * to implement what is logically one conversion; the inner nodes are
541 * forced to IMPLICIT_CAST format. This does not change their semantics,
542 * only display behavior.
544 * It is caller error to call this on something that doesn't have a
545 * CoercionForm field.
548 hide_coercion_node(Node *node)
550 if (IsA(node, FuncExpr))
551 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
552 else if (IsA(node, RelabelType))
553 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
554 else if (IsA(node, RowExpr))
555 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
556 else if (IsA(node, CoerceToDomain))
557 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
559 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
563 * build_coercion_expression()
564 * Construct a function-call expression for applying a pg_cast entry.
566 * This is used for both type-coercion and length-coercion functions,
567 * since there is no difference in terms of the calling convention.
570 build_coercion_expression(Node *node, Oid funcId,
571 Oid targetTypeId, int32 targetTypMod,
572 CoercionForm cformat, bool isExplicit)
575 Form_pg_proc procstruct;
580 tp = SearchSysCache(PROCOID,
581 ObjectIdGetDatum(funcId),
583 if (!HeapTupleIsValid(tp))
584 elog(ERROR, "cache lookup failed for function %u", funcId);
585 procstruct = (Form_pg_proc) GETSTRUCT(tp);
588 * Asserts essentially check that function is a legal coercion function.
589 * We can't make the seemingly obvious tests on prorettype and
590 * proargtypes[0], because of various binary-compatibility cases.
592 /* Assert(targetTypeId == procstruct->prorettype); */
593 Assert(!procstruct->proretset);
594 Assert(!procstruct->proisagg);
595 nargs = procstruct->pronargs;
596 Assert(nargs >= 1 && nargs <= 3);
597 /* Assert(procstruct->proargtypes[0] == exprType(node)); */
598 Assert(nargs < 2 || procstruct->proargtypes[1] == INT4OID);
599 Assert(nargs < 3 || procstruct->proargtypes[2] == BOOLOID);
603 args = list_make1(node);
607 /* Pass target typmod as an int4 constant */
608 cons = makeConst(INT4OID,
610 Int32GetDatum(targetTypMod),
614 args = lappend(args, cons);
619 /* Pass it a boolean isExplicit parameter, too */
620 cons = makeConst(BOOLOID,
622 BoolGetDatum(isExplicit),
626 args = lappend(args, cons);
629 return (Node *) makeFuncExpr(funcId, targetTypeId, args, cformat);
634 * coerce_record_to_complex
635 * Coerce a RECORD to a specific composite type.
637 * Currently we only support this for inputs that are RowExprs or whole-row
641 coerce_record_to_complex(ParseState *pstate, Node *node,
643 CoercionContext ccontext,
644 CoercionForm cformat)
653 if (node && IsA(node, RowExpr))
655 args = ((RowExpr *) node)->args;
657 else if (node && IsA(node, Var) &&
658 ((Var *) node)->varattno == InvalidAttrNumber)
664 rte = GetRTEByRangeTablePosn(pstate,
665 ((Var *) node)->varno,
666 ((Var *) node)->varlevelsup);
667 nfields = list_length(rte->eref->colnames);
668 for (nf = 1; nf <= nfields; nf++)
673 get_rte_attribute_type(rte, nf, &vartype, &vartypmod);
675 makeVar(((Var *) node)->varno,
679 ((Var *) node)->varlevelsup));
684 (errcode(ERRCODE_CANNOT_COERCE),
685 errmsg("cannot cast type %s to %s",
686 format_type_be(RECORDOID),
687 format_type_be(targetTypeId))));
689 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
690 if (list_length(args) != tupdesc->natts)
692 (errcode(ERRCODE_CANNOT_COERCE),
693 errmsg("cannot cast type %s to %s",
694 format_type_be(RECORDOID),
695 format_type_be(targetTypeId)),
696 errdetail("Input has wrong number of columns.")));
701 Node *expr = (Node *) lfirst(arg);
702 Oid exprtype = exprType(expr);
704 expr = coerce_to_target_type(pstate,
706 tupdesc->attrs[i]->atttypid,
707 tupdesc->attrs[i]->atttypmod,
709 COERCE_IMPLICIT_CAST);
712 (errcode(ERRCODE_CANNOT_COERCE),
713 errmsg("cannot cast type %s to %s",
714 format_type_be(RECORDOID),
715 format_type_be(targetTypeId)),
716 errdetail("Cannot cast type %s to %s in column %d.",
717 format_type_be(exprtype),
718 format_type_be(tupdesc->attrs[i]->atttypid),
720 newargs = lappend(newargs, expr);
724 rowexpr = makeNode(RowExpr);
725 rowexpr->args = newargs;
726 rowexpr->row_typeid = targetTypeId;
727 rowexpr->row_format = cformat;
728 return (Node *) rowexpr;
731 /* coerce_to_boolean()
732 * Coerce an argument of a construct that requires boolean input
733 * (AND, OR, NOT, etc). Also check that input is not a set.
735 * Returns the possibly-transformed node tree.
737 * As with coerce_type, pstate may be NULL if no special unknown-Param
738 * processing is wanted.
741 coerce_to_boolean(ParseState *pstate, Node *node,
742 const char *constructName)
744 Oid inputTypeId = exprType(node);
746 if (inputTypeId != BOOLOID)
748 node = coerce_to_target_type(pstate, node, inputTypeId,
751 COERCE_IMPLICIT_CAST);
754 (errcode(ERRCODE_DATATYPE_MISMATCH),
755 /* translator: first %s is name of a SQL construct, eg WHERE */
756 errmsg("argument of %s must be type boolean, not type %s",
757 constructName, format_type_be(inputTypeId))));
760 if (expression_returns_set(node))
762 (errcode(ERRCODE_DATATYPE_MISMATCH),
763 /* translator: %s is name of a SQL construct, eg WHERE */
764 errmsg("argument of %s must not return a set",
770 /* coerce_to_integer()
771 * Coerce an argument of a construct that requires integer input
772 * (LIMIT, OFFSET, etc). Also check that input is not a set.
774 * Returns the possibly-transformed node tree.
776 * As with coerce_type, pstate may be NULL if no special unknown-Param
777 * processing is wanted.
780 coerce_to_integer(ParseState *pstate, Node *node,
781 const char *constructName)
783 Oid inputTypeId = exprType(node);
785 if (inputTypeId != INT4OID)
787 node = coerce_to_target_type(pstate, node, inputTypeId,
790 COERCE_IMPLICIT_CAST);
793 (errcode(ERRCODE_DATATYPE_MISMATCH),
794 /* translator: first %s is name of a SQL construct, eg LIMIT */
795 errmsg("argument of %s must be type integer, not type %s",
796 constructName, format_type_be(inputTypeId))));
799 if (expression_returns_set(node))
801 (errcode(ERRCODE_DATATYPE_MISMATCH),
802 /* translator: %s is name of a SQL construct, eg LIMIT */
803 errmsg("argument of %s must not return a set",
810 /* select_common_type()
811 * Determine the common supertype of a list of input expression types.
812 * This is used for determining the output type of CASE and UNION
815 * typeids is a nonempty list of type OIDs. Note that earlier items
816 * in the list will be preferred if there is doubt.
817 * 'context' is a phrase to use in the error message if we fail to select
821 select_common_type(List *typeids, const char *context)
827 Assert(typeids != NIL);
828 ptype = getBaseType(linitial_oid(typeids));
829 pcategory = TypeCategory(ptype);
831 for_each_cell(type_item, lnext(list_head(typeids)))
833 Oid ntype = getBaseType(lfirst_oid(type_item));
835 /* move on to next one if no new information... */
836 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
838 if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
840 /* so far, only nulls so take anything... */
842 pcategory = TypeCategory(ptype);
844 else if (TypeCategory(ntype) != pcategory)
847 * both types in different categories? then not much
851 (errcode(ERRCODE_DATATYPE_MISMATCH),
853 * translator: first %s is name of a SQL construct, eg
856 errmsg("%s types %s and %s cannot be matched",
858 format_type_be(ptype),
859 format_type_be(ntype))));
861 else if (!IsPreferredType(pcategory, ptype) &&
862 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
863 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
866 * take new type if can coerce to it implicitly but not
867 * the other way; but if we have a preferred type, stay on
871 pcategory = TypeCategory(ptype);
877 * If all the inputs were UNKNOWN type --- ie, unknown-type literals
878 * --- then resolve as type TEXT. This situation comes up with
879 * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
880 * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
881 * the construct's output type as UNKNOWN, but that really doesn't
882 * work, because we'd probably end up needing a runtime coercion from
883 * UNKNOWN to something else, and we usually won't have it. We need
884 * to coerce the unknown literals while they are still literals, so a
885 * decision has to be made now.
887 if (ptype == UNKNOWNOID)
893 /* coerce_to_common_type()
894 * Coerce an expression to the given type.
896 * This is used following select_common_type() to coerce the individual
897 * expressions to the desired type. 'context' is a phrase to use in the
898 * error message if we fail to coerce.
900 * As with coerce_type, pstate may be NULL if no special unknown-Param
901 * processing is wanted.
904 coerce_to_common_type(ParseState *pstate, Node *node,
905 Oid targetTypeId, const char *context)
907 Oid inputTypeId = exprType(node);
909 if (inputTypeId == targetTypeId)
910 return node; /* no work */
911 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
912 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
913 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
916 (errcode(ERRCODE_CANNOT_COERCE),
917 /* translator: first %s is name of a SQL construct, eg CASE */
918 errmsg("%s could not convert type %s to %s",
920 format_type_be(inputTypeId),
921 format_type_be(targetTypeId))));
926 * check_generic_type_consistency()
927 * Are the actual arguments potentially compatible with a
928 * polymorphic function?
930 * The argument consistency rules are:
932 * 1) All arguments declared ANYARRAY must have matching datatypes,
933 * and must in fact be varlena arrays.
934 * 2) All arguments declared ANYELEMENT must have matching datatypes.
935 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
936 * the actual ANYELEMENT datatype is in fact the element type for
937 * the actual ANYARRAY datatype.
939 * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
940 * or ANYARRAY argument, assume it is okay.
942 * If an input is of type ANYARRAY (ie, we know it's an array, but not
943 * what element type), we will accept it as a match to an argument declared
944 * ANYARRAY, so long as we don't have to determine an element type ---
945 * that is, so long as there is no use of ANYELEMENT. This is mostly for
946 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
948 * We do not ereport here, but just return FALSE if a rule is violated.
951 check_generic_type_consistency(Oid *actual_arg_types,
952 Oid *declared_arg_types,
956 Oid elem_typeid = InvalidOid;
957 Oid array_typeid = InvalidOid;
959 bool have_anyelement = false;
962 * Loop through the arguments to see if we have any that are ANYARRAY
963 * or ANYELEMENT. If so, require the actual types to be
966 for (j = 0; j < nargs; j++)
968 Oid actual_type = actual_arg_types[j];
970 if (declared_arg_types[j] == ANYELEMENTOID)
972 have_anyelement = true;
973 if (actual_type == UNKNOWNOID)
975 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
977 elem_typeid = actual_type;
979 else if (declared_arg_types[j] == ANYARRAYOID)
981 if (actual_type == UNKNOWNOID)
983 if (OidIsValid(array_typeid) && actual_type != array_typeid)
985 array_typeid = actual_type;
989 /* Get the element type based on the array type, if we have one */
990 if (OidIsValid(array_typeid))
992 if (array_typeid == ANYARRAYOID)
994 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1000 array_typelem = get_element_type(array_typeid);
1001 if (!OidIsValid(array_typelem))
1002 return false; /* should be an array, but isn't */
1004 if (!OidIsValid(elem_typeid))
1007 * if we don't have an element type yet, use the one we just
1010 elem_typeid = array_typelem;
1012 else if (array_typelem != elem_typeid)
1014 /* otherwise, they better match */
1024 * enforce_generic_type_consistency()
1025 * Make sure a polymorphic function is legally callable, and
1026 * deduce actual argument and result types.
1028 * If ANYARRAY or ANYELEMENT is used for a function's arguments or
1029 * return type, we make sure the actual data types are consistent with
1030 * each other. The argument consistency rules are shown above for
1031 * check_generic_type_consistency().
1033 * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
1034 * or ANYARRAY argument, we attempt to deduce the actual type it should
1035 * have. If successful, we alter that position of declared_arg_types[]
1036 * so that make_fn_arguments will coerce the literal to the right thing.
1038 * Rules are applied to the function's return type (possibly altering it)
1039 * if it is declared ANYARRAY or ANYELEMENT:
1041 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1042 * argument's actual type as the function's return type.
1043 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1044 * is ANYELEMENT, use the actual type of the argument to determine
1045 * the function's return type, i.e. the element type's corresponding
1047 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1048 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1049 * and is therefore not expected here.
1050 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1051 * argument's actual type as the function's return type.
1052 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1053 * argument is ANYARRAY, use the actual type of the argument to determine
1054 * the function's return type, i.e. the array type's corresponding
1056 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1057 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1058 * and is therefore not expected here.
1061 enforce_generic_type_consistency(Oid *actual_arg_types,
1062 Oid *declared_arg_types,
1067 bool have_generics = false;
1068 bool have_unknowns = false;
1069 Oid elem_typeid = InvalidOid;
1070 Oid array_typeid = InvalidOid;
1072 bool have_anyelement = (rettype == ANYELEMENTOID);
1075 * Loop through the arguments to see if we have any that are ANYARRAY
1076 * or ANYELEMENT. If so, require the actual types to be
1079 for (j = 0; j < nargs; j++)
1081 Oid actual_type = actual_arg_types[j];
1083 if (declared_arg_types[j] == ANYELEMENTOID)
1085 have_generics = have_anyelement = true;
1086 if (actual_type == UNKNOWNOID)
1088 have_unknowns = true;
1091 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1093 (errcode(ERRCODE_DATATYPE_MISMATCH),
1094 errmsg("arguments declared \"anyelement\" are not all alike"),
1095 errdetail("%s versus %s",
1096 format_type_be(elem_typeid),
1097 format_type_be(actual_type))));
1098 elem_typeid = actual_type;
1100 else if (declared_arg_types[j] == ANYARRAYOID)
1102 have_generics = true;
1103 if (actual_type == UNKNOWNOID)
1105 have_unknowns = true;
1108 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1110 (errcode(ERRCODE_DATATYPE_MISMATCH),
1111 errmsg("arguments declared \"anyarray\" are not all alike"),
1112 errdetail("%s versus %s",
1113 format_type_be(array_typeid),
1114 format_type_be(actual_type))));
1115 array_typeid = actual_type;
1120 * Fast Track: if none of the arguments are ANYARRAY or ANYELEMENT,
1121 * return the unmodified rettype.
1126 /* Get the element type based on the array type, if we have one */
1127 if (OidIsValid(array_typeid))
1129 if (array_typeid == ANYARRAYOID && !have_anyelement)
1131 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1132 array_typelem = InvalidOid;
1136 array_typelem = get_element_type(array_typeid);
1137 if (!OidIsValid(array_typelem))
1139 (errcode(ERRCODE_DATATYPE_MISMATCH),
1140 errmsg("argument declared \"anyarray\" is not an array but type %s",
1141 format_type_be(array_typeid))));
1144 if (!OidIsValid(elem_typeid))
1147 * if we don't have an element type yet, use the one we just
1150 elem_typeid = array_typelem;
1152 else if (array_typelem != elem_typeid)
1154 /* otherwise, they better match */
1156 (errcode(ERRCODE_DATATYPE_MISMATCH),
1157 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1158 errdetail("%s versus %s",
1159 format_type_be(array_typeid),
1160 format_type_be(elem_typeid))));
1163 else if (!OidIsValid(elem_typeid))
1165 /* Only way to get here is if all the generic args are UNKNOWN */
1167 (errcode(ERRCODE_DATATYPE_MISMATCH),
1168 errmsg("could not determine anyarray/anyelement type because input has type \"unknown\"")));
1172 * If we had any unknown inputs, re-scan to assign correct types
1176 for (j = 0; j < nargs; j++)
1178 Oid actual_type = actual_arg_types[j];
1180 if (actual_type != UNKNOWNOID)
1183 if (declared_arg_types[j] == ANYELEMENTOID)
1184 declared_arg_types[j] = elem_typeid;
1185 else if (declared_arg_types[j] == ANYARRAYOID)
1187 if (!OidIsValid(array_typeid))
1189 array_typeid = get_array_type(elem_typeid);
1190 if (!OidIsValid(array_typeid))
1192 (errcode(ERRCODE_UNDEFINED_OBJECT),
1193 errmsg("could not find array type for data type %s",
1194 format_type_be(elem_typeid))));
1196 declared_arg_types[j] = array_typeid;
1201 /* if we return ANYARRAYOID use the appropriate argument type */
1202 if (rettype == ANYARRAYOID)
1204 if (!OidIsValid(array_typeid))
1206 array_typeid = get_array_type(elem_typeid);
1207 if (!OidIsValid(array_typeid))
1209 (errcode(ERRCODE_UNDEFINED_OBJECT),
1210 errmsg("could not find array type for data type %s",
1211 format_type_be(elem_typeid))));
1213 return array_typeid;
1216 /* if we return ANYELEMENTOID use the appropriate argument type */
1217 if (rettype == ANYELEMENTOID)
1220 /* we don't return a generic type; send back the original return type */
1225 * resolve_generic_type()
1226 * Deduce an individual actual datatype on the assumption that
1227 * the rules for ANYARRAY/ANYELEMENT are being followed.
1229 * declared_type is the declared datatype we want to resolve.
1230 * context_actual_type is the actual input datatype to some argument
1231 * that has declared datatype context_declared_type.
1233 * If declared_type isn't polymorphic, we just return it. Otherwise,
1234 * context_declared_type must be polymorphic, and we deduce the correct
1235 * return type based on the relationship of the two polymorphic types.
1238 resolve_generic_type(Oid declared_type,
1239 Oid context_actual_type,
1240 Oid context_declared_type)
1242 if (declared_type == ANYARRAYOID)
1244 if (context_declared_type == ANYARRAYOID)
1246 /* Use actual type, but it must be an array */
1247 Oid array_typelem = get_element_type(context_actual_type);
1249 if (!OidIsValid(array_typelem))
1251 (errcode(ERRCODE_DATATYPE_MISMATCH),
1252 errmsg("argument declared \"anyarray\" is not an array but type %s",
1253 format_type_be(context_actual_type))));
1254 return context_actual_type;
1256 else if (context_declared_type == ANYELEMENTOID)
1258 /* Use the array type corresponding to actual type */
1259 Oid array_typeid = get_array_type(context_actual_type);
1261 if (!OidIsValid(array_typeid))
1263 (errcode(ERRCODE_UNDEFINED_OBJECT),
1264 errmsg("could not find array type for data type %s",
1265 format_type_be(context_actual_type))));
1266 return array_typeid;
1269 else if (declared_type == ANYELEMENTOID)
1271 if (context_declared_type == ANYARRAYOID)
1273 /* Use the element type corresponding to actual type */
1274 Oid array_typelem = get_element_type(context_actual_type);
1276 if (!OidIsValid(array_typelem))
1278 (errcode(ERRCODE_DATATYPE_MISMATCH),
1279 errmsg("argument declared \"anyarray\" is not an array but type %s",
1280 format_type_be(context_actual_type))));
1281 return array_typelem;
1283 else if (context_declared_type == ANYELEMENTOID)
1285 /* Use the actual type; it doesn't matter if array or not */
1286 return context_actual_type;
1291 /* declared_type isn't polymorphic, so return it as-is */
1292 return declared_type;
1294 /* If we get here, declared_type is polymorphic and context isn't */
1295 /* NB: this is a calling-code logic error, not a user error */
1296 elog(ERROR, "could not determine ANYARRAY/ANYELEMENT type because context isn't polymorphic");
1297 return InvalidOid; /* keep compiler quiet */
1302 * Assign a category to the specified type OID.
1304 * NB: this must not return INVALID_TYPE.
1306 * XXX This should be moved to system catalog lookups
1307 * to allow for better type extensibility.
1308 * - thomas 2001-09-30
1311 TypeCategory(Oid inType)
1318 result = BOOLEAN_TYPE;
1326 result = STRING_TYPE;
1331 result = BITSTRING_TYPE;
1336 case (REGPROCEDUREOID):
1338 case (REGOPERATOROID):
1348 result = NUMERIC_TYPE;
1355 case (TIMESTAMPOID):
1356 case (TIMESTAMPTZOID):
1357 result = DATETIME_TYPE;
1361 case (TINTERVALOID):
1363 result = TIMESPAN_TYPE;
1373 result = GEOMETRIC_TYPE;
1378 result = NETWORK_TYPE;
1383 result = UNKNOWN_TYPE;
1392 case (LANGUAGE_HANDLEROID):
1395 case (ANYELEMENTOID):
1396 result = GENERIC_TYPE;
1404 } /* TypeCategory() */
1407 /* IsPreferredType()
1408 * Check if this type is a preferred type for the given category.
1410 * If category is INVALID_TYPE, then we'll return TRUE for preferred types
1411 * of any category; otherwise, only for preferred types of that category.
1413 * XXX This should be moved to system catalog lookups
1414 * to allow for better type extensibility.
1415 * - thomas 2001-09-30
1418 IsPreferredType(CATEGORY category, Oid type)
1422 if (category == INVALID_TYPE)
1423 category = TypeCategory(type);
1424 else if (category != TypeCategory(type))
1428 * This switch should agree with TypeCategory(), above. Note that at
1429 * this point, category certainly matches the type.
1433 case (UNKNOWN_TYPE):
1434 case (GENERIC_TYPE):
1435 preftype = UNKNOWNOID;
1438 case (BOOLEAN_TYPE):
1446 case (BITSTRING_TYPE):
1447 preftype = VARBITOID;
1450 case (NUMERIC_TYPE):
1451 if (type == OIDOID ||
1452 type == REGPROCOID ||
1453 type == REGPROCEDUREOID ||
1454 type == REGOPEROID ||
1455 type == REGOPERATOROID ||
1456 type == REGCLASSOID ||
1460 preftype = FLOAT8OID;
1463 case (DATETIME_TYPE):
1464 if (type == DATEOID)
1465 preftype = TIMESTAMPOID;
1467 preftype = TIMESTAMPTZOID;
1470 case (TIMESPAN_TYPE):
1471 preftype = INTERVALOID;
1474 case (GEOMETRIC_TYPE):
1478 case (NETWORK_TYPE):
1487 elog(ERROR, "unrecognized type category: %d", (int) category);
1488 preftype = UNKNOWNOID;
1492 return (type == preftype);
1493 } /* IsPreferredType() */
1496 /* IsBinaryCoercible()
1497 * Check if srctype is binary-coercible to targettype.
1499 * This notion allows us to cheat and directly exchange values without
1500 * going through the trouble of calling a conversion function. Note that
1501 * in general, this should only be an implementation shortcut. Before 7.4,
1502 * this was also used as a heuristic for resolving overloaded functions and
1503 * operators, but that's basically a bad idea.
1505 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1506 * We consider two types binary-coercible if there is an implicitly
1507 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1508 * binary-coercible to its base type, though *not* vice versa (in the other
1509 * direction, one must apply domain constraint checks before accepting the
1510 * value as legitimate). We also need to special-case the polymorphic
1513 * This function replaces IsBinaryCompatible(), which was an inherently
1514 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1515 * the order of the operands is now significant.
1518 IsBinaryCoercible(Oid srctype, Oid targettype)
1521 Form_pg_cast castForm;
1524 /* Fast path if same type */
1525 if (srctype == targettype)
1528 /* If srctype is a domain, reduce to its base type */
1529 if (OidIsValid(srctype))
1530 srctype = getBaseType(srctype);
1532 /* Somewhat-fast path for domain -> base type case */
1533 if (srctype == targettype)
1536 /* Also accept any array type as coercible to ANYARRAY */
1537 if (targettype == ANYARRAYOID)
1538 if (get_element_type(srctype) != InvalidOid)
1541 /* Else look in pg_cast */
1542 tuple = SearchSysCache(CASTSOURCETARGET,
1543 ObjectIdGetDatum(srctype),
1544 ObjectIdGetDatum(targettype),
1546 if (!HeapTupleIsValid(tuple))
1547 return false; /* no cast */
1548 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1550 result = (castForm->castfunc == InvalidOid &&
1551 castForm->castcontext == COERCION_CODE_IMPLICIT);
1553 ReleaseSysCache(tuple);
1560 * find_coercion_pathway
1561 * Look for a coercion pathway between two types.
1563 * ccontext determines the set of available casts.
1565 * If we find a suitable entry in pg_cast, return TRUE, and set *funcid
1566 * to the castfunc value, which may be InvalidOid for a binary-compatible
1569 * NOTE: *funcid == InvalidOid does not necessarily mean that no work is
1570 * needed to do the coercion; if the target is a domain then we may need to
1571 * apply domain constraint checking. If you want to check for a zero-effort
1572 * conversion then use IsBinaryCoercible().
1575 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1576 CoercionContext ccontext,
1579 bool result = false;
1582 *funcid = InvalidOid;
1584 /* Perhaps the types are domains; if so, look at their base types */
1585 if (OidIsValid(sourceTypeId))
1586 sourceTypeId = getBaseType(sourceTypeId);
1587 if (OidIsValid(targetTypeId))
1588 targetTypeId = getBaseType(targetTypeId);
1590 /* Domains are always coercible to and from their base type */
1591 if (sourceTypeId == targetTypeId)
1594 /* Look in pg_cast */
1595 tuple = SearchSysCache(CASTSOURCETARGET,
1596 ObjectIdGetDatum(sourceTypeId),
1597 ObjectIdGetDatum(targetTypeId),
1600 if (HeapTupleIsValid(tuple))
1602 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1603 CoercionContext castcontext;
1605 /* convert char value for castcontext to CoercionContext enum */
1606 switch (castForm->castcontext)
1608 case COERCION_CODE_IMPLICIT:
1609 castcontext = COERCION_IMPLICIT;
1611 case COERCION_CODE_ASSIGNMENT:
1612 castcontext = COERCION_ASSIGNMENT;
1614 case COERCION_CODE_EXPLICIT:
1615 castcontext = COERCION_EXPLICIT;
1618 elog(ERROR, "unrecognized castcontext: %d",
1619 (int) castForm->castcontext);
1620 castcontext = 0; /* keep compiler quiet */
1624 /* Rely on ordering of enum for correct behavior here */
1625 if (ccontext >= castcontext)
1627 *funcid = castForm->castfunc;
1631 ReleaseSysCache(tuple);
1636 * If there's no pg_cast entry, perhaps we are dealing with a pair
1637 * of array types. If so, and if the element types have a suitable
1638 * cast, use array_type_coerce() or array_type_length_coerce().
1644 if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid &&
1645 (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid)
1647 if (find_coercion_pathway(targetElemType, sourceElemType,
1648 ccontext, &elemfuncid))
1650 if (!OidIsValid(elemfuncid))
1652 /* binary-compatible element type conversion */
1653 *funcid = F_ARRAY_TYPE_COERCE;
1657 /* does the function take a typmod arg? */
1658 Oid argtypes[FUNC_MAX_ARGS];
1661 (void) get_func_signature(elemfuncid, argtypes, &nargs);
1663 *funcid = F_ARRAY_TYPE_LENGTH_COERCE;
1665 *funcid = F_ARRAY_TYPE_COERCE;
1677 * find_typmod_coercion_function -- does the given type need length coercion?
1679 * If the target type possesses a pg_cast function from itself to itself,
1680 * it must need length coercion.
1682 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1684 * If the given type is a varlena array type, we do not look for a coercion
1685 * function associated directly with the array type, but instead look for
1686 * one associated with the element type. If one exists, we report
1687 * array_length_coerce() as the coercion function to use.
1690 find_typmod_coercion_function(Oid typeId)
1692 Oid funcid = InvalidOid;
1693 bool isArray = false;
1695 Form_pg_type typeForm;
1698 targetType = typeidType(typeId);
1699 typeForm = (Form_pg_type) GETSTRUCT(targetType);
1701 /* Check for a varlena array type (and not a domain) */
1702 if (typeForm->typelem != InvalidOid &&
1703 typeForm->typlen == -1 &&
1704 typeForm->typtype != 'd')
1706 /* Yes, switch our attention to the element type */
1707 typeId = typeForm->typelem;
1710 ReleaseSysCache(targetType);
1712 /* Look in pg_cast */
1713 tuple = SearchSysCache(CASTSOURCETARGET,
1714 ObjectIdGetDatum(typeId),
1715 ObjectIdGetDatum(typeId),
1718 if (HeapTupleIsValid(tuple))
1720 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1722 funcid = castForm->castfunc;
1723 ReleaseSysCache(tuple);
1727 * Now, if we did find a coercion function for an array element type,
1728 * report array_length_coerce() as the function to use.
1730 if (isArray && OidIsValid(funcid))
1731 funcid = F_ARRAY_LENGTH_COERCE;