1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.68 2002/03/20 19:44:22 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_proc.h"
18 #include "nodes/makefuncs.h"
19 #include "optimizer/clauses.h"
20 #include "parser/parse_coerce.h"
21 #include "parser/parse_expr.h"
22 #include "parser/parse_func.h"
23 #include "parser/parse_type.h"
24 #include "utils/builtins.h"
25 #include "utils/lsyscache.h"
26 #include "utils/syscache.h"
29 Oid DemoteType(Oid inType);
30 Oid PromoteTypeToNext(Oid inType);
32 static Oid PreferredType(CATEGORY category, Oid type);
33 static Node *build_func_call(Oid funcid, Oid rettype, List *args);
34 static Oid find_coercion_function(Oid targetTypeId, Oid inputTypeId,
39 * Convert a function argument to a different type.
42 coerce_type(ParseState *pstate, Node *node, Oid inputTypeId,
43 Oid targetTypeId, int32 atttypmod)
47 if (targetTypeId == inputTypeId ||
48 targetTypeId == InvalidOid ||
51 /* no conversion needed */
54 else if (inputTypeId == UNKNOWNOID && IsA(node, Const))
57 * Input is a string constant with previously undetermined type.
58 * Apply the target type's typinput function to it to produce a
59 * constant of the target type.
61 * NOTE: this case cannot be folded together with the other
62 * constant-input case, since the typinput function does not
63 * necessarily behave the same as a type conversion function. For
64 * example, int4's typinput function will reject "1.2", whereas
65 * float-to-int type conversion will round to integer.
67 * XXX if the typinput function is not cachable, we really ought to
68 * postpone evaluation of the function call until runtime. But
69 * there is no way to represent a typinput function call as an
70 * expression tree, because C-string values are not Datums.
72 Const *con = (Const *) node;
73 Const *newcon = makeNode(Const);
74 Type targetType = typeidType(targetTypeId);
76 newcon->consttype = targetTypeId;
77 newcon->constlen = typeLen(targetType);
78 newcon->constbyval = typeByVal(targetType);
79 newcon->constisnull = con->constisnull;
80 newcon->constisset = false;
82 if (!con->constisnull)
84 /* We know the source constant is really of type 'text' */
85 char *val = DatumGetCString(DirectFunctionCall1(textout,
88 newcon->constvalue = stringTypeDatum(targetType, val, atttypmod);
92 ReleaseSysCache(targetType);
94 result = (Node *) newcon;
96 else if (IsBinaryCompatible(inputTypeId, targetTypeId))
99 * We don't really need to do a conversion, but we do need to
100 * attach a RelabelType node so that the expression will be seen
101 * to have the intended type when inspected by higher-level code.
103 * XXX could we label result with exprTypmod(node) instead of
104 * default -1 typmod, to save a possible length-coercion later?
105 * Would work if both types have same interpretation of typmod,
106 * which is likely but not certain.
108 result = (Node *) makeRelabelType(node, targetTypeId, -1);
110 else if (typeInheritsFrom(inputTypeId, targetTypeId))
113 * Input class type is a subclass of target, so nothing to do
114 * --- except relabel the type. This is binary compatibility
117 result = (Node *) makeRelabelType(node, targetTypeId, -1);
122 * Otherwise, find the appropriate type conversion function
123 * (caller should have determined that there is one), and generate
124 * an expression tree representing run-time application of the
125 * conversion function.
127 * For domains, we use the coercion function for the base type.
129 Oid baseTypeId = getBaseType(targetTypeId);
132 funcId = find_coercion_function(baseTypeId,
133 getBaseType(inputTypeId),
135 if (!OidIsValid(funcId))
136 elog(ERROR, "coerce_type: no conversion function from %s to %s",
137 format_type_be(inputTypeId), format_type_be(targetTypeId));
139 result = build_func_call(funcId, baseTypeId, makeList1(node));
141 /* if domain, relabel with domain type ID */
142 if (targetTypeId != baseTypeId)
143 result = (Node *) makeRelabelType(result, targetTypeId, -1);
146 * If the input is a constant, apply the type conversion function
147 * now instead of delaying to runtime. (We could, of course, just
148 * leave this to be done during planning/optimization; but it's a
149 * very frequent special case, and we save cycles in the rewriter
150 * if we fold the expression now.)
152 * Note that no folding will occur if the conversion function is not
153 * marked 'iscachable'.
155 * HACK: if constant is NULL, don't fold it here. This is needed by
156 * make_subplan(), which calls this routine on placeholder Const
157 * nodes that mustn't be collapsed. (It'd be a lot cleaner to
158 * make a separate node type for that purpose...)
160 if (IsA(node, Const) &&
161 !((Const *) node)->constisnull)
162 result = eval_const_expressions(result);
170 * Can input_typeids be coerced to func_typeids?
172 * There are a few types which are known apriori to be convertible.
173 * We will check for those cases first, and then look for possible
174 * conversion functions.
177 * This uses the same mechanism as the CAST() SQL construct in gram.y.
180 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
184 /* run through argument list... */
185 for (i = 0; i < nargs; i++)
187 Oid inputTypeId = input_typeids[i];
188 Oid targetTypeId = func_typeids[i];
191 /* no problem if same type */
192 if (inputTypeId == targetTypeId)
196 * one of the known-good transparent conversions? then drop
199 if (IsBinaryCompatible(inputTypeId, targetTypeId))
202 /* don't know what to do for the output type? then quit... */
203 if (targetTypeId == InvalidOid)
205 /* don't know what to do for the input type? then quit... */
206 if (inputTypeId == InvalidOid)
210 * If input is an untyped string constant, assume we can convert
211 * it to anything except a class type.
213 if (inputTypeId == UNKNOWNOID)
215 if (ISCOMPLEX(targetTypeId))
221 * If input is a class type that inherits from target, no problem
223 if (typeInheritsFrom(inputTypeId, targetTypeId))
226 /* don't choke on references to no-longer-existing types */
227 if (!typeidIsValid(inputTypeId))
229 if (!typeidIsValid(targetTypeId))
233 * Else, try for explicit conversion using functions: look for a
234 * single-argument function named with the target type name and
235 * accepting the source type.
237 * If either type is a domain, use its base type instead.
239 funcId = find_coercion_function(getBaseType(targetTypeId),
240 getBaseType(inputTypeId),
242 if (!OidIsValid(funcId))
249 /* coerce_type_typmod()
250 * Force a value to a particular typmod, if meaningful and possible.
252 * This is applied to values that are going to be stored in a relation
253 * (where we have an atttypmod for the column) as well as values being
254 * explicitly CASTed (where the typmod comes from the target type spec).
256 * The caller must have already ensured that the value is of the correct
257 * type, typically by applying coerce_type.
259 * If the target column type possesses a function named for the type
260 * and having parameter signature (columntype, int4), we assume that
261 * the type requires coercion to its own length and that the said
262 * function should be invoked to do that.
264 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
267 coerce_type_typmod(ParseState *pstate, Node *node,
268 Oid targetTypeId, int32 atttypmod)
274 * A negative typmod is assumed to mean that no coercion is wanted.
276 if (atttypmod < 0 || atttypmod == exprTypmod(node))
279 /* If given type is a domain, use base type instead */
280 baseTypeId = getBaseType(targetTypeId);
282 funcId = find_coercion_function(baseTypeId, baseTypeId, INT4OID);
284 if (OidIsValid(funcId))
288 cons = makeConst(INT4OID,
290 Int32GetDatum(atttypmod),
296 node = build_func_call(funcId, baseTypeId, makeList2(node, cons));
298 /* relabel if it's domain case */
299 if (targetTypeId != baseTypeId)
300 node = (Node *) makeRelabelType(node, targetTypeId, atttypmod);
307 /* coerce_to_boolean()
308 * Coerce an argument of a construct that requires boolean input
309 * (AND, OR, NOT, etc).
311 * If successful, update *pnode to be the transformed argument (if any
312 * transformation is needed), and return TRUE. If fail, return FALSE.
313 * (The caller must check for FALSE and emit a suitable error message.)
316 coerce_to_boolean(ParseState *pstate, Node **pnode)
318 Oid inputTypeId = exprType(*pnode);
321 if (inputTypeId == BOOLOID)
322 return true; /* no work */
323 targetTypeId = BOOLOID;
324 if (!can_coerce_type(1, &inputTypeId, &targetTypeId))
325 return false; /* fail, but let caller choose error msg */
326 *pnode = coerce_type(pstate, *pnode, inputTypeId, targetTypeId, -1);
331 /* select_common_type()
332 * Determine the common supertype of a list of input expression types.
333 * This is used for determining the output type of CASE and UNION
336 * typeids is a nonempty integer list of type OIDs. Note that earlier items
337 * in the list will be preferred if there is doubt.
338 * 'context' is a phrase to use in the error message if we fail to select
341 * XXX this code is WRONG, since (for example) given the input (int4,int8)
342 * it will select int4, whereas according to SQL92 clause 9.3 the correct
343 * answer is clearly int8. To fix this we need a notion of a promotion
344 * hierarchy within type categories --- something more complete than
345 * just a single preferred type.
348 select_common_type(List *typeids, const char *context)
354 Assert(typeids != NIL);
355 ptype = (Oid) lfirsti(typeids);
356 pcategory = TypeCategory(ptype);
357 foreach(l, lnext(typeids))
359 Oid ntype = (Oid) lfirsti(l);
361 /* move on to next one if no new information... */
362 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
364 if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
366 /* so far, only nulls so take anything... */
368 pcategory = TypeCategory(ptype);
370 else if (TypeCategory(ntype) != pcategory)
373 * both types in different categories? then not much
376 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
377 context, typeidTypeName(ptype), typeidTypeName(ntype));
379 else if (IsPreferredType(pcategory, ntype)
380 && !IsPreferredType(pcategory, ptype)
381 && can_coerce_type(1, &ptype, &ntype))
384 * new one is preferred and can convert? then take it...
387 pcategory = TypeCategory(ptype);
393 * If all the inputs were UNKNOWN type --- ie, unknown-type literals
394 * --- then resolve as type TEXT. This situation comes up with
395 * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
396 * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
397 * the construct's output type as UNKNOWN, but that really doesn't
398 * work, because we'd probably end up needing a runtime coercion from
399 * UNKNOWN to something else, and we usually won't have it. We need
400 * to coerce the unknown literals while they are still literals, so a
401 * decision has to be made now.
403 if (ptype == UNKNOWNOID)
409 /* coerce_to_common_type()
410 * Coerce an expression to the given type.
412 * This is used following select_common_type() to coerce the individual
413 * expressions to the desired type. 'context' is a phrase to use in the
414 * error message if we fail to coerce.
416 * NOTE: pstate may be NULL.
419 coerce_to_common_type(ParseState *pstate, Node *node,
423 Oid inputTypeId = exprType(node);
425 if (inputTypeId == targetTypeId)
426 return node; /* no work */
427 if (can_coerce_type(1, &inputTypeId, &targetTypeId))
428 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1);
431 elog(ERROR, "%s unable to convert to type \"%s\"",
432 context, typeidTypeName(targetTypeId));
439 * Assign a category to the specified OID.
440 * XXX This should be moved to system catalog lookups
441 * to allow for better type extensibility.
442 * - thomas 2001-09-30
445 TypeCategory(Oid inType)
452 result = BOOLEAN_TYPE;
460 result = STRING_TYPE;
465 result = BITSTRING_TYPE;
477 result = NUMERIC_TYPE;
485 case (TIMESTAMPTZOID):
486 result = DATETIME_TYPE;
492 result = TIMESPAN_TYPE;
502 result = GEOMETRIC_TYPE;
507 result = NETWORK_TYPE;
512 result = UNKNOWN_TYPE;
520 } /* TypeCategory() */
523 /* IsBinaryCompatible()
524 * Check if two types are binary-compatible.
526 * This notion allows us to cheat and directly exchange values without
527 * going through the trouble of calling a conversion function.
529 * XXX This should be moved to system catalog lookups
530 * to allow for better type extensibility.
534 * This macro describes hard-coded knowledge of binary compatibility
535 * for built-in types.
537 #define IS_BINARY_COMPATIBLE(a,b) \
538 (((a) == BPCHAROID && (b) == TEXTOID) \
539 || ((a) == BPCHAROID && (b) == VARCHAROID) \
540 || ((a) == VARCHAROID && (b) == TEXTOID) \
541 || ((a) == VARCHAROID && (b) == BPCHAROID) \
542 || ((a) == TEXTOID && (b) == BPCHAROID) \
543 || ((a) == TEXTOID && (b) == VARCHAROID) \
544 || ((a) == OIDOID && (b) == INT4OID) \
545 || ((a) == OIDOID && (b) == REGPROCOID) \
546 || ((a) == INT4OID && (b) == OIDOID) \
547 || ((a) == INT4OID && (b) == REGPROCOID) \
548 || ((a) == REGPROCOID && (b) == OIDOID) \
549 || ((a) == REGPROCOID && (b) == INT4OID) \
550 || ((a) == ABSTIMEOID && (b) == INT4OID) \
551 || ((a) == INT4OID && (b) == ABSTIMEOID) \
552 || ((a) == RELTIMEOID && (b) == INT4OID) \
553 || ((a) == INT4OID && (b) == RELTIMEOID) \
554 || ((a) == INETOID && (b) == CIDROID) \
555 || ((a) == CIDROID && (b) == INETOID) \
556 || ((a) == BITOID && (b) == VARBITOID) \
557 || ((a) == VARBITOID && (b) == BITOID))
560 IsBinaryCompatible(Oid type1, Oid type2)
564 if (IS_BINARY_COMPATIBLE(type1, type2))
567 * Perhaps the types are domains; if so, look at their base types
569 if (OidIsValid(type1))
570 type1 = getBaseType(type1);
571 if (OidIsValid(type2))
572 type2 = getBaseType(type2);
575 if (IS_BINARY_COMPATIBLE(type1, type2))
582 * Check if this type is a preferred type.
583 * XXX This should be moved to system catalog lookups
584 * to allow for better type extensibility.
585 * - thomas 2001-09-30
588 IsPreferredType(CATEGORY category, Oid type)
590 return (type == PreferredType(category, type));
591 } /* IsPreferredType() */
595 * Return the preferred type OID for the specified category.
596 * XXX This should be moved to system catalog lookups
597 * to allow for better type extensibility.
598 * - thomas 2001-09-30
601 PreferredType(CATEGORY category, Oid type)
615 case (BITSTRING_TYPE):
622 else if (type == NUMERICOID)
628 case (DATETIME_TYPE):
630 result = TIMESTAMPOID;
632 result = TIMESTAMPTZOID;
635 case (TIMESPAN_TYPE):
636 result = INTERVALOID;
643 case (GEOMETRIC_TYPE):
653 } /* PreferredType() */
656 * find_coercion_function
657 * Look for a coercion function between two types.
659 * A coercion function must be named after (the internal name of) its
660 * result type, and must accept exactly the specified input type.
662 * This routine is also used to look for length-coercion functions, which
663 * are similar but accept a second argument. secondArgType is the type
664 * of the second argument (normally INT4OID), or InvalidOid if we are
665 * looking for a regular coercion function.
667 * If a function is found, return its pg_proc OID; else return InvalidOid.
670 find_coercion_function(Oid targetTypeId, Oid inputTypeId, Oid secondArgType)
673 Oid oid_array[FUNC_MAX_ARGS];
679 funcname = typeidTypeName(targetTypeId);
680 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
681 oid_array[0] = inputTypeId;
682 if (OidIsValid(secondArgType))
684 oid_array[1] = secondArgType;
690 ftup = SearchSysCache(PROCNAME,
691 PointerGetDatum(funcname),
692 Int32GetDatum(nargs),
693 PointerGetDatum(oid_array),
695 if (!HeapTupleIsValid(ftup))
697 /* Make sure the function's result type is as expected, too */
698 pform = (Form_pg_proc) GETSTRUCT(ftup);
699 if (pform->prorettype != targetTypeId)
701 ReleaseSysCache(ftup);
704 funcid = ftup->t_data->t_oid;
705 ReleaseSysCache(ftup);
710 * Build an expression tree representing a function call.
712 * The argument expressions must have been transformed already.
715 build_func_call(Oid funcid, Oid rettype, List *args)
720 funcnode = makeNode(Func);
721 funcnode->funcid = funcid;
722 funcnode->functype = rettype;
723 funcnode->func_fcache = NULL;
725 expr = makeNode(Expr);
726 expr->typeOid = rettype;
727 expr->opType = FUNC_EXPR;
728 expr->oper = (Node *) funcnode;
731 return (Node *) expr;