]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Tweak select_common_type() to deal with possibility of multiple preferred
[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-2000, PostgreSQL, Inc
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.52 2000/12/17 04:32:29 tgl 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                 /*
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.
55                  *
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.
61                  *
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.
66                  */
67                 Const      *con = (Const *) node;
68                 Const      *newcon = makeNode(Const);
69                 Type            targetType = typeidType(targetTypeId);
70
71                 newcon->consttype = targetTypeId;
72                 newcon->constlen = typeLen(targetType);
73                 newcon->constbyval = typeByVal(targetType);
74                 newcon->constisnull = con->constisnull;
75                 newcon->constisset = false;
76
77                 if (!con->constisnull)
78                 {
79                         /* We know the source constant is really of type 'text' */
80                         char       *val = DatumGetCString(DirectFunctionCall1(textout,
81                                                                                                                 con->constvalue));
82
83                         newcon->constvalue = stringTypeDatum(targetType, val, atttypmod);
84                         pfree(val);
85                 }
86
87                 ReleaseSysCache(targetType);
88
89                 result = (Node *) newcon;
90         }
91         else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
92         {
93
94                 /*
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.
98                  */
99                 RelabelType *relabel = makeNode(RelabelType);
100
101                 relabel->arg = node;
102                 relabel->resulttype = targetTypeId;
103
104                 /*
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.
109                  */
110                 relabel->resulttypmod = -1;
111
112                 result = (Node *) relabel;
113         }
114         else if (typeInheritsFrom(inputTypeId, targetTypeId))
115         {
116                 /* Input class type is a subclass of target, so nothing to do */
117                 result = node;
118         }
119         else
120         {
121
122                 /*
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.
127                  */
128                 FuncCall   *n = makeNode(FuncCall);
129
130                 n->funcname = typeidTypeName(targetTypeId);
131                 n->args = lcons(node, NIL);
132                 n->agg_star = false;
133                 n->agg_distinct = false;
134
135                 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
136
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)));
142
143                 /*
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.)
149                  *
150                  * Note that no folding will occur if the conversion function is not
151                  * marked 'iscachable'.
152                  *
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...)
157                  */
158                 if (IsA(node, Const) &&!((Const *) node)->constisnull)
159                         result = eval_const_expressions(result);
160         }
161
162         return result;
163 }
164
165
166 /* can_coerce_type()
167  * Can input_typeids be coerced to func_typeids?
168  *
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.
172  *
173  * Notes:
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
178  */
179 bool
180 can_coerce_type(int nargs, Oid *input_typeids, Oid *func_typeids)
181 {
182         int                     i;
183         HeapTuple       ftup;
184         Form_pg_proc pform;
185         Oid                     oid_array[FUNC_MAX_ARGS];
186
187         /* run through argument list... */
188         for (i = 0; i < nargs; i++)
189         {
190                 Oid                     inputTypeId = input_typeids[i];
191                 Oid                     targetTypeId = func_typeids[i];
192
193                 /* no problem if same type */
194                 if (inputTypeId == targetTypeId)
195                         continue;
196
197                 /*
198                  * one of the known-good transparent conversions? then drop
199                  * through...
200                  */
201                 if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
202                         continue;
203
204                 /* don't know what to do for the output type? then quit... */
205                 if (targetTypeId == InvalidOid)
206                         return false;
207                 /* don't know what to do for the input type? then quit... */
208                 if (inputTypeId == InvalidOid)
209                         return false;
210
211                 /*
212                  * If input is an untyped string constant, assume we can convert
213                  * it to anything except a class type.
214                  */
215                 if (inputTypeId == UNKNOWNOID)
216                 {
217                         if (ISCOMPLEX(targetTypeId))
218                                 return false;
219                         continue;
220                 }
221
222                 /*
223                  * If input is a class type that inherits from target, no problem
224                  */
225                 if (typeInheritsFrom(inputTypeId, targetTypeId))
226                         continue;
227
228                 /*
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.
232                  */
233                 MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
234                 oid_array[0] = inputTypeId;
235
236                 ftup = SearchSysCache(PROCNAME,
237                                                           PointerGetDatum(typeidTypeName(targetTypeId)),
238                                                           Int32GetDatum(1),
239                                                           PointerGetDatum(oid_array),
240                                                           0);
241                 if (!HeapTupleIsValid(ftup))
242                         return false;
243                 /* Make sure the function's result type is as expected, too */
244                 pform = (Form_pg_proc) GETSTRUCT(ftup);
245                 if (pform->prorettype != targetTypeId)
246                 {
247                         ReleaseSysCache(ftup);
248                         return false;
249                 }
250                 ReleaseSysCache(ftup);
251         }
252
253         return true;
254 }
255
256 /* coerce_type_typmod()
257  * Force a value to a particular typmod, if meaningful and possible.
258  *
259  * This is applied to values that are going to be stored in a relation
260  * (where we have an atttypmod for the column) as well as values being
261  * explicitly CASTed (where the typmod comes from the target type spec).
262  *
263  * The caller must have already ensured that the value is of the correct
264  * type, typically by applying coerce_type.
265  *
266  * If the target column type possesses a function named for the type
267  * and having parameter signature (columntype, int4), we assume that
268  * the type requires coercion to its own length and that the said
269  * function should be invoked to do that.
270  *
271  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
272  */
273 Node *
274 coerce_type_typmod(ParseState *pstate, Node *node,
275                                    Oid targetTypeId, int32 atttypmod)
276 {
277         char       *funcname;
278         Oid                     oid_array[FUNC_MAX_ARGS];
279
280         /*
281          * We assume that only typmod values greater than 0 indicate a forced
282          * conversion is necessary.
283          */
284         if (atttypmod <= 0 ||
285                 atttypmod == exprTypmod(node))
286                 return node;
287
288         funcname = typeidTypeName(targetTypeId);
289         MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
290         oid_array[0] = targetTypeId;
291         oid_array[1] = INT4OID;
292
293         /* attempt to find with arguments exactly as specified... */
294         if (SearchSysCacheExists(PROCNAME,
295                                                          PointerGetDatum(funcname),
296                                                          Int32GetDatum(2),
297                                                          PointerGetDatum(oid_array),
298                                                          0))
299         {
300                 A_Const    *cons = makeNode(A_Const);
301                 FuncCall   *func = makeNode(FuncCall);
302
303                 cons->val.type = T_Integer;
304                 cons->val.val.ival = atttypmod;
305
306                 func->funcname = funcname;
307                 func->args = lappend(lcons(node, NIL), cons);
308                 func->agg_star = false;
309                 func->agg_distinct = false;
310
311                 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
312         }
313
314         return node;
315 }
316
317
318 /* select_common_type()
319  *              Determine the common supertype of a list of input expression types.
320  *              This is used for determining the output type of CASE and UNION
321  *              constructs.
322  *
323  * typeids is a nonempty integer list of type OIDs.  Note that earlier items
324  * in the list will be preferred if there is doubt.
325  * 'context' is a phrase to use in the error message if we fail to select
326  * a usable type.
327  *
328  * XXX this code is WRONG, since (for example) given the input (int4,int8)
329  * it will select int4, whereas according to SQL92 clause 9.3 the correct
330  * answer is clearly int8.  To fix this we need a notion of a promotion
331  * hierarchy within type categories --- something more complete than
332  * just a single preferred type.
333  */
334 Oid
335 select_common_type(List *typeids, const char *context)
336 {
337         Oid                     ptype;
338         CATEGORY        pcategory;
339         List       *l;
340
341         Assert(typeids != NIL);
342         ptype = (Oid) lfirsti(typeids);
343         pcategory = TypeCategory(ptype);
344         foreach(l, lnext(typeids))
345         {
346                 Oid             ntype = (Oid) lfirsti(l);
347
348                 /* move on to next one if no new information... */
349                 if (ntype && (ntype != UNKNOWNOID) && (ntype != ptype))
350                 {
351                         if (!ptype || ptype == UNKNOWNOID)
352                         {
353                                 /* so far, only nulls so take anything... */
354                                 ptype = ntype;
355                                 pcategory = TypeCategory(ptype);
356                         }
357                         else if (TypeCategory(ntype) != pcategory)
358                         {
359                                 /*
360                                  * both types in different categories? then
361                                  * not much hope...
362                                  */
363                                 elog(ERROR, "%s types \"%s\" and \"%s\" not matched",
364                                          context, typeidTypeName(ptype), typeidTypeName(ntype));
365                         }
366                         else if (IsPreferredType(pcategory, ntype)
367                                          && !IsPreferredType(pcategory, ptype)
368                                          && can_coerce_type(1, &ptype, &ntype))
369                         {
370                                 /*
371                                  * new one is preferred and can convert? then
372                                  * take it...
373                                  */
374                                 ptype = ntype;
375                                 pcategory = TypeCategory(ptype);
376                         }
377                 }
378         }
379
380         /*
381          * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
382          * then resolve as type TEXT.  This situation comes up with constructs
383          * like
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.
391          */
392         if (ptype == UNKNOWNOID)
393                 ptype = TEXTOID;
394
395         return ptype;
396 }
397
398 /* coerce_to_common_type()
399  *              Coerce an expression to the given type.
400  *
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.
404  *
405  * NOTE: pstate may be NULL.
406  */
407 Node *
408 coerce_to_common_type(ParseState *pstate, Node *node,
409                                           Oid targetTypeId,
410                                           const char *context)
411 {
412         Oid                     inputTypeId = exprType(node);
413
414         if (inputTypeId == targetTypeId)
415                 return node;                    /* no work */
416         if (can_coerce_type(1, &inputTypeId, &targetTypeId))
417         {
418                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1);
419         }
420         else
421         {
422                 elog(ERROR, "%s unable to convert to type \"%s\"",
423                          context, typeidTypeName(targetTypeId));
424         }
425         return node;
426 }
427
428
429 /* TypeCategory()
430  * Assign a category to the specified OID.
431  */
432 CATEGORY
433 TypeCategory(Oid inType)
434 {
435         CATEGORY        result;
436
437         switch (inType)
438         {
439                 case (BOOLOID):
440                         result = BOOLEAN_TYPE;
441                         break;
442
443                 case (CHAROID):
444                 case (NAMEOID):
445                 case (BPCHAROID):
446                 case (VARCHAROID):
447                 case (TEXTOID):
448                         result = STRING_TYPE;
449                         break;
450
451                 case (ZPBITOID):
452                 case (VARBITOID):
453                         result = BITSTRING_TYPE;
454                         break;
455
456                 case (OIDOID):
457                 case (REGPROCOID):
458                 case (INT2OID):
459                 case (INT4OID):
460                 case (INT8OID):
461                 case (FLOAT4OID):
462                 case (FLOAT8OID):
463                 case (NUMERICOID):
464                 case (CASHOID):
465                         result = NUMERIC_TYPE;
466                         break;
467
468                 case (DATEOID):
469                 case (TIMEOID):
470                 case (TIMETZOID):
471                 case (ABSTIMEOID):
472                 case (TIMESTAMPOID):
473                         result = DATETIME_TYPE;
474                         break;
475
476                 case (RELTIMEOID):
477                 case (TINTERVALOID):
478                 case (INTERVALOID):
479                         result = TIMESPAN_TYPE;
480                         break;
481
482                 case (POINTOID):
483                 case (LSEGOID):
484                 case (PATHOID):
485                 case (BOXOID):
486                 case (POLYGONOID):
487                 case (LINEOID):
488                 case (CIRCLEOID):
489                         result = GEOMETRIC_TYPE;
490                         break;
491
492                 case (INETOID):
493                 case (CIDROID):
494                         result = NETWORK_TYPE;
495                         break;
496
497                 case (UNKNOWNOID):
498                 case (InvalidOid):
499                         result = UNKNOWN_TYPE;
500                         break;
501
502                 default:
503                         result = USER_TYPE;
504                         break;
505         }
506         return result;
507 }       /* TypeCategory() */
508
509
510 /* IsPreferredType()
511  * Check if this type is a preferred type.
512  */
513 bool
514 IsPreferredType(CATEGORY category, Oid type)
515 {
516         return type == PreferredType(category, type);
517 }       /* IsPreferredType() */
518
519
520 /* PreferredType()
521  * Return the preferred type OID for the specified category.
522  */
523 static Oid
524 PreferredType(CATEGORY category, Oid type)
525 {
526         Oid                     result;
527
528         switch (category)
529         {
530                 case (BOOLEAN_TYPE):
531                         result = BOOLOID;
532                         break;
533
534                 case (STRING_TYPE):
535                         result = TEXTOID;
536                         break;
537
538                 case (BITSTRING_TYPE):
539                         result = VARBITOID;
540                         break;
541
542                 case (NUMERIC_TYPE):
543                         if (type == OIDOID)
544                                 result = OIDOID;
545                         else if (type == NUMERICOID)
546                                 result = NUMERICOID;
547                         else
548                                 result = FLOAT8OID;
549                         break;
550
551                 case (DATETIME_TYPE):
552                         result = TIMESTAMPOID;
553                         break;
554
555                 case (TIMESPAN_TYPE):
556                         result = INTERVALOID;
557                         break;
558
559                 case (NETWORK_TYPE):
560                         result = INETOID;
561                         break;
562
563                 case (GEOMETRIC_TYPE):
564                 case (USER_TYPE):
565                         result = type;
566                         break;
567
568                 default:
569                         result = UNKNOWNOID;
570                         break;
571         }
572         return result;
573 }       /* PreferredType() */
574
575
576 #ifdef NOT_USED
577 Oid
578 PromoteTypeToNext(Oid inType)
579 {
580         Oid                     result;
581
582         switch (inType)
583         {
584                 case (CHAROID):
585                 case (BPCHAROID):
586                         result = VARCHAROID;
587                         break;
588
589                 case (VARCHAROID):
590                         result = TEXTOID;
591                         break;
592
593                 case (INT2OID):
594                 case (CASHOID):
595                         result = INT4OID;
596                         break;
597
598                 case (INT4OID):
599                 case (INT8OID):
600                 case (FLOAT4OID):
601                         result = FLOAT8OID;
602                         break;
603
604                 case (NUMERICOID):
605                         result = NUMERICOID;
606                         break;
607
608                 case (DATEOID):
609                 case (ABSTIMEOID):
610                         result = TIMESTAMPOID;
611                         break;
612
613                 case (TIMEOID):
614                 case (RELTIMEOID):
615                         result = INTERVALOID;
616                         break;
617
618                 case (BOOLOID):
619                 case (TEXTOID):
620                 case (FLOAT8OID):
621                 case (TIMESTAMPOID):
622                 case (INTERVALOID):
623                 default:
624                         result = inType;
625                         break;
626         }
627         return result;
628 }       /* PromoteTypeToNext() */
629
630
631 Oid
632 DemoteType(Oid inType)
633 {
634         Oid                     result;
635
636         switch (inType)
637         {
638                 case (FLOAT4OID):
639                 case (FLOAT8OID):
640                         result = INT4OID;
641                         break;
642
643                 default:
644                         result = inType;
645                         break;
646         }
647         return result;
648 }       /* DemoteType() */
649
650
651 Oid
652 PromoteLesserType(Oid inType1, Oid inType2, Oid *newType1, Oid *newType2)
653 {
654         Oid                     result;
655
656         if (inType1 == inType2)
657         {
658                 result = PromoteTypeToNext(inType1);
659                 inType1 = result;
660                 *arg2 = result;
661                 return result;
662         }
663
664         kind1 = ClassifyType(inType1);
665         kind2 = ClassifyType(*arg2);
666         if (kind1 != kind2)
667         {
668                 *newType1 = inType1;
669                 *newType2 = inType2;
670                 result = InvalidOid;
671         }
672
673         isBuiltIn1 = IS_BUILTIN_TYPE(inType1);
674         isBuiltIn2 = IS_BUILTIN_TYPE(*arg2);
675
676         if (isBuiltIn1 && isBuiltIn2)
677         {
678                 switch (*arg1)
679                 {
680                         case (CHAROID):
681                                 switch (*arg2)
682                                 {
683                                         case (BPCHAROID):
684                                         case (VARCHAROID):
685                                         case (TEXTOID):
686
687                                         case (INT2OID):
688                                         case (INT4OID):
689                                         case (FLOAT4OID):
690                                         case (FLOAT8OID):
691                                         case (CASHOID):
692
693                                         case (POINTOID):
694                                         case (LSEGOID):
695                                         case (LINEOID):
696                                         case (BOXOID):
697                                         case (PATHOID):
698                                         case (CIRCLEOID):
699                                         case (POLYGONOID):
700
701                                         case (InvalidOid):
702                                         case (UNKNOWNOID):
703                                         case (BOOLOID):
704                                         default:
705                                                 *arg1 = InvalidOid;
706                                                 *arg2 = InvalidOid;
707                                                 result = InvalidOid;
708                                 }
709                 }
710         }
711         else if (isBuiltIn1 && !isBuiltIn2)
712         {
713                 if ((promotedType = PromoteBuiltInType(*arg1)) != *arg1)
714                 {
715                         *arg1 = promotedType;
716                         return promotedType;
717                 }
718                 else if (CanCoerceType(*arg1, *arg2))
719                 {
720                         *arg1 = *arg2;
721                         return *arg2;
722                 }
723         }
724         else if (!isBuiltIn1 && isBuiltIn2)
725         {
726                 if ((promotedType = PromoteBuiltInType(*arg2)) != *arg2)
727                 {
728                         *arg2 = promotedType;
729                         return promotedType;
730                 }
731                 else if (CanCoerceType(*arg2, *arg1))
732                 {
733                         *arg2 = *arg1;
734                         return *arg1;
735                 }
736         }
737
738
739         if (*arg2 == InvalidOid)
740                 return InvalidOid;
741
742         switch (*arg1)
743         {
744                 case (CHAROID):
745                         switch (*arg2)
746                         {
747                                 case (BPCHAROID):
748                                 case (VARCHAROID):
749                                 case (TEXTOID):
750
751                                 case (INT2OID):
752                                 case (INT4OID):
753                                 case (FLOAT4OID):
754                                 case (FLOAT8OID):
755                                 case (CASHOID):
756
757                                 case (POINTOID):
758                                 case (LSEGOID):
759                                 case (LINEOID):
760                                 case (BOXOID):
761                                 case (PATHOID):
762                                 case (CIRCLEOID):
763                                 case (POLYGONOID):
764
765                                 case (InvalidOid):
766                                 case (UNKNOWNOID):
767                                 case (BOOLOID):
768                                 default:
769                                         *arg1 = InvalidOid;
770                                         *arg2 = InvalidOid;
771                                         result = InvalidOid;
772                         }
773         }
774 }
775
776 #endif