1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.50 2000/11/17 19:57:47 petere Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_proc.h"
18 #include "optimizer/clauses.h"
19 #include "parser/parse_coerce.h"
20 #include "parser/parse_expr.h"
21 #include "parser/parse_func.h"
22 #include "parser/parse_type.h"
23 #include "utils/builtins.h"
24 #include "utils/syscache.h"
26 Oid DemoteType(Oid inType);
27 Oid PromoteTypeToNext(Oid inType);
29 static Oid PreferredType(CATEGORY category, Oid type);
33 * Convert a function argument to a different type.
36 coerce_type(ParseState *pstate, Node *node, Oid inputTypeId,
37 Oid targetTypeId, int32 atttypmod)
41 if (targetTypeId == inputTypeId ||
42 targetTypeId == InvalidOid ||
45 /* no conversion needed */
48 else if (inputTypeId == UNKNOWNOID && IsA(node, Const))
52 * Input is a string constant with previously undetermined type.
53 * Apply the target type's typinput function to it to produce a
54 * constant of the target type.
56 * NOTE: this case cannot be folded together with the other
57 * constant-input case, since the typinput function does not
58 * necessarily behave the same as a type conversion function. For
59 * example, int4's typinput function will reject "1.2", whereas
60 * float-to-int type conversion will round to integer.
62 * XXX if the typinput function is not cachable, we really ought to
63 * postpone evaluation of the function call until runtime. But
64 * there is no way to represent a typinput function call as an
65 * expression tree, because C-string values are not Datums.
67 Const *con = (Const *) node;
68 Const *newcon = makeNode(Const);
69 Type targetType = typeidType(targetTypeId);
71 newcon->consttype = targetTypeId;
72 newcon->constlen = typeLen(targetType);
73 newcon->constbyval = typeByVal(targetType);
74 newcon->constisnull = con->constisnull;
75 newcon->constisset = false;
77 if (!con->constisnull)
79 /* We know the source constant is really of type 'text' */
80 char *val = DatumGetCString(DirectFunctionCall1(textout,
83 newcon->constvalue = stringTypeDatum(targetType, val, atttypmod);
87 ReleaseSysCache(targetType);
89 result = (Node *) newcon;
91 else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
95 * We don't really need to do a conversion, but we do need to
96 * attach a RelabelType node so that the expression will be seen
97 * to have the intended type when inspected by higher-level code.
99 RelabelType *relabel = makeNode(RelabelType);
102 relabel->resulttype = targetTypeId;
105 * XXX could we label result with exprTypmod(node) instead of
106 * default -1 typmod, to save a possible length-coercion later?
107 * Would work if both types have same interpretation of typmod,
108 * which is likely but not certain.
110 relabel->resulttypmod = -1;
112 result = (Node *) relabel;
114 else if (typeInheritsFrom(inputTypeId, targetTypeId))
116 /* Input class type is a subclass of target, so nothing to do */
123 * Otherwise, find the appropriate type conversion function
124 * (caller should have determined that there is one), and generate
125 * an expression tree representing run-time application of the
126 * conversion function.
128 FuncCall *n = makeNode(FuncCall);
130 n->funcname = typeidTypeName(targetTypeId);
131 n->args = lcons(node, NIL);
133 n->agg_distinct = false;
135 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
137 /* safety check that we got the right thing */
138 if (exprType(result) != targetTypeId)
139 elog(ERROR, "coerce_type: conversion function %s produced %s",
140 typeidTypeName(targetTypeId),
141 typeidTypeName(exprType(result)));
144 * If the input is a constant, apply the type conversion function
145 * now instead of delaying to runtime. (We could, of course, just
146 * leave this to be done during planning/optimization; but it's a
147 * very frequent special case, and we save cycles in the rewriter
148 * if we fold the expression now.)
150 * Note that no folding will occur if the conversion function is not
151 * marked 'iscachable'.
153 * HACK: if constant is NULL, don't fold it here. This is needed by
154 * make_subplan(), which calls this routine on placeholder Const
155 * nodes that mustn't be collapsed. (It'd be a lot cleaner to
156 * make a separate node type for that purpose...)
158 if (IsA(node, Const) &&!((Const *) node)->constisnull)
159 result = eval_const_expressions(result);
167 * Can input_typeids be coerced to func_typeids?
169 * There are a few types which are known apriori to be convertible.
170 * We will check for those cases first, and then look for possible
171 * conversion functions.
174 * This uses the same mechanism as the CAST() SQL construct in gram.y.
175 * We should also check the function return type on candidate conversion
176 * routines just to be safe but we do not do that yet...
177 * We need to have a zero-filled OID array here, otherwise the cache lookup fails.
178 * - thomas 1998-03-31
181 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
186 Oid oid_array[FUNC_MAX_ARGS];
188 /* run through argument list... */
189 for (i = 0; i < nargs; i++)
191 Oid inputTypeId = input_typeids[i];
192 Oid targetTypeId = func_typeids[i];
194 /* no problem if same type */
195 if (inputTypeId == targetTypeId)
199 * one of the known-good transparent conversions? then drop
202 if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
205 /* don't know what to do for the output type? then quit... */
206 if (targetTypeId == InvalidOid)
208 /* don't know what to do for the input type? then quit... */
209 if (inputTypeId == InvalidOid)
213 * If input is an untyped string constant, assume we can convert
214 * it to anything except a class type.
216 if (inputTypeId == UNKNOWNOID)
218 if (ISCOMPLEX(targetTypeId))
224 * If input is a class type that inherits from target, no problem
226 if (typeInheritsFrom(inputTypeId, targetTypeId))
230 * Else, try for explicit conversion using functions: look for a
231 * single-argument function named with the target type name and
232 * accepting the source type.
234 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
235 oid_array[0] = inputTypeId;
237 ftup = SearchSysCache(PROCNAME,
238 PointerGetDatum(typeidTypeName(targetTypeId)),
240 PointerGetDatum(oid_array),
242 if (!HeapTupleIsValid(ftup))
244 /* Make sure the function's result type is as expected, too */
245 pform = (Form_pg_proc) GETSTRUCT(ftup);
246 if (pform->prorettype != targetTypeId)
248 ReleaseSysCache(ftup);
251 ReleaseSysCache(ftup);
257 /* coerce_type_typmod()
258 * Force a value to a particular typmod, if meaningful and possible.
260 * This is applied to values that are going to be stored in a relation
261 * (where we have an atttypmod for the column) as well as values being
262 * explicitly CASTed (where the typmod comes from the target type spec).
264 * The caller must have already ensured that the value is of the correct
265 * type, typically by applying coerce_type.
267 * If the target column type possesses a function named for the type
268 * and having parameter signature (columntype, int4), we assume that
269 * the type requires coercion to its own length and that the said
270 * function should be invoked to do that.
272 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
275 coerce_type_typmod(ParseState *pstate, Node *node,
276 Oid targetTypeId, int32 atttypmod)
279 Oid oid_array[FUNC_MAX_ARGS];
282 * We assume that only typmod values greater than 0 indicate a forced
283 * conversion is necessary.
285 if (atttypmod <= 0 ||
286 atttypmod == exprTypmod(node))
289 funcname = typeidTypeName(targetTypeId);
290 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
291 oid_array[0] = targetTypeId;
292 oid_array[1] = INT4OID;
294 /* attempt to find with arguments exactly as specified... */
295 if (SearchSysCacheExists(PROCNAME,
296 PointerGetDatum(funcname),
298 PointerGetDatum(oid_array),
301 A_Const *cons = makeNode(A_Const);
302 FuncCall *func = makeNode(FuncCall);
304 cons->val.type = T_Integer;
305 cons->val.val.ival = atttypmod;
307 func->funcname = funcname;
308 func->args = lappend(lcons(node, NIL), cons);
309 func->agg_star = false;
310 func->agg_distinct = false;
312 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
319 /* select_common_type()
320 * Determine the common supertype of a list of input expression types.
321 * This is used for determining the output type of CASE and UNION
324 * typeids is a nonempty integer list of type OIDs. Note that earlier items
325 * in the list will be preferred if there is doubt.
326 * 'context' is a phrase to use in the error message if we fail to select
329 * XXX this code is WRONG, since (for example) given the input (int4,int8)
330 * it will select int4, whereas according to SQL92 clause 9.3 the correct
331 * answer is clearly int8. To fix this we need a notion of a promotion
332 * hierarchy within type categories --- something more complete than
333 * just a single preferred type.
336 select_common_type(List *typeids, const char *context)
342 Assert(typeids != NIL);
343 ptype = (Oid) lfirsti(typeids);
344 pcategory = TypeCategory(ptype);
345 foreach(l, lnext(typeids))
347 Oid ntype = (Oid) lfirsti(l);
349 /* move on to next one if no new information... */
350 if (ntype && (ntype != UNKNOWNOID) && (ntype != ptype))
352 if (!ptype || ptype == UNKNOWNOID)
354 /* so far, only nulls so take anything... */
356 pcategory = TypeCategory(ptype);
358 else if (TypeCategory(ntype) != pcategory)
361 * both types in different categories? then
364 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
365 context, typeidTypeName(ptype), typeidTypeName(ntype));
367 else if (IsPreferredType(pcategory, ntype)
368 && can_coerce_type(1, &ptype, &ntype))
371 * new one is preferred and can convert? then
375 pcategory = TypeCategory(ptype);
381 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
382 * then resolve as type TEXT. This situation comes up with constructs
384 * SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
385 * SELECT 'foo' UNION SELECT 'bar';
386 * It might seem desirable to leave the construct's output type as
387 * UNKNOWN, but that really doesn't work, because we'd probably end up
388 * needing a runtime coercion from UNKNOWN to something else, and we
389 * usually won't have it. We need to coerce the unknown literals while
390 * they are still literals, so a decision has to be made now.
392 if (ptype == UNKNOWNOID)
398 /* coerce_to_common_type()
399 * Coerce an expression to the given type.
401 * This is used following select_common_type() to coerce the individual
402 * expressions to the desired type. 'context' is a phrase to use in the
403 * error message if we fail to coerce.
405 * NOTE: pstate may be NULL.
408 coerce_to_common_type(ParseState *pstate, Node *node,
412 Oid inputTypeId = exprType(node);
414 if (inputTypeId == targetTypeId)
415 return node; /* no work */
416 if (can_coerce_type(1, &inputTypeId, &targetTypeId))
418 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1);
422 elog(ERROR, "%s unable to convert to type \"%s\"",
423 context, typeidTypeName(targetTypeId));
430 * Assign a category to the specified OID.
433 TypeCategory(Oid inType)
440 result = BOOLEAN_TYPE;
448 result = STRING_TYPE;
452 * Kluge added 4/8/00 by tgl: treat the new BIT types as
453 * strings, so that 'unknown' || 'unknown' continues to
454 * resolve as textcat rather than generating an
455 * ambiguous-operator error. Probably BIT types should have
456 * their own type category, or maybe they should be numeric?
457 * Need a better way of handling unknown types first.
461 result = BITSTRING_TYPE;
473 result = NUMERIC_TYPE;
481 result = DATETIME_TYPE;
487 result = TIMESPAN_TYPE;
497 result = GEOMETRIC_TYPE;
502 result = NETWORK_TYPE;
507 result = UNKNOWN_TYPE;
515 } /* TypeCategory() */
519 * Check if this type is a preferred type.
522 IsPreferredType(CATEGORY category, Oid type)
524 return type == PreferredType(category, type);
525 } /* IsPreferredType() */
529 * Return the preferred type OID for the specified category.
532 PreferredType(CATEGORY category, Oid type)
546 case (BITSTRING_TYPE):
553 else if (type == NUMERICOID)
559 case (DATETIME_TYPE):
560 result = TIMESTAMPOID;
563 case (TIMESPAN_TYPE):
564 result = INTERVALOID;
571 case (GEOMETRIC_TYPE):
581 } /* PreferredType() */
586 PromoteTypeToNext(Oid inType)
618 result = TIMESTAMPOID;
623 result = INTERVALOID;
636 } /* PromoteTypeToNext() */
640 DemoteType(Oid inType)
660 PromoteLesserType(Oid inType1, Oid inType2, Oid *newType1, Oid *newType2)
664 if (inType1 == inType2)
666 result = PromoteTypeToNext(inType1);
672 kind1 = ClassifyType(inType1);
673 kind2 = ClassifyType(*arg2);
681 isBuiltIn1 = IS_BUILTIN_TYPE(inType1);
682 isBuiltIn2 = IS_BUILTIN_TYPE(*arg2);
684 if (isBuiltIn1 && isBuiltIn2)
719 else if (isBuiltIn1 && !isBuiltIn2)
721 if ((promotedType = PromoteBuiltInType(*arg1)) != *arg1)
723 *arg1 = promotedType;
726 else if (CanCoerceType(*arg1, *arg2))
732 else if (!isBuiltIn1 && isBuiltIn2)
734 if ((promotedType = PromoteBuiltInType(*arg2)) != *arg2)
736 *arg2 = promotedType;
739 else if (CanCoerceType(*arg2, *arg1))
747 if (*arg2 == InvalidOid)