]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Type lztext is toast.
[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.46 2000/07/30 22:13:50 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                 result = (Node *) newcon;
88         }
89         else if (IS_BINARY_COMPATIBLE(inputTypeId, targetTypeId))
90         {
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                 /*
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.
125                  */
126                 FuncCall   *n = makeNode(FuncCall);
127                 Type            targetType = typeidType(targetTypeId);
128
129                 n->funcname = typeTypeName(targetType);
130                 n->args = lcons(node, NIL);
131                 n->agg_star = false;
132                 n->agg_distinct = false;
133
134                 result = transformExpr(pstate, (Node *) n, EXPR_COLUMN_FIRST);
135
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)));
141
142                 /*
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.)
148                  *
149                  * Note that no folding will occur if the conversion function is not
150                  * marked 'iscachable'.
151                  *
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...)
156                  */
157                 if (IsA(node, Const) &&!((Const *) node)->constisnull)
158                         result = eval_const_expressions(result);
159         }
160
161         return result;
162 }
163
164
165 /* can_coerce_type()
166  * Can input_typeids be coerced to func_typeids?
167  *
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.
171  *
172  * Notes:
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
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 = SearchSysCacheTuple(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                         return false;
247         }
248
249         return true;
250 }
251
252 /* coerce_type_typmod()
253  * Force a value to a particular typmod, if meaningful and possible.
254  *
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).
258  *
259  * The caller must have already ensured that the value is of the correct
260  * type, typically by applying coerce_type.
261  *
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.
266  *
267  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
268  */
269 Node *
270 coerce_type_typmod(ParseState *pstate, Node *node,
271                                    Oid targetTypeId, int32 atttypmod)
272 {
273         char       *funcname;
274         Oid                     oid_array[FUNC_MAX_ARGS];
275         HeapTuple       ftup;
276
277         /*
278          * We assume that only typmod values greater than 0 indicate a forced
279          * conversion is necessary.
280          */
281         if (atttypmod <= 0 ||
282                 atttypmod == exprTypmod(node))
283                 return node;
284
285         funcname = typeidTypeName(targetTypeId);
286         MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
287         oid_array[0] = targetTypeId;
288         oid_array[1] = INT4OID;
289
290         /* attempt to find with arguments exactly as specified... */
291         ftup = SearchSysCacheTuple(PROCNAME,
292                                                            PointerGetDatum(funcname),
293                                                            Int32GetDatum(2),
294                                                            PointerGetDatum(oid_array),
295                                                            0);
296
297         if (HeapTupleIsValid(ftup))
298         {
299                 A_Const    *cons = makeNode(A_Const);
300                 FuncCall   *func = makeNode(FuncCall);
301
302                 cons->val.type = T_Integer;
303                 cons->val.val.ival = atttypmod;
304
305                 func->funcname = funcname;
306                 func->args = lappend(lcons(node, NIL), cons);
307                 func->agg_star = false;
308                 func->agg_distinct = false;
309
310                 node = transformExpr(pstate, (Node *) func, EXPR_COLUMN_FIRST);
311         }
312
313         return node;
314 }
315
316
317 /* TypeCategory()
318  * Assign a category to the specified OID.
319  */
320 CATEGORY
321 TypeCategory(Oid inType)
322 {
323         CATEGORY        result;
324
325         switch (inType)
326         {
327                 case (BOOLOID):
328                         result = BOOLEAN_TYPE;
329                         break;
330
331                 case (CHAROID):
332                 case (NAMEOID):
333                 case (BPCHAROID):
334                 case (VARCHAROID):
335                 case (TEXTOID):
336                         result = STRING_TYPE;
337                         break;
338
339                         /*
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.
346                          */
347                 case (ZPBITOID):
348                 case (VARBITOID):
349                         result = STRING_TYPE;
350                         break;
351
352                 case (OIDOID):
353                 case (REGPROCOID):
354                 case (INT2OID):
355                 case (INT4OID):
356                 case (INT8OID):
357                 case (FLOAT4OID):
358                 case (FLOAT8OID):
359                 case (NUMERICOID):
360                 case (CASHOID):
361                         result = NUMERIC_TYPE;
362                         break;
363
364                 case (DATEOID):
365                 case (TIMEOID):
366                 case (TIMETZOID):
367                 case (ABSTIMEOID):
368                 case (TIMESTAMPOID):
369                         result = DATETIME_TYPE;
370                         break;
371
372                 case (RELTIMEOID):
373                 case (TINTERVALOID):
374                 case (INTERVALOID):
375                         result = TIMESPAN_TYPE;
376                         break;
377
378                 case (POINTOID):
379                 case (LSEGOID):
380                 case (PATHOID):
381                 case (BOXOID):
382                 case (POLYGONOID):
383                 case (LINEOID):
384                 case (CIRCLEOID):
385                         result = GEOMETRIC_TYPE;
386                         break;
387
388                 case (INETOID):
389                 case (CIDROID):
390                         result = NETWORK_TYPE;
391                         break;
392
393                 case (UNKNOWNOID):
394                 case (InvalidOid):
395                         result = UNKNOWN_TYPE;
396                         break;
397
398                 default:
399                         result = USER_TYPE;
400                         break;
401         }
402         return result;
403 }       /* TypeCategory() */
404
405
406 /* IsPreferredType()
407  * Check if this type is a preferred type.
408  */
409 bool
410 IsPreferredType(CATEGORY category, Oid type)
411 {
412         return type == PreferredType(category, type);
413 }       /* IsPreferredType() */
414
415
416 /* PreferredType()
417  * Return the preferred type OID for the specified category.
418  */
419 static Oid
420 PreferredType(CATEGORY category, Oid type)
421 {
422         Oid                     result;
423
424         switch (category)
425         {
426                 case (BOOLEAN_TYPE):
427                         result = BOOLOID;
428                         break;
429
430                 case (STRING_TYPE):
431                         result = TEXTOID;
432                         break;
433
434                 case (NUMERIC_TYPE):
435                         if (type == OIDOID)
436                                 result = OIDOID;
437                         else if (type == NUMERICOID)
438                                 result = NUMERICOID;
439                         else
440                                 result = FLOAT8OID;
441                         break;
442
443                 case (DATETIME_TYPE):
444                         result = TIMESTAMPOID;
445                         break;
446
447                 case (TIMESPAN_TYPE):
448                         result = INTERVALOID;
449                         break;
450
451                 case (NETWORK_TYPE):
452                         result = INETOID;
453                         break;
454
455                 case (GEOMETRIC_TYPE):
456                 case (USER_TYPE):
457                         result = type;
458                         break;
459
460                 default:
461                         result = UNKNOWNOID;
462                         break;
463         }
464         return result;
465 }       /* PreferredType() */
466
467
468 #ifdef NOT_USED
469 Oid
470 PromoteTypeToNext(Oid inType)
471 {
472         Oid                     result;
473
474         switch (inType)
475         {
476                 case (CHAROID):
477                 case (BPCHAROID):
478                         result = VARCHAROID;
479                         break;
480
481                 case (VARCHAROID):
482                         result = TEXTOID;
483                         break;
484
485                 case (INT2OID):
486                 case (CASHOID):
487                         result = INT4OID;
488                         break;
489
490                 case (INT4OID):
491                 case (INT8OID):
492                 case (FLOAT4OID):
493                         result = FLOAT8OID;
494                         break;
495
496                 case (NUMERICOID):
497                         result = NUMERICOID;
498                         break;
499
500                 case (DATEOID):
501                 case (ABSTIMEOID):
502                         result = TIMESTAMPOID;
503                         break;
504
505                 case (TIMEOID):
506                 case (RELTIMEOID):
507                         result = INTERVALOID;
508                         break;
509
510                 case (BOOLOID):
511                 case (TEXTOID):
512                 case (FLOAT8OID):
513                 case (TIMESTAMPOID):
514                 case (INTERVALOID):
515                 default:
516                         result = inType;
517                         break;
518         }
519         return result;
520 }       /* PromoteTypeToNext() */
521
522
523 Oid
524 DemoteType(Oid inType)
525 {
526         Oid                     result;
527
528         switch (inType)
529         {
530                 case (FLOAT4OID):
531                 case (FLOAT8OID):
532                         result = INT4OID;
533                         break;
534
535                 default:
536                         result = inType;
537                         break;
538         }
539         return result;
540 }       /* DemoteType() */
541
542
543 Oid
544 PromoteLesserType(Oid inType1, Oid inType2, Oid *newType1, Oid *newType2)
545 {
546         Oid                     result;
547
548         if (inType1 == inType2)
549         {
550                 result = PromoteTypeToNext(inType1);
551                 inType1 = result;
552                 *arg2 = result;
553                 return result;
554         }
555
556         kind1 = ClassifyType(inType1);
557         kind2 = ClassifyType(*arg2);
558         if (kind1 != kind2)
559         {
560                 *newType1 = inType1;
561                 *newType2 = inType2;
562                 result = InvalidOid;
563         }
564
565         isBuiltIn1 = IS_BUILTIN_TYPE(inType1);
566         isBuiltIn2 = IS_BUILTIN_TYPE(*arg2);
567
568         if (isBuiltIn1 && isBuiltIn2)
569         {
570                 switch (*arg1)
571                 {
572                         case (CHAROID):
573                                 switch (*arg2)
574                                 {
575                                         case (BPCHAROID):
576                                         case (VARCHAROID):
577                                         case (TEXTOID):
578
579                                         case (INT2OID):
580                                         case (INT4OID):
581                                         case (FLOAT4OID):
582                                         case (FLOAT8OID):
583                                         case (CASHOID):
584
585                                         case (POINTOID):
586                                         case (LSEGOID):
587                                         case (LINEOID):
588                                         case (BOXOID):
589                                         case (PATHOID):
590                                         case (CIRCLEOID):
591                                         case (POLYGONOID):
592
593                                         case (InvalidOid):
594                                         case (UNKNOWNOID):
595                                         case (BOOLOID):
596                                         default:
597                                                 *arg1 = InvalidOid;
598                                                 *arg2 = InvalidOid;
599                                                 result = InvalidOid;
600                                 }
601                 }
602         }
603         else if (isBuiltIn1 && !isBuiltIn2)
604         {
605                 if ((promotedType = PromoteBuiltInType(*arg1)) != *arg1)
606                 {
607                         *arg1 = promotedType;
608                         return promotedType;
609                 }
610                 else if (CanCoerceType(*arg1, *arg2))
611                 {
612                         *arg1 = *arg2;
613                         return *arg2;
614                 }
615         }
616         else if (!isBuiltIn1 && isBuiltIn2)
617         {
618                 if ((promotedType = PromoteBuiltInType(*arg2)) != *arg2)
619                 {
620                         *arg2 = promotedType;
621                         return promotedType;
622                 }
623                 else if (CanCoerceType(*arg2, *arg1))
624                 {
625                         *arg2 = *arg1;
626                         return *arg1;
627                 }
628         }
629
630
631         if (*arg2 == InvalidOid)
632                 return InvalidOid;
633
634         switch (*arg1)
635         {
636                 case (CHAROID):
637                         switch (*arg2)
638                         {
639                                 case (BPCHAROID):
640                                 case (VARCHAROID):
641                                 case (TEXTOID):
642
643                                 case (INT2OID):
644                                 case (INT4OID):
645                                 case (FLOAT4OID):
646                                 case (FLOAT8OID):
647                                 case (CASHOID):
648
649                                 case (POINTOID):
650                                 case (LSEGOID):
651                                 case (LINEOID):
652                                 case (BOXOID):
653                                 case (PATHOID):
654                                 case (CIRCLEOID):
655                                 case (POLYGONOID):
656
657                                 case (InvalidOid):
658                                 case (UNKNOWNOID):
659                                 case (BOOLOID):
660                                 default:
661                                         *arg1 = InvalidOid;
662                                         *arg2 = InvalidOid;
663                                         result = InvalidOid;
664                         }
665         }
666 }
667
668 #endif