]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Represent type-specific length coercion functions as pg_cast entries,
[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-2003, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.119 2004/06/16 01:26:44 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 "nodes/params.h"
21 #include "optimizer/clauses.h"
22 #include "parser/parsetree.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_expr.h"
25 #include "parser/parse_func.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/fmgroids.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/typcache.h"
33
34
35 static Node *coerce_type_typmod(Node *node,
36                                                                 Oid targetTypeId, int32 targetTypMod,
37                                                                 CoercionForm cformat, bool isExplicit,
38                                                                 bool hideInputCoercion);
39 static void hide_coercion_node(Node *node);
40 static Node *build_coercion_expression(Node *node, Oid funcId,
41                                                                            Oid targetTypeId, int32 targetTypMod,
42                                                                            CoercionForm cformat, bool isExplicit);
43 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
44                                                                           Oid targetTypeId,
45                                                                           CoercionContext ccontext,
46                                                                           CoercionForm cformat);
47
48
49 /*
50  * coerce_to_target_type()
51  *              Convert an expression to a target type and typmod.
52  *
53  * This is the general-purpose entry point for arbitrary type coercion
54  * operations.  Direct use of the component operations can_coerce_type,
55  * coerce_type, and coerce_type_typmod should be restricted to special
56  * cases (eg, when the conversion is expected to succeed).
57  *
58  * Returns the possibly-transformed expression tree, or NULL if the type
59  * conversion is not possible.  (We do this, rather than ereport'ing directly,
60  * so that callers can generate custom error messages indicating context.)
61  *
62  * pstate - parse state (can be NULL, see coerce_type)
63  * expr - input expression tree (already transformed by transformExpr)
64  * exprtype - result type of expr
65  * targettype - desired result type
66  * targettypmod - desired result typmod
67  * ccontext, cformat - context indicators to control coercions
68  */
69 Node *
70 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
71                                           Oid targettype, int32 targettypmod,
72                                           CoercionContext ccontext,
73                                           CoercionForm cformat)
74 {
75         Node    *result;
76
77         if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
78                 return NULL;
79
80         result = coerce_type(pstate, expr, exprtype,
81                                                  targettype, targettypmod,
82                                                  ccontext, cformat);
83
84         /*
85          * If the target is a fixed-length type, it may need a length coercion
86          * as well as a type coercion.  If we find ourselves adding both,
87          * force the inner coercion node to implicit display form.
88          */
89         result = coerce_type_typmod(result,
90                                                                 targettype, targettypmod,
91                                                                 cformat,
92                                                                 (cformat != COERCE_IMPLICIT_CAST),
93                                                                 (result != expr && !IsA(result, Const)));
94
95         return result;
96 }
97
98
99 /*
100  * coerce_type()
101  *              Convert an expression to a different type.
102  *
103  * The caller should already have determined that the coercion is possible;
104  * see can_coerce_type.
105  *
106  * Normally, no coercion to a typmod (length) is performed here.  The caller
107  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
108  * (But if the target type is a domain, it may internally contain a
109  * typmod constraint, which will be applied inside coerce_to_domain.)
110  * In some cases pg_cast specifies a type coercion function that also
111  * applies length conversion, and in those cases only, the result will
112  * already be properly coerced to the specified typmod.
113  *
114  * pstate is only used in the case that we are able to resolve the type of
115  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
116  * caller does not want type information updated for Params.
117  */
118 Node *
119 coerce_type(ParseState *pstate, Node *node,
120                         Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
121                         CoercionContext ccontext, CoercionForm cformat)
122 {
123         Node       *result;
124         Oid                     funcId;
125
126         if (targetTypeId == inputTypeId ||
127                 node == NULL)
128         {
129                 /* no conversion needed */
130                 return node;
131         }
132         if (targetTypeId == ANYOID ||
133                 targetTypeId == ANYARRAYOID ||
134                 targetTypeId == ANYELEMENTOID)
135         {
136                 /* assume can_coerce_type verified that implicit coercion is okay */
137                 /* NB: we do NOT want a RelabelType here */
138                 return node;
139         }
140         if (inputTypeId == UNKNOWNOID && IsA(node, Const))
141         {
142                 /*
143                  * Input is a string constant with previously undetermined type.
144                  * Apply the target type's typinput function to it to produce a
145                  * constant of the target type.
146                  *
147                  * NOTE: this case cannot be folded together with the other
148                  * constant-input case, since the typinput function does not
149                  * necessarily behave the same as a type conversion function. For
150                  * example, int4's typinput function will reject "1.2", whereas
151                  * float-to-int type conversion will round to integer.
152                  *
153                  * XXX if the typinput function is not immutable, we really ought to
154                  * postpone evaluation of the function call until runtime. But
155                  * there is no way to represent a typinput function call as an
156                  * expression tree, because C-string values are not Datums. (XXX
157                  * This *is* possible as of 7.3, do we want to do it?)
158                  */
159                 Const      *con = (Const *) node;
160                 Const      *newcon = makeNode(Const);
161                 Type            targetType = typeidType(targetTypeId);
162                 char            targetTyptype = typeTypType(targetType);
163
164                 newcon->consttype = targetTypeId;
165                 newcon->constlen = typeLen(targetType);
166                 newcon->constbyval = typeByVal(targetType);
167                 newcon->constisnull = con->constisnull;
168
169                 if (!con->constisnull)
170                 {
171                         char       *val = DatumGetCString(DirectFunctionCall1(unknownout,
172                                                                                                            con->constvalue));
173
174                         /*
175                          * We pass typmod -1 to the input routine, primarily because
176                          * existing input routines follow implicit-coercion semantics
177                          * for length checks, which is not always what we want here.
178                          * Any length constraint will be applied later by our caller.
179                          *
180                          * Note that we call stringTypeDatum using the domain's pg_type
181                          * row, if it's a domain.  This works because the domain row
182                          * has the same typinput and typelem as the base type ---
183                          * ugly...
184                          */
185                         newcon->constvalue = stringTypeDatum(targetType, val, -1);
186                         pfree(val);
187                 }
188
189                 result = (Node *) newcon;
190
191                 /* If target is a domain, apply constraints. */
192                 if (targetTyptype == 'd')
193                         result = coerce_to_domain(result, InvalidOid, targetTypeId,
194                                                                           cformat, false);
195
196                 ReleaseSysCache(targetType);
197
198                 return result;
199         }
200         if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
201                 ((Param *) node)->paramkind == PARAM_NUM &&
202                 pstate != NULL && pstate->p_variableparams)
203         {
204                 /*
205                  * Input is a Param of previously undetermined type, and we want
206                  * to update our knowledge of the Param's type.  Find the topmost
207                  * ParseState and update the state.
208                  */
209                 Param      *param = (Param *) node;
210                 int                     paramno = param->paramid;
211                 ParseState *toppstate;
212
213                 toppstate = pstate;
214                 while (toppstate->parentParseState != NULL)
215                         toppstate = toppstate->parentParseState;
216
217                 if (paramno <= 0 ||             /* shouldn't happen, but... */
218                         paramno > toppstate->p_numparams)
219                         ereport(ERROR,
220                                         (errcode(ERRCODE_UNDEFINED_PARAMETER),
221                                          errmsg("there is no parameter $%d", paramno)));
222
223                 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
224                 {
225                         /* We've successfully resolved the type */
226                         toppstate->p_paramtypes[paramno - 1] = targetTypeId;
227                 }
228                 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
229                 {
230                         /* We previously resolved the type, and it matches */
231                 }
232                 else
233                 {
234                         /* Ooops */
235                         ereport(ERROR,
236                                         (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
237                                    errmsg("inconsistent types deduced for parameter $%d",
238                                                   paramno),
239                                          errdetail("%s versus %s",
240                                         format_type_be(toppstate->p_paramtypes[paramno - 1]),
241                                                            format_type_be(targetTypeId))));
242                 }
243
244                 param->paramtype = targetTypeId;
245                 return (Node *) param;
246         }
247         if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
248                                                           &funcId))
249         {
250                 if (OidIsValid(funcId))
251                 {
252                         /*
253                          * Generate an expression tree representing run-time
254                          * application of the conversion function.      If we are dealing
255                          * with a domain target type, the conversion function will
256                          * yield the base type (and we assume targetTypeMod must be -1).
257                          */
258                         Oid                     baseTypeId = getBaseType(targetTypeId);
259
260                         result = build_coercion_expression(node, funcId,
261                                                                                            baseTypeId, targetTypeMod,
262                                                                                            cformat,
263                                                                                            (cformat != COERCE_IMPLICIT_CAST));
264
265                         /*
266                          * If domain, coerce to the domain type and relabel with
267                          * domain type ID
268                          */
269                         if (targetTypeId != baseTypeId)
270                                 result = coerce_to_domain(result, baseTypeId, targetTypeId,
271                                                                                   cformat, true);
272                 }
273                 else
274                 {
275                         /*
276                          * We don't need to do a physical conversion, but we do need
277                          * to attach a RelabelType node so that the expression will be
278                          * seen to have the intended type when inspected by
279                          * higher-level code.
280                          *
281                          * Also, domains may have value restrictions beyond the base type
282                          * that must be accounted for.  If the destination is a domain
283                          * then we won't need a RelabelType node.
284                          */
285                         result = coerce_to_domain(node, InvalidOid, targetTypeId,
286                                                                           cformat, false);
287                         if (result == node)
288                         {
289                                 /*
290                                  * XXX could we label result with exprTypmod(node) instead
291                                  * of default -1 typmod, to save a possible
292                                  * length-coercion later? Would work if both types have
293                                  * same interpretation of typmod, which is likely but not
294                                  * certain.
295                                  */
296                                 result = (Node *) makeRelabelType((Expr *) result,
297                                                                                                   targetTypeId, -1,
298                                                                                                   cformat);
299                         }
300                 }
301                 return result;
302         }
303         if (inputTypeId == RECORDOID &&
304                 ISCOMPLEX(targetTypeId))
305         {
306                 /* Coerce a RECORD to a specific complex type */
307                 return coerce_record_to_complex(pstate, node, targetTypeId,
308                                                                                 ccontext, cformat);
309         }
310         if (typeInheritsFrom(inputTypeId, targetTypeId))
311         {
312                 /*
313                  * Input class type is a subclass of target, so nothing to do ---
314                  * except relabel the type.  This is binary compatibility for
315                  * complex types.
316                  */
317                 return (Node *) makeRelabelType((Expr *) node,
318                                                                                 targetTypeId, -1,
319                                                                                 cformat);
320         }
321         /* If we get here, caller blew it */
322         elog(ERROR, "failed to find conversion function from %s to %s",
323                  format_type_be(inputTypeId), format_type_be(targetTypeId));
324         return NULL;                            /* keep compiler quiet */
325 }
326
327
328 /*
329  * can_coerce_type()
330  *              Can input_typeids be coerced to target_typeids?
331  *
332  * We must be told the context (CAST construct, assignment, implicit coercion)
333  * as this determines the set of available casts.
334  */
335 bool
336 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
337                                 CoercionContext ccontext)
338 {
339         bool            have_generics = false;
340         int                     i;
341
342         /* run through argument list... */
343         for (i = 0; i < nargs; i++)
344         {
345                 Oid                     inputTypeId = input_typeids[i];
346                 Oid                     targetTypeId = target_typeids[i];
347                 Oid                     funcId;
348
349                 /* no problem if same type */
350                 if (inputTypeId == targetTypeId)
351                         continue;
352
353                 /* don't choke on references to no-longer-existing types */
354                 if (!typeidIsValid(inputTypeId))
355                         return false;
356                 if (!typeidIsValid(targetTypeId))
357                         return false;
358
359                 /* accept if target is ANY */
360                 if (targetTypeId == ANYOID)
361                         continue;
362
363                 /* accept if target is ANYARRAY or ANYELEMENT, for now */
364                 if (targetTypeId == ANYARRAYOID ||
365                         targetTypeId == ANYELEMENTOID)
366                 {
367                         have_generics = true;           /* do more checking later */
368                         continue;
369                 }
370
371                 /*
372                  * If input is an untyped string constant, assume we can convert
373                  * it to anything.
374                  */
375                 if (inputTypeId == UNKNOWNOID)
376                         continue;
377
378                 /*
379                  * If pg_cast shows that we can coerce, accept.  This test now
380                  * covers both binary-compatible and coercion-function cases.
381                  */
382                 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
383                                                                   &funcId))
384                         continue;
385
386                 /*
387                  * If input is RECORD and target is a composite type, assume
388                  * we can coerce (may need tighter checking here)
389                  */
390                 if (inputTypeId == RECORDOID &&
391                         ISCOMPLEX(targetTypeId))
392                         continue;
393
394                 /*
395                  * If input is a class type that inherits from target, accept
396                  */
397                 if (typeInheritsFrom(inputTypeId, targetTypeId))
398                         continue;
399
400                 /*
401                  * Else, cannot coerce at this argument position
402                  */
403                 return false;
404         }
405
406         /* If we found any generic argument types, cross-check them */
407         if (have_generics)
408         {
409                 if (!check_generic_type_consistency(input_typeids, target_typeids,
410                                                                                         nargs))
411                         return false;
412         }
413
414         return true;
415 }
416
417
418 /*
419  * Create an expression tree to represent coercion to a domain type.
420  *
421  * 'arg': input expression
422  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
423  *              has not bothered to look this up)
424  * 'typeId': target type to coerce to
425  * 'cformat': coercion format
426  * 'hideInputCoercion': if true, hide the input coercion under this one.
427  *
428  * If the target type isn't a domain, the given 'arg' is returned as-is.
429  */
430 Node *
431 coerce_to_domain(Node *arg, Oid baseTypeId, Oid typeId,
432                                  CoercionForm cformat, bool hideInputCoercion)
433 {
434         CoerceToDomain *result;
435         int32           typmod;
436
437         /* Get the base type if it hasn't been supplied */
438         if (baseTypeId == InvalidOid)
439                 baseTypeId = getBaseType(typeId);
440
441         /* If it isn't a domain, return the node as it was passed in */
442         if (baseTypeId == typeId)
443                 return arg;
444
445         /* Suppress display of nested coercion steps */
446         if (hideInputCoercion)
447                 hide_coercion_node(arg);
448
449         /*
450          * If the domain applies a typmod to its base type, build the
451          * appropriate coercion step.  Mark it implicit for display purposes,
452          * because we don't want it shown separately by ruleutils.c; but the
453          * isExplicit flag passed to the conversion function depends on the
454          * manner in which the domain coercion is invoked, so that the
455          * semantics of implicit and explicit coercion differ.  (Is that
456          * really the behavior we want?)
457          *
458          * NOTE: because we apply this as part of the fixed expression structure,
459          * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that
460          * that would be safe to do anyway, without lots of knowledge about
461          * what the base type thinks the typmod means.
462          */
463         typmod = get_typtypmod(typeId);
464         if (typmod >= 0)
465                 arg = coerce_type_typmod(arg, baseTypeId, typmod,
466                                                                  COERCE_IMPLICIT_CAST,
467                                                                  (cformat != COERCE_IMPLICIT_CAST),
468                                                                  false);
469
470         /*
471          * Now build the domain coercion node.  This represents run-time
472          * checking of any constraints currently attached to the domain.  This
473          * also ensures that the expression is properly labeled as to result
474          * type.
475          */
476         result = makeNode(CoerceToDomain);
477         result->arg = (Expr *) arg;
478         result->resulttype = typeId;
479         result->resulttypmod = -1;      /* currently, always -1 for domains */
480         result->coercionformat = cformat;
481
482         return (Node *) result;
483 }
484
485
486 /*
487  * coerce_type_typmod()
488  *              Force a value to a particular typmod, if meaningful and possible.
489  *
490  * This is applied to values that are going to be stored in a relation
491  * (where we have an atttypmod for the column) as well as values being
492  * explicitly CASTed (where the typmod comes from the target type spec).
493  *
494  * The caller must have already ensured that the value is of the correct
495  * type, typically by applying coerce_type.
496  *
497  * cformat determines the display properties of the generated node (if any),
498  * while isExplicit may affect semantics.  If hideInputCoercion is true
499  * *and* we generate a node, the input node is forced to IMPLICIT display
500  * form, so that only the typmod coercion node will be visible when
501  * displaying the expression.
502  *
503  * NOTE: this does not need to work on domain types, because any typmod
504  * coercion for a domain is considered to be part of the type coercion
505  * needed to produce the domain value in the first place.  So, no getBaseType.
506  */
507 static Node *
508 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
509                                    CoercionForm cformat, bool isExplicit,
510                                    bool hideInputCoercion)
511 {
512         Oid                     funcId;
513
514         /*
515          * A negative typmod is assumed to mean that no coercion is wanted.
516          * Also, skip coercion if already done.
517          */
518         if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
519                 return node;
520
521         funcId = find_typmod_coercion_function(targetTypeId);
522
523         if (OidIsValid(funcId))
524         {
525                 /* Suppress display of nested coercion steps */
526                 if (hideInputCoercion)
527                         hide_coercion_node(node);
528
529                 node = build_coercion_expression(node, funcId,
530                                                                                  targetTypeId, targetTypMod,
531                                                                                  cformat, isExplicit);
532         }
533
534         return node;
535 }
536
537 /*
538  * Mark a coercion node as IMPLICIT so it will never be displayed by
539  * ruleutils.c.  We use this when we generate a nest of coercion nodes
540  * to implement what is logically one conversion; the inner nodes are
541  * forced to IMPLICIT_CAST format.  This does not change their semantics,
542  * only display behavior.
543  *
544  * It is caller error to call this on something that doesn't have a
545  * CoercionForm field.
546  */
547 static void
548 hide_coercion_node(Node *node)
549 {
550         if (IsA(node, FuncExpr))
551                 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
552         else if (IsA(node, RelabelType))
553                 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
554         else if (IsA(node, RowExpr))
555                 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
556         else if (IsA(node, CoerceToDomain))
557                 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
558         else
559                 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
560 }
561
562 /*
563  * build_coercion_expression()
564  *              Construct a function-call expression for applying a pg_cast entry.
565  *
566  * This is used for both type-coercion and length-coercion functions,
567  * since there is no difference in terms of the calling convention.
568  */
569 static Node *
570 build_coercion_expression(Node *node, Oid funcId,
571                                                   Oid targetTypeId, int32 targetTypMod,
572                                                   CoercionForm cformat, bool isExplicit)
573 {
574         HeapTuple       tp;
575         Form_pg_proc procstruct;
576         int                     nargs;
577         List       *args;
578         Const      *cons;
579
580         tp = SearchSysCache(PROCOID,
581                                                 ObjectIdGetDatum(funcId),
582                                                 0, 0, 0);
583         if (!HeapTupleIsValid(tp))
584                 elog(ERROR, "cache lookup failed for function %u", funcId);
585         procstruct = (Form_pg_proc) GETSTRUCT(tp);
586
587         /*
588          * Asserts essentially check that function is a legal coercion function.
589          * We can't make the seemingly obvious tests on prorettype and
590          * proargtypes[0], because of various binary-compatibility cases.
591          */
592         /* Assert(targetTypeId == procstruct->prorettype); */
593         Assert(!procstruct->proretset);
594         Assert(!procstruct->proisagg);
595         nargs = procstruct->pronargs;
596         Assert(nargs >= 1 && nargs <= 3);
597         /* Assert(procstruct->proargtypes[0] == exprType(node)); */
598         Assert(nargs < 2 || procstruct->proargtypes[1] == INT4OID);
599         Assert(nargs < 3 || procstruct->proargtypes[2] == BOOLOID);
600
601         ReleaseSysCache(tp);
602
603         args = list_make1(node);
604
605         if (nargs >= 2)
606         {
607                 /* Pass target typmod as an int4 constant */
608                 cons = makeConst(INT4OID,
609                                                  sizeof(int32),
610                                                  Int32GetDatum(targetTypMod),
611                                                  false,
612                                                  true);
613
614                 args = lappend(args, cons);
615         }
616
617         if (nargs == 3)
618         {
619                 /* Pass it a boolean isExplicit parameter, too */
620                 cons = makeConst(BOOLOID,
621                                                  sizeof(bool),
622                                                  BoolGetDatum(isExplicit),
623                                                  false,
624                                                  true);
625
626                 args = lappend(args, cons);
627         }
628
629         return (Node *) makeFuncExpr(funcId, targetTypeId, args, cformat);
630 }
631
632
633 /*
634  * coerce_record_to_complex
635  *              Coerce a RECORD to a specific composite type.
636  *
637  * Currently we only support this for inputs that are RowExprs or whole-row
638  * Vars.
639  */
640 static Node *
641 coerce_record_to_complex(ParseState *pstate, Node *node,
642                                                  Oid targetTypeId,
643                                                  CoercionContext ccontext,
644                                                  CoercionForm cformat)
645 {
646         RowExpr    *rowexpr;
647         TupleDesc       tupdesc;
648         List       *args = NIL;
649         List       *newargs;
650         int                     i;
651         ListCell   *arg;
652
653         if (node && IsA(node, RowExpr))
654         {
655                 args = ((RowExpr *) node)->args;
656         }
657         else if (node && IsA(node, Var) &&
658                          ((Var *) node)->varattno == InvalidAttrNumber)
659         {
660                 RangeTblEntry *rte;
661                 AttrNumber nfields;
662                 AttrNumber nf;
663
664                 rte = GetRTEByRangeTablePosn(pstate,
665                                                                          ((Var *) node)->varno,
666                                                                          ((Var *) node)->varlevelsup);
667                 nfields = list_length(rte->eref->colnames);
668                 for (nf = 1; nf <= nfields; nf++)
669                 {
670                         Oid             vartype;
671                         int32   vartypmod;
672
673                         get_rte_attribute_type(rte, nf, &vartype, &vartypmod);
674                         args = lappend(args,
675                                                    makeVar(((Var *) node)->varno,
676                                                                    nf,
677                                                                    vartype,
678                                                                    vartypmod,
679                                                                    ((Var *) node)->varlevelsup));
680                 }
681         }
682         else
683                 ereport(ERROR,
684                                 (errcode(ERRCODE_CANNOT_COERCE),
685                                  errmsg("cannot cast type %s to %s",
686                                                 format_type_be(RECORDOID),
687                                                 format_type_be(targetTypeId))));
688
689         tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
690         if (list_length(args) != tupdesc->natts)
691                 ereport(ERROR,
692                                 (errcode(ERRCODE_CANNOT_COERCE),
693                                  errmsg("cannot cast type %s to %s",
694                                                 format_type_be(RECORDOID),
695                                                 format_type_be(targetTypeId)),
696                                  errdetail("Input has wrong number of columns.")));
697         newargs = NIL;
698         i = 0;
699         foreach(arg, args)
700         {
701                 Node   *expr = (Node *) lfirst(arg);
702                 Oid             exprtype = exprType(expr);
703
704                 expr = coerce_to_target_type(pstate,
705                                                                          expr, exprtype,
706                                                                          tupdesc->attrs[i]->atttypid,
707                                                                          tupdesc->attrs[i]->atttypmod,
708                                                                          ccontext,
709                                                                          COERCE_IMPLICIT_CAST);
710                 if (expr == NULL)
711                         ereport(ERROR,
712                                         (errcode(ERRCODE_CANNOT_COERCE),
713                                          errmsg("cannot cast type %s to %s",
714                                                         format_type_be(RECORDOID),
715                                                         format_type_be(targetTypeId)),
716                                          errdetail("Cannot cast type %s to %s in column %d.",
717                                                            format_type_be(exprtype),
718                                                            format_type_be(tupdesc->attrs[i]->atttypid),
719                                                            i + 1)));
720                 newargs = lappend(newargs, expr);
721                 i++;
722         }
723
724         rowexpr = makeNode(RowExpr);
725         rowexpr->args = newargs;
726         rowexpr->row_typeid = targetTypeId;
727         rowexpr->row_format = cformat;
728         return (Node *) rowexpr;
729 }
730
731 /* coerce_to_boolean()
732  *              Coerce an argument of a construct that requires boolean input
733  *              (AND, OR, NOT, etc).  Also check that input is not a set.
734  *
735  * Returns the possibly-transformed node tree.
736  *
737  * As with coerce_type, pstate may be NULL if no special unknown-Param
738  * processing is wanted.
739  */
740 Node *
741 coerce_to_boolean(ParseState *pstate, Node *node,
742                                   const char *constructName)
743 {
744         Oid                     inputTypeId = exprType(node);
745
746         if (inputTypeId != BOOLOID)
747         {
748                 node = coerce_to_target_type(pstate, node, inputTypeId,
749                                                                          BOOLOID, -1,
750                                                                          COERCION_ASSIGNMENT,
751                                                                          COERCE_IMPLICIT_CAST);
752                 if (node == NULL)
753                         ereport(ERROR,
754                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
755                         /* translator: first %s is name of a SQL construct, eg WHERE */
756                            errmsg("argument of %s must be type boolean, not type %s",
757                                           constructName, format_type_be(inputTypeId))));
758         }
759
760         if (expression_returns_set(node))
761                 ereport(ERROR,
762                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
763                 /* translator: %s is name of a SQL construct, eg WHERE */
764                                  errmsg("argument of %s must not return a set",
765                                                 constructName)));
766
767         return node;
768 }
769
770 /* coerce_to_integer()
771  *              Coerce an argument of a construct that requires integer input
772  *              (LIMIT, OFFSET, etc).  Also check that input is not a set.
773  *
774  * Returns the possibly-transformed node tree.
775  *
776  * As with coerce_type, pstate may be NULL if no special unknown-Param
777  * processing is wanted.
778  */
779 Node *
780 coerce_to_integer(ParseState *pstate, Node *node,
781                                   const char *constructName)
782 {
783         Oid                     inputTypeId = exprType(node);
784
785         if (inputTypeId != INT4OID)
786         {
787                 node = coerce_to_target_type(pstate, node, inputTypeId,
788                                                                          INT4OID, -1,
789                                                                          COERCION_ASSIGNMENT,
790                                                                          COERCE_IMPLICIT_CAST);
791                 if (node == NULL)
792                         ereport(ERROR,
793                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
794                         /* translator: first %s is name of a SQL construct, eg LIMIT */
795                            errmsg("argument of %s must be type integer, not type %s",
796                                           constructName, format_type_be(inputTypeId))));
797         }
798
799         if (expression_returns_set(node))
800                 ereport(ERROR,
801                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
802                 /* translator: %s is name of a SQL construct, eg LIMIT */
803                                  errmsg("argument of %s must not return a set",
804                                                 constructName)));
805
806         return node;
807 }
808
809
810 /* select_common_type()
811  *              Determine the common supertype of a list of input expression types.
812  *              This is used for determining the output type of CASE and UNION
813  *              constructs.
814  *
815  * typeids is a nonempty list of type OIDs.  Note that earlier items
816  * in the list will be preferred if there is doubt.
817  * 'context' is a phrase to use in the error message if we fail to select
818  * a usable type.
819  */
820 Oid
821 select_common_type(List *typeids, const char *context)
822 {
823         Oid                     ptype;
824         CATEGORY        pcategory;
825         ListCell   *type_item;
826
827         Assert(typeids != NIL);
828         ptype = getBaseType(linitial_oid(typeids));
829         pcategory = TypeCategory(ptype);
830
831         for_each_cell(type_item, lnext(list_head(typeids)))
832         {
833                 Oid                     ntype = getBaseType(lfirst_oid(type_item));
834
835                 /* move on to next one if no new information... */
836                 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
837                 {
838                         if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
839                         {
840                                 /* so far, only nulls so take anything... */
841                                 ptype = ntype;
842                                 pcategory = TypeCategory(ptype);
843                         }
844                         else if (TypeCategory(ntype) != pcategory)
845                         {
846                                 /*
847                                  * both types in different categories? then not much
848                                  * hope...
849                                  */
850                                 ereport(ERROR,
851                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
852                                 /*
853                                  * translator: first %s is name of a SQL construct, eg
854                                  * CASE
855                                  */
856                                                  errmsg("%s types %s and %s cannot be matched",
857                                                                 context,
858                                                                 format_type_be(ptype),
859                                                                 format_type_be(ntype))));
860                         }
861                         else if (!IsPreferredType(pcategory, ptype) &&
862                                  can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
863                                   !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
864                         {
865                                 /*
866                                  * take new type if can coerce to it implicitly but not
867                                  * the other way; but if we have a preferred type, stay on
868                                  * it.
869                                  */
870                                 ptype = ntype;
871                                 pcategory = TypeCategory(ptype);
872                         }
873                 }
874         }
875
876         /*
877          * If all the inputs were UNKNOWN type --- ie, unknown-type literals
878          * --- then resolve as type TEXT.  This situation comes up with
879          * constructs like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END);
880          * SELECT 'foo' UNION SELECT 'bar'; It might seem desirable to leave
881          * the construct's output type as UNKNOWN, but that really doesn't
882          * work, because we'd probably end up needing a runtime coercion from
883          * UNKNOWN to something else, and we usually won't have it.  We need
884          * to coerce the unknown literals while they are still literals, so a
885          * decision has to be made now.
886          */
887         if (ptype == UNKNOWNOID)
888                 ptype = TEXTOID;
889
890         return ptype;
891 }
892
893 /* coerce_to_common_type()
894  *              Coerce an expression to the given type.
895  *
896  * This is used following select_common_type() to coerce the individual
897  * expressions to the desired type.  'context' is a phrase to use in the
898  * error message if we fail to coerce.
899  *
900  * As with coerce_type, pstate may be NULL if no special unknown-Param
901  * processing is wanted.
902  */
903 Node *
904 coerce_to_common_type(ParseState *pstate, Node *node,
905                                           Oid targetTypeId, const char *context)
906 {
907         Oid                     inputTypeId = exprType(node);
908
909         if (inputTypeId == targetTypeId)
910                 return node;                    /* no work */
911         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
912                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
913                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
914         else
915                 ereport(ERROR,
916                                 (errcode(ERRCODE_CANNOT_COERCE),
917                 /* translator: first %s is name of a SQL construct, eg CASE */
918                                  errmsg("%s could not convert type %s to %s",
919                                                 context,
920                                                 format_type_be(inputTypeId),
921                                                 format_type_be(targetTypeId))));
922         return node;
923 }
924
925 /*
926  * check_generic_type_consistency()
927  *              Are the actual arguments potentially compatible with a
928  *              polymorphic function?
929  *
930  * The argument consistency rules are:
931  *
932  * 1) All arguments declared ANYARRAY must have matching datatypes,
933  *        and must in fact be varlena arrays.
934  * 2) All arguments declared ANYELEMENT must have matching datatypes.
935  * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
936  *        the actual ANYELEMENT datatype is in fact the element type for
937  *        the actual ANYARRAY datatype.
938  *
939  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
940  * or ANYARRAY argument, assume it is okay.
941  *
942  * If an input is of type ANYARRAY (ie, we know it's an array, but not
943  * what element type), we will accept it as a match to an argument declared
944  * ANYARRAY, so long as we don't have to determine an element type ---
945  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
946  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
947  *
948  * We do not ereport here, but just return FALSE if a rule is violated.
949  */
950 bool
951 check_generic_type_consistency(Oid *actual_arg_types,
952                                                            Oid *declared_arg_types,
953                                                            int nargs)
954 {
955         int                     j;
956         Oid                     elem_typeid = InvalidOid;
957         Oid                     array_typeid = InvalidOid;
958         Oid                     array_typelem;
959         bool            have_anyelement = false;
960
961         /*
962          * Loop through the arguments to see if we have any that are ANYARRAY
963          * or ANYELEMENT. If so, require the actual types to be
964          * self-consistent
965          */
966         for (j = 0; j < nargs; j++)
967         {
968                 Oid                     actual_type = actual_arg_types[j];
969
970                 if (declared_arg_types[j] == ANYELEMENTOID)
971                 {
972                         have_anyelement = true;
973                         if (actual_type == UNKNOWNOID)
974                                 continue;
975                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
976                                 return false;
977                         elem_typeid = actual_type;
978                 }
979                 else if (declared_arg_types[j] == ANYARRAYOID)
980                 {
981                         if (actual_type == UNKNOWNOID)
982                                 continue;
983                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
984                                 return false;
985                         array_typeid = actual_type;
986                 }
987         }
988
989         /* Get the element type based on the array type, if we have one */
990         if (OidIsValid(array_typeid))
991         {
992                 if (array_typeid == ANYARRAYOID)
993                 {
994                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
995                         if (have_anyelement)
996                                 return false;
997                         return true;
998                 }
999
1000                 array_typelem = get_element_type(array_typeid);
1001                 if (!OidIsValid(array_typelem))
1002                         return false;           /* should be an array, but isn't */
1003
1004                 if (!OidIsValid(elem_typeid))
1005                 {
1006                         /*
1007                          * if we don't have an element type yet, use the one we just
1008                          * got
1009                          */
1010                         elem_typeid = array_typelem;
1011                 }
1012                 else if (array_typelem != elem_typeid)
1013                 {
1014                         /* otherwise, they better match */
1015                         return false;
1016                 }
1017         }
1018
1019         /* Looks valid */
1020         return true;
1021 }
1022
1023 /*
1024  * enforce_generic_type_consistency()
1025  *              Make sure a polymorphic function is legally callable, and
1026  *              deduce actual argument and result types.
1027  *
1028  * If ANYARRAY or ANYELEMENT is used for a function's arguments or
1029  * return type, we make sure the actual data types are consistent with
1030  * each other. The argument consistency rules are shown above for
1031  * check_generic_type_consistency().
1032  *
1033  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
1034  * or ANYARRAY argument, we attempt to deduce the actual type it should
1035  * have.  If successful, we alter that position of declared_arg_types[]
1036  * so that make_fn_arguments will coerce the literal to the right thing.
1037  *
1038  * Rules are applied to the function's return type (possibly altering it)
1039  * if it is declared ANYARRAY or ANYELEMENT:
1040  *
1041  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1042  *        argument's actual type as the function's return type.
1043  * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1044  *        is ANYELEMENT, use the actual type of the argument to determine
1045  *        the function's return type, i.e. the element type's corresponding
1046  *        array type.
1047  * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1048  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1049  *        and is therefore not expected here.
1050  * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1051  *        argument's actual type as the function's return type.
1052  * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1053  *        argument is ANYARRAY, use the actual type of the argument to determine
1054  *        the function's return type, i.e. the array type's corresponding
1055  *        element type.
1056  * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1057  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1058  *        and is therefore not expected here.
1059  */
1060 Oid
1061 enforce_generic_type_consistency(Oid *actual_arg_types,
1062                                                                  Oid *declared_arg_types,
1063                                                                  int nargs,
1064                                                                  Oid rettype)
1065 {
1066         int                     j;
1067         bool            have_generics = false;
1068         bool            have_unknowns = false;
1069         Oid                     elem_typeid = InvalidOid;
1070         Oid                     array_typeid = InvalidOid;
1071         Oid                     array_typelem;
1072         bool            have_anyelement = (rettype == ANYELEMENTOID);
1073
1074         /*
1075          * Loop through the arguments to see if we have any that are ANYARRAY
1076          * or ANYELEMENT. If so, require the actual types to be
1077          * self-consistent
1078          */
1079         for (j = 0; j < nargs; j++)
1080         {
1081                 Oid                     actual_type = actual_arg_types[j];
1082
1083                 if (declared_arg_types[j] == ANYELEMENTOID)
1084                 {
1085                         have_generics = have_anyelement = true;
1086                         if (actual_type == UNKNOWNOID)
1087                         {
1088                                 have_unknowns = true;
1089                                 continue;
1090                         }
1091                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1092                                 ereport(ERROR,
1093                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1094                                 errmsg("arguments declared \"anyelement\" are not all alike"),
1095                                                  errdetail("%s versus %s",
1096                                                                    format_type_be(elem_typeid),
1097                                                                    format_type_be(actual_type))));
1098                         elem_typeid = actual_type;
1099                 }
1100                 else if (declared_arg_types[j] == ANYARRAYOID)
1101                 {
1102                         have_generics = true;
1103                         if (actual_type == UNKNOWNOID)
1104                         {
1105                                 have_unknowns = true;
1106                                 continue;
1107                         }
1108                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1109                                 ereport(ERROR,
1110                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1111                                  errmsg("arguments declared \"anyarray\" are not all alike"),
1112                                                  errdetail("%s versus %s",
1113                                                                    format_type_be(array_typeid),
1114                                                                    format_type_be(actual_type))));
1115                         array_typeid = actual_type;
1116                 }
1117         }
1118
1119         /*
1120          * Fast Track: if none of the arguments are ANYARRAY or ANYELEMENT,
1121          * return the unmodified rettype.
1122          */
1123         if (!have_generics)
1124                 return rettype;
1125
1126         /* Get the element type based on the array type, if we have one */
1127         if (OidIsValid(array_typeid))
1128         {
1129                 if (array_typeid == ANYARRAYOID && !have_anyelement)
1130                 {
1131                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1132                         array_typelem = InvalidOid;
1133                 }
1134                 else
1135                 {
1136                         array_typelem = get_element_type(array_typeid);
1137                         if (!OidIsValid(array_typelem))
1138                                 ereport(ERROR,
1139                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1140                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1141                                                                 format_type_be(array_typeid))));
1142                 }
1143
1144                 if (!OidIsValid(elem_typeid))
1145                 {
1146                         /*
1147                          * if we don't have an element type yet, use the one we just
1148                          * got
1149                          */
1150                         elem_typeid = array_typelem;
1151                 }
1152                 else if (array_typelem != elem_typeid)
1153                 {
1154                         /* otherwise, they better match */
1155                         ereport(ERROR,
1156                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1157                                          errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1158                                          errdetail("%s versus %s",
1159                                                            format_type_be(array_typeid),
1160                                                            format_type_be(elem_typeid))));
1161                 }
1162         }
1163         else if (!OidIsValid(elem_typeid))
1164         {
1165                 /* Only way to get here is if all the generic args are UNKNOWN */
1166                 ereport(ERROR,
1167                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1168                                  errmsg("could not determine anyarray/anyelement type because input has type \"unknown\"")));
1169         }
1170
1171         /*
1172          * If we had any unknown inputs, re-scan to assign correct types
1173          */
1174         if (have_unknowns)
1175         {
1176                 for (j = 0; j < nargs; j++)
1177                 {
1178                         Oid                     actual_type = actual_arg_types[j];
1179
1180                         if (actual_type != UNKNOWNOID)
1181                                 continue;
1182
1183                         if (declared_arg_types[j] == ANYELEMENTOID)
1184                                 declared_arg_types[j] = elem_typeid;
1185                         else if (declared_arg_types[j] == ANYARRAYOID)
1186                         {
1187                                 if (!OidIsValid(array_typeid))
1188                                 {
1189                                         array_typeid = get_array_type(elem_typeid);
1190                                         if (!OidIsValid(array_typeid))
1191                                                 ereport(ERROR,
1192                                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1193                                                                  errmsg("could not find array type for data type %s",
1194                                                                                 format_type_be(elem_typeid))));
1195                                 }
1196                                 declared_arg_types[j] = array_typeid;
1197                         }
1198                 }
1199         }
1200
1201         /* if we return ANYARRAYOID use the appropriate argument type */
1202         if (rettype == ANYARRAYOID)
1203         {
1204                 if (!OidIsValid(array_typeid))
1205                 {
1206                         array_typeid = get_array_type(elem_typeid);
1207                         if (!OidIsValid(array_typeid))
1208                                 ereport(ERROR,
1209                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1210                                           errmsg("could not find array type for data type %s",
1211                                                          format_type_be(elem_typeid))));
1212                 }
1213                 return array_typeid;
1214         }
1215
1216         /* if we return ANYELEMENTOID use the appropriate argument type */
1217         if (rettype == ANYELEMENTOID)
1218                 return elem_typeid;
1219
1220         /* we don't return a generic type; send back the original return type */
1221         return rettype;
1222 }
1223
1224 /*
1225  * resolve_generic_type()
1226  *              Deduce an individual actual datatype on the assumption that
1227  *              the rules for ANYARRAY/ANYELEMENT are being followed.
1228  *
1229  * declared_type is the declared datatype we want to resolve.
1230  * context_actual_type is the actual input datatype to some argument
1231  * that has declared datatype context_declared_type.
1232  *
1233  * If declared_type isn't polymorphic, we just return it.  Otherwise,
1234  * context_declared_type must be polymorphic, and we deduce the correct
1235  * return type based on the relationship of the two polymorphic types.
1236  */
1237 Oid
1238 resolve_generic_type(Oid declared_type,
1239                                          Oid context_actual_type,
1240                                          Oid context_declared_type)
1241 {
1242         if (declared_type == ANYARRAYOID)
1243         {
1244                 if (context_declared_type == ANYARRAYOID)
1245                 {
1246                         /* Use actual type, but it must be an array */
1247                         Oid                     array_typelem = get_element_type(context_actual_type);
1248
1249                         if (!OidIsValid(array_typelem))
1250                                 ereport(ERROR,
1251                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1252                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1253                                                                 format_type_be(context_actual_type))));
1254                         return context_actual_type;
1255                 }
1256                 else if (context_declared_type == ANYELEMENTOID)
1257                 {
1258                         /* Use the array type corresponding to actual type */
1259                         Oid                     array_typeid = get_array_type(context_actual_type);
1260
1261                         if (!OidIsValid(array_typeid))
1262                                 ereport(ERROR,
1263                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1264                                           errmsg("could not find array type for data type %s",
1265                                                          format_type_be(context_actual_type))));
1266                         return array_typeid;
1267                 }
1268         }
1269         else if (declared_type == ANYELEMENTOID)
1270         {
1271                 if (context_declared_type == ANYARRAYOID)
1272                 {
1273                         /* Use the element type corresponding to actual type */
1274                         Oid                     array_typelem = get_element_type(context_actual_type);
1275
1276                         if (!OidIsValid(array_typelem))
1277                                 ereport(ERROR,
1278                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1279                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1280                                                                 format_type_be(context_actual_type))));
1281                         return array_typelem;
1282                 }
1283                 else if (context_declared_type == ANYELEMENTOID)
1284                 {
1285                         /* Use the actual type; it doesn't matter if array or not */
1286                         return context_actual_type;
1287                 }
1288         }
1289         else
1290         {
1291                 /* declared_type isn't polymorphic, so return it as-is */
1292                 return declared_type;
1293         }
1294         /* If we get here, declared_type is polymorphic and context isn't */
1295         /* NB: this is a calling-code logic error, not a user error */
1296         elog(ERROR, "could not determine ANYARRAY/ANYELEMENT type because context isn't polymorphic");
1297         return InvalidOid;                      /* keep compiler quiet */
1298 }
1299
1300
1301 /* TypeCategory()
1302  *              Assign a category to the specified type OID.
1303  *
1304  * NB: this must not return INVALID_TYPE.
1305  *
1306  * XXX This should be moved to system catalog lookups
1307  * to allow for better type extensibility.
1308  * - thomas 2001-09-30
1309  */
1310 CATEGORY
1311 TypeCategory(Oid inType)
1312 {
1313         CATEGORY        result;
1314
1315         switch (inType)
1316         {
1317                 case (BOOLOID):
1318                         result = BOOLEAN_TYPE;
1319                         break;
1320
1321                 case (CHAROID):
1322                 case (NAMEOID):
1323                 case (BPCHAROID):
1324                 case (VARCHAROID):
1325                 case (TEXTOID):
1326                         result = STRING_TYPE;
1327                         break;
1328
1329                 case (BITOID):
1330                 case (VARBITOID):
1331                         result = BITSTRING_TYPE;
1332                         break;
1333
1334                 case (OIDOID):
1335                 case (REGPROCOID):
1336                 case (REGPROCEDUREOID):
1337                 case (REGOPEROID):
1338                 case (REGOPERATOROID):
1339                 case (REGCLASSOID):
1340                 case (REGTYPEOID):
1341                 case (INT2OID):
1342                 case (INT4OID):
1343                 case (INT8OID):
1344                 case (FLOAT4OID):
1345                 case (FLOAT8OID):
1346                 case (NUMERICOID):
1347                 case (CASHOID):
1348                         result = NUMERIC_TYPE;
1349                         break;
1350
1351                 case (DATEOID):
1352                 case (TIMEOID):
1353                 case (TIMETZOID):
1354                 case (ABSTIMEOID):
1355                 case (TIMESTAMPOID):
1356                 case (TIMESTAMPTZOID):
1357                         result = DATETIME_TYPE;
1358                         break;
1359
1360                 case (RELTIMEOID):
1361                 case (TINTERVALOID):
1362                 case (INTERVALOID):
1363                         result = TIMESPAN_TYPE;
1364                         break;
1365
1366                 case (POINTOID):
1367                 case (LSEGOID):
1368                 case (PATHOID):
1369                 case (BOXOID):
1370                 case (POLYGONOID):
1371                 case (LINEOID):
1372                 case (CIRCLEOID):
1373                         result = GEOMETRIC_TYPE;
1374                         break;
1375
1376                 case (INETOID):
1377                 case (CIDROID):
1378                         result = NETWORK_TYPE;
1379                         break;
1380
1381                 case (UNKNOWNOID):
1382                 case (InvalidOid):
1383                         result = UNKNOWN_TYPE;
1384                         break;
1385
1386                 case (RECORDOID):
1387                 case (CSTRINGOID):
1388                 case (ANYOID):
1389                 case (ANYARRAYOID):
1390                 case (VOIDOID):
1391                 case (TRIGGEROID):
1392                 case (LANGUAGE_HANDLEROID):
1393                 case (INTERNALOID):
1394                 case (OPAQUEOID):
1395                 case (ANYELEMENTOID):
1396                         result = GENERIC_TYPE;
1397                         break;
1398
1399                 default:
1400                         result = USER_TYPE;
1401                         break;
1402         }
1403         return result;
1404 }       /* TypeCategory() */
1405
1406
1407 /* IsPreferredType()
1408  *              Check if this type is a preferred type for the given category.
1409  *
1410  * If category is INVALID_TYPE, then we'll return TRUE for preferred types
1411  * of any category; otherwise, only for preferred types of that category.
1412  *
1413  * XXX This should be moved to system catalog lookups
1414  * to allow for better type extensibility.
1415  * - thomas 2001-09-30
1416  */
1417 bool
1418 IsPreferredType(CATEGORY category, Oid type)
1419 {
1420         Oid                     preftype;
1421
1422         if (category == INVALID_TYPE)
1423                 category = TypeCategory(type);
1424         else if (category != TypeCategory(type))
1425                 return false;
1426
1427         /*
1428          * This switch should agree with TypeCategory(), above.  Note that at
1429          * this point, category certainly matches the type.
1430          */
1431         switch (category)
1432         {
1433                 case (UNKNOWN_TYPE):
1434                 case (GENERIC_TYPE):
1435                         preftype = UNKNOWNOID;
1436                         break;
1437
1438                 case (BOOLEAN_TYPE):
1439                         preftype = BOOLOID;
1440                         break;
1441
1442                 case (STRING_TYPE):
1443                         preftype = TEXTOID;
1444                         break;
1445
1446                 case (BITSTRING_TYPE):
1447                         preftype = VARBITOID;
1448                         break;
1449
1450                 case (NUMERIC_TYPE):
1451                         if (type == OIDOID ||
1452                                 type == REGPROCOID ||
1453                                 type == REGPROCEDUREOID ||
1454                                 type == REGOPEROID ||
1455                                 type == REGOPERATOROID ||
1456                                 type == REGCLASSOID ||
1457                                 type == REGTYPEOID)
1458                                 preftype = OIDOID;
1459                         else
1460                                 preftype = FLOAT8OID;
1461                         break;
1462
1463                 case (DATETIME_TYPE):
1464                         if (type == DATEOID)
1465                                 preftype = TIMESTAMPOID;
1466                         else
1467                                 preftype = TIMESTAMPTZOID;
1468                         break;
1469
1470                 case (TIMESPAN_TYPE):
1471                         preftype = INTERVALOID;
1472                         break;
1473
1474                 case (GEOMETRIC_TYPE):
1475                         preftype = type;
1476                         break;
1477
1478                 case (NETWORK_TYPE):
1479                         preftype = INETOID;
1480                         break;
1481
1482                 case (USER_TYPE):
1483                         preftype = type;
1484                         break;
1485
1486                 default:
1487                         elog(ERROR, "unrecognized type category: %d", (int) category);
1488                         preftype = UNKNOWNOID;
1489                         break;
1490         }
1491
1492         return (type == preftype);
1493 }       /* IsPreferredType() */
1494
1495
1496 /* IsBinaryCoercible()
1497  *              Check if srctype is binary-coercible to targettype.
1498  *
1499  * This notion allows us to cheat and directly exchange values without
1500  * going through the trouble of calling a conversion function.  Note that
1501  * in general, this should only be an implementation shortcut.  Before 7.4,
1502  * this was also used as a heuristic for resolving overloaded functions and
1503  * operators, but that's basically a bad idea.
1504  *
1505  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1506  * We consider two types binary-coercible if there is an implicitly
1507  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
1508  * binary-coercible to its base type, though *not* vice versa (in the other
1509  * direction, one must apply domain constraint checks before accepting the
1510  * value as legitimate).  We also need to special-case the polymorphic
1511  * ANYARRAY type.
1512  *
1513  * This function replaces IsBinaryCompatible(), which was an inherently
1514  * symmetric test.      Since the pg_cast entries aren't necessarily symmetric,
1515  * the order of the operands is now significant.
1516  */
1517 bool
1518 IsBinaryCoercible(Oid srctype, Oid targettype)
1519 {
1520         HeapTuple       tuple;
1521         Form_pg_cast castForm;
1522         bool            result;
1523
1524         /* Fast path if same type */
1525         if (srctype == targettype)
1526                 return true;
1527
1528         /* If srctype is a domain, reduce to its base type */
1529         if (OidIsValid(srctype))
1530                 srctype = getBaseType(srctype);
1531
1532         /* Somewhat-fast path for domain -> base type case */
1533         if (srctype == targettype)
1534                 return true;
1535
1536         /* Also accept any array type as coercible to ANYARRAY */
1537         if (targettype == ANYARRAYOID)
1538                 if (get_element_type(srctype) != InvalidOid)
1539                         return true;
1540
1541         /* Else look in pg_cast */
1542         tuple = SearchSysCache(CASTSOURCETARGET,
1543                                                    ObjectIdGetDatum(srctype),
1544                                                    ObjectIdGetDatum(targettype),
1545                                                    0, 0);
1546         if (!HeapTupleIsValid(tuple))
1547                 return false;                   /* no cast */
1548         castForm = (Form_pg_cast) GETSTRUCT(tuple);
1549
1550         result = (castForm->castfunc == InvalidOid &&
1551                           castForm->castcontext == COERCION_CODE_IMPLICIT);
1552
1553         ReleaseSysCache(tuple);
1554
1555         return result;
1556 }
1557
1558
1559 /*
1560  * find_coercion_pathway
1561  *              Look for a coercion pathway between two types.
1562  *
1563  * ccontext determines the set of available casts.
1564  *
1565  * If we find a suitable entry in pg_cast, return TRUE, and set *funcid
1566  * to the castfunc value, which may be InvalidOid for a binary-compatible
1567  * coercion.
1568  *
1569  * NOTE: *funcid == InvalidOid does not necessarily mean that no work is
1570  * needed to do the coercion; if the target is a domain then we may need to
1571  * apply domain constraint checking.  If you want to check for a zero-effort
1572  * conversion then use IsBinaryCoercible().
1573  */
1574 bool
1575 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1576                                           CoercionContext ccontext,
1577                                           Oid *funcid)
1578 {
1579         bool            result = false;
1580         HeapTuple       tuple;
1581
1582         *funcid = InvalidOid;
1583
1584         /* Perhaps the types are domains; if so, look at their base types */
1585         if (OidIsValid(sourceTypeId))
1586                 sourceTypeId = getBaseType(sourceTypeId);
1587         if (OidIsValid(targetTypeId))
1588                 targetTypeId = getBaseType(targetTypeId);
1589
1590         /* Domains are always coercible to and from their base type */
1591         if (sourceTypeId == targetTypeId)
1592                 return true;
1593
1594         /* Look in pg_cast */
1595         tuple = SearchSysCache(CASTSOURCETARGET,
1596                                                    ObjectIdGetDatum(sourceTypeId),
1597                                                    ObjectIdGetDatum(targetTypeId),
1598                                                    0, 0);
1599
1600         if (HeapTupleIsValid(tuple))
1601         {
1602                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1603                 CoercionContext castcontext;
1604
1605                 /* convert char value for castcontext to CoercionContext enum */
1606                 switch (castForm->castcontext)
1607                 {
1608                         case COERCION_CODE_IMPLICIT:
1609                                 castcontext = COERCION_IMPLICIT;
1610                                 break;
1611                         case COERCION_CODE_ASSIGNMENT:
1612                                 castcontext = COERCION_ASSIGNMENT;
1613                                 break;
1614                         case COERCION_CODE_EXPLICIT:
1615                                 castcontext = COERCION_EXPLICIT;
1616                                 break;
1617                         default:
1618                                 elog(ERROR, "unrecognized castcontext: %d",
1619                                          (int) castForm->castcontext);
1620                                 castcontext = 0;        /* keep compiler quiet */
1621                                 break;
1622                 }
1623
1624                 /* Rely on ordering of enum for correct behavior here */
1625                 if (ccontext >= castcontext)
1626                 {
1627                         *funcid = castForm->castfunc;
1628                         result = true;
1629                 }
1630
1631                 ReleaseSysCache(tuple);
1632         }
1633         else
1634         {
1635                 /*
1636                  * If there's no pg_cast entry, perhaps we are dealing with a pair
1637                  * of array types.      If so, and if the element types have a suitable
1638                  * cast, use array_type_coerce() or array_type_length_coerce().
1639                  */
1640                 Oid                     targetElemType;
1641                 Oid                     sourceElemType;
1642                 Oid                     elemfuncid;
1643
1644                 if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid &&
1645                  (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid)
1646                 {
1647                         if (find_coercion_pathway(targetElemType, sourceElemType,
1648                                                                           ccontext, &elemfuncid))
1649                         {
1650                                 if (!OidIsValid(elemfuncid))
1651                                 {
1652                                         /* binary-compatible element type conversion */
1653                                         *funcid = F_ARRAY_TYPE_COERCE;
1654                                 }
1655                                 else
1656                                 {
1657                                         /* does the function take a typmod arg? */
1658                                         Oid             argtypes[FUNC_MAX_ARGS];
1659                                         int             nargs;
1660
1661                                         (void) get_func_signature(elemfuncid, argtypes, &nargs);
1662                                         if (nargs > 1)
1663                                                 *funcid = F_ARRAY_TYPE_LENGTH_COERCE;
1664                                         else
1665                                                 *funcid = F_ARRAY_TYPE_COERCE;
1666                                 }
1667                                 result = true;
1668                         }
1669                 }
1670         }
1671
1672         return result;
1673 }
1674
1675
1676 /*
1677  * find_typmod_coercion_function -- does the given type need length coercion?
1678  *
1679  * If the target type possesses a pg_cast function from itself to itself,
1680  * it must need length coercion.
1681  *
1682  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1683  *
1684  * If the given type is a varlena array type, we do not look for a coercion
1685  * function associated directly with the array type, but instead look for
1686  * one associated with the element type.  If one exists, we report
1687  * array_length_coerce() as the coercion function to use.
1688  */
1689 Oid
1690 find_typmod_coercion_function(Oid typeId)
1691 {
1692         Oid                     funcid = InvalidOid;
1693         bool            isArray = false;
1694         Type            targetType;
1695         Form_pg_type typeForm;
1696         HeapTuple       tuple;
1697
1698         targetType = typeidType(typeId);
1699         typeForm = (Form_pg_type) GETSTRUCT(targetType);
1700
1701         /* Check for a varlena array type (and not a domain) */
1702         if (typeForm->typelem != InvalidOid &&
1703                 typeForm->typlen == -1 &&
1704                 typeForm->typtype != 'd')
1705         {
1706                 /* Yes, switch our attention to the element type */
1707                 typeId = typeForm->typelem;
1708                 isArray = true;
1709         }
1710         ReleaseSysCache(targetType);
1711
1712         /* Look in pg_cast */
1713         tuple = SearchSysCache(CASTSOURCETARGET,
1714                                                    ObjectIdGetDatum(typeId),
1715                                                    ObjectIdGetDatum(typeId),
1716                                                    0, 0);
1717
1718         if (HeapTupleIsValid(tuple))
1719         {
1720                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1721
1722                 funcid = castForm->castfunc;
1723                 ReleaseSysCache(tuple);
1724         }
1725
1726         /*
1727          * Now, if we did find a coercion function for an array element type,
1728          * report array_length_coerce() as the function to use.
1729          */
1730         if (isArray && OidIsValid(funcid))
1731                 funcid = F_ARRAY_LENGTH_COERCE;
1732
1733         return funcid;
1734 }