]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Add DOMAIN support. Includes manual pages and regression tests, from
[postgresql] / src / backend / parser / parse_coerce.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_coerce.c
4  *              handle type coercions/conversions for parser
5  *
6  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/parser/parse_coerce.c,v 2.67 2002/03/19 02:18:20 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
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"
25
26 Oid                     DemoteType(Oid inType);
27 Oid                     PromoteTypeToNext(Oid inType);
28
29 static Oid      PreferredType(CATEGORY category, Oid type);
30
31
32 /* coerce_type()
33  * Convert a function argument to a different type.
34  */
35 Node *
36 coerce_type(ParseState *pstate, Node *node, Oid inputTypeId,
37                         Oid targetTypeId, int32 atttypmod)
38 {
39         Node       *result;
40
41         if (targetTypeId == inputTypeId ||
42                 targetTypeId == InvalidOid ||
43                 node == NULL)
44         {
45                 /* no conversion needed */
46                 result = node;
47         }
48         else if (inputTypeId == UNKNOWNOID && IsA(node, Const))
49         {
50                 /*
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.
54                  *
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.
60                  *
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.
65                  */
66                 Const      *con = (Const *) node;
67                 Const      *newcon = makeNode(Const);
68                 Type            targetType = typeidType(targetTypeId);
69
70                 newcon->consttype = targetTypeId;
71                 newcon->constlen = typeLen(targetType);
72                 newcon->constbyval = typeByVal(targetType);
73                 newcon->constisnull = con->constisnull;
74                 newcon->constisset = false;
75
76                 if (!con->constisnull)
77                 {
78                         /* We know the source constant is really of type 'text' */
79                         char       *val = DatumGetCString(DirectFunctionCall1(textout,
80                                                                                                            con->constvalue));
81
82                         newcon->constvalue = stringTypeDatum(targetType, val, atttypmod);
83                         pfree(val);
84                 }
85
86                 ReleaseSysCache(targetType);
87
88                 result = (Node *) newcon;
89         }
90         else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
91         {
92                 /*
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.
96                  */
97                 RelabelType *relabel = makeNode(RelabelType);
98
99                 relabel->arg = node;
100                 relabel->resulttype = targetTypeId;
101
102                 /*
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.
107                  */
108                 relabel->resulttypmod = -1;
109
110                 result = (Node *) relabel;
111         }
112         else if (typeInheritsFrom(inputTypeId, targetTypeId))
113         {
114                 /* Input class type is a subclass of target, so nothing to do */
115                 result = node;
116         }
117         else
118         {
119                 /*
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.
124                  */
125                 FuncCall   *n = makeNode(FuncCall);
126
127                 n->funcname = typeidTypeName(targetTypeId);
128                 n->args = makeList1(node);
129                 n->agg_star = false;
130                 n->agg_distinct = false;
131
132                 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
133
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)));
139
140                 /*
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.)
146                  *
147                  * Note that no folding will occur if the conversion function is not
148                  * marked 'iscachable'.
149                  *
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...)
154                  */
155                 if (IsA(node, Const) &&!((Const *) node)->constisnull)
156                         result = eval_const_expressions(result);
157         }
158
159         return result;
160 }
161
162
163 /* can_coerce_type()
164  * Can input_typeids be coerced to func_typeids?
165  *
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.
169  *
170  * Notes:
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
175  */
176 bool
177 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
178 {
179         int                     i;
180         HeapTuple       ftup;
181         Form_pg_proc pform;
182         Oid                     oid_array[FUNC_MAX_ARGS];
183
184         /* run through argument list... */
185         for (i = 0; i < nargs; i++)
186         {
187                 Oid                     inputTypeId = input_typeids[i];
188                 Oid                     targetTypeId = func_typeids[i];
189
190                 /* no problem if same type */
191                 if (inputTypeId == targetTypeId)
192                         continue;
193
194                 /*
195                  * one of the known-good transparent conversions? then drop
196                  * through...
197                  */
198                 if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
199                         continue;
200
201                 /* don't know what to do for the output type? then quit... */
202                 if (targetTypeId == InvalidOid)
203                         return false;
204                 /* don't know what to do for the input type? then quit... */
205                 if (inputTypeId == InvalidOid)
206                         return false;
207
208                 /*
209                  * If input is an untyped string constant, assume we can convert
210                  * it to anything except a class type.
211                  */
212                 if (inputTypeId == UNKNOWNOID)
213                 {
214                         if (ISCOMPLEX(targetTypeId))
215                                 return false;
216                         continue;
217                 }
218
219                 /*
220                  * If input is a class type that inherits from target, no problem
221                  */
222                 if (typeInheritsFrom(inputTypeId, targetTypeId))
223                         continue;
224
225                 /* don't choke on references to no-longer-existing types */
226                 if (!typeidIsValid(inputTypeId))
227                         return false;
228                 if (!typeidIsValid(targetTypeId))
229                         return false;
230
231                 /*
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.
235                  */
236                 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
237                 oid_array[0] = inputTypeId;
238
239                 ftup = SearchSysCache(PROCNAME,
240                                                    PointerGetDatum(typeidTypeName(targetTypeId)),
241                                                           Int32GetDatum(1),
242                                                           PointerGetDatum(oid_array),
243                                                           0);
244                 if (!HeapTupleIsValid(ftup))
245                         return false;
246                 /* Make sure the function's result type is as expected, too */
247                 pform = (Form_pg_proc) GETSTRUCT(ftup);
248                 if (pform->prorettype != targetTypeId)
249                 {
250                         ReleaseSysCache(ftup);
251                         return false;
252                 }
253                 ReleaseSysCache(ftup);
254         }
255
256         return true;
257 }
258
259 /* coerce_type_typmod()
260  * Force a value to a particular typmod, if meaningful and possible.
261  *
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).
265  *
266  * The caller must have already ensured that the value is of the correct
267  * type, typically by applying coerce_type.
268  *
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.
273  *
274  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
275  */
276 Node *
277 coerce_type_typmod(ParseState *pstate, Node *node,
278                                    Oid targetTypeId, int32 atttypmod)
279 {
280         char       *funcname;
281         Oid                     oid_array[FUNC_MAX_ARGS];
282
283         /*
284          * A negative typmod is assumed to mean that no coercion is wanted.
285          */
286         if (atttypmod < 0 || atttypmod == exprTypmod(node))
287                 return node;
288
289         funcname = typeidTypeName(targetTypeId);
290         MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
291         oid_array[0] = targetTypeId;
292         oid_array[1] = INT4OID;
293
294         /* attempt to find with arguments exactly as specified... */
295         if (SearchSysCacheExists(PROCNAME,
296                                                          PointerGetDatum(funcname),
297                                                          Int32GetDatum(2),
298                                                          PointerGetDatum(oid_array),
299                                                          0))
300         {
301                 A_Const    *cons = makeNode(A_Const);
302                 FuncCall   *func = makeNode(FuncCall);
303
304                 cons->val.type = T_Integer;
305                 cons->val.val.ival = atttypmod;
306
307                 func->funcname = funcname;
308                 func->args = makeList2(node, cons);
309                 func->agg_star = false;
310                 func->agg_distinct = false;
311
312                 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
313         }
314
315         return node;
316 }
317
318
319 /* coerce_to_boolean()
320  *              Coerce an argument of a construct that requires boolean input
321  *              (AND, OR, NOT, etc).
322  *
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.)
326  */
327 bool
328 coerce_to_boolean(ParseState *pstate, Node **pnode)
329 {
330         Oid                     inputTypeId = exprType(*pnode);
331         Oid                     targetTypeId;
332
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);
339         return true;
340 }
341
342
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
346  *              constructs.
347  *
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
351  * a usable type.
352  *
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.
358  */
359 Oid
360 select_common_type(List *typeids, const char *context)
361 {
362         Oid                     ptype;
363         CATEGORY        pcategory;
364         List       *l;
365
366         Assert(typeids != NIL);
367         ptype = (Oid) lfirsti(typeids);
368         pcategory = TypeCategory(ptype);
369         foreach(l, lnext(typeids))
370         {
371                 Oid                     ntype = (Oid) lfirsti(l);
372
373                 /* move on to next one if no new information... */
374                 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
375                 {
376                         if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
377                         {
378                                 /* so far, only nulls so take anything... */
379                                 ptype = ntype;
380                                 pcategory = TypeCategory(ptype);
381                         }
382                         else if (TypeCategory(ntype) != pcategory)
383                         {
384                                 /*
385                                  * both types in different categories? then not much
386                                  * hope...
387                                  */
388                                 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
389                                   context, typeidTypeName(ptype), typeidTypeName(ntype));
390                         }
391                         else if (IsPreferredType(pcategory, ntype)
392                                          && !IsPreferredType(pcategory, ptype)
393                                          && can_coerce_type(1, &ptype, &ntype))
394                         {
395                                 /*
396                                  * new one is preferred and can convert? then take it...
397                                  */
398                                 ptype = ntype;
399                                 pcategory = TypeCategory(ptype);
400                         }
401                 }
402         }
403
404         /*
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.
414          */
415         if (ptype == UNKNOWNOID)
416                 ptype = TEXTOID;
417
418         return ptype;
419 }
420
421 /* coerce_to_common_type()
422  *              Coerce an expression to the given type.
423  *
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.
427  *
428  * NOTE: pstate may be NULL.
429  */
430 Node *
431 coerce_to_common_type(ParseState *pstate, Node *node,
432                                           Oid targetTypeId,
433                                           const char *context)
434 {
435         Oid                     inputTypeId = exprType(node);
436
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);
441         else
442         {
443                 elog(ERROR, "%s unable to convert to type \"%s\"",
444                          context, typeidTypeName(targetTypeId));
445         }
446         return node;
447 }
448
449
450 /* TypeCategory()
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
455  */
456 CATEGORY
457 TypeCategory(Oid inType)
458 {
459         CATEGORY        result;
460
461         switch (inType)
462         {
463                 case (BOOLOID):
464                         result = BOOLEAN_TYPE;
465                         break;
466
467                 case (CHAROID):
468                 case (NAMEOID):
469                 case (BPCHAROID):
470                 case (VARCHAROID):
471                 case (TEXTOID):
472                         result = STRING_TYPE;
473                         break;
474
475                 case (BITOID):
476                 case (VARBITOID):
477                         result = BITSTRING_TYPE;
478                         break;
479
480                 case (OIDOID):
481                 case (REGPROCOID):
482                 case (INT2OID):
483                 case (INT4OID):
484                 case (INT8OID):
485                 case (FLOAT4OID):
486                 case (FLOAT8OID):
487                 case (NUMERICOID):
488                 case (CASHOID):
489                         result = NUMERIC_TYPE;
490                         break;
491
492                 case (DATEOID):
493                 case (TIMEOID):
494                 case (TIMETZOID):
495                 case (ABSTIMEOID):
496                 case (TIMESTAMPOID):
497                 case (TIMESTAMPTZOID):
498                         result = DATETIME_TYPE;
499                         break;
500
501                 case (RELTIMEOID):
502                 case (TINTERVALOID):
503                 case (INTERVALOID):
504                         result = TIMESPAN_TYPE;
505                         break;
506
507                 case (POINTOID):
508                 case (LSEGOID):
509                 case (PATHOID):
510                 case (BOXOID):
511                 case (POLYGONOID):
512                 case (LINEOID):
513                 case (CIRCLEOID):
514                         result = GEOMETRIC_TYPE;
515                         break;
516
517                 case (INETOID):
518                 case (CIDROID):
519                         result = NETWORK_TYPE;
520                         break;
521
522                 case (UNKNOWNOID):
523                 case (InvalidOid):
524                         result = UNKNOWN_TYPE;
525                         break;
526
527                 default:
528                         result = USER_TYPE;
529                         break;
530         }
531         return result;
532 }       /* TypeCategory() */
533
534
535 /* IsPreferredType()
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
540  */
541 bool
542 IsPreferredType(CATEGORY category, Oid type)
543 {
544         return (type == PreferredType(category, type));
545 }       /* IsPreferredType() */
546
547
548 /* PreferredType()
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
553  */
554 static Oid
555 PreferredType(CATEGORY category, Oid type)
556 {
557         Oid                     result;
558
559         switch (category)
560         {
561                 case (BOOLEAN_TYPE):
562                         result = BOOLOID;
563                         break;
564
565                 case (STRING_TYPE):
566                         result = TEXTOID;
567                         break;
568
569                 case (BITSTRING_TYPE):
570                         result = VARBITOID;
571                         break;
572
573                 case (NUMERIC_TYPE):
574                         if (type == OIDOID)
575                                 result = OIDOID;
576                         else if (type == NUMERICOID)
577                                 result = NUMERICOID;
578                         else
579                                 result = FLOAT8OID;
580                         break;
581
582                 case (DATETIME_TYPE):
583                         if (type == DATEOID)
584                                 result = TIMESTAMPOID;
585                         else
586                                 result = TIMESTAMPTZOID;
587                         break;
588
589                 case (TIMESPAN_TYPE):
590                         result = INTERVALOID;
591                         break;
592
593                 case (NETWORK_TYPE):
594                         result = INETOID;
595                         break;
596
597                 case (GEOMETRIC_TYPE):
598                 case (USER_TYPE):
599                         result = type;
600                         break;
601
602                 default:
603                         result = UNKNOWNOID;
604                         break;
605         }
606         return result;
607 }       /* PreferredType() */
608
609
610 /*
611  * If the targetTypeId is a domain, we really want to coerce
612  * the tuple to the domain type -- not the domain itself
613  */
614 Oid
615 getBaseType(Oid inType)
616 {
617         HeapTuple       tup;
618         Form_pg_type typTup;
619
620         tup = SearchSysCache(TYPEOID,
621                                                  ObjectIdGetDatum(inType),
622                                                  0, 0, 0);
623
624         typTup = ((Form_pg_type) GETSTRUCT(tup));
625
626         /*
627          * Assume that typbasetype exists and is a base type, where inType
628          * was a domain
629          */
630         if (typTup->typtype == 'd')
631                 inType = typTup->typbasetype;
632
633         ReleaseSysCache(tup);
634
635         return inType;
636 }