]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
First phase of work on array improvements. ARRAY[x,y,z] constructor
[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-2002, 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.94 2003/04/08 23:20:02 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "nodes/makefuncs.h"
20 #include "optimizer/clauses.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_expr.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_type.h"
25 #include "utils/builtins.h"
26 #include "utils/fmgroids.h"
27 #include "utils/lsyscache.h"
28 #include "utils/syscache.h"
29
30
31 static Node *coerce_type_typmod(Node *node,
32                                                                 Oid targetTypeId, int32 targetTypMod,
33                                                                 CoercionForm cformat, bool isExplicit);
34 static Oid      PreferredType(CATEGORY category, Oid type);
35 static Node *build_func_call(Oid funcid, Oid rettype, List *args,
36                                                          CoercionForm fformat);
37
38
39 /*
40  * coerce_to_target_type()
41  *              Convert an expression to a target type and typmod.
42  *
43  * This is the general-purpose entry point for arbitrary type coercion
44  * operations.  Direct use of the component operations can_coerce_type,
45  * coerce_type, and coerce_type_typmod should be restricted to special
46  * cases (eg, when the conversion is expected to succeed).
47  *
48  * Returns the possibly-transformed expression tree, or NULL if the type
49  * conversion is not possible.  (We do this, rather than elog'ing directly,
50  * so that callers can generate custom error messages indicating context.)
51  *
52  * expr - input expression tree (already transformed by transformExpr)
53  * exprtype - result type of expr
54  * targettype - desired result type
55  * targettypmod - desired result typmod
56  * ccontext, cformat - context indicators to control coercions
57  */
58 Node *
59 coerce_to_target_type(Node *expr, Oid exprtype,
60                                           Oid targettype, int32 targettypmod,
61                                           CoercionContext ccontext,
62                                           CoercionForm cformat)
63 {
64         if (can_coerce_type(1, &exprtype, &targettype, ccontext))
65                 expr = coerce_type(expr, exprtype, targettype,
66                                                    ccontext, cformat);
67         /*
68          * String hacks to get transparent conversions for char and varchar:
69          * if a coercion to text is available, use it for forced coercions to
70          * char(n) or varchar(n).
71          *
72          * This is pretty grotty, but seems easier to maintain than providing
73          * entries in pg_cast that parallel all the ones for text.
74          */
75         else if (ccontext >= COERCION_ASSIGNMENT &&
76                          (targettype == BPCHAROID || targettype == VARCHAROID))
77         {
78                 Oid                     text_id = TEXTOID;
79
80                 if (can_coerce_type(1, &exprtype, &text_id, ccontext))
81                 {
82                         expr = coerce_type(expr, exprtype, text_id,
83                                                            ccontext, cformat);
84                         /* Need a RelabelType if no typmod coercion is performed */
85                         if (targettypmod < 0)
86                                 expr = (Node *) makeRelabelType((Expr *) expr,
87                                                                                                 targettype, -1,
88                                                                                                 cformat);
89                 }
90                 else
91                         expr = NULL;
92         }
93         else
94                 expr = NULL;
95
96         /*
97          * If the target is a fixed-length type, it may need a length coercion
98          * as well as a type coercion.
99          */
100         if (expr != NULL)
101                 expr = coerce_type_typmod(expr, targettype, targettypmod,
102                                                                   cformat,
103                                                                   (cformat != COERCE_IMPLICIT_CAST));
104
105         return expr;
106 }
107
108
109 /*
110  * coerce_type()
111  *              Convert an expression to a different type.
112  *
113  * The caller should already have determined that the coercion is possible;
114  * see can_coerce_type.
115  *
116  * No coercion to a typmod (length) is performed here.  The caller must
117  * call coerce_type_typmod as well, if a typmod constraint is wanted.
118  * (But if the target type is a domain, it may internally contain a
119  * typmod constraint, which will be applied inside coerce_to_domain.)
120  */
121 Node *
122 coerce_type(Node *node, Oid inputTypeId, Oid targetTypeId,
123                         CoercionContext ccontext, CoercionForm cformat)
124 {
125         Node       *result;
126         Oid                     funcId;
127
128         if (targetTypeId == inputTypeId ||
129                 node == NULL)
130         {
131                 /* no conversion needed */
132                 result = node;
133         }
134         else if (inputTypeId == UNKNOWNOID && IsA(node, Const))
135         {
136                 /*
137                  * Input is a string constant with previously undetermined type.
138                  * Apply the target type's typinput function to it to produce a
139                  * constant of the target type.
140                  *
141                  * NOTE: this case cannot be folded together with the other
142                  * constant-input case, since the typinput function does not
143                  * necessarily behave the same as a type conversion function. For
144                  * example, int4's typinput function will reject "1.2", whereas
145                  * float-to-int type conversion will round to integer.
146                  *
147                  * XXX if the typinput function is not immutable, we really ought to
148                  * postpone evaluation of the function call until runtime. But
149                  * there is no way to represent a typinput function call as an
150                  * expression tree, because C-string values are not Datums. (XXX
151                  * This *is* possible as of 7.3, do we want to do it?)
152                  */
153                 Const      *con = (Const *) node;
154                 Const      *newcon = makeNode(Const);
155                 Type            targetType = typeidType(targetTypeId);
156                 char            targetTyptype = typeTypType(targetType);
157
158                 newcon->consttype = targetTypeId;
159                 newcon->constlen = typeLen(targetType);
160                 newcon->constbyval = typeByVal(targetType);
161                 newcon->constisnull = con->constisnull;
162
163                 if (!con->constisnull)
164                 {
165                         char       *val = DatumGetCString(DirectFunctionCall1(unknownout,
166                                                                                                            con->constvalue));
167
168                         /*
169                          * We pass typmod -1 to the input routine, primarily because
170                          * existing input routines follow implicit-coercion semantics
171                          * for length checks, which is not always what we want here.
172                          * Any length constraint will be applied later by our caller.
173                          *
174                          * Note that we call stringTypeDatum using the domain's pg_type
175                          * row, if it's a domain.  This works because the domain row has
176                          * the same typinput and typelem as the base type --- ugly...
177                          */
178                         newcon->constvalue = stringTypeDatum(targetType, val, -1);
179                         pfree(val);
180                 }
181
182                 result = (Node *) newcon;
183
184                 /* If target is a domain, apply constraints. */
185                 if (targetTyptype == 'd')
186                         result = coerce_to_domain(result, InvalidOid, targetTypeId,
187                                                                           cformat);
188
189                 ReleaseSysCache(targetType);
190         }
191         else if (targetTypeId == ANYOID ||
192                          targetTypeId == ANYARRAYOID ||
193                          targetTypeId == ANYELEMENTOID)
194         {
195                 /* assume can_coerce_type verified that implicit coercion is okay */
196                 /* NB: we do NOT want a RelabelType here */
197                 result = node;
198         }
199         else if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
200                                                                    &funcId))
201         {
202                 if (OidIsValid(funcId))
203                 {
204                         /*
205                          * Generate an expression tree representing run-time
206                          * application of the conversion function.      If we are dealing
207                          * with a domain target type, the conversion function will
208                          * yield the base type.
209                          */
210                         Oid                     baseTypeId = getBaseType(targetTypeId);
211
212                         result = build_func_call(funcId, baseTypeId, makeList1(node),
213                                                                          cformat);
214
215                         /*
216                          * If domain, coerce to the domain type and relabel with
217                          * domain type ID
218                          */
219                         if (targetTypeId != baseTypeId)
220                                 result = coerce_to_domain(result, baseTypeId, targetTypeId,
221                                                                                   cformat);
222
223                         /*
224                          * If the input is a constant, apply the type conversion
225                          * function now instead of delaying to runtime.  (We could, of
226                          * course, just leave this to be done during
227                          * planning/optimization; but it's a very frequent special
228                          * case, and we save cycles in the rewriter if we fold the
229                          * expression now.)
230                          *
231                          * Note that no folding will occur if the conversion function is
232                          * not marked 'immutable'.
233                          */
234                         if (IsA(node, Const))
235                                 result = eval_const_expressions(result);
236                 }
237                 else
238                 {
239                         /*
240                          * We don't need to do a physical conversion, but we do need
241                          * to attach a RelabelType node so that the expression will be
242                          * seen to have the intended type when inspected by
243                          * higher-level code.
244                          *
245                          * Also, domains may have value restrictions beyond the base type
246                          * that must be accounted for.  If the destination is a domain
247                          * then we won't need a RelabelType node.
248                          */
249                         result = coerce_to_domain(node, InvalidOid, targetTypeId,
250                                                                           cformat);
251                         if (result == node)
252                         {
253                                 /*
254                                  * XXX could we label result with exprTypmod(node) instead of
255                                  * default -1 typmod, to save a possible length-coercion
256                                  * later? Would work if both types have same interpretation of
257                                  * typmod, which is likely but not certain.
258                                  */
259                                 result = (Node *) makeRelabelType((Expr *) result,
260                                                                                                   targetTypeId, -1,
261                                                                                                   cformat);
262                         }
263                 }
264         }
265         else if (typeInheritsFrom(inputTypeId, targetTypeId))
266         {
267                 /*
268                  * Input class type is a subclass of target, so nothing to do ---
269                  * except relabel the type.  This is binary compatibility for
270                  * complex types.
271                  */
272                 result = (Node *) makeRelabelType((Expr *) node,
273                                                                                   targetTypeId, -1,
274                                                                                   cformat);
275         }
276         else
277         {
278                 /* If we get here, caller blew it */
279                 elog(ERROR, "coerce_type: no conversion function from %s to %s",
280                          format_type_be(inputTypeId), format_type_be(targetTypeId));
281                 result = NULL;                  /* keep compiler quiet */
282         }
283
284         return result;
285 }
286
287
288 /*
289  * can_coerce_type()
290  *              Can input_typeids be coerced to target_typeids?
291  *
292  * We must be told the context (CAST construct, assignment, implicit coercion)
293  * as this determines the set of available casts.
294  */
295 bool
296 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
297                                 CoercionContext ccontext)
298 {
299         bool            have_generics = false;
300         int                     i;
301
302         /* run through argument list... */
303         for (i = 0; i < nargs; i++)
304         {
305                 Oid                     inputTypeId = input_typeids[i];
306                 Oid                     targetTypeId = target_typeids[i];
307                 Oid                     funcId;
308
309                 /* no problem if same type */
310                 if (inputTypeId == targetTypeId)
311                         continue;
312
313                 /* don't choke on references to no-longer-existing types */
314                 if (!typeidIsValid(inputTypeId))
315                         return false;
316                 if (!typeidIsValid(targetTypeId))
317                         return false;
318
319                 /*
320                  * If input is an untyped string constant, assume we can convert
321                  * it to anything except a class type.
322                  */
323                 if (inputTypeId == UNKNOWNOID)
324                 {
325                         if (ISCOMPLEX(targetTypeId))
326                                 return false;
327                         continue;
328                 }
329
330                 /* accept if target is ANY */
331                 if (targetTypeId == ANYOID)
332                         continue;
333
334                 /* accept if target is ANYARRAY or ANYELEMENT, for now */
335                 if (targetTypeId == ANYARRAYOID ||
336                         targetTypeId == ANYELEMENTOID)
337                 {
338                         have_generics = true; /* do more checking later */
339                         continue;
340                 }
341
342                 /*
343                  * If pg_cast shows that we can coerce, accept.  This test now
344                  * covers both binary-compatible and coercion-function cases.
345                  */
346                 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
347                                                                   &funcId))
348                         continue;
349
350                 /*
351                  * If input is a class type that inherits from target, accept
352                  */
353                 if (typeInheritsFrom(inputTypeId, targetTypeId))
354                         continue;
355
356                 /*
357                  * Else, cannot coerce at this argument position
358                  */
359                 return false;
360         }
361
362         /* If we found any generic argument types, cross-check them */
363         if (have_generics)
364         {
365                 if (!check_generic_type_consistency(input_typeids, target_typeids,
366                                                                                         nargs))
367                         return false;
368         }
369
370         return true;
371 }
372
373
374 /*
375  * Create an expression tree to represent coercion to a domain type.
376  *
377  * 'arg': input expression
378  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
379  *              has not bothered to look this up)
380  * 'typeId': target type to coerce to
381  * 'cformat': coercion format
382  *
383  * If the target type isn't a domain, the given 'arg' is returned as-is.
384  */
385 Node *
386 coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId, CoercionForm cformat)
387 {
388         CoerceToDomain *result;
389         int32   typmod;
390
391         /* Get the base type if it hasn't been supplied */
392         if (baseTypeId == InvalidOid)
393                 baseTypeId = getBaseType(typeId);
394
395         /* If it isn't a domain, return the node as it was passed in */
396         if (baseTypeId == typeId)
397                 return arg;
398
399         /*
400          * If the domain applies a typmod to its base type, build the appropriate
401          * coercion step.  Mark it implicit for display purposes, because we don't
402          * want it shown separately by ruleutils.c; but the isExplicit flag passed
403          * to the conversion function depends on the manner in which the domain
404          * coercion is invoked, so that the semantics of implicit and explicit
405          * coercion differ.  (Is that really the behavior we want?)
406          *
407          * NOTE: because we apply this as part of the fixed expression structure,
408          * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
409          * would be safe to do anyway, without lots of knowledge about what the
410          * base type thinks the typmod means.
411          */
412         typmod = get_typtypmod(typeId);
413         if (typmod >= 0)
414                 arg = coerce_type_typmod(arg, baseTypeId, typmod,
415                                                                  COERCE_IMPLICIT_CAST,
416                                                                  (cformat != COERCE_IMPLICIT_CAST));
417
418         /*
419          * Now build the domain coercion node.  This represents run-time checking
420          * of any constraints currently attached to the domain.  This also
421          * ensures that the expression is properly labeled as to result type.
422          */
423         result = makeNode(CoerceToDomain);
424         result->arg = (Expr *) arg;
425         result->resulttype = typeId;
426         result->resulttypmod = -1;      /* currently, always -1 for domains */
427         result->coercionformat = cformat;
428
429         return (Node *) result;
430 }
431
432
433 /*
434  * coerce_type_typmod()
435  *              Force a value to a particular typmod, if meaningful and possible.
436  *
437  * This is applied to values that are going to be stored in a relation
438  * (where we have an atttypmod for the column) as well as values being
439  * explicitly CASTed (where the typmod comes from the target type spec).
440  *
441  * The caller must have already ensured that the value is of the correct
442  * type, typically by applying coerce_type.
443  *
444  * NOTE: this does not need to work on domain types, because any typmod
445  * coercion for a domain is considered to be part of the type coercion
446  * needed to produce the domain value in the first place.  So, no getBaseType.
447  */
448 static Node *
449 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
450                                    CoercionForm cformat, bool isExplicit)
451 {
452         Oid                     funcId;
453         int                     nargs;
454
455         /*
456          * A negative typmod is assumed to mean that no coercion is wanted.
457          */
458         if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
459                 return node;
460
461         funcId = find_typmod_coercion_function(targetTypeId, &nargs);
462
463         if (OidIsValid(funcId))
464         {
465                 List       *args;
466                 Const      *cons;
467                 Node       *fcall;
468
469                 /* Pass given value, plus target typmod as an int4 constant */
470                 cons = makeConst(INT4OID,
471                                                  sizeof(int32),
472                                                  Int32GetDatum(targetTypMod),
473                                                  false,
474                                                  true);
475
476                 args = makeList2(node, cons);
477
478                 if (nargs == 3)
479                 {
480                         /* Pass it a boolean isExplicit parameter, too */
481                         cons = makeConst(BOOLOID,
482                                                          sizeof(bool),
483                                                          BoolGetDatum(isExplicit),
484                                                          false,
485                                                          true);
486
487                         args = lappend(args, cons);
488                 }
489
490                 fcall = build_func_call(funcId, targetTypeId, args, cformat);
491
492                 /*
493                  * If the input is a constant, apply the length coercion
494                  * function now instead of delaying to runtime.
495                  *
496                  * See the comments for the similar case in coerce_type.
497                  */
498                 if (node && IsA(node, Const))
499                         node = eval_const_expressions(fcall);
500                 else
501                         node = fcall;
502         }
503
504         return node;
505 }
506
507
508 /* coerce_to_boolean()
509  *              Coerce an argument of a construct that requires boolean input
510  *              (AND, OR, NOT, etc).  Also check that input is not a set.
511  *
512  * Returns the possibly-transformed node tree.
513  */
514 Node *
515 coerce_to_boolean(Node *node, const char *constructName)
516 {
517         Oid                     inputTypeId = exprType(node);
518
519         if (inputTypeId != BOOLOID)
520         {
521                 node = coerce_to_target_type(node, inputTypeId,
522                                                                          BOOLOID, -1,
523                                                                          COERCION_ASSIGNMENT,
524                                                                          COERCE_IMPLICIT_CAST);
525                 if (node == NULL)
526                 {
527                         /* translator: first %s is name of a SQL construct, eg WHERE */
528                         elog(ERROR, "Argument of %s must be type boolean, not type %s",
529                                  constructName, format_type_be(inputTypeId));
530                 }
531         }
532
533         if (expression_returns_set(node))
534         {
535                 /* translator: %s is name of a SQL construct, eg WHERE */
536                 elog(ERROR, "Argument of %s must not be a set function",
537                          constructName);
538         }
539
540         return node;
541 }
542
543
544 /* select_common_type()
545  *              Determine the common supertype of a list of input expression types.
546  *              This is used for determining the output type of CASE and UNION
547  *              constructs.
548  *
549  * typeids is a nonempty list of type OIDs.  Note that earlier items
550  * in the list will be preferred if there is doubt.
551  * 'context' is a phrase to use in the error message if we fail to select
552  * a usable type.
553  */
554 Oid
555 select_common_type(List *typeids, const char *context)
556 {
557         Oid                     ptype;
558         CATEGORY        pcategory;
559         List       *l;
560
561         Assert(typeids != NIL);
562         ptype = lfirsto(typeids);
563         pcategory = TypeCategory(ptype);
564         foreach(l, lnext(typeids))
565         {
566                 Oid                     ntype = lfirsto(l);
567
568                 /* move on to next one if no new information... */
569                 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
570                 {
571                         if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
572                         {
573                                 /* so far, only nulls so take anything... */
574                                 ptype = ntype;
575                                 pcategory = TypeCategory(ptype);
576                         }
577                         else if (TypeCategory(ntype) != pcategory)
578                         {
579                                 /*
580                                  * both types in different categories? then not much
581                                  * hope...
582                                  */
583                                 elog(ERROR, "%s types '%s' and '%s' not matched",
584                                   context, format_type_be(ptype), format_type_be(ntype));
585                         }
586                         else if (!IsPreferredType(pcategory, ptype) &&
587                                          can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
588                                          !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
589                         {
590                                 /*
591                                  * take new type if can coerce to it implicitly but not the
592                                  * other way; but if we have a preferred type, stay on it.
593                                  */
594                                 ptype = ntype;
595                                 pcategory = TypeCategory(ptype);
596                         }
597                 }
598         }
599
600         /*
601          * If all the inputs were UNKNOWN type --- ie, unknown-type literals
602          * --- then resolve as type TEXT.  This situation comes up with
603          * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
604          * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
605          * the construct's output type as UNKNOWN, but that really doesn't
606          * work, because we'd probably end up needing a runtime coercion from
607          * UNKNOWN to something else, and we usually won't have it.  We need
608          * to coerce the unknown literals while they are still literals, so a
609          * decision has to be made now.
610          */
611         if (ptype == UNKNOWNOID)
612                 ptype = TEXTOID;
613
614         return ptype;
615 }
616
617 /* coerce_to_common_type()
618  *              Coerce an expression to the given type.
619  *
620  * This is used following select_common_type() to coerce the individual
621  * expressions to the desired type.  'context' is a phrase to use in the
622  * error message if we fail to coerce.
623  */
624 Node *
625 coerce_to_common_type(Node *node, Oid targetTypeId, const char *context)
626 {
627         Oid                     inputTypeId = exprType(node);
628
629         if (inputTypeId == targetTypeId)
630                 return node;                    /* no work */
631         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
632                 node = coerce_type(node, inputTypeId, targetTypeId,
633                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
634         else
635                 elog(ERROR, "%s unable to convert to type %s",
636                          context, format_type_be(targetTypeId));
637         return node;
638 }
639
640 /*
641  * check_generic_type_consistency()
642  *              Are the actual arguments potentially compatible with a
643  *              polymorphic function?
644  *
645  * The argument consistency rules are:
646  *
647  * 1) All arguments declared ANYARRAY must have matching datatypes,
648  *        and must in fact be varlena arrays.
649  * 2) All arguments declared ANYELEMENT must have matching datatypes.
650  * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
651  *    the actual ANYELEMENT datatype is in fact the element type for
652  *    the actual ANYARRAY datatype.
653  *
654  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
655  * or ANYARRAY argument, assume it is okay.
656  *
657  * We do not elog here, but just return FALSE if a rule is violated.
658  */
659 bool
660 check_generic_type_consistency(Oid *actual_arg_types,
661                                                            Oid *declared_arg_types,
662                                                            int nargs)
663 {
664         int                     j;
665         Oid                     elem_typeid = InvalidOid;
666         Oid                     array_typeid = InvalidOid;
667         Oid                     array_typelem;
668
669         /*
670          * Loop through the arguments to see if we have any that are
671          * ANYARRAY or ANYELEMENT. If so, require the actual types to be
672          * self-consistent
673          */
674         for (j = 0; j < nargs; j++)
675         {
676                 Oid             actual_type = actual_arg_types[j];
677
678                 if (declared_arg_types[j] == ANYELEMENTOID)
679                 {
680                         if (actual_type == UNKNOWNOID)
681                                 continue;
682                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
683                                 return false;
684                         elem_typeid = actual_type;
685                 }
686                 else if (declared_arg_types[j] == ANYARRAYOID)
687                 {
688                         if (actual_type == UNKNOWNOID)
689                                 continue;
690                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
691                                 return false;
692                         array_typeid = actual_type;
693                 }
694         }
695
696         /* Get the element type based on the array type, if we have one */
697         if (OidIsValid(array_typeid))
698         {
699                 array_typelem = get_element_type(array_typeid);
700                 if (!OidIsValid(array_typelem))
701                         return false;           /* should be an array, but isn't */
702
703                 if (!OidIsValid(elem_typeid))
704                 {
705                         /* if we don't have an element type yet, use the one we just got */
706                         elem_typeid = array_typelem;
707                 }
708                 else if (array_typelem != elem_typeid)
709                 {
710                         /* otherwise, they better match */
711                         return false;
712                 }
713         }
714
715         /* Looks valid */
716         return true;
717 }
718
719 /*
720  * enforce_generic_type_consistency()
721  *              Make sure a polymorphic function is legally callable, and
722  *              deduce actual argument and result types.
723  *
724  * If ANYARRAY or ANYELEMENT is used for a function's arguments or
725  * return type, we make sure the actual data types are consistent with
726  * each other. The argument consistency rules are shown above for
727  * check_generic_type_consistency().
728  *
729  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
730  * or ANYARRAY argument, we attempt to deduce the actual type it should
731  * have.  If successful, we alter that position of declared_arg_types[]
732  * so that make_fn_arguments will coerce the literal to the right thing.
733  *
734  * Rules are applied to the function's return type (possibly altering it)
735  * if it is declared ANYARRAY or ANYELEMENT:
736  *
737  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
738  *    argument's actual type as the function's return type.
739  * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
740  *    is ANYELEMENT, use the actual type of the argument to determine
741  *    the function's return type, i.e. the element type's corresponding
742  *    array type.
743  * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
744  *    generate an ERROR. This condition is prevented by CREATE FUNCTION
745  *    and is therefore not expected here.
746  * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
747  *    argument's actual type as the function's return type.
748  * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
749  *    argument is ANYARRAY, use the actual type of the argument to determine
750  *    the function's return type, i.e. the array type's corresponding
751  *    element type.
752  * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
753  *    generate an ERROR. This condition is prevented by CREATE FUNCTION
754  *    and is therefore not expected here.
755  */
756 Oid
757 enforce_generic_type_consistency(Oid *actual_arg_types,
758                                                                  Oid *declared_arg_types,
759                                                                  int nargs,
760                                                                  Oid rettype)
761 {
762         int                     j;
763         bool            have_generics = false;
764         bool            have_unknowns = false;
765         Oid                     elem_typeid = InvalidOid;
766         Oid                     array_typeid = InvalidOid;
767         Oid                     array_typelem = InvalidOid;
768
769         /*
770          * Loop through the arguments to see if we have any that are
771          * ANYARRAY or ANYELEMENT. If so, require the actual types to be
772          * self-consistent
773          */
774         for (j = 0; j < nargs; j++)
775         {
776                 Oid             actual_type = actual_arg_types[j];
777
778                 if (declared_arg_types[j] == ANYELEMENTOID)
779                 {
780                         have_generics = true;
781                         if (actual_type == UNKNOWNOID)
782                         {
783                                 have_unknowns = true;
784                                 continue;
785                         }
786                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
787                                 elog(ERROR, "Arguments declared ANYELEMENT are not all alike: %s vs %s",
788                                          format_type_be(elem_typeid),
789                                          format_type_be(actual_type));
790                         elem_typeid = actual_type;
791                 }
792                 else if (declared_arg_types[j] == ANYARRAYOID)
793                 {
794                         have_generics = true;
795                         if (actual_type == UNKNOWNOID)
796                         {
797                                 have_unknowns = true;
798                                 continue;
799                         }
800                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
801                                 elog(ERROR, "Arguments declared ANYARRAY are not all alike: %s vs %s",
802                                          format_type_be(array_typeid),
803                                          format_type_be(actual_type));
804                         array_typeid = actual_type;
805                 }
806         }
807
808         /*
809          * Fast Track: if none of the arguments are ANYARRAY or ANYELEMENT,
810          * return the unmodified rettype.
811          */
812         if (!have_generics)
813                 return rettype;
814
815         /* Get the element type based on the array type, if we have one */
816         if (OidIsValid(array_typeid))
817         {
818                 array_typelem = get_element_type(array_typeid);
819                 if (!OidIsValid(array_typelem))
820                         elog(ERROR, "Argument declared ANYARRAY is not an array: %s",
821                                  format_type_be(array_typeid));
822
823                 if (!OidIsValid(elem_typeid))
824                 {
825                         /* if we don't have an element type yet, use the one we just got */
826                         elem_typeid = array_typelem;
827                 }
828                 else if (array_typelem != elem_typeid)
829                 {
830                         /* otherwise, they better match */
831                         elog(ERROR, "Argument declared ANYARRAY is not consistent with "
832                                  "argument declared ANYELEMENT: %s vs %s",
833                                  format_type_be(array_typeid),
834                                  format_type_be(elem_typeid));
835                 }
836         }
837         else if (!OidIsValid(elem_typeid))
838         {
839                 /* Only way to get here is if all the generic args are UNKNOWN */
840                 elog(ERROR, "Cannot determine ANYARRAY/ANYELEMENT type because input is UNKNOWN");
841         }
842
843         /*
844          * If we had any unknown inputs, re-scan to assign correct types
845          */
846         if (have_unknowns)
847         {
848                 for (j = 0; j < nargs; j++)
849                 {
850                         Oid             actual_type = actual_arg_types[j];
851
852                         if (actual_type != UNKNOWNOID)
853                                 continue;
854
855                         if (declared_arg_types[j] == ANYELEMENTOID)
856                         {
857                                 declared_arg_types[j] = elem_typeid;
858                         }
859                         else if (declared_arg_types[j] == ANYARRAYOID)
860                         {
861                                 if (!OidIsValid(array_typeid))
862                                 {
863                                         array_typeid = get_array_type(elem_typeid);
864                                         if (!OidIsValid(array_typeid))
865                                                 elog(ERROR, "Cannot find array type for datatype %s",
866                                                          format_type_be(elem_typeid));
867                                 }
868                                 declared_arg_types[j] = array_typeid;
869                         }
870                 }
871         }
872
873         /* if we return ANYARRAYOID use the appropriate argument type */
874         if (rettype == ANYARRAYOID)
875         {
876                 if (!OidIsValid(array_typeid))
877                 {
878                         array_typeid = get_array_type(elem_typeid);
879                         if (!OidIsValid(array_typeid))
880                                 elog(ERROR, "Cannot find array type for datatype %s",
881                                          format_type_be(elem_typeid));
882                 }
883                 return array_typeid;
884         }
885
886         /* if we return ANYELEMENTOID use the appropriate argument type */
887         if (rettype == ANYELEMENTOID)
888                 return elem_typeid;
889
890         /* we don't return a generic type; send back the original return type */
891         return rettype;
892 }
893
894
895 /* TypeCategory()
896  * Assign a category to the specified OID.
897  * XXX This should be moved to system catalog lookups
898  * to allow for better type extensibility.
899  * - thomas 2001-09-30
900  */
901 CATEGORY
902 TypeCategory(Oid inType)
903 {
904         CATEGORY        result;
905
906         switch (inType)
907         {
908                 case (BOOLOID):
909                         result = BOOLEAN_TYPE;
910                         break;
911
912                 case (CHAROID):
913                 case (NAMEOID):
914                 case (BPCHAROID):
915                 case (VARCHAROID):
916                 case (TEXTOID):
917                         result = STRING_TYPE;
918                         break;
919
920                 case (BITOID):
921                 case (VARBITOID):
922                         result = BITSTRING_TYPE;
923                         break;
924
925                 case (OIDOID):
926                 case (REGPROCOID):
927                 case (REGPROCEDUREOID):
928                 case (REGOPEROID):
929                 case (REGOPERATOROID):
930                 case (REGCLASSOID):
931                 case (REGTYPEOID):
932                 case (INT2OID):
933                 case (INT4OID):
934                 case (INT8OID):
935                 case (FLOAT4OID):
936                 case (FLOAT8OID):
937                 case (NUMERICOID):
938                 case (CASHOID):
939                         result = NUMERIC_TYPE;
940                         break;
941
942                 case (DATEOID):
943                 case (TIMEOID):
944                 case (TIMETZOID):
945                 case (ABSTIMEOID):
946                 case (TIMESTAMPOID):
947                 case (TIMESTAMPTZOID):
948                         result = DATETIME_TYPE;
949                         break;
950
951                 case (RELTIMEOID):
952                 case (TINTERVALOID):
953                 case (INTERVALOID):
954                         result = TIMESPAN_TYPE;
955                         break;
956
957                 case (POINTOID):
958                 case (LSEGOID):
959                 case (PATHOID):
960                 case (BOXOID):
961                 case (POLYGONOID):
962                 case (LINEOID):
963                 case (CIRCLEOID):
964                         result = GEOMETRIC_TYPE;
965                         break;
966
967                 case (INETOID):
968                 case (CIDROID):
969                         result = NETWORK_TYPE;
970                         break;
971
972                 case (UNKNOWNOID):
973                 case (InvalidOid):
974                         result = UNKNOWN_TYPE;
975                         break;
976
977                 case (RECORDOID):
978                 case (CSTRINGOID):
979                 case (ANYOID):
980                 case (ANYARRAYOID):
981                 case (VOIDOID):
982                 case (TRIGGEROID):
983                 case (LANGUAGE_HANDLEROID):
984                 case (INTERNALOID):
985                 case (OPAQUEOID):
986                 case (ANYELEMENTOID):
987                         result = GENERIC_TYPE;
988                         break;
989
990                 default:
991                         result = USER_TYPE;
992                         break;
993         }
994         return result;
995 }       /* TypeCategory() */
996
997
998 /* IsPreferredType()
999  * Check if this type is a preferred type.
1000  * XXX This should be moved to system catalog lookups
1001  * to allow for better type extensibility.
1002  * - thomas 2001-09-30
1003  */
1004 bool
1005 IsPreferredType(CATEGORY category, Oid type)
1006 {
1007         return (type == PreferredType(category, type));
1008 }       /* IsPreferredType() */
1009
1010
1011 /* PreferredType()
1012  * Return the preferred type OID for the specified category.
1013  * XXX This should be moved to system catalog lookups
1014  * to allow for better type extensibility.
1015  * - thomas 2001-09-30
1016  */
1017 static Oid
1018 PreferredType(CATEGORY category, Oid type)
1019 {
1020         Oid                     result;
1021
1022         switch (category)
1023         {
1024                 case (INVALID_TYPE):
1025                 case (UNKNOWN_TYPE):
1026                 case (GENERIC_TYPE):
1027                         result = UNKNOWNOID;
1028                         break;
1029
1030                 case (BOOLEAN_TYPE):
1031                         result = BOOLOID;
1032                         break;
1033
1034                 case (STRING_TYPE):
1035                         result = TEXTOID;
1036                         break;
1037
1038                 case (BITSTRING_TYPE):
1039                         result = VARBITOID;
1040                         break;
1041
1042                 case (NUMERIC_TYPE):
1043                         if (type == OIDOID ||
1044                                 type == REGPROCOID ||
1045                                 type == REGPROCEDUREOID ||
1046                                 type == REGOPEROID ||
1047                                 type == REGOPERATOROID ||
1048                                 type == REGCLASSOID ||
1049                                 type == REGTYPEOID)
1050                                 result = OIDOID;
1051                         else
1052                                 result = FLOAT8OID;
1053                         break;
1054
1055                 case (DATETIME_TYPE):
1056                         if (type == DATEOID)
1057                                 result = TIMESTAMPOID;
1058                         else
1059                                 result = TIMESTAMPTZOID;
1060                         break;
1061
1062                 case (TIMESPAN_TYPE):
1063                         result = INTERVALOID;
1064                         break;
1065
1066                 case (GEOMETRIC_TYPE):
1067                         result = type;
1068                         break;
1069
1070                 case (NETWORK_TYPE):
1071                         result = INETOID;
1072                         break;
1073
1074                 case (USER_TYPE):
1075                         result = type;
1076                         break;
1077
1078                 default:
1079                         elog(ERROR, "PreferredType: unknown category");
1080                         result = UNKNOWNOID;
1081                         break;
1082         }
1083         return result;
1084 }       /* PreferredType() */
1085
1086
1087 /* IsBinaryCoercible()
1088  *              Check if srctype is binary-coercible to targettype.
1089  *
1090  * This notion allows us to cheat and directly exchange values without
1091  * going through the trouble of calling a conversion function.
1092  *
1093  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1094  * We consider two types binary-coercible if there is an implicitly
1095  * invokable, no-function-needed pg_cast entry.
1096  *
1097  * This function replaces IsBinaryCompatible(), which was an inherently
1098  * symmetric test.  Since the pg_cast entries aren't necessarily symmetric,
1099  * the order of the operands is now significant.
1100  */
1101 bool
1102 IsBinaryCoercible(Oid srctype, Oid targettype)
1103 {
1104         HeapTuple       tuple;
1105         Form_pg_cast castForm;
1106         bool            result;
1107
1108         /* Fast path if same type */
1109         if (srctype == targettype)
1110                 return true;
1111
1112         /* Perhaps the types are domains; if so, look at their base types */
1113         if (OidIsValid(srctype))
1114                 srctype = getBaseType(srctype);
1115         if (OidIsValid(targettype))
1116                 targettype = getBaseType(targettype);
1117
1118         /* Somewhat-fast path if same base type */
1119         if (srctype == targettype)
1120                 return true;
1121
1122         /* Else look in pg_cast */
1123         tuple = SearchSysCache(CASTSOURCETARGET,
1124                                                    ObjectIdGetDatum(srctype),
1125                                                    ObjectIdGetDatum(targettype),
1126                                                    0, 0);
1127         if (!HeapTupleIsValid(tuple))
1128                 return false;                   /* no cast */
1129         castForm = (Form_pg_cast) GETSTRUCT(tuple);
1130
1131         result = (castForm->castfunc == InvalidOid &&
1132                           castForm->castcontext == COERCION_CODE_IMPLICIT);
1133
1134         ReleaseSysCache(tuple);
1135
1136         return result;
1137 }
1138
1139
1140 /*
1141  * find_coercion_pathway
1142  *              Look for a coercion pathway between two types.
1143  *
1144  * ccontext determines the set of available casts.
1145  *
1146  * If we find a suitable entry in pg_cast, return TRUE, and set *funcid
1147  * to the castfunc value (which may be InvalidOid for a binary-compatible
1148  * coercion).
1149  */
1150 bool
1151 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1152                                           CoercionContext ccontext,
1153                                           Oid *funcid)
1154 {
1155         bool            result = false;
1156         HeapTuple       tuple;
1157
1158         *funcid = InvalidOid;
1159
1160         /* Perhaps the types are domains; if so, look at their base types */
1161         if (OidIsValid(sourceTypeId))
1162                 sourceTypeId = getBaseType(sourceTypeId);
1163         if (OidIsValid(targetTypeId))
1164                 targetTypeId = getBaseType(targetTypeId);
1165
1166         /* Domains are automatically binary-compatible with their base type */
1167         if (sourceTypeId == targetTypeId)
1168                 return true;
1169
1170         /* Look in pg_cast */
1171         tuple = SearchSysCache(CASTSOURCETARGET,
1172                                                    ObjectIdGetDatum(sourceTypeId),
1173                                                    ObjectIdGetDatum(targetTypeId),
1174                                                    0, 0);
1175
1176         if (HeapTupleIsValid(tuple))
1177         {
1178                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1179                 CoercionContext castcontext;
1180
1181                 /* convert char value for castcontext to CoercionContext enum */
1182                 switch (castForm->castcontext)
1183                 {
1184                         case COERCION_CODE_IMPLICIT:
1185                                 castcontext = COERCION_IMPLICIT;
1186                                 break;
1187                         case COERCION_CODE_ASSIGNMENT:
1188                                 castcontext = COERCION_ASSIGNMENT;
1189                                 break;
1190                         case COERCION_CODE_EXPLICIT:
1191                                 castcontext = COERCION_EXPLICIT;
1192                                 break;
1193                         default:
1194                                 elog(ERROR, "find_coercion_pathway: bogus castcontext %c",
1195                                          castForm->castcontext);
1196                                 castcontext = 0;        /* keep compiler quiet */
1197                                 break;
1198                 }
1199
1200                 /* Rely on ordering of enum for correct behavior here */
1201                 if (ccontext >= castcontext)
1202                 {
1203                         *funcid = castForm->castfunc;
1204                         result = true;
1205                 }
1206
1207                 ReleaseSysCache(tuple);
1208         }
1209         else
1210         {
1211                 /*
1212                  * If there's no pg_cast entry, perhaps we are dealing with a
1213                  * pair of array types.  If so, and if the element types have
1214                  * a suitable cast, use array_type_coerce().
1215                  */
1216                 Oid                     targetElemType;
1217                 Oid                     sourceElemType;
1218                 Oid                     elemfuncid;
1219
1220                 if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid &&
1221                         (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid)
1222                 {
1223                         if (find_coercion_pathway(targetElemType, sourceElemType,
1224                                                                           ccontext, &elemfuncid))
1225                         {
1226                                 *funcid = F_ARRAY_TYPE_COERCE;
1227                                 result = true;
1228                         }
1229                 }
1230         }
1231
1232         return result;
1233 }
1234
1235
1236 /*
1237  * find_typmod_coercion_function -- does the given type need length coercion?
1238  *
1239  * If the target type possesses a function named for the type
1240  * and having parameter signature (targettype, int4), we assume that
1241  * the type requires coercion to its own length and that the said
1242  * function should be invoked to do that.
1243  *
1244  * Alternatively, the length-coercing function may have the signature
1245  * (targettype, int4, bool).  On success, *nargs is set to report which
1246  * signature we found.
1247  *
1248  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1249  *
1250  * If the given type is a varlena array type, we do not look for a coercion
1251  * function associated directly with the array type, but instead look for
1252  * one associated with the element type.  If one exists, we report
1253  * array_length_coerce() as the coercion function to use.
1254  *
1255  * This mechanism may seem pretty grotty and in need of replacement by
1256  * something in pg_cast, but since typmod is only interesting for datatypes
1257  * that have special handling in the grammar, there's not really much
1258  * percentage in making it any easier to apply such coercions ...
1259  */
1260 Oid
1261 find_typmod_coercion_function(Oid typeId, int *nargs)
1262 {
1263         Oid                     funcid = InvalidOid;
1264         bool            isArray = false;
1265         Type            targetType;
1266         Form_pg_type typeForm;
1267         char       *typname;
1268         Oid                     typnamespace;
1269         Oid                     oid_array[FUNC_MAX_ARGS];
1270         HeapTuple       ftup;
1271
1272         targetType = typeidType(typeId);
1273         typeForm = (Form_pg_type) GETSTRUCT(targetType);
1274
1275         /* Check for a varlena array type (and not a domain) */
1276         if (typeForm->typelem != InvalidOid &&
1277                 typeForm->typlen == -1 &&
1278                 typeForm->typtype != 'd')
1279         {
1280                 /* Yes, switch our attention to the element type */
1281                 typeId = typeForm->typelem;
1282                 ReleaseSysCache(targetType);
1283                 targetType = typeidType(typeId);
1284                 typeForm = (Form_pg_type) GETSTRUCT(targetType);
1285                 isArray = true;
1286         }
1287
1288         /* Function name is same as type internal name, and in same namespace */
1289         typname = NameStr(typeForm->typname);
1290         typnamespace = typeForm->typnamespace;
1291
1292         /* First look for parameters (type, int4) */
1293         MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
1294         oid_array[0] = typeId;
1295         oid_array[1] = INT4OID;
1296         *nargs = 2;
1297
1298         ftup = SearchSysCache(PROCNAMENSP,
1299                                                   CStringGetDatum(typname),
1300                                                   Int16GetDatum(2),
1301                                                   PointerGetDatum(oid_array),
1302                                                   ObjectIdGetDatum(typnamespace));
1303         if (HeapTupleIsValid(ftup))
1304         {
1305                 Form_pg_proc pform = (Form_pg_proc) GETSTRUCT(ftup);
1306
1307                 /* Make sure the function's result type is as expected */
1308                 if (pform->prorettype == typeId && !pform->proretset &&
1309                         !pform->proisagg)
1310                 {
1311                         /* Okay to use it */
1312                         funcid = HeapTupleGetOid(ftup);
1313                 }
1314                 ReleaseSysCache(ftup);
1315         }
1316
1317         if (!OidIsValid(funcid))
1318         {
1319                 /* Didn't find a function, so now try (type, int4, bool) */
1320                 oid_array[2] = BOOLOID;
1321                 *nargs = 3;
1322
1323                 ftup = SearchSysCache(PROCNAMENSP,
1324                                                           CStringGetDatum(typname),
1325                                                           Int16GetDatum(3),
1326                                                           PointerGetDatum(oid_array),
1327                                                           ObjectIdGetDatum(typnamespace));
1328                 if (HeapTupleIsValid(ftup))
1329                 {
1330                         Form_pg_proc pform = (Form_pg_proc) GETSTRUCT(ftup);
1331
1332                         /* Make sure the function's result type is as expected */
1333                         if (pform->prorettype == typeId && !pform->proretset &&
1334                                 !pform->proisagg)
1335                         {
1336                                 /* Okay to use it */
1337                                 funcid = HeapTupleGetOid(ftup);
1338                         }
1339                         ReleaseSysCache(ftup);
1340                 }
1341         }
1342
1343         ReleaseSysCache(targetType);
1344
1345         /*
1346          * Now, if we did find a coercion function for an array element type,
1347          * report array_length_coerce() as the function to use.  We know it
1348          * takes three arguments always.
1349          */
1350         if (isArray && OidIsValid(funcid))
1351         {
1352                 funcid = F_ARRAY_LENGTH_COERCE;
1353                 *nargs = 3;
1354         }
1355
1356         return funcid;
1357 }
1358
1359 /*
1360  * Build an expression tree representing a function call.
1361  *
1362  * The argument expressions must have been transformed already.
1363  */
1364 static Node *
1365 build_func_call(Oid funcid, Oid rettype, List *args, CoercionForm fformat)
1366 {
1367         FuncExpr   *funcexpr;
1368
1369         funcexpr = makeNode(FuncExpr);
1370         funcexpr->funcid = funcid;
1371         funcexpr->funcresulttype = rettype;
1372         funcexpr->funcretset = false;           /* only possible case here */
1373         funcexpr->funcformat = fformat;
1374         funcexpr->args = args;
1375
1376         return (Node *) funcexpr;
1377 }