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.67 2002/03/19 02:18:20 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))
51 * Input is a string constant with previously undetermined type.
52 * Apply the target type's typinput function to it to produce a
53 * constant of the target type.
55 * NOTE: this case cannot be folded together with the other
56 * constant-input case, since the typinput function does not
57 * necessarily behave the same as a type conversion function. For
58 * example, int4's typinput function will reject "1.2", whereas
59 * float-to-int type conversion will round to integer.
61 * XXX if the typinput function is not cachable, we really ought to
62 * postpone evaluation of the function call until runtime. But
63 * there is no way to represent a typinput function call as an
64 * expression tree, because C-string values are not Datums.
66 Const *con = (Const *) node;
67 Const *newcon = makeNode(Const);
68 Type targetType = typeidType(targetTypeId);
70 newcon->consttype = targetTypeId;
71 newcon->constlen = typeLen(targetType);
72 newcon->constbyval = typeByVal(targetType);
73 newcon->constisnull = con->constisnull;
74 newcon->constisset = false;
76 if (!con->constisnull)
78 /* We know the source constant is really of type 'text' */
79 char *val = DatumGetCString(DirectFunctionCall1(textout,
82 newcon->constvalue = stringTypeDatum(targetType, val, atttypmod);
86 ReleaseSysCache(targetType);
88 result = (Node *) newcon;
90 else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
93 * We don't really need to do a conversion, but we do need to
94 * attach a RelabelType node so that the expression will be seen
95 * to have the intended type when inspected by higher-level code.
97 RelabelType *relabel = makeNode(RelabelType);
100 relabel->resulttype = targetTypeId;
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 relabel->resulttypmod = -1;
110 result = (Node *) relabel;
112 else if (typeInheritsFrom(inputTypeId, targetTypeId))
114 /* Input class type is a subclass of target, so nothing to do */
120 * Otherwise, find the appropriate type conversion function
121 * (caller should have determined that there is one), and generate
122 * an expression tree representing run-time application of the
123 * conversion function.
125 FuncCall *n = makeNode(FuncCall);
127 n->funcname = typeidTypeName(targetTypeId);
128 n->args = makeList1(node);
130 n->agg_distinct = false;
132 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
134 /* safety check that we got the right thing */
135 if (exprType(result) != targetTypeId)
136 elog(ERROR, "coerce_type: conversion function %s produced %s",
137 typeidTypeName(targetTypeId),
138 typeidTypeName(exprType(result)));
141 * If the input is a constant, apply the type conversion function
142 * now instead of delaying to runtime. (We could, of course, just
143 * leave this to be done during planning/optimization; but it's a
144 * very frequent special case, and we save cycles in the rewriter
145 * if we fold the expression now.)
147 * Note that no folding will occur if the conversion function is not
148 * marked 'iscachable'.
150 * HACK: if constant is NULL, don't fold it here. This is needed by
151 * make_subplan(), which calls this routine on placeholder Const
152 * nodes that mustn't be collapsed. (It'd be a lot cleaner to
153 * make a separate node type for that purpose...)
155 if (IsA(node, Const) &&!((Const *) node)->constisnull)
156 result = eval_const_expressions(result);
164 * Can input_typeids be coerced to func_typeids?
166 * There are a few types which are known apriori to be convertible.
167 * We will check for those cases first, and then look for possible
168 * conversion functions.
171 * This uses the same mechanism as the CAST() SQL construct in gram.y.
172 * We should also check the function return type on candidate conversion
173 * routines just to be safe but we do not do that yet...
174 * - thomas 1998-03-31
177 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
182 Oid oid_array[FUNC_MAX_ARGS];
184 /* run through argument list... */
185 for (i = 0; i < nargs; i++)
187 Oid inputTypeId = input_typeids[i];
188 Oid targetTypeId = func_typeids[i];
190 /* no problem if same type */
191 if (inputTypeId == targetTypeId)
195 * one of the known-good transparent conversions? then drop
198 if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
201 /* don't know what to do for the output type? then quit... */
202 if (targetTypeId == InvalidOid)
204 /* don't know what to do for the input type? then quit... */
205 if (inputTypeId == InvalidOid)
209 * If input is an untyped string constant, assume we can convert
210 * it to anything except a class type.
212 if (inputTypeId == UNKNOWNOID)
214 if (ISCOMPLEX(targetTypeId))
220 * If input is a class type that inherits from target, no problem
222 if (typeInheritsFrom(inputTypeId, targetTypeId))
225 /* don't choke on references to no-longer-existing types */
226 if (!typeidIsValid(inputTypeId))
228 if (!typeidIsValid(targetTypeId))
232 * Else, try for explicit conversion using functions: look for a
233 * single-argument function named with the target type name and
234 * accepting the source type.
236 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
237 oid_array[0] = inputTypeId;
239 ftup = SearchSysCache(PROCNAME,
240 PointerGetDatum(typeidTypeName(targetTypeId)),
242 PointerGetDatum(oid_array),
244 if (!HeapTupleIsValid(ftup))
246 /* Make sure the function's result type is as expected, too */
247 pform = (Form_pg_proc) GETSTRUCT(ftup);
248 if (pform->prorettype != targetTypeId)
250 ReleaseSysCache(ftup);
253 ReleaseSysCache(ftup);
259 /* coerce_type_typmod()
260 * Force a value to a particular typmod, if meaningful and possible.
262 * This is applied to values that are going to be stored in a relation
263 * (where we have an atttypmod for the column) as well as values being
264 * explicitly CASTed (where the typmod comes from the target type spec).
266 * The caller must have already ensured that the value is of the correct
267 * type, typically by applying coerce_type.
269 * If the target column type possesses a function named for the type
270 * and having parameter signature (columntype, int4), we assume that
271 * the type requires coercion to its own length and that the said
272 * function should be invoked to do that.
274 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
277 coerce_type_typmod(ParseState *pstate, Node *node,
278 Oid targetTypeId, int32 atttypmod)
281 Oid oid_array[FUNC_MAX_ARGS];
284 * A negative typmod is assumed to mean that no coercion is wanted.
286 if (atttypmod < 0 || 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 = makeList2(node, cons);
309 func->agg_star = false;
310 func->agg_distinct = false;
312 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
319 /* coerce_to_boolean()
320 * Coerce an argument of a construct that requires boolean input
321 * (AND, OR, NOT, etc).
323 * If successful, update *pnode to be the transformed argument (if any
324 * transformation is needed), and return TRUE. If fail, return FALSE.
325 * (The caller must check for FALSE and emit a suitable error message.)
328 coerce_to_boolean(ParseState *pstate, Node **pnode)
330 Oid inputTypeId = exprType(*pnode);
333 if (inputTypeId == BOOLOID)
334 return true; /* no work */
335 targetTypeId = BOOLOID;
336 if (!can_coerce_type(1, &inputTypeId, &targetTypeId))
337 return false; /* fail, but let caller choose error msg */
338 *pnode = coerce_type(pstate, *pnode, inputTypeId, targetTypeId, -1);
343 /* select_common_type()
344 * Determine the common supertype of a list of input expression types.
345 * This is used for determining the output type of CASE and UNION
348 * typeids is a nonempty integer list of type OIDs. Note that earlier items
349 * in the list will be preferred if there is doubt.
350 * 'context' is a phrase to use in the error message if we fail to select
353 * XXX this code is WRONG, since (for example) given the input (int4,int8)
354 * it will select int4, whereas according to SQL92 clause 9.3 the correct
355 * answer is clearly int8. To fix this we need a notion of a promotion
356 * hierarchy within type categories --- something more complete than
357 * just a single preferred type.
360 select_common_type(List *typeids, const char *context)
366 Assert(typeids != NIL);
367 ptype = (Oid) lfirsti(typeids);
368 pcategory = TypeCategory(ptype);
369 foreach(l, lnext(typeids))
371 Oid ntype = (Oid) lfirsti(l);
373 /* move on to next one if no new information... */
374 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
376 if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
378 /* so far, only nulls so take anything... */
380 pcategory = TypeCategory(ptype);
382 else if (TypeCategory(ntype) != pcategory)
385 * both types in different categories? then not much
388 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
389 context, typeidTypeName(ptype), typeidTypeName(ntype));
391 else if (IsPreferredType(pcategory, ntype)
392 && !IsPreferredType(pcategory, ptype)
393 && can_coerce_type(1, &ptype, &ntype))
396 * new one is preferred and can convert? then take it...
399 pcategory = TypeCategory(ptype);
405 * If all the inputs were UNKNOWN type --- ie, unknown-type literals
406 * --- then resolve as type TEXT. This situation comes up with
407 * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
408 * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
409 * the construct's output type as UNKNOWN, but that really doesn't
410 * work, because we'd probably end up needing a runtime coercion from
411 * UNKNOWN to something else, and we usually won't have it. We need
412 * to coerce the unknown literals while they are still literals, so a
413 * decision has to be made now.
415 if (ptype == UNKNOWNOID)
421 /* coerce_to_common_type()
422 * Coerce an expression to the given type.
424 * This is used following select_common_type() to coerce the individual
425 * expressions to the desired type. 'context' is a phrase to use in the
426 * error message if we fail to coerce.
428 * NOTE: pstate may be NULL.
431 coerce_to_common_type(ParseState *pstate, Node *node,
435 Oid inputTypeId = exprType(node);
437 if (inputTypeId == targetTypeId)
438 return node; /* no work */
439 if (can_coerce_type(1, &inputTypeId, &targetTypeId))
440 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1);
443 elog(ERROR, "%s unable to convert to type \"%s\"",
444 context, typeidTypeName(targetTypeId));
451 * Assign a category to the specified OID.
452 * XXX This should be moved to system catalog lookups
453 * to allow for better type extensibility.
454 * - thomas 2001-09-30
457 TypeCategory(Oid inType)
464 result = BOOLEAN_TYPE;
472 result = STRING_TYPE;
477 result = BITSTRING_TYPE;
489 result = NUMERIC_TYPE;
497 case (TIMESTAMPTZOID):
498 result = DATETIME_TYPE;
504 result = TIMESPAN_TYPE;
514 result = GEOMETRIC_TYPE;
519 result = NETWORK_TYPE;
524 result = UNKNOWN_TYPE;
532 } /* TypeCategory() */
536 * Check if this type is a preferred type.
537 * XXX This should be moved to system catalog lookups
538 * to allow for better type extensibility.
539 * - thomas 2001-09-30
542 IsPreferredType(CATEGORY category, Oid type)
544 return (type == PreferredType(category, type));
545 } /* IsPreferredType() */
549 * Return the preferred type OID for the specified category.
550 * XXX This should be moved to system catalog lookups
551 * to allow for better type extensibility.
552 * - thomas 2001-09-30
555 PreferredType(CATEGORY category, Oid type)
569 case (BITSTRING_TYPE):
576 else if (type == NUMERICOID)
582 case (DATETIME_TYPE):
584 result = TIMESTAMPOID;
586 result = TIMESTAMPTZOID;
589 case (TIMESPAN_TYPE):
590 result = INTERVALOID;
597 case (GEOMETRIC_TYPE):
607 } /* PreferredType() */
611 * If the targetTypeId is a domain, we really want to coerce
612 * the tuple to the domain type -- not the domain itself
615 getBaseType(Oid inType)
620 tup = SearchSysCache(TYPEOID,
621 ObjectIdGetDatum(inType),
624 typTup = ((Form_pg_type) GETSTRUCT(tup));
627 * Assume that typbasetype exists and is a base type, where inType
630 if (typTup->typtype == 'd')
631 inType = typTup->typbasetype;
633 ReleaseSysCache(tup);