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.59 2001/06/23 22:23:49 momjian 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 = makeList1(node);
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 * - thomas 1998-03-31
180 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
185 Oid oid_array[FUNC_MAX_ARGS];
187 /* run through argument list... */
188 for (i = 0; i < nargs; i++)
190 Oid inputTypeId = input_typeids[i];
191 Oid targetTypeId = func_typeids[i];
193 /* no problem if same type */
194 if (inputTypeId == targetTypeId)
198 * one of the known-good transparent conversions? then drop
201 if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
204 /* don't know what to do for the output type? then quit... */
205 if (targetTypeId == InvalidOid)
207 /* don't know what to do for the input type? then quit... */
208 if (inputTypeId == InvalidOid)
212 * If input is an untyped string constant, assume we can convert
213 * it to anything except a class type.
215 if (inputTypeId == UNKNOWNOID)
217 if (ISCOMPLEX(targetTypeId))
223 * If input is a class type that inherits from target, no problem
225 if (typeInheritsFrom(inputTypeId, targetTypeId))
228 /* don't choke on references to no-longer-existing types */
229 if (!typeidIsValid(inputTypeId))
231 if (!typeidIsValid(targetTypeId))
235 * Else, try for explicit conversion using functions: look for a
236 * single-argument function named with the target type name and
237 * accepting the source type.
239 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
240 oid_array[0] = inputTypeId;
242 ftup = SearchSysCache(PROCNAME,
243 PointerGetDatum(typeidTypeName(targetTypeId)),
245 PointerGetDatum(oid_array),
247 if (!HeapTupleIsValid(ftup))
249 /* Make sure the function's result type is as expected, too */
250 pform = (Form_pg_proc) GETSTRUCT(ftup);
251 if (pform->prorettype != targetTypeId)
253 ReleaseSysCache(ftup);
256 ReleaseSysCache(ftup);
262 /* coerce_type_typmod()
263 * Force a value to a particular typmod, if meaningful and possible.
265 * This is applied to values that are going to be stored in a relation
266 * (where we have an atttypmod for the column) as well as values being
267 * explicitly CASTed (where the typmod comes from the target type spec).
269 * The caller must have already ensured that the value is of the correct
270 * type, typically by applying coerce_type.
272 * If the target column type possesses a function named for the type
273 * and having parameter signature (columntype, int4), we assume that
274 * the type requires coercion to its own length and that the said
275 * function should be invoked to do that.
277 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
280 coerce_type_typmod(ParseState *pstate, Node *node,
281 Oid targetTypeId, int32 atttypmod)
284 Oid oid_array[FUNC_MAX_ARGS];
287 * We assume that only typmod values greater than 0 indicate a forced
288 * conversion is necessary.
290 if (atttypmod <= 0 ||
291 atttypmod == exprTypmod(node))
294 funcname = typeidTypeName(targetTypeId);
295 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
296 oid_array[0] = targetTypeId;
297 oid_array[1] = INT4OID;
299 /* attempt to find with arguments exactly as specified... */
300 if (SearchSysCacheExists(PROCNAME,
301 PointerGetDatum(funcname),
303 PointerGetDatum(oid_array),
306 A_Const *cons = makeNode(A_Const);
307 FuncCall *func = makeNode(FuncCall);
309 cons->val.type = T_Integer;
310 cons->val.val.ival = atttypmod;
312 func->funcname = funcname;
313 func->args = makeList2(node, cons);
314 func->agg_star = false;
315 func->agg_distinct = false;
317 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
324 /* coerce_to_boolean()
325 * Coerce an argument of a construct that requires boolean input
326 * (AND, OR, NOT, etc).
328 * If successful, update *pnode to be the transformed argument (if any
329 * transformation is needed), and return TRUE. If fail, return FALSE.
330 * (The caller must check for FALSE and emit a suitable error message.)
333 coerce_to_boolean(ParseState *pstate, Node **pnode)
335 Oid inputTypeId = exprType(*pnode);
338 if (inputTypeId == BOOLOID)
339 return true; /* no work */
340 targetTypeId = BOOLOID;
341 if (! can_coerce_type(1, &inputTypeId, &targetTypeId))
342 return false; /* fail, but let caller choose error msg */
343 *pnode = coerce_type(pstate, *pnode, inputTypeId, targetTypeId, -1);
348 /* select_common_type()
349 * Determine the common supertype of a list of input expression types.
350 * This is used for determining the output type of CASE and UNION
353 * typeids is a nonempty integer list of type OIDs. Note that earlier items
354 * in the list will be preferred if there is doubt.
355 * 'context' is a phrase to use in the error message if we fail to select
358 * XXX this code is WRONG, since (for example) given the input (int4,int8)
359 * it will select int4, whereas according to SQL92 clause 9.3 the correct
360 * answer is clearly int8. To fix this we need a notion of a promotion
361 * hierarchy within type categories --- something more complete than
362 * just a single preferred type.
365 select_common_type(List *typeids, const char *context)
371 Assert(typeids != NIL);
372 ptype = (Oid) lfirsti(typeids);
373 pcategory = TypeCategory(ptype);
374 foreach(l, lnext(typeids))
376 Oid ntype = (Oid) lfirsti(l);
378 /* move on to next one if no new information... */
379 if (ntype && (ntype != UNKNOWNOID) && (ntype != ptype))
381 if (!ptype || ptype == UNKNOWNOID)
383 /* so far, only nulls so take anything... */
385 pcategory = TypeCategory(ptype);
387 else if (TypeCategory(ntype) != pcategory)
391 * both types in different categories? then not much
394 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
395 context, typeidTypeName(ptype), typeidTypeName(ntype));
397 else if (IsPreferredType(pcategory, ntype)
398 && !IsPreferredType(pcategory, ptype)
399 && can_coerce_type(1, &ptype, &ntype))
403 * new one is preferred and can convert? then take it...
406 pcategory = TypeCategory(ptype);
412 * If all the inputs were UNKNOWN type --- ie, unknown-type literals
413 * --- then resolve as type TEXT. This situation comes up with
414 * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
415 * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
416 * the construct's output type as UNKNOWN, but that really doesn't
417 * work, because we'd probably end up needing a runtime coercion from
418 * UNKNOWN to something else, and we usually won't have it. We need
419 * to coerce the unknown literals while they are still literals, so a
420 * decision has to be made now.
422 if (ptype == UNKNOWNOID)
428 /* coerce_to_common_type()
429 * Coerce an expression to the given type.
431 * This is used following select_common_type() to coerce the individual
432 * expressions to the desired type. 'context' is a phrase to use in the
433 * error message if we fail to coerce.
435 * NOTE: pstate may be NULL.
438 coerce_to_common_type(ParseState *pstate, Node *node,
442 Oid inputTypeId = exprType(node);
444 if (inputTypeId == targetTypeId)
445 return node; /* no work */
446 if (can_coerce_type(1, &inputTypeId, &targetTypeId))
447 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1);
450 elog(ERROR, "%s unable to convert to type \"%s\"",
451 context, typeidTypeName(targetTypeId));
458 * Assign a category to the specified OID.
461 TypeCategory(Oid inType)
468 result = BOOLEAN_TYPE;
477 result = STRING_TYPE;
482 result = BITSTRING_TYPE;
494 result = NUMERIC_TYPE;
502 result = DATETIME_TYPE;
508 result = TIMESPAN_TYPE;
518 result = GEOMETRIC_TYPE;
523 result = NETWORK_TYPE;
528 result = UNKNOWN_TYPE;
536 } /* TypeCategory() */
540 * Check if this type is a preferred type.
543 IsPreferredType(CATEGORY category, Oid type)
545 return type == PreferredType(category, type);
546 } /* IsPreferredType() */
550 * Return the preferred type OID for the specified category.
553 PreferredType(CATEGORY category, Oid type)
567 case (BITSTRING_TYPE):
574 else if (type == NUMERICOID)
580 case (DATETIME_TYPE):
581 result = TIMESTAMPOID;
584 case (TIMESPAN_TYPE):
585 result = INTERVALOID;
592 case (GEOMETRIC_TYPE):
602 } /* PreferredType() */
607 PromoteTypeToNext(Oid inType)
640 result = TIMESTAMPOID;
645 result = INTERVALOID;
658 } /* PromoteTypeToNext() */
662 DemoteType(Oid inType)
682 PromoteLesserType(Oid inType1, Oid inType2, Oid *newType1, Oid *newType2)
686 if (inType1 == inType2)
688 result = PromoteTypeToNext(inType1);
694 kind1 = ClassifyType(inType1);
695 kind2 = ClassifyType(*arg2);
703 isBuiltIn1 = IS_BUILTIN_TYPE(inType1);
704 isBuiltIn2 = IS_BUILTIN_TYPE(*arg2);
706 if (isBuiltIn1 && isBuiltIn2)
742 else if (isBuiltIn1 && !isBuiltIn2)
744 if ((promotedType = PromoteBuiltInType(*arg1)) != *arg1)
746 *arg1 = promotedType;
749 else if (CanCoerceType(*arg1, *arg2))
755 else if (!isBuiltIn1 && isBuiltIn2)
757 if ((promotedType = PromoteBuiltInType(*arg2)) != *arg2)
759 *arg2 = promotedType;
762 else if (CanCoerceType(*arg2, *arg1))
770 if (*arg2 == InvalidOid)