1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2005, 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.133 2005/11/22 18:17:16 momjian 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 as
86 * well as a type coercion. If we find ourselves adding both, force the
87 * 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. Apply
144 * the target type's typinput function to it to produce a constant of
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 there
155 * is no way to represent a typinput function call as an expression
156 * tree, because C-string values are not Datums. (XXX This *is*
157 * 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)
172 * We assume here that UNKNOWN's internal representation is the
175 char *val = DatumGetCString(con->constvalue);
178 * We pass typmod -1 to the input routine, primarily because
179 * existing input routines follow implicit-coercion semantics for
180 * length checks, which is not always what we want here. Any
181 * length constraint will be applied later by our caller.
183 * Note that we call stringTypeDatum using the domain's pg_type
184 * row, if it's a domain. This works because the domain row has
185 * the same typinput and typelem as the base type --- ugly...
187 newcon->constvalue = stringTypeDatum(targetType, val, -1);
190 result = (Node *) newcon;
192 /* If target is a domain, apply constraints. */
193 if (targetTyptype == 'd')
194 result = coerce_to_domain(result, InvalidOid, targetTypeId,
195 cformat, false, false);
197 ReleaseSysCache(targetType);
201 if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
202 ((Param *) node)->paramkind == PARAM_NUM &&
203 pstate != NULL && pstate->p_variableparams)
206 * Input is a Param of previously undetermined type, and we want to
207 * update our knowledge of the Param's type. Find the topmost
208 * ParseState and update the state.
210 Param *param = (Param *) node;
211 int paramno = param->paramid;
212 ParseState *toppstate;
215 while (toppstate->parentParseState != NULL)
216 toppstate = toppstate->parentParseState;
218 if (paramno <= 0 || /* shouldn't happen, but... */
219 paramno > toppstate->p_numparams)
221 (errcode(ERRCODE_UNDEFINED_PARAMETER),
222 errmsg("there is no parameter $%d", paramno)));
224 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
226 /* We've successfully resolved the type */
227 toppstate->p_paramtypes[paramno - 1] = targetTypeId;
229 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
231 /* We previously resolved the type, and it matches */
237 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
238 errmsg("inconsistent types deduced for parameter $%d",
240 errdetail("%s versus %s",
241 format_type_be(toppstate->p_paramtypes[paramno - 1]),
242 format_type_be(targetTypeId))));
245 param->paramtype = targetTypeId;
246 return (Node *) param;
248 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
251 if (OidIsValid(funcId))
254 * Generate an expression tree representing run-time application
255 * of the conversion function. If we are dealing with a domain
256 * target type, the conversion function will yield the base type,
257 * and we need to extract the correct typmod to use from the
258 * domain's typtypmod.
260 Oid baseTypeId = getBaseType(targetTypeId);
263 if (targetTypeId != baseTypeId)
264 baseTypeMod = get_typtypmod(targetTypeId);
266 baseTypeMod = targetTypeMod;
268 result = build_coercion_expression(node, funcId,
269 baseTypeId, baseTypeMod,
271 (cformat != COERCE_IMPLICIT_CAST));
274 * If domain, coerce to the domain type and relabel with domain
275 * type ID. We can skip the internal length-coercion step if the
276 * selected coercion function was a type-and-length coercion.
278 if (targetTypeId != baseTypeId)
279 result = coerce_to_domain(result, baseTypeId, targetTypeId,
281 exprIsLengthCoercion(result,
287 * We don't need to do a physical conversion, but we do need to
288 * attach a RelabelType node so that the expression will be seen
289 * to have the intended type when inspected by higher-level code.
291 * Also, domains may have value restrictions beyond the base type
292 * that must be accounted for. If the destination is a domain
293 * then we won't need a RelabelType node.
295 result = coerce_to_domain(node, InvalidOid, targetTypeId,
296 cformat, false, false);
300 * XXX could we label result with exprTypmod(node) instead of
301 * default -1 typmod, to save a possible length-coercion
302 * later? Would work if both types have same interpretation of
303 * typmod, which is likely but not certain.
305 result = (Node *) makeRelabelType((Expr *) result,
312 if (inputTypeId == RECORDOID &&
313 ISCOMPLEX(targetTypeId))
315 /* Coerce a RECORD to a specific complex type */
316 return coerce_record_to_complex(pstate, node, targetTypeId,
319 if (targetTypeId == RECORDOID &&
320 ISCOMPLEX(inputTypeId))
322 /* Coerce a specific complex type to RECORD */
323 /* NB: we do NOT want a RelabelType here */
326 if (typeInheritsFrom(inputTypeId, targetTypeId))
329 * Input class type is a subclass of target, so generate an
330 * appropriate runtime conversion (removing unneeded columns and
331 * possibly rearranging the ones that are wanted).
333 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
335 r->arg = (Expr *) node;
336 r->resulttype = targetTypeId;
337 r->convertformat = cformat;
340 /* If we get here, caller blew it */
341 elog(ERROR, "failed to find conversion function from %s to %s",
342 format_type_be(inputTypeId), format_type_be(targetTypeId));
343 return NULL; /* keep compiler quiet */
349 * Can input_typeids be coerced to target_typeids?
351 * We must be told the context (CAST construct, assignment, implicit coercion)
352 * as this determines the set of available casts.
355 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
356 CoercionContext ccontext)
358 bool have_generics = false;
361 /* run through argument list... */
362 for (i = 0; i < nargs; i++)
364 Oid inputTypeId = input_typeids[i];
365 Oid targetTypeId = target_typeids[i];
368 /* no problem if same type */
369 if (inputTypeId == targetTypeId)
372 /* accept if target is ANY */
373 if (targetTypeId == ANYOID)
376 /* accept if target is ANYARRAY or ANYELEMENT, for now */
377 if (targetTypeId == ANYARRAYOID ||
378 targetTypeId == ANYELEMENTOID)
380 have_generics = true; /* do more checking later */
385 * If input is an untyped string constant, assume we can convert it to
388 if (inputTypeId == UNKNOWNOID)
392 * If pg_cast shows that we can coerce, accept. This test now covers
393 * both binary-compatible and coercion-function cases.
395 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
400 * If input is RECORD and target is a composite type, assume we can
401 * coerce (may need tighter checking here)
403 if (inputTypeId == RECORDOID &&
404 ISCOMPLEX(targetTypeId))
408 * If input is a composite type and target is RECORD, accept
410 if (targetTypeId == RECORDOID &&
411 ISCOMPLEX(inputTypeId))
415 * If input is a class type that inherits from target, accept
417 if (typeInheritsFrom(inputTypeId, targetTypeId))
421 * Else, cannot coerce at this argument position
426 /* If we found any generic argument types, cross-check them */
429 if (!check_generic_type_consistency(input_typeids, target_typeids,
439 * Create an expression tree to represent coercion to a domain type.
441 * 'arg': input expression
442 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
443 * has not bothered to look this up)
444 * 'typeId': target type to coerce to
445 * 'cformat': coercion format
446 * 'hideInputCoercion': if true, hide the input coercion under this one.
447 * 'lengthCoercionDone': if true, caller already accounted for length.
449 * If the target type isn't a domain, the given 'arg' is returned as-is.
452 coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId,
453 CoercionForm cformat, bool hideInputCoercion,
454 bool lengthCoercionDone)
456 CoerceToDomain *result;
458 /* Get the base type if it hasn't been supplied */
459 if (baseTypeId == InvalidOid)
460 baseTypeId = getBaseType(typeId);
462 /* If it isn't a domain, return the node as it was passed in */
463 if (baseTypeId == typeId)
466 /* Suppress display of nested coercion steps */
467 if (hideInputCoercion)
468 hide_coercion_node(arg);
471 * If the domain applies a typmod to its base type, build the appropriate
472 * coercion step. Mark it implicit for display purposes, because we don't
473 * want it shown separately by ruleutils.c; but the isExplicit flag passed
474 * to the conversion function depends on the manner in which the domain
475 * coercion is invoked, so that the semantics of implicit and explicit
476 * coercion differ. (Is that really the behavior we want?)
478 * NOTE: because we apply this as part of the fixed expression structure,
479 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
480 * would be safe to do anyway, without lots of knowledge about what the
481 * base type thinks the typmod means.
483 if (!lengthCoercionDone)
485 int32 typmod = get_typtypmod(typeId);
488 arg = coerce_type_typmod(arg, baseTypeId, typmod,
489 COERCE_IMPLICIT_CAST,
490 (cformat != COERCE_IMPLICIT_CAST),
495 * Now build the domain coercion node. This represents run-time checking
496 * of any constraints currently attached to the domain. This also ensures
497 * that the expression is properly labeled as to result type.
499 result = makeNode(CoerceToDomain);
500 result->arg = (Expr *) arg;
501 result->resulttype = typeId;
502 result->resulttypmod = -1; /* currently, always -1 for domains */
503 result->coercionformat = cformat;
505 return (Node *) result;
510 * coerce_type_typmod()
511 * Force a value to a particular typmod, if meaningful and possible.
513 * This is applied to values that are going to be stored in a relation
514 * (where we have an atttypmod for the column) as well as values being
515 * explicitly CASTed (where the typmod comes from the target type spec).
517 * The caller must have already ensured that the value is of the correct
518 * type, typically by applying coerce_type.
520 * cformat determines the display properties of the generated node (if any),
521 * while isExplicit may affect semantics. If hideInputCoercion is true
522 * *and* we generate a node, the input node is forced to IMPLICIT display
523 * form, so that only the typmod coercion node will be visible when
524 * displaying the expression.
526 * NOTE: this does not need to work on domain types, because any typmod
527 * coercion for a domain is considered to be part of the type coercion
528 * needed to produce the domain value in the first place. So, no getBaseType.
531 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
532 CoercionForm cformat, bool isExplicit,
533 bool hideInputCoercion)
538 * A negative typmod is assumed to mean that no coercion is wanted. Also,
539 * skip coercion if already done.
541 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
544 funcId = find_typmod_coercion_function(targetTypeId);
546 if (OidIsValid(funcId))
548 /* Suppress display of nested coercion steps */
549 if (hideInputCoercion)
550 hide_coercion_node(node);
552 node = build_coercion_expression(node, funcId,
553 targetTypeId, targetTypMod,
554 cformat, isExplicit);
561 * Mark a coercion node as IMPLICIT so it will never be displayed by
562 * ruleutils.c. We use this when we generate a nest of coercion nodes
563 * to implement what is logically one conversion; the inner nodes are
564 * forced to IMPLICIT_CAST format. This does not change their semantics,
565 * only display behavior.
567 * It is caller error to call this on something that doesn't have a
568 * CoercionForm field.
571 hide_coercion_node(Node *node)
573 if (IsA(node, FuncExpr))
574 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
575 else if (IsA(node, RelabelType))
576 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
577 else if (IsA(node, ConvertRowtypeExpr))
578 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
579 else if (IsA(node, RowExpr))
580 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
581 else if (IsA(node, CoerceToDomain))
582 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
584 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
588 * build_coercion_expression()
589 * Construct a function-call expression for applying a pg_cast entry.
591 * This is used for both type-coercion and length-coercion functions,
592 * since there is no difference in terms of the calling convention.
595 build_coercion_expression(Node *node, Oid funcId,
596 Oid targetTypeId, int32 targetTypMod,
597 CoercionForm cformat, bool isExplicit)
600 Form_pg_proc procstruct;
605 tp = SearchSysCache(PROCOID,
606 ObjectIdGetDatum(funcId),
608 if (!HeapTupleIsValid(tp))
609 elog(ERROR, "cache lookup failed for function %u", funcId);
610 procstruct = (Form_pg_proc) GETSTRUCT(tp);
613 * Asserts essentially check that function is a legal coercion function.
614 * We can't make the seemingly obvious tests on prorettype and
615 * proargtypes[0], because of various binary-compatibility cases.
617 /* Assert(targetTypeId == procstruct->prorettype); */
618 Assert(!procstruct->proretset);
619 Assert(!procstruct->proisagg);
620 nargs = procstruct->pronargs;
621 Assert(nargs >= 1 && nargs <= 3);
622 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
623 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
624 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
628 args = list_make1(node);
632 /* Pass target typmod as an int4 constant */
633 cons = makeConst(INT4OID,
635 Int32GetDatum(targetTypMod),
639 args = lappend(args, cons);
644 /* Pass it a boolean isExplicit parameter, too */
645 cons = makeConst(BOOLOID,
647 BoolGetDatum(isExplicit),
651 args = lappend(args, cons);
654 return (Node *) makeFuncExpr(funcId, targetTypeId, args, cformat);
659 * coerce_record_to_complex
660 * Coerce a RECORD to a specific composite type.
662 * Currently we only support this for inputs that are RowExprs or whole-row
666 coerce_record_to_complex(ParseState *pstate, Node *node,
668 CoercionContext ccontext,
669 CoercionForm cformat)
679 if (node && IsA(node, RowExpr))
682 * Since the RowExpr must be of type RECORD, we needn't worry about it
683 * containing any dropped columns.
685 args = ((RowExpr *) node)->args;
687 else if (node && IsA(node, Var) &&
688 ((Var *) node)->varattno == InvalidAttrNumber)
690 int rtindex = ((Var *) node)->varno;
691 int sublevels_up = ((Var *) node)->varlevelsup;
694 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
695 expandRTE(rte, rtindex, sublevels_up, false,
700 (errcode(ERRCODE_CANNOT_COERCE),
701 errmsg("cannot cast type %s to %s",
702 format_type_be(RECORDOID),
703 format_type_be(targetTypeId))));
705 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
708 arg = list_head(args);
709 for (i = 0; i < tupdesc->natts; i++)
714 /* Fill in NULLs for dropped columns in rowtype */
715 if (tupdesc->attrs[i]->attisdropped)
718 * can't use atttypid here, but it doesn't really matter what type
719 * the Const claims to be.
721 newargs = lappend(newargs, makeNullConst(INT4OID));
727 (errcode(ERRCODE_CANNOT_COERCE),
728 errmsg("cannot cast type %s to %s",
729 format_type_be(RECORDOID),
730 format_type_be(targetTypeId)),
731 errdetail("Input has too few columns.")));
732 expr = (Node *) lfirst(arg);
733 exprtype = exprType(expr);
735 expr = coerce_to_target_type(pstate,
737 tupdesc->attrs[i]->atttypid,
738 tupdesc->attrs[i]->atttypmod,
740 COERCE_IMPLICIT_CAST);
743 (errcode(ERRCODE_CANNOT_COERCE),
744 errmsg("cannot cast type %s to %s",
745 format_type_be(RECORDOID),
746 format_type_be(targetTypeId)),
747 errdetail("Cannot cast type %s to %s in column %d.",
748 format_type_be(exprtype),
749 format_type_be(tupdesc->attrs[i]->atttypid),
751 newargs = lappend(newargs, expr);
757 (errcode(ERRCODE_CANNOT_COERCE),
758 errmsg("cannot cast type %s to %s",
759 format_type_be(RECORDOID),
760 format_type_be(targetTypeId)),
761 errdetail("Input has too many columns.")));
763 rowexpr = makeNode(RowExpr);
764 rowexpr->args = newargs;
765 rowexpr->row_typeid = targetTypeId;
766 rowexpr->row_format = cformat;
767 return (Node *) rowexpr;
770 /* coerce_to_boolean()
771 * Coerce an argument of a construct that requires boolean input
772 * (AND, OR, NOT, 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_boolean(ParseState *pstate, Node *node,
781 const char *constructName)
783 Oid inputTypeId = exprType(node);
785 if (inputTypeId != BOOLOID)
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 WHERE */
795 errmsg("argument of %s must be type boolean, 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 WHERE */
803 errmsg("argument of %s must not return a set",
809 /* coerce_to_integer()
810 * Coerce an argument of a construct that requires integer input
811 * (LIMIT, OFFSET, etc). Also check that input is not a set.
813 * Returns the possibly-transformed node tree.
815 * As with coerce_type, pstate may be NULL if no special unknown-Param
816 * processing is wanted.
819 coerce_to_integer(ParseState *pstate, Node *node,
820 const char *constructName)
822 Oid inputTypeId = exprType(node);
824 if (inputTypeId != INT4OID)
826 node = coerce_to_target_type(pstate, node, inputTypeId,
829 COERCE_IMPLICIT_CAST);
832 (errcode(ERRCODE_DATATYPE_MISMATCH),
833 /* translator: first %s is name of a SQL construct, eg LIMIT */
834 errmsg("argument of %s must be type integer, not type %s",
835 constructName, format_type_be(inputTypeId))));
838 if (expression_returns_set(node))
840 (errcode(ERRCODE_DATATYPE_MISMATCH),
841 /* translator: %s is name of a SQL construct, eg LIMIT */
842 errmsg("argument of %s must not return a set",
849 /* select_common_type()
850 * Determine the common supertype of a list of input expression types.
851 * This is used for determining the output type of CASE and UNION
854 * typeids is a nonempty list of type OIDs. Note that earlier items
855 * in the list will be preferred if there is doubt.
856 * 'context' is a phrase to use in the error message if we fail to select
860 select_common_type(List *typeids, const char *context)
866 Assert(typeids != NIL);
867 ptype = getBaseType(linitial_oid(typeids));
868 pcategory = TypeCategory(ptype);
870 for_each_cell(type_item, lnext(list_head(typeids)))
872 Oid ntype = getBaseType(lfirst_oid(type_item));
874 /* move on to next one if no new information... */
875 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
877 if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
879 /* so far, only nulls so take anything... */
881 pcategory = TypeCategory(ptype);
883 else if (TypeCategory(ntype) != pcategory)
886 * both types in different categories? then not much hope...
889 (errcode(ERRCODE_DATATYPE_MISMATCH),
892 * translator: first %s is name of a SQL construct, eg CASE
894 errmsg("%s types %s and %s cannot be matched",
896 format_type_be(ptype),
897 format_type_be(ntype))));
899 else if (!IsPreferredType(pcategory, ptype) &&
900 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
901 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
904 * take new type if can coerce to it implicitly but not the
905 * other way; but if we have a preferred type, stay on it.
908 pcategory = TypeCategory(ptype);
914 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
915 * then resolve as type TEXT. This situation comes up with constructs
916 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
917 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
918 * output type as UNKNOWN, but that really doesn't work, because we'd
919 * probably end up needing a runtime coercion from UNKNOWN to something
920 * else, and we usually won't have it. We need to coerce the unknown
921 * literals while they are still literals, so a decision has to be made
924 if (ptype == UNKNOWNOID)
930 /* coerce_to_common_type()
931 * Coerce an expression to the given type.
933 * This is used following select_common_type() to coerce the individual
934 * expressions to the desired type. 'context' is a phrase to use in the
935 * error message if we fail to coerce.
937 * As with coerce_type, pstate may be NULL if no special unknown-Param
938 * processing is wanted.
941 coerce_to_common_type(ParseState *pstate, Node *node,
942 Oid targetTypeId, const char *context)
944 Oid inputTypeId = exprType(node);
946 if (inputTypeId == targetTypeId)
947 return node; /* no work */
948 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
949 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
950 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
953 (errcode(ERRCODE_CANNOT_COERCE),
954 /* translator: first %s is name of a SQL construct, eg CASE */
955 errmsg("%s could not convert type %s to %s",
957 format_type_be(inputTypeId),
958 format_type_be(targetTypeId))));
963 * check_generic_type_consistency()
964 * Are the actual arguments potentially compatible with a
965 * polymorphic function?
967 * The argument consistency rules are:
969 * 1) All arguments declared ANYARRAY must have matching datatypes,
970 * and must in fact be varlena arrays.
971 * 2) All arguments declared ANYELEMENT must have matching datatypes.
972 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
973 * the actual ANYELEMENT datatype is in fact the element type for
974 * the actual ANYARRAY datatype.
976 * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
977 * or ANYARRAY argument, assume it is okay.
979 * If an input is of type ANYARRAY (ie, we know it's an array, but not
980 * what element type), we will accept it as a match to an argument declared
981 * ANYARRAY, so long as we don't have to determine an element type ---
982 * that is, so long as there is no use of ANYELEMENT. This is mostly for
983 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
985 * We do not ereport here, but just return FALSE if a rule is violated.
988 check_generic_type_consistency(Oid *actual_arg_types,
989 Oid *declared_arg_types,
993 Oid elem_typeid = InvalidOid;
994 Oid array_typeid = InvalidOid;
996 bool have_anyelement = false;
999 * Loop through the arguments to see if we have any that are ANYARRAY or
1000 * ANYELEMENT. If so, require the actual types to be self-consistent
1002 for (j = 0; j < nargs; j++)
1004 Oid actual_type = actual_arg_types[j];
1006 if (declared_arg_types[j] == ANYELEMENTOID)
1008 have_anyelement = true;
1009 if (actual_type == UNKNOWNOID)
1011 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1013 elem_typeid = actual_type;
1015 else if (declared_arg_types[j] == ANYARRAYOID)
1017 if (actual_type == UNKNOWNOID)
1019 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1021 array_typeid = actual_type;
1025 /* Get the element type based on the array type, if we have one */
1026 if (OidIsValid(array_typeid))
1028 if (array_typeid == ANYARRAYOID)
1030 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1031 if (have_anyelement)
1036 array_typelem = get_element_type(array_typeid);
1037 if (!OidIsValid(array_typelem))
1038 return false; /* should be an array, but isn't */
1040 if (!OidIsValid(elem_typeid))
1043 * if we don't have an element type yet, use the one we just got
1045 elem_typeid = array_typelem;
1047 else if (array_typelem != elem_typeid)
1049 /* otherwise, they better match */
1059 * enforce_generic_type_consistency()
1060 * Make sure a polymorphic function is legally callable, and
1061 * deduce actual argument and result types.
1063 * If ANYARRAY or ANYELEMENT is used for a function's arguments or
1064 * return type, we make sure the actual data types are consistent with
1065 * each other. The argument consistency rules are shown above for
1066 * check_generic_type_consistency().
1068 * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
1069 * or ANYARRAY argument, we attempt to deduce the actual type it should
1070 * have. If successful, we alter that position of declared_arg_types[]
1071 * so that make_fn_arguments will coerce the literal to the right thing.
1073 * Rules are applied to the function's return type (possibly altering it)
1074 * if it is declared ANYARRAY or ANYELEMENT:
1076 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1077 * argument's actual type as the function's return type.
1078 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1079 * is ANYELEMENT, use the actual type of the argument to determine
1080 * the function's return type, i.e. the element type's corresponding
1082 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1083 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1084 * and is therefore not expected here.
1085 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1086 * argument's actual type as the function's return type.
1087 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1088 * argument is ANYARRAY, use the actual type of the argument to determine
1089 * the function's return type, i.e. the array type's corresponding
1091 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1092 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1093 * and is therefore not expected here.
1096 enforce_generic_type_consistency(Oid *actual_arg_types,
1097 Oid *declared_arg_types,
1102 bool have_generics = false;
1103 bool have_unknowns = false;
1104 Oid elem_typeid = InvalidOid;
1105 Oid array_typeid = InvalidOid;
1107 bool have_anyelement = (rettype == ANYELEMENTOID);
1110 * Loop through the arguments to see if we have any that are ANYARRAY or
1111 * ANYELEMENT. If so, require the actual types to be self-consistent
1113 for (j = 0; j < nargs; j++)
1115 Oid actual_type = actual_arg_types[j];
1117 if (declared_arg_types[j] == ANYELEMENTOID)
1119 have_generics = have_anyelement = true;
1120 if (actual_type == UNKNOWNOID)
1122 have_unknowns = true;
1125 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1127 (errcode(ERRCODE_DATATYPE_MISMATCH),
1128 errmsg("arguments declared \"anyelement\" are not all alike"),
1129 errdetail("%s versus %s",
1130 format_type_be(elem_typeid),
1131 format_type_be(actual_type))));
1132 elem_typeid = actual_type;
1134 else if (declared_arg_types[j] == ANYARRAYOID)
1136 have_generics = true;
1137 if (actual_type == UNKNOWNOID)
1139 have_unknowns = true;
1142 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1144 (errcode(ERRCODE_DATATYPE_MISMATCH),
1145 errmsg("arguments declared \"anyarray\" are not all alike"),
1146 errdetail("%s versus %s",
1147 format_type_be(array_typeid),
1148 format_type_be(actual_type))));
1149 array_typeid = actual_type;
1154 * Fast Track: if none of the arguments are ANYARRAY or ANYELEMENT, return
1155 * the unmodified rettype.
1160 /* Get the element type based on the array type, if we have one */
1161 if (OidIsValid(array_typeid))
1163 if (array_typeid == ANYARRAYOID && !have_anyelement)
1165 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1166 array_typelem = InvalidOid;
1170 array_typelem = get_element_type(array_typeid);
1171 if (!OidIsValid(array_typelem))
1173 (errcode(ERRCODE_DATATYPE_MISMATCH),
1174 errmsg("argument declared \"anyarray\" is not an array but type %s",
1175 format_type_be(array_typeid))));
1178 if (!OidIsValid(elem_typeid))
1181 * if we don't have an element type yet, use the one we just got
1183 elem_typeid = array_typelem;
1185 else if (array_typelem != elem_typeid)
1187 /* otherwise, they better match */
1189 (errcode(ERRCODE_DATATYPE_MISMATCH),
1190 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1191 errdetail("%s versus %s",
1192 format_type_be(array_typeid),
1193 format_type_be(elem_typeid))));
1196 else if (!OidIsValid(elem_typeid))
1198 /* Only way to get here is if all the generic args are UNKNOWN */
1200 (errcode(ERRCODE_DATATYPE_MISMATCH),
1201 errmsg("could not determine anyarray/anyelement type because input has type \"unknown\"")));
1205 * If we had any unknown inputs, re-scan to assign correct types
1209 for (j = 0; j < nargs; j++)
1211 Oid actual_type = actual_arg_types[j];
1213 if (actual_type != UNKNOWNOID)
1216 if (declared_arg_types[j] == ANYELEMENTOID)
1217 declared_arg_types[j] = elem_typeid;
1218 else if (declared_arg_types[j] == ANYARRAYOID)
1220 if (!OidIsValid(array_typeid))
1222 array_typeid = get_array_type(elem_typeid);
1223 if (!OidIsValid(array_typeid))
1225 (errcode(ERRCODE_UNDEFINED_OBJECT),
1226 errmsg("could not find array type for data type %s",
1227 format_type_be(elem_typeid))));
1229 declared_arg_types[j] = array_typeid;
1234 /* if we return ANYARRAYOID use the appropriate argument type */
1235 if (rettype == ANYARRAYOID)
1237 if (!OidIsValid(array_typeid))
1239 array_typeid = get_array_type(elem_typeid);
1240 if (!OidIsValid(array_typeid))
1242 (errcode(ERRCODE_UNDEFINED_OBJECT),
1243 errmsg("could not find array type for data type %s",
1244 format_type_be(elem_typeid))));
1246 return array_typeid;
1249 /* if we return ANYELEMENTOID use the appropriate argument type */
1250 if (rettype == ANYELEMENTOID)
1253 /* we don't return a generic type; send back the original return type */
1258 * resolve_generic_type()
1259 * Deduce an individual actual datatype on the assumption that
1260 * the rules for ANYARRAY/ANYELEMENT are being followed.
1262 * declared_type is the declared datatype we want to resolve.
1263 * context_actual_type is the actual input datatype to some argument
1264 * that has declared datatype context_declared_type.
1266 * If declared_type isn't polymorphic, we just return it. Otherwise,
1267 * context_declared_type must be polymorphic, and we deduce the correct
1268 * return type based on the relationship of the two polymorphic types.
1271 resolve_generic_type(Oid declared_type,
1272 Oid context_actual_type,
1273 Oid context_declared_type)
1275 if (declared_type == ANYARRAYOID)
1277 if (context_declared_type == ANYARRAYOID)
1279 /* Use actual type, but it must be an array */
1280 Oid array_typelem = get_element_type(context_actual_type);
1282 if (!OidIsValid(array_typelem))
1284 (errcode(ERRCODE_DATATYPE_MISMATCH),
1285 errmsg("argument declared \"anyarray\" is not an array but type %s",
1286 format_type_be(context_actual_type))));
1287 return context_actual_type;
1289 else if (context_declared_type == ANYELEMENTOID)
1291 /* Use the array type corresponding to actual type */
1292 Oid array_typeid = get_array_type(context_actual_type);
1294 if (!OidIsValid(array_typeid))
1296 (errcode(ERRCODE_UNDEFINED_OBJECT),
1297 errmsg("could not find array type for data type %s",
1298 format_type_be(context_actual_type))));
1299 return array_typeid;
1302 else if (declared_type == ANYELEMENTOID)
1304 if (context_declared_type == ANYARRAYOID)
1306 /* Use the element type corresponding to actual type */
1307 Oid array_typelem = get_element_type(context_actual_type);
1309 if (!OidIsValid(array_typelem))
1311 (errcode(ERRCODE_DATATYPE_MISMATCH),
1312 errmsg("argument declared \"anyarray\" is not an array but type %s",
1313 format_type_be(context_actual_type))));
1314 return array_typelem;
1316 else if (context_declared_type == ANYELEMENTOID)
1318 /* Use the actual type; it doesn't matter if array or not */
1319 return context_actual_type;
1324 /* declared_type isn't polymorphic, so return it as-is */
1325 return declared_type;
1327 /* If we get here, declared_type is polymorphic and context isn't */
1328 /* NB: this is a calling-code logic error, not a user error */
1329 elog(ERROR, "could not determine ANYARRAY/ANYELEMENT type because context isn't polymorphic");
1330 return InvalidOid; /* keep compiler quiet */
1335 * Assign a category to the specified type OID.
1337 * NB: this must not return INVALID_TYPE.
1339 * XXX This should be moved to system catalog lookups
1340 * to allow for better type extensibility.
1341 * - thomas 2001-09-30
1344 TypeCategory(Oid inType)
1351 result = BOOLEAN_TYPE;
1359 result = STRING_TYPE;
1364 result = BITSTRING_TYPE;
1369 case (REGPROCEDUREOID):
1371 case (REGOPERATOROID):
1381 result = NUMERIC_TYPE;
1388 case (TIMESTAMPOID):
1389 case (TIMESTAMPTZOID):
1390 result = DATETIME_TYPE;
1394 case (TINTERVALOID):
1396 result = TIMESPAN_TYPE;
1406 result = GEOMETRIC_TYPE;
1411 result = NETWORK_TYPE;
1416 result = UNKNOWN_TYPE;
1425 case (LANGUAGE_HANDLEROID):
1428 case (ANYELEMENTOID):
1429 result = GENERIC_TYPE;
1437 } /* TypeCategory() */
1440 /* IsPreferredType()
1441 * Check if this type is a preferred type for the given category.
1443 * If category is INVALID_TYPE, then we'll return TRUE for preferred types
1444 * of any category; otherwise, only for preferred types of that category.
1446 * XXX This should be moved to system catalog lookups
1447 * to allow for better type extensibility.
1448 * - thomas 2001-09-30
1451 IsPreferredType(CATEGORY category, Oid type)
1455 if (category == INVALID_TYPE)
1456 category = TypeCategory(type);
1457 else if (category != TypeCategory(type))
1461 * This switch should agree with TypeCategory(), above. Note that at this
1462 * point, category certainly matches the type.
1466 case (UNKNOWN_TYPE):
1467 case (GENERIC_TYPE):
1468 preftype = UNKNOWNOID;
1471 case (BOOLEAN_TYPE):
1479 case (BITSTRING_TYPE):
1480 preftype = VARBITOID;
1483 case (NUMERIC_TYPE):
1484 if (type == OIDOID ||
1485 type == REGPROCOID ||
1486 type == REGPROCEDUREOID ||
1487 type == REGOPEROID ||
1488 type == REGOPERATOROID ||
1489 type == REGCLASSOID ||
1493 preftype = FLOAT8OID;
1496 case (DATETIME_TYPE):
1497 if (type == DATEOID)
1498 preftype = TIMESTAMPOID;
1500 preftype = TIMESTAMPTZOID;
1503 case (TIMESPAN_TYPE):
1504 preftype = INTERVALOID;
1507 case (GEOMETRIC_TYPE):
1511 case (NETWORK_TYPE):
1520 elog(ERROR, "unrecognized type category: %d", (int) category);
1521 preftype = UNKNOWNOID;
1525 return (type == preftype);
1526 } /* IsPreferredType() */
1529 /* IsBinaryCoercible()
1530 * Check if srctype is binary-coercible to targettype.
1532 * This notion allows us to cheat and directly exchange values without
1533 * going through the trouble of calling a conversion function. Note that
1534 * in general, this should only be an implementation shortcut. Before 7.4,
1535 * this was also used as a heuristic for resolving overloaded functions and
1536 * operators, but that's basically a bad idea.
1538 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1539 * We consider two types binary-coercible if there is an implicitly
1540 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1541 * binary-coercible to its base type, though *not* vice versa (in the other
1542 * direction, one must apply domain constraint checks before accepting the
1543 * value as legitimate). We also need to special-case the polymorphic
1546 * This function replaces IsBinaryCompatible(), which was an inherently
1547 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1548 * the order of the operands is now significant.
1551 IsBinaryCoercible(Oid srctype, Oid targettype)
1554 Form_pg_cast castForm;
1557 /* Fast path if same type */
1558 if (srctype == targettype)
1561 /* If srctype is a domain, reduce to its base type */
1562 if (OidIsValid(srctype))
1563 srctype = getBaseType(srctype);
1565 /* Somewhat-fast path for domain -> base type case */
1566 if (srctype == targettype)
1569 /* Also accept any array type as coercible to ANYARRAY */
1570 if (targettype == ANYARRAYOID)
1571 if (get_element_type(srctype) != InvalidOid)
1574 /* Else look in pg_cast */
1575 tuple = SearchSysCache(CASTSOURCETARGET,
1576 ObjectIdGetDatum(srctype),
1577 ObjectIdGetDatum(targettype),
1579 if (!HeapTupleIsValid(tuple))
1580 return false; /* no cast */
1581 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1583 result = (castForm->castfunc == InvalidOid &&
1584 castForm->castcontext == COERCION_CODE_IMPLICIT);
1586 ReleaseSysCache(tuple);
1593 * find_coercion_pathway
1594 * Look for a coercion pathway between two types.
1596 * ccontext determines the set of available casts.
1598 * If we find a suitable entry in pg_cast, return TRUE, and set *funcid
1599 * to the castfunc value, which may be InvalidOid for a binary-compatible
1602 * NOTE: *funcid == InvalidOid does not necessarily mean that no work is
1603 * needed to do the coercion; if the target is a domain then we may need to
1604 * apply domain constraint checking. If you want to check for a zero-effort
1605 * conversion then use IsBinaryCoercible().
1608 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1609 CoercionContext ccontext,
1612 bool result = false;
1615 *funcid = InvalidOid;
1617 /* Perhaps the types are domains; if so, look at their base types */
1618 if (OidIsValid(sourceTypeId))
1619 sourceTypeId = getBaseType(sourceTypeId);
1620 if (OidIsValid(targetTypeId))
1621 targetTypeId = getBaseType(targetTypeId);
1623 /* Domains are always coercible to and from their base type */
1624 if (sourceTypeId == targetTypeId)
1627 /* Look in pg_cast */
1628 tuple = SearchSysCache(CASTSOURCETARGET,
1629 ObjectIdGetDatum(sourceTypeId),
1630 ObjectIdGetDatum(targetTypeId),
1633 if (HeapTupleIsValid(tuple))
1635 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1636 CoercionContext castcontext;
1638 /* convert char value for castcontext to CoercionContext enum */
1639 switch (castForm->castcontext)
1641 case COERCION_CODE_IMPLICIT:
1642 castcontext = COERCION_IMPLICIT;
1644 case COERCION_CODE_ASSIGNMENT:
1645 castcontext = COERCION_ASSIGNMENT;
1647 case COERCION_CODE_EXPLICIT:
1648 castcontext = COERCION_EXPLICIT;
1651 elog(ERROR, "unrecognized castcontext: %d",
1652 (int) castForm->castcontext);
1653 castcontext = 0; /* keep compiler quiet */
1657 /* Rely on ordering of enum for correct behavior here */
1658 if (ccontext >= castcontext)
1660 *funcid = castForm->castfunc;
1664 ReleaseSysCache(tuple);
1669 * If there's no pg_cast entry, perhaps we are dealing with a pair of
1670 * array types. If so, and if the element types have a suitable cast,
1671 * use array_type_coerce() or array_type_length_coerce().
1673 * Hack: disallow coercions to oidvector and int2vector, which
1674 * otherwise tend to capture coercions that should go to "real" array
1675 * types. We want those types to be considered "real" arrays for many
1676 * purposes, but not this one. (Also, array_type_coerce isn't
1677 * guaranteed to produce an output that meets the restrictions of
1678 * these datatypes, such as being 1-dimensional.)
1684 if (targetTypeId == OIDVECTOROID || targetTypeId == INT2VECTOROID)
1687 if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid &&
1688 (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid)
1690 if (find_coercion_pathway(targetElemType, sourceElemType,
1691 ccontext, &elemfuncid))
1693 if (!OidIsValid(elemfuncid))
1695 /* binary-compatible element type conversion */
1696 *funcid = F_ARRAY_TYPE_COERCE;
1700 /* does the function take a typmod arg? */
1701 if (get_func_nargs(elemfuncid) > 1)
1702 *funcid = F_ARRAY_TYPE_LENGTH_COERCE;
1704 *funcid = F_ARRAY_TYPE_COERCE;
1716 * find_typmod_coercion_function -- does the given type need length coercion?
1718 * If the target type possesses a pg_cast function from itself to itself,
1719 * it must need length coercion.
1721 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1723 * If the given type is a varlena array type, we do not look for a coercion
1724 * function associated directly with the array type, but instead look for
1725 * one associated with the element type. If one exists, we report
1726 * array_length_coerce() as the coercion function to use.
1729 find_typmod_coercion_function(Oid typeId)
1731 Oid funcid = InvalidOid;
1732 bool isArray = false;
1734 Form_pg_type typeForm;
1737 targetType = typeidType(typeId);
1738 typeForm = (Form_pg_type) GETSTRUCT(targetType);
1740 /* Check for a varlena array type (and not a domain) */
1741 if (typeForm->typelem != InvalidOid &&
1742 typeForm->typlen == -1 &&
1743 typeForm->typtype != 'd')
1745 /* Yes, switch our attention to the element type */
1746 typeId = typeForm->typelem;
1749 ReleaseSysCache(targetType);
1751 /* Look in pg_cast */
1752 tuple = SearchSysCache(CASTSOURCETARGET,
1753 ObjectIdGetDatum(typeId),
1754 ObjectIdGetDatum(typeId),
1757 if (HeapTupleIsValid(tuple))
1759 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1761 funcid = castForm->castfunc;
1762 ReleaseSysCache(tuple);
1766 * Now, if we did find a coercion function for an array element type,
1767 * report array_length_coerce() as the function to use.
1769 if (isArray && OidIsValid(funcid))
1770 funcid = F_ARRAY_LENGTH_COERCE;