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.46 2000/07/30 22:13:50 tgl 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 result = (Node *) newcon;
89 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 */
121 * Otherwise, find the appropriate type conversion function
122 * (caller should have determined that there is one), and generate
123 * an expression tree representing run-time application of the
124 * conversion function.
126 FuncCall *n = makeNode(FuncCall);
127 Type targetType = typeidType(targetTypeId);
129 n->funcname = typeTypeName(targetType);
130 n->args = lcons(node, NIL);
132 n->agg_distinct = false;
134 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
136 /* safety check that we got the right thing */
137 if (exprType(result) != targetTypeId)
138 elog(ERROR, "coerce_type: conversion function %s produced %s",
139 typeTypeName(targetType),
140 typeidTypeName(exprType(result)));
143 * If the input is a constant, apply the type conversion function
144 * now instead of delaying to runtime. (We could, of course, just
145 * leave this to be done during planning/optimization; but it's a
146 * very frequent special case, and we save cycles in the rewriter
147 * if we fold the expression now.)
149 * Note that no folding will occur if the conversion function is not
150 * marked 'iscachable'.
152 * HACK: if constant is NULL, don't fold it here. This is needed by
153 * make_subplan(), which calls this routine on placeholder Const
154 * nodes that mustn't be collapsed. (It'd be a lot cleaner to
155 * make a separate node type for that purpose...)
157 if (IsA(node, Const) &&!((Const *) node)->constisnull)
158 result = eval_const_expressions(result);
166 * Can input_typeids be coerced to func_typeids?
168 * There are a few types which are known apriori to be convertible.
169 * We will check for those cases first, and then look for possible
170 * conversion functions.
173 * This uses the same mechanism as the CAST() SQL construct in gram.y.
174 * We should also check the function return type on candidate conversion
175 * routines just to be safe but we do not do that yet...
176 * We need to have a zero-filled OID array here, otherwise the cache lookup fails.
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))
229 * Else, try for explicit conversion using functions: look for a
230 * single-argument function named with the target type name and
231 * accepting the source type.
233 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
234 oid_array[0] = inputTypeId;
236 ftup = SearchSysCacheTuple(PROCNAME,
237 PointerGetDatum(typeidTypeName(targetTypeId)),
239 PointerGetDatum(oid_array),
241 if (!HeapTupleIsValid(ftup))
243 /* Make sure the function's result type is as expected, too */
244 pform = (Form_pg_proc) GETSTRUCT(ftup);
245 if (pform->prorettype != targetTypeId)
252 /* coerce_type_typmod()
253 * Force a value to a particular typmod, if meaningful and possible.
255 * This is applied to values that are going to be stored in a relation
256 * (where we have an atttypmod for the column) as well as values being
257 * explicitly CASTed (where the typmod comes from the target type spec).
259 * The caller must have already ensured that the value is of the correct
260 * type, typically by applying coerce_type.
262 * If the target column type possesses a function named for the type
263 * and having parameter signature (columntype, int4), we assume that
264 * the type requires coercion to its own length and that the said
265 * function should be invoked to do that.
267 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
270 coerce_type_typmod(ParseState *pstate, Node *node,
271 Oid targetTypeId, int32 atttypmod)
274 Oid oid_array[FUNC_MAX_ARGS];
278 * We assume that only typmod values greater than 0 indicate a forced
279 * conversion is necessary.
281 if (atttypmod <= 0 ||
282 atttypmod == exprTypmod(node))
285 funcname = typeidTypeName(targetTypeId);
286 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
287 oid_array[0] = targetTypeId;
288 oid_array[1] = INT4OID;
290 /* attempt to find with arguments exactly as specified... */
291 ftup = SearchSysCacheTuple(PROCNAME,
292 PointerGetDatum(funcname),
294 PointerGetDatum(oid_array),
297 if (HeapTupleIsValid(ftup))
299 A_Const *cons = makeNode(A_Const);
300 FuncCall *func = makeNode(FuncCall);
302 cons->val.type = T_Integer;
303 cons->val.val.ival = atttypmod;
305 func->funcname = funcname;
306 func->args = lappend(lcons(node, NIL), cons);
307 func->agg_star = false;
308 func->agg_distinct = false;
310 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
318 * Assign a category to the specified OID.
321 TypeCategory(Oid inType)
328 result = BOOLEAN_TYPE;
336 result = STRING_TYPE;
340 * Kluge added 4/8/00 by tgl: treat the new BIT types as
341 * strings, so that 'unknown' || 'unknown' continues to
342 * resolve as textcat rather than generating an
343 * ambiguous-operator error. Probably BIT types should have
344 * their own type category, or maybe they should be numeric?
345 * Need a better way of handling unknown types first.
349 result = STRING_TYPE;
361 result = NUMERIC_TYPE;
369 result = DATETIME_TYPE;
375 result = TIMESPAN_TYPE;
385 result = GEOMETRIC_TYPE;
390 result = NETWORK_TYPE;
395 result = UNKNOWN_TYPE;
403 } /* TypeCategory() */
407 * Check if this type is a preferred type.
410 IsPreferredType(CATEGORY category, Oid type)
412 return type == PreferredType(category, type);
413 } /* IsPreferredType() */
417 * Return the preferred type OID for the specified category.
420 PreferredType(CATEGORY category, Oid type)
437 else if (type == NUMERICOID)
443 case (DATETIME_TYPE):
444 result = TIMESTAMPOID;
447 case (TIMESPAN_TYPE):
448 result = INTERVALOID;
455 case (GEOMETRIC_TYPE):
465 } /* PreferredType() */
470 PromoteTypeToNext(Oid inType)
502 result = TIMESTAMPOID;
507 result = INTERVALOID;
520 } /* PromoteTypeToNext() */
524 DemoteType(Oid inType)
544 PromoteLesserType(Oid inType1, Oid inType2, Oid *newType1, Oid *newType2)
548 if (inType1 == inType2)
550 result = PromoteTypeToNext(inType1);
556 kind1 = ClassifyType(inType1);
557 kind2 = ClassifyType(*arg2);
565 isBuiltIn1 = IS_BUILTIN_TYPE(inType1);
566 isBuiltIn2 = IS_BUILTIN_TYPE(*arg2);
568 if (isBuiltIn1 && isBuiltIn2)
603 else if (isBuiltIn1 && !isBuiltIn2)
605 if ((promotedType = PromoteBuiltInType(*arg1)) != *arg1)
607 *arg1 = promotedType;
610 else if (CanCoerceType(*arg1, *arg2))
616 else if (!isBuiltIn1 && isBuiltIn2)
618 if ((promotedType = PromoteBuiltInType(*arg2)) != *arg2)
620 *arg2 = promotedType;
623 else if (CanCoerceType(*arg2, *arg1))
631 if (*arg2 == InvalidOid)