]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Update copyright for 2009.
[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-2009, 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.174 2009/01/01 17:23:45 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_coerce.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_relation.h"
25 #include "parser/parse_type.h"
26 #include "utils/builtins.h"
27 #include "utils/fmgroids.h"
28 #include "utils/lsyscache.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
31
32
33 static Node *coerce_type_typmod(Node *node,
34                                    Oid targetTypeId, int32 targetTypMod,
35                                    CoercionForm cformat, int location,
36                                    bool isExplicit, bool hideInputCoercion);
37 static void hide_coercion_node(Node *node);
38 static Node *build_coercion_expression(Node *node,
39                                                   CoercionPathType pathtype,
40                                                   Oid funcId,
41                                                   Oid targetTypeId, int32 targetTypMod,
42                                                   CoercionForm cformat, int location,
43                                                   bool isExplicit);
44 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
45                                                  Oid targetTypeId,
46                                                  CoercionContext ccontext,
47                                                  CoercionForm cformat,
48                                                  int location);
49 static bool is_complex_array(Oid typid);
50
51
52 /*
53  * coerce_to_target_type()
54  *              Convert an expression to a target type and typmod.
55  *
56  * This is the general-purpose entry point for arbitrary type coercion
57  * operations.  Direct use of the component operations can_coerce_type,
58  * coerce_type, and coerce_type_typmod should be restricted to special
59  * cases (eg, when the conversion is expected to succeed).
60  *
61  * Returns the possibly-transformed expression tree, or NULL if the type
62  * conversion is not possible.  (We do this, rather than ereport'ing directly,
63  * so that callers can generate custom error messages indicating context.)
64  *
65  * pstate - parse state (can be NULL, see coerce_type)
66  * expr - input expression tree (already transformed by transformExpr)
67  * exprtype - result type of expr
68  * targettype - desired result type
69  * targettypmod - desired result typmod
70  * ccontext, cformat - context indicators to control coercions
71  * location - parse location of the coercion request, or -1 if unknown/implicit
72  */
73 Node *
74 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
75                                           Oid targettype, int32 targettypmod,
76                                           CoercionContext ccontext,
77                                           CoercionForm cformat,
78                                           int location)
79 {
80         Node       *result;
81
82         if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
83                 return NULL;
84
85         result = coerce_type(pstate, expr, exprtype,
86                                                  targettype, targettypmod,
87                                                  ccontext, cformat, location);
88
89         /*
90          * If the target is a fixed-length type, it may need a length coercion as
91          * well as a type coercion.  If we find ourselves adding both, force the
92          * inner coercion node to implicit display form.
93          */
94         result = coerce_type_typmod(result,
95                                                                 targettype, targettypmod,
96                                                                 cformat, location,
97                                                                 (cformat != COERCE_IMPLICIT_CAST),
98                                                                 (result != expr && !IsA(result, Const)));
99
100         return result;
101 }
102
103
104 /*
105  * coerce_type()
106  *              Convert an expression to a different type.
107  *
108  * The caller should already have determined that the coercion is possible;
109  * see can_coerce_type.
110  *
111  * Normally, no coercion to a typmod (length) is performed here.  The caller
112  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
113  * (But if the target type is a domain, it may internally contain a
114  * typmod constraint, which will be applied inside coerce_to_domain.)
115  * In some cases pg_cast specifies a type coercion function that also
116  * applies length conversion, and in those cases only, the result will
117  * already be properly coerced to the specified typmod.
118  *
119  * pstate is only used in the case that we are able to resolve the type of
120  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
121  * caller does not want type information updated for Params.
122  */
123 Node *
124 coerce_type(ParseState *pstate, Node *node,
125                         Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
126                         CoercionContext ccontext, CoercionForm cformat, int location)
127 {
128         Node       *result;
129         CoercionPathType pathtype;
130         Oid                     funcId;
131
132         if (targetTypeId == inputTypeId ||
133                 node == NULL)
134         {
135                 /* no conversion needed */
136                 return node;
137         }
138         if (targetTypeId == ANYOID ||
139                 targetTypeId == ANYELEMENTOID ||
140                 targetTypeId == ANYNONARRAYOID ||
141                 (targetTypeId == ANYARRAYOID && inputTypeId != UNKNOWNOID) ||
142                 (targetTypeId == ANYENUMOID && inputTypeId != UNKNOWNOID))
143         {
144                 /*
145                  * Assume can_coerce_type verified that implicit coercion is okay.
146                  *
147                  * Note: by returning the unmodified node here, we are saying that
148                  * it's OK to treat an UNKNOWN constant as a valid input for a
149                  * function accepting ANY, ANYELEMENT, or ANYNONARRAY.  This should be
150                  * all right, since an UNKNOWN value is still a perfectly valid Datum.
151                  * However an UNKNOWN value is definitely *not* an array, and so we
152                  * mustn't accept it for ANYARRAY.  (Instead, we will call anyarray_in
153                  * below, which will produce an error.)  Likewise, UNKNOWN input is no
154                  * good for ANYENUM.
155                  *
156                  * NB: we do NOT want a RelabelType here.
157                  */
158                 return node;
159         }
160         if (inputTypeId == UNKNOWNOID && IsA(node, Const))
161         {
162                 /*
163                  * Input is a string constant with previously undetermined type. Apply
164                  * the target type's typinput function to it to produce a constant of
165                  * the target type.
166                  *
167                  * NOTE: this case cannot be folded together with the other
168                  * constant-input case, since the typinput function does not
169                  * necessarily behave the same as a type conversion function. For
170                  * example, int4's typinput function will reject "1.2", whereas
171                  * float-to-int type conversion will round to integer.
172                  *
173                  * XXX if the typinput function is not immutable, we really ought to
174                  * postpone evaluation of the function call until runtime. But there
175                  * is no way to represent a typinput function call as an expression
176                  * tree, because C-string values are not Datums. (XXX This *is*
177                  * possible as of 7.3, do we want to do it?)
178                  */
179                 Const      *con = (Const *) node;
180                 Const      *newcon = makeNode(Const);
181                 Oid                     baseTypeId;
182                 int32           baseTypeMod;
183                 int32           inputTypeMod;
184                 Type            targetType;
185                 ParseCallbackState pcbstate;
186
187                 /*
188                  * If the target type is a domain, we want to call its base type's
189                  * input routine, not domain_in().      This is to avoid premature failure
190                  * when the domain applies a typmod: existing input routines follow
191                  * implicit-coercion semantics for length checks, which is not always
192                  * what we want here.  The needed check will be applied properly
193                  * inside coerce_to_domain().
194                  */
195                 baseTypeMod = targetTypeMod;
196                 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
197
198                 /*
199                  * For most types we pass typmod -1 to the input routine, because
200                  * existing input routines follow implicit-coercion semantics for
201                  * length checks, which is not always what we want here.  Any length
202                  * constraint will be applied later by our caller.  An exception
203                  * however is the INTERVAL type, for which we *must* pass the typmod
204                  * or it won't be able to obey the bizarre SQL-spec input rules.
205                  * (Ugly as sin, but so is this part of the spec...)
206                  */
207                 if (baseTypeId == INTERVALOID)
208                         inputTypeMod = baseTypeMod;
209                 else
210                         inputTypeMod = -1;
211
212                 targetType = typeidType(baseTypeId);
213
214                 newcon->consttype = baseTypeId;
215                 newcon->consttypmod = inputTypeMod;
216                 newcon->constlen = typeLen(targetType);
217                 newcon->constbyval = typeByVal(targetType);
218                 newcon->constisnull = con->constisnull;
219                 /* Use the leftmost of the constant's and coercion's locations */
220                 if (location < 0)
221                         newcon->location = con->location;
222                 else if (con->location >= 0 && con->location < location)
223                         newcon->location = con->location;
224                 else
225                         newcon->location = location;
226
227                 /*
228                  * Set up to point at the constant's text if the input routine
229                  * throws an error.
230                  */
231                 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
232
233                 /*
234                  * We assume here that UNKNOWN's internal representation is the same
235                  * as CSTRING.
236                  */
237                 if (!con->constisnull)
238                         newcon->constvalue = stringTypeDatum(targetType,
239                                                                                         DatumGetCString(con->constvalue),
240                                                                                                  inputTypeMod);
241                 else
242                         newcon->constvalue = stringTypeDatum(targetType,
243                                                                                                  NULL,
244                                                                                                  inputTypeMod);
245
246                 cancel_parser_errposition_callback(&pcbstate);
247
248                 result = (Node *) newcon;
249
250                 /* If target is a domain, apply constraints. */
251                 if (baseTypeId != targetTypeId)
252                         result = coerce_to_domain(result,
253                                                                           baseTypeId, baseTypeMod,
254                                                                           targetTypeId,
255                                                                           cformat, location, false, false);
256
257                 ReleaseSysCache(targetType);
258
259                 return result;
260         }
261         if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
262                 ((Param *) node)->paramkind == PARAM_EXTERN &&
263                 pstate != NULL && pstate->p_variableparams)
264         {
265                 /*
266                  * Input is a Param of previously undetermined type, and we want to
267                  * update our knowledge of the Param's type.  Find the topmost
268                  * ParseState and update the state.
269                  */
270                 Param      *param = (Param *) node;
271                 int                     paramno = param->paramid;
272                 ParseState *toppstate;
273
274                 toppstate = pstate;
275                 while (toppstate->parentParseState != NULL)
276                         toppstate = toppstate->parentParseState;
277
278                 if (paramno <= 0 ||             /* shouldn't happen, but... */
279                         paramno > toppstate->p_numparams)
280                         ereport(ERROR,
281                                         (errcode(ERRCODE_UNDEFINED_PARAMETER),
282                                          errmsg("there is no parameter $%d", paramno),
283                                          parser_errposition(pstate, param->location)));
284
285                 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
286                 {
287                         /* We've successfully resolved the type */
288                         toppstate->p_paramtypes[paramno - 1] = targetTypeId;
289                 }
290                 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
291                 {
292                         /* We previously resolved the type, and it matches */
293                 }
294                 else
295                 {
296                         /* Ooops */
297                         ereport(ERROR,
298                                         (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
299                                          errmsg("inconsistent types deduced for parameter $%d",
300                                                         paramno),
301                                          errdetail("%s versus %s",
302                                                 format_type_be(toppstate->p_paramtypes[paramno - 1]),
303                                                            format_type_be(targetTypeId)),
304                                          parser_errposition(pstate, param->location)));
305                 }
306
307                 param->paramtype = targetTypeId;
308
309                 /*
310                  * Note: it is tempting here to set the Param's paramtypmod to
311                  * targetTypeMod, but that is probably unwise because we have no
312                  * infrastructure that enforces that the value delivered for a Param
313                  * will match any particular typmod.  Leaving it -1 ensures that a
314                  * run-time length check/coercion will occur if needed.
315                  */
316                 param->paramtypmod = -1;
317
318                 /* Use the leftmost of the param's and coercion's locations */
319                 if (location >= 0 &&
320                         (param->location < 0 || location < param->location))
321                         param->location = location;
322
323                 return (Node *) param;
324         }
325         pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
326                                                                          &funcId);
327         if (pathtype != COERCION_PATH_NONE)
328         {
329                 if (pathtype != COERCION_PATH_RELABELTYPE)
330                 {
331                         /*
332                          * Generate an expression tree representing run-time application
333                          * of the conversion function.  If we are dealing with a domain
334                          * target type, the conversion function will yield the base type,
335                          * and we need to extract the correct typmod to use from the
336                          * domain's typtypmod.
337                          */
338                         Oid                     baseTypeId;
339                         int32           baseTypeMod;
340
341                         baseTypeMod = targetTypeMod;
342                         baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
343
344                         result = build_coercion_expression(node, pathtype, funcId,
345                                                                                            baseTypeId, baseTypeMod,
346                                                                                            cformat, location,
347                                                                                   (cformat != COERCE_IMPLICIT_CAST));
348
349                         /*
350                          * If domain, coerce to the domain type and relabel with domain
351                          * type ID.  We can skip the internal length-coercion step if the
352                          * selected coercion function was a type-and-length coercion.
353                          */
354                         if (targetTypeId != baseTypeId)
355                                 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
356                                                                                   targetTypeId,
357                                                                                   cformat, location, true,
358                                                                                   exprIsLengthCoercion(result,
359                                                                                                                            NULL));
360                 }
361                 else
362                 {
363                         /*
364                          * We don't need to do a physical conversion, but we do need to
365                          * attach a RelabelType node so that the expression will be seen
366                          * to have the intended type when inspected by higher-level code.
367                          *
368                          * Also, domains may have value restrictions beyond the base type
369                          * that must be accounted for.  If the destination is a domain
370                          * then we won't need a RelabelType node.
371                          */
372                         result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
373                                                                           cformat, location, false, false);
374                         if (result == node)
375                         {
376                                 /*
377                                  * XXX could we label result with exprTypmod(node) instead of
378                                  * default -1 typmod, to save a possible length-coercion
379                                  * later? Would work if both types have same interpretation of
380                                  * typmod, which is likely but not certain.
381                                  */
382                                 RelabelType *r = makeRelabelType((Expr *) result,
383                                                                                                  targetTypeId, -1,
384                                                                                                  cformat);
385
386                                 r->location = location;
387                                 result = (Node *) r;
388                         }
389                 }
390                 return result;
391         }
392         if (inputTypeId == RECORDOID &&
393                 ISCOMPLEX(targetTypeId))
394         {
395                 /* Coerce a RECORD to a specific complex type */
396                 return coerce_record_to_complex(pstate, node, targetTypeId,
397                                                                                 ccontext, cformat, location);
398         }
399         if (targetTypeId == RECORDOID &&
400                 ISCOMPLEX(inputTypeId))
401         {
402                 /* Coerce a specific complex type to RECORD */
403                 /* NB: we do NOT want a RelabelType here */
404                 return node;
405         }
406 #ifdef NOT_USED
407         if (inputTypeId == RECORDARRAYOID &&
408                 is_complex_array(targetTypeId))
409         {
410                 /* Coerce record[] to a specific complex array type */
411                 /* not implemented yet ... */
412         }
413 #endif
414         if (targetTypeId == RECORDARRAYOID &&
415                 is_complex_array(inputTypeId))
416         {
417                 /* Coerce a specific complex array type to record[] */
418                 /* NB: we do NOT want a RelabelType here */
419                 return node;
420         }
421         if (typeInheritsFrom(inputTypeId, targetTypeId))
422         {
423                 /*
424                  * Input class type is a subclass of target, so generate an
425                  * appropriate runtime conversion (removing unneeded columns and
426                  * possibly rearranging the ones that are wanted).
427                  */
428                 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
429
430                 r->arg = (Expr *) node;
431                 r->resulttype = targetTypeId;
432                 r->convertformat = cformat;
433                 r->location = location;
434                 return (Node *) r;
435         }
436         /* If we get here, caller blew it */
437         elog(ERROR, "failed to find conversion function from %s to %s",
438                  format_type_be(inputTypeId), format_type_be(targetTypeId));
439         return NULL;                            /* keep compiler quiet */
440 }
441
442
443 /*
444  * can_coerce_type()
445  *              Can input_typeids be coerced to target_typeids?
446  *
447  * We must be told the context (CAST construct, assignment, implicit coercion)
448  * as this determines the set of available casts.
449  */
450 bool
451 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
452                                 CoercionContext ccontext)
453 {
454         bool            have_generics = false;
455         int                     i;
456
457         /* run through argument list... */
458         for (i = 0; i < nargs; i++)
459         {
460                 Oid                     inputTypeId = input_typeids[i];
461                 Oid                     targetTypeId = target_typeids[i];
462                 CoercionPathType pathtype;
463                 Oid                     funcId;
464
465                 /* no problem if same type */
466                 if (inputTypeId == targetTypeId)
467                         continue;
468
469                 /* accept if target is ANY */
470                 if (targetTypeId == ANYOID)
471                         continue;
472
473                 /* accept if target is polymorphic, for now */
474                 if (IsPolymorphicType(targetTypeId))
475                 {
476                         have_generics = true;           /* do more checking later */
477                         continue;
478                 }
479
480                 /*
481                  * If input is an untyped string constant, assume we can convert it to
482                  * anything.
483                  */
484                 if (inputTypeId == UNKNOWNOID)
485                         continue;
486
487                 /*
488                  * If pg_cast shows that we can coerce, accept.  This test now covers
489                  * both binary-compatible and coercion-function cases.
490                  */
491                 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
492                                                                                  &funcId);
493                 if (pathtype != COERCION_PATH_NONE)
494                         continue;
495
496                 /*
497                  * If input is RECORD and target is a composite type, assume we can
498                  * coerce (may need tighter checking here)
499                  */
500                 if (inputTypeId == RECORDOID &&
501                         ISCOMPLEX(targetTypeId))
502                         continue;
503
504                 /*
505                  * If input is a composite type and target is RECORD, accept
506                  */
507                 if (targetTypeId == RECORDOID &&
508                         ISCOMPLEX(inputTypeId))
509                         continue;
510
511 #ifdef NOT_USED                                 /* not implemented yet */
512                 /*
513                  * If input is record[] and target is a composite array type,
514                  * assume we can coerce (may need tighter checking here)
515                  */
516                 if (inputTypeId == RECORDARRAYOID &&
517                         is_complex_array(targetTypeId))
518                         continue;
519 #endif
520
521                 /*
522                  * If input is a composite array type and target is record[], accept
523                  */
524                 if (targetTypeId == RECORDARRAYOID &&
525                         is_complex_array(inputTypeId))
526                         continue;
527
528                 /*
529                  * If input is a class type that inherits from target, accept
530                  */
531                 if (typeInheritsFrom(inputTypeId, targetTypeId))
532                         continue;
533
534                 /*
535                  * Else, cannot coerce at this argument position
536                  */
537                 return false;
538         }
539
540         /* If we found any generic argument types, cross-check them */
541         if (have_generics)
542         {
543                 if (!check_generic_type_consistency(input_typeids, target_typeids,
544                                                                                         nargs))
545                         return false;
546         }
547
548         return true;
549 }
550
551
552 /*
553  * Create an expression tree to represent coercion to a domain type.
554  *
555  * 'arg': input expression
556  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
557  *              has not bothered to look this up)
558  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
559  *              has not bothered to look this up)
560  * 'typeId': target type to coerce to
561  * 'cformat': coercion format
562  * 'location': coercion request location
563  * 'hideInputCoercion': if true, hide the input coercion under this one.
564  * 'lengthCoercionDone': if true, caller already accounted for length,
565  *              ie the input is already of baseTypMod as well as baseTypeId.
566  *
567  * If the target type isn't a domain, the given 'arg' is returned as-is.
568  */
569 Node *
570 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
571                                  CoercionForm cformat, int location,
572                                  bool hideInputCoercion,
573                                  bool lengthCoercionDone)
574 {
575         CoerceToDomain *result;
576
577         /* Get the base type if it hasn't been supplied */
578         if (baseTypeId == InvalidOid)
579                 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
580
581         /* If it isn't a domain, return the node as it was passed in */
582         if (baseTypeId == typeId)
583                 return arg;
584
585         /* Suppress display of nested coercion steps */
586         if (hideInputCoercion)
587                 hide_coercion_node(arg);
588
589         /*
590          * If the domain applies a typmod to its base type, build the appropriate
591          * coercion step.  Mark it implicit for display purposes, because we don't
592          * want it shown separately by ruleutils.c; but the isExplicit flag passed
593          * to the conversion function depends on the manner in which the domain
594          * coercion is invoked, so that the semantics of implicit and explicit
595          * coercion differ.  (Is that really the behavior we want?)
596          *
597          * NOTE: because we apply this as part of the fixed expression structure,
598          * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
599          * would be safe to do anyway, without lots of knowledge about what the
600          * base type thinks the typmod means.
601          */
602         if (!lengthCoercionDone)
603         {
604                 if (baseTypeMod >= 0)
605                         arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
606                                                                          COERCE_IMPLICIT_CAST, location,
607                                                                          (cformat != COERCE_IMPLICIT_CAST),
608                                                                          false);
609         }
610
611         /*
612          * Now build the domain coercion node.  This represents run-time checking
613          * of any constraints currently attached to the domain.  This also ensures
614          * that the expression is properly labeled as to result type.
615          */
616         result = makeNode(CoerceToDomain);
617         result->arg = (Expr *) arg;
618         result->resulttype = typeId;
619         result->resulttypmod = -1;      /* currently, always -1 for domains */
620         result->coercionformat = cformat;
621         result->location = location;
622
623         return (Node *) result;
624 }
625
626
627 /*
628  * coerce_type_typmod()
629  *              Force a value to a particular typmod, if meaningful and possible.
630  *
631  * This is applied to values that are going to be stored in a relation
632  * (where we have an atttypmod for the column) as well as values being
633  * explicitly CASTed (where the typmod comes from the target type spec).
634  *
635  * The caller must have already ensured that the value is of the correct
636  * type, typically by applying coerce_type.
637  *
638  * cformat determines the display properties of the generated node (if any),
639  * while isExplicit may affect semantics.  If hideInputCoercion is true
640  * *and* we generate a node, the input node is forced to IMPLICIT display
641  * form, so that only the typmod coercion node will be visible when
642  * displaying the expression.
643  *
644  * NOTE: this does not need to work on domain types, because any typmod
645  * coercion for a domain is considered to be part of the type coercion
646  * needed to produce the domain value in the first place.  So, no getBaseType.
647  */
648 static Node *
649 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
650                                    CoercionForm cformat, int location,
651                                    bool isExplicit, bool hideInputCoercion)
652 {
653         CoercionPathType pathtype;
654         Oid                     funcId;
655
656         /*
657          * A negative typmod is assumed to mean that no coercion is wanted. Also,
658          * skip coercion if already done.
659          */
660         if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
661                 return node;
662
663         pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
664
665         if (pathtype != COERCION_PATH_NONE)
666         {
667                 /* Suppress display of nested coercion steps */
668                 if (hideInputCoercion)
669                         hide_coercion_node(node);
670
671                 node = build_coercion_expression(node, pathtype, funcId,
672                                                                                  targetTypeId, targetTypMod,
673                                                                                  cformat, location,
674                                                                                  isExplicit);
675         }
676
677         return node;
678 }
679
680 /*
681  * Mark a coercion node as IMPLICIT so it will never be displayed by
682  * ruleutils.c.  We use this when we generate a nest of coercion nodes
683  * to implement what is logically one conversion; the inner nodes are
684  * forced to IMPLICIT_CAST format.      This does not change their semantics,
685  * only display behavior.
686  *
687  * It is caller error to call this on something that doesn't have a
688  * CoercionForm field.
689  */
690 static void
691 hide_coercion_node(Node *node)
692 {
693         if (IsA(node, FuncExpr))
694                 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
695         else if (IsA(node, RelabelType))
696                 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
697         else if (IsA(node, CoerceViaIO))
698                 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
699         else if (IsA(node, ArrayCoerceExpr))
700                 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
701         else if (IsA(node, ConvertRowtypeExpr))
702                 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
703         else if (IsA(node, RowExpr))
704                 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
705         else if (IsA(node, CoerceToDomain))
706                 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
707         else
708                 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
709 }
710
711 /*
712  * build_coercion_expression()
713  *              Construct an expression tree for applying a pg_cast entry.
714  *
715  * This is used for both type-coercion and length-coercion operations,
716  * since there is no difference in terms of the calling convention.
717  */
718 static Node *
719 build_coercion_expression(Node *node,
720                                                   CoercionPathType pathtype,
721                                                   Oid funcId,
722                                                   Oid targetTypeId, int32 targetTypMod,
723                                                   CoercionForm cformat, int location,
724                                                   bool isExplicit)
725 {
726         int                     nargs = 0;
727
728         if (OidIsValid(funcId))
729         {
730                 HeapTuple       tp;
731                 Form_pg_proc procstruct;
732
733                 tp = SearchSysCache(PROCOID,
734                                                         ObjectIdGetDatum(funcId),
735                                                         0, 0, 0);
736                 if (!HeapTupleIsValid(tp))
737                         elog(ERROR, "cache lookup failed for function %u", funcId);
738                 procstruct = (Form_pg_proc) GETSTRUCT(tp);
739
740                 /*
741                  * These Asserts essentially check that function is a legal coercion
742                  * function.  We can't make the seemingly obvious tests on prorettype
743                  * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
744                  * various binary-compatibility cases.
745                  */
746                 /* Assert(targetTypeId == procstruct->prorettype); */
747                 Assert(!procstruct->proretset);
748                 Assert(!procstruct->proisagg);
749                 Assert(!procstruct->proiswindow);
750                 nargs = procstruct->pronargs;
751                 Assert(nargs >= 1 && nargs <= 3);
752                 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
753                 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
754                 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
755
756                 ReleaseSysCache(tp);
757         }
758
759         if (pathtype == COERCION_PATH_FUNC)
760         {
761                 /* We build an ordinary FuncExpr with special arguments */
762                 FuncExpr   *fexpr;
763                 List       *args;
764                 Const      *cons;
765
766                 Assert(OidIsValid(funcId));
767
768                 args = list_make1(node);
769
770                 if (nargs >= 2)
771                 {
772                         /* Pass target typmod as an int4 constant */
773                         cons = makeConst(INT4OID,
774                                                          -1,
775                                                          sizeof(int32),
776                                                          Int32GetDatum(targetTypMod),
777                                                          false,
778                                                          true);
779
780                         args = lappend(args, cons);
781                 }
782
783                 if (nargs == 3)
784                 {
785                         /* Pass it a boolean isExplicit parameter, too */
786                         cons = makeConst(BOOLOID,
787                                                          -1,
788                                                          sizeof(bool),
789                                                          BoolGetDatum(isExplicit),
790                                                          false,
791                                                          true);
792
793                         args = lappend(args, cons);
794                 }
795
796                 fexpr = makeFuncExpr(funcId, targetTypeId, args, cformat);
797                 fexpr->location = location;
798                 return (Node *) fexpr;
799         }
800         else if (pathtype == COERCION_PATH_ARRAYCOERCE)
801         {
802                 /* We need to build an ArrayCoerceExpr */
803                 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
804
805                 acoerce->arg = (Expr *) node;
806                 acoerce->elemfuncid = funcId;
807                 acoerce->resulttype = targetTypeId;
808
809                 /*
810                  * Label the output as having a particular typmod only if we are
811                  * really invoking a length-coercion function, ie one with more than
812                  * one argument.
813                  */
814                 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
815                 acoerce->isExplicit = isExplicit;
816                 acoerce->coerceformat = cformat;
817                 acoerce->location = location;
818
819                 return (Node *) acoerce;
820         }
821         else if (pathtype == COERCION_PATH_COERCEVIAIO)
822         {
823                 /* We need to build a CoerceViaIO node */
824                 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
825
826                 Assert(!OidIsValid(funcId));
827
828                 iocoerce->arg = (Expr *) node;
829                 iocoerce->resulttype = targetTypeId;
830                 iocoerce->coerceformat = cformat;
831                 iocoerce->location = location;
832
833                 return (Node *) iocoerce;
834         }
835         else
836         {
837                 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
838                          (int) pathtype);
839                 return NULL;                    /* keep compiler quiet */
840         }
841 }
842
843
844 /*
845  * coerce_record_to_complex
846  *              Coerce a RECORD to a specific composite type.
847  *
848  * Currently we only support this for inputs that are RowExprs or whole-row
849  * Vars.
850  */
851 static Node *
852 coerce_record_to_complex(ParseState *pstate, Node *node,
853                                                  Oid targetTypeId,
854                                                  CoercionContext ccontext,
855                                                  CoercionForm cformat,
856                                                  int location)
857 {
858         RowExpr    *rowexpr;
859         TupleDesc       tupdesc;
860         List       *args = NIL;
861         List       *newargs;
862         int                     i;
863         int                     ucolno;
864         ListCell   *arg;
865
866         if (node && IsA(node, RowExpr))
867         {
868                 /*
869                  * Since the RowExpr must be of type RECORD, we needn't worry about it
870                  * containing any dropped columns.
871                  */
872                 args = ((RowExpr *) node)->args;
873         }
874         else if (node && IsA(node, Var) &&
875                          ((Var *) node)->varattno == InvalidAttrNumber)
876         {
877                 int                     rtindex = ((Var *) node)->varno;
878                 int                     sublevels_up = ((Var *) node)->varlevelsup;
879                 int                     vlocation = ((Var *) node)->location;
880                 RangeTblEntry *rte;
881
882                 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
883                 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
884                                   NULL, &args);
885         }
886         else
887                 ereport(ERROR,
888                                 (errcode(ERRCODE_CANNOT_COERCE),
889                                  errmsg("cannot cast type %s to %s",
890                                                 format_type_be(RECORDOID),
891                                                 format_type_be(targetTypeId)),
892                                  parser_coercion_errposition(pstate, location, node)));
893
894         tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
895         newargs = NIL;
896         ucolno = 1;
897         arg = list_head(args);
898         for (i = 0; i < tupdesc->natts; i++)
899         {
900                 Node       *expr;
901                 Node       *cexpr;
902                 Oid                     exprtype;
903
904                 /* Fill in NULLs for dropped columns in rowtype */
905                 if (tupdesc->attrs[i]->attisdropped)
906                 {
907                         /*
908                          * can't use atttypid here, but it doesn't really matter what type
909                          * the Const claims to be.
910                          */
911                         newargs = lappend(newargs, makeNullConst(INT4OID, -1));
912                         continue;
913                 }
914
915                 if (arg == NULL)
916                         ereport(ERROR,
917                                         (errcode(ERRCODE_CANNOT_COERCE),
918                                          errmsg("cannot cast type %s to %s",
919                                                         format_type_be(RECORDOID),
920                                                         format_type_be(targetTypeId)),
921                                          errdetail("Input has too few columns."),
922                                          parser_coercion_errposition(pstate, location, node)));
923                 expr = (Node *) lfirst(arg);
924                 exprtype = exprType(expr);
925
926                 cexpr = coerce_to_target_type(pstate,
927                                                                           expr, exprtype,
928                                                                           tupdesc->attrs[i]->atttypid,
929                                                                           tupdesc->attrs[i]->atttypmod,
930                                                                           ccontext,
931                                                                           COERCE_IMPLICIT_CAST,
932                                                                           -1);
933                 if (cexpr == NULL)
934                         ereport(ERROR,
935                                         (errcode(ERRCODE_CANNOT_COERCE),
936                                          errmsg("cannot cast type %s to %s",
937                                                         format_type_be(RECORDOID),
938                                                         format_type_be(targetTypeId)),
939                                          errdetail("Cannot cast type %s to %s in column %d.",
940                                                            format_type_be(exprtype),
941                                                            format_type_be(tupdesc->attrs[i]->atttypid),
942                                                            ucolno),
943                                          parser_coercion_errposition(pstate, location, expr)));
944                 newargs = lappend(newargs, cexpr);
945                 ucolno++;
946                 arg = lnext(arg);
947         }
948         if (arg != NULL)
949                 ereport(ERROR,
950                                 (errcode(ERRCODE_CANNOT_COERCE),
951                                  errmsg("cannot cast type %s to %s",
952                                                 format_type_be(RECORDOID),
953                                                 format_type_be(targetTypeId)),
954                                  errdetail("Input has too many columns."),
955                                  parser_coercion_errposition(pstate, location, node)));
956
957         ReleaseTupleDesc(tupdesc);
958
959         rowexpr = makeNode(RowExpr);
960         rowexpr->args = newargs;
961         rowexpr->row_typeid = targetTypeId;
962         rowexpr->row_format = cformat;
963         rowexpr->colnames = NIL;        /* not needed for named target type */
964         rowexpr->location = location;
965         return (Node *) rowexpr;
966 }
967
968 /*
969  * coerce_to_boolean()
970  *              Coerce an argument of a construct that requires boolean input
971  *              (AND, OR, NOT, etc).  Also check that input is not a set.
972  *
973  * Returns the possibly-transformed node tree.
974  *
975  * As with coerce_type, pstate may be NULL if no special unknown-Param
976  * processing is wanted.
977  */
978 Node *
979 coerce_to_boolean(ParseState *pstate, Node *node,
980                                   const char *constructName)
981 {
982         Oid                     inputTypeId = exprType(node);
983
984         if (inputTypeId != BOOLOID)
985         {
986                 Node    *newnode;
987
988                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
989                                                                                 BOOLOID, -1,
990                                                                                 COERCION_ASSIGNMENT,
991                                                                                 COERCE_IMPLICIT_CAST,
992                                                                                 -1);
993                 if (newnode == NULL)
994                         ereport(ERROR,
995                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
996                         /* translator: first %s is name of a SQL construct, eg WHERE */
997                                          errmsg("argument of %s must be type boolean, not type %s",
998                                                         constructName, format_type_be(inputTypeId)),
999                                          parser_errposition(pstate, exprLocation(node))));
1000                 node = newnode;
1001         }
1002
1003         if (expression_returns_set(node))
1004                 ereport(ERROR,
1005                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1006                 /* translator: %s is name of a SQL construct, eg WHERE */
1007                                  errmsg("argument of %s must not return a set",
1008                                                 constructName),
1009                                  parser_errposition(pstate, exprLocation(node))));
1010
1011         return node;
1012 }
1013
1014 /*
1015  * coerce_to_specific_type()
1016  *              Coerce an argument of a construct that requires a specific data type.
1017  *              Also check that input is not a set.
1018  *
1019  * Returns the possibly-transformed node tree.
1020  *
1021  * As with coerce_type, pstate may be NULL if no special unknown-Param
1022  * processing is wanted.
1023  */
1024 Node *
1025 coerce_to_specific_type(ParseState *pstate, Node *node,
1026                                                 Oid targetTypeId,
1027                                                 const char *constructName)
1028 {
1029         Oid                     inputTypeId = exprType(node);
1030
1031         if (inputTypeId != targetTypeId)
1032         {
1033                 Node    *newnode;
1034
1035                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1036                                                                                 targetTypeId, -1,
1037                                                                                 COERCION_ASSIGNMENT,
1038                                                                                 COERCE_IMPLICIT_CAST,
1039                                                                                 -1);
1040                 if (newnode == NULL)
1041                         ereport(ERROR,
1042                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1043                         /* translator: first %s is name of a SQL construct, eg LIMIT */
1044                                          errmsg("argument of %s must be type %s, not type %s",
1045                                                         constructName,
1046                                                         format_type_be(targetTypeId),
1047                                                         format_type_be(inputTypeId)),
1048                                          parser_errposition(pstate, exprLocation(node))));
1049                 node = newnode;
1050         }
1051
1052         if (expression_returns_set(node))
1053                 ereport(ERROR,
1054                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1055                 /* translator: %s is name of a SQL construct, eg LIMIT */
1056                                  errmsg("argument of %s must not return a set",
1057                                                 constructName),
1058                                  parser_errposition(pstate, exprLocation(node))));
1059
1060         return node;
1061 }
1062
1063
1064 /*
1065  * parser_coercion_errposition - report coercion error location, if possible
1066  *
1067  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1068  * but there may be no such location in the case of an implicit coercion.
1069  * In that case point at the input expression.
1070  *
1071  * XXX possibly this is more generally useful than coercion errors;
1072  * if so, should rename and place with parser_errposition.
1073  */
1074 int
1075 parser_coercion_errposition(ParseState *pstate,
1076                                                         int coerce_location,
1077                                                         Node *input_expr)
1078 {
1079         if (coerce_location >= 0)
1080                 return parser_errposition(pstate, coerce_location);
1081         else
1082                 return parser_errposition(pstate, exprLocation(input_expr));
1083 }
1084
1085
1086 /*
1087  * select_common_type()
1088  *              Determine the common supertype of a list of input expressions.
1089  *              This is used for determining the output type of CASE, UNION,
1090  *              and similar constructs.
1091  *
1092  * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
1093  * in the list will be preferred if there is doubt.
1094  * 'context' is a phrase to use in the error message if we fail to select
1095  * a usable type.  Pass NULL to have the routine return InvalidOid
1096  * rather than throwing an error on failure.
1097  * 'which_expr': if not NULL, receives a pointer to the particular input
1098  * expression from which the result type was taken.
1099  */
1100 Oid
1101 select_common_type(ParseState *pstate, List *exprs, const char *context,
1102                                    Node **which_expr)
1103 {
1104         Node       *pexpr;
1105         Oid                     ptype;
1106         TYPCATEGORY     pcategory;
1107         bool            pispreferred;
1108         ListCell   *lc;
1109
1110         Assert(exprs != NIL);
1111         pexpr = (Node *) linitial(exprs);
1112         lc = lnext(list_head(exprs));
1113         ptype = exprType(pexpr);
1114
1115         /*
1116          * If all input types are valid and exactly the same, just pick that type.
1117          * This is the only way that we will resolve the result as being a domain
1118          * type; otherwise domains are smashed to their base types for comparison.
1119          */
1120         if (ptype != UNKNOWNOID)
1121         {
1122                 for_each_cell(lc, lc)
1123                 {
1124                         Node   *nexpr = (Node *) lfirst(lc);
1125                         Oid             ntype = exprType(nexpr);
1126
1127                         if (ntype != ptype)
1128                                 break;
1129                 }
1130                 if (lc == NULL)                 /* got to the end of the list? */
1131                 {
1132                         if (which_expr)
1133                                 *which_expr = pexpr;
1134                         return ptype;
1135                 }
1136         }
1137
1138         /*
1139          * Nope, so set up for the full algorithm.  Note that at this point,
1140          * lc points to the first list item with type different from pexpr's;
1141          * we need not re-examine any items the previous loop advanced over.
1142          */
1143         ptype = getBaseType(ptype);
1144         get_type_category_preferred(ptype, &pcategory, &pispreferred);
1145
1146         for_each_cell(lc, lc)
1147         {
1148                 Node       *nexpr = (Node *) lfirst(lc);
1149                 Oid                     ntype = getBaseType(exprType(nexpr));
1150
1151                 /* move on to next one if no new information... */
1152                 if (ntype != UNKNOWNOID && ntype != ptype)
1153                 {
1154                         TYPCATEGORY     ncategory;
1155                         bool            nispreferred;
1156
1157                         get_type_category_preferred(ntype, &ncategory, &nispreferred);
1158                         if (ptype == UNKNOWNOID)
1159                         {
1160                                 /* so far, only unknowns so take anything... */
1161                                 pexpr = nexpr;
1162                                 ptype = ntype;
1163                                 pcategory = ncategory;
1164                                 pispreferred = nispreferred;
1165                         }
1166                         else if (ncategory != pcategory)
1167                         {
1168                                 /*
1169                                  * both types in different categories? then not much hope...
1170                                  */
1171                                 if (context == NULL)
1172                                         return InvalidOid;
1173                                 ereport(ERROR,
1174                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1175                                 /*------
1176                                   translator: first %s is name of a SQL construct, eg CASE */
1177                                                  errmsg("%s types %s and %s cannot be matched",
1178                                                                 context,
1179                                                                 format_type_be(ptype),
1180                                                                 format_type_be(ntype)),
1181                                                  parser_errposition(pstate, exprLocation(nexpr))));
1182                         }
1183                         else if (!pispreferred &&
1184                                          can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1185                                          !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1186                         {
1187                                 /*
1188                                  * take new type if can coerce to it implicitly but not the
1189                                  * other way; but if we have a preferred type, stay on it.
1190                                  */
1191                                 pexpr = nexpr;
1192                                 ptype = ntype;
1193                                 pcategory = ncategory;
1194                                 pispreferred = nispreferred;
1195                         }
1196                 }
1197         }
1198
1199         /*
1200          * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1201          * then resolve as type TEXT.  This situation comes up with constructs
1202          * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1203          * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1204          * output type as UNKNOWN, but that really doesn't work, because we'd
1205          * probably end up needing a runtime coercion from UNKNOWN to something
1206          * else, and we usually won't have it.  We need to coerce the unknown
1207          * literals while they are still literals, so a decision has to be made
1208          * now.
1209          */
1210         if (ptype == UNKNOWNOID)
1211                 ptype = TEXTOID;
1212
1213         if (which_expr)
1214                 *which_expr = pexpr;
1215         return ptype;
1216 }
1217
1218 /*
1219  * coerce_to_common_type()
1220  *              Coerce an expression to the given type.
1221  *
1222  * This is used following select_common_type() to coerce the individual
1223  * expressions to the desired type.  'context' is a phrase to use in the
1224  * error message if we fail to coerce.
1225  *
1226  * As with coerce_type, pstate may be NULL if no special unknown-Param
1227  * processing is wanted.
1228  */
1229 Node *
1230 coerce_to_common_type(ParseState *pstate, Node *node,
1231                                           Oid targetTypeId, const char *context)
1232 {
1233         Oid                     inputTypeId = exprType(node);
1234
1235         if (inputTypeId == targetTypeId)
1236                 return node;                    /* no work */
1237         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1238                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1239                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1240         else
1241                 ereport(ERROR,
1242                                 (errcode(ERRCODE_CANNOT_COERCE),
1243                 /* translator: first %s is name of a SQL construct, eg CASE */
1244                                  errmsg("%s could not convert type %s to %s",
1245                                                 context,
1246                                                 format_type_be(inputTypeId),
1247                                                 format_type_be(targetTypeId)),
1248                                  parser_errposition(pstate, exprLocation(node))));
1249         return node;
1250 }
1251
1252 /*
1253  * check_generic_type_consistency()
1254  *              Are the actual arguments potentially compatible with a
1255  *              polymorphic function?
1256  *
1257  * The argument consistency rules are:
1258  *
1259  * 1) All arguments declared ANYARRAY must have matching datatypes,
1260  *        and must in fact be varlena arrays.
1261  * 2) All arguments declared ANYELEMENT must have matching datatypes.
1262  * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1263  *        the actual ANYELEMENT datatype is in fact the element type for
1264  *        the actual ANYARRAY datatype.
1265  * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1266  *        (alone or in combination with plain ANYELEMENT), we add the extra
1267  *        condition that the ANYELEMENT type must be an enum.
1268  * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1269  *        we add the extra condition that the ANYELEMENT type must not be an array.
1270  *        (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1271  *        is an extra restriction if not.)
1272  *
1273  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1274  * argument, assume it is okay.
1275  *
1276  * If an input is of type ANYARRAY (ie, we know it's an array, but not
1277  * what element type), we will accept it as a match to an argument declared
1278  * ANYARRAY, so long as we don't have to determine an element type ---
1279  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
1280  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1281  *
1282  * We do not ereport here, but just return FALSE if a rule is violated.
1283  */
1284 bool
1285 check_generic_type_consistency(Oid *actual_arg_types,
1286                                                            Oid *declared_arg_types,
1287                                                            int nargs)
1288 {
1289         int                     j;
1290         Oid                     elem_typeid = InvalidOid;
1291         Oid                     array_typeid = InvalidOid;
1292         Oid                     array_typelem;
1293         bool            have_anyelement = false;
1294         bool            have_anynonarray = false;
1295         bool            have_anyenum = false;
1296
1297         /*
1298          * Loop through the arguments to see if we have any that are polymorphic.
1299          * If so, require the actual types to be consistent.
1300          */
1301         for (j = 0; j < nargs; j++)
1302         {
1303                 Oid                     decl_type = declared_arg_types[j];
1304                 Oid                     actual_type = actual_arg_types[j];
1305
1306                 if (decl_type == ANYELEMENTOID ||
1307                         decl_type == ANYNONARRAYOID ||
1308                         decl_type == ANYENUMOID)
1309                 {
1310                         have_anyelement = true;
1311                         if (decl_type == ANYNONARRAYOID)
1312                                 have_anynonarray = true;
1313                         else if (decl_type == ANYENUMOID)
1314                                 have_anyenum = true;
1315                         if (actual_type == UNKNOWNOID)
1316                                 continue;
1317                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1318                                 return false;
1319                         elem_typeid = actual_type;
1320                 }
1321                 else if (decl_type == ANYARRAYOID)
1322                 {
1323                         if (actual_type == UNKNOWNOID)
1324                                 continue;
1325                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1326                                 return false;
1327                         array_typeid = actual_type;
1328                 }
1329         }
1330
1331         /* Get the element type based on the array type, if we have one */
1332         if (OidIsValid(array_typeid))
1333         {
1334                 if (array_typeid == ANYARRAYOID)
1335                 {
1336                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1337                         if (have_anyelement)
1338                                 return false;
1339                         return true;
1340                 }
1341
1342                 array_typelem = get_element_type(array_typeid);
1343                 if (!OidIsValid(array_typelem))
1344                         return false;           /* should be an array, but isn't */
1345
1346                 if (!OidIsValid(elem_typeid))
1347                 {
1348                         /*
1349                          * if we don't have an element type yet, use the one we just got
1350                          */
1351                         elem_typeid = array_typelem;
1352                 }
1353                 else if (array_typelem != elem_typeid)
1354                 {
1355                         /* otherwise, they better match */
1356                         return false;
1357                 }
1358         }
1359
1360         if (have_anynonarray)
1361         {
1362                 /* require the element type to not be an array */
1363                 if (type_is_array(elem_typeid))
1364                         return false;
1365         }
1366
1367         if (have_anyenum)
1368         {
1369                 /* require the element type to be an enum */
1370                 if (!type_is_enum(elem_typeid))
1371                         return false;
1372         }
1373
1374         /* Looks valid */
1375         return true;
1376 }
1377
1378 /*
1379  * enforce_generic_type_consistency()
1380  *              Make sure a polymorphic function is legally callable, and
1381  *              deduce actual argument and result types.
1382  *
1383  * If any polymorphic pseudotype is used in a function's arguments or
1384  * return type, we make sure the actual data types are consistent with
1385  * each other. The argument consistency rules are shown above for
1386  * check_generic_type_consistency().
1387  *
1388  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1389  * argument, we attempt to deduce the actual type it should have.  If
1390  * successful, we alter that position of declared_arg_types[] so that
1391  * make_fn_arguments will coerce the literal to the right thing.
1392  *
1393  * Rules are applied to the function's return type (possibly altering it)
1394  * if it is declared as a polymorphic type:
1395  *
1396  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1397  *        argument's actual type as the function's return type.
1398  * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1399  *        is ANYELEMENT, use the actual type of the argument to determine
1400  *        the function's return type, i.e. the element type's corresponding
1401  *        array type.
1402  * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1403  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1404  *        and is therefore not expected here.
1405  * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1406  *        argument's actual type as the function's return type.
1407  * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1408  *        argument is ANYARRAY, use the actual type of the argument to determine
1409  *        the function's return type, i.e. the array type's corresponding
1410  *        element type.
1411  * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1412  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1413  *        and is therefore not expected here.
1414  * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1415  *        (alone or in combination with plain ANYELEMENT), we add the extra
1416  *        condition that the ANYELEMENT type must be an enum.
1417  * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1418  *        we add the extra condition that the ANYELEMENT type must not be an array.
1419  *        (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1420  *        is an extra restriction if not.)
1421  *
1422  * When allow_poly is false, we are not expecting any of the actual_arg_types
1423  * to be polymorphic, and we should not return a polymorphic result type
1424  * either.  When allow_poly is true, it is okay to have polymorphic "actual"
1425  * arg types, and we can return ANYARRAY or ANYELEMENT as the result.  (This
1426  * case is currently used only to check compatibility of an aggregate's
1427  * declaration with the underlying transfn.)
1428  *
1429  * A special case is that we could see ANYARRAY as an actual_arg_type even
1430  * when allow_poly is false (this is possible only because pg_statistic has
1431  * columns shown as anyarray in the catalogs).  We allow this to match a
1432  * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1433  * or result (since we can't determine a specific element type to match to
1434  * ANYELEMENT).  Note this means that functions taking ANYARRAY had better
1435  * behave sanely if applied to the pg_statistic columns; they can't just
1436  * assume that successive inputs are of the same actual element type.
1437  */
1438 Oid
1439 enforce_generic_type_consistency(Oid *actual_arg_types,
1440                                                                  Oid *declared_arg_types,
1441                                                                  int nargs,
1442                                                                  Oid rettype,
1443                                                                  bool allow_poly)
1444 {
1445         int                     j;
1446         bool            have_generics = false;
1447         bool            have_unknowns = false;
1448         Oid                     elem_typeid = InvalidOid;
1449         Oid                     array_typeid = InvalidOid;
1450         Oid                     array_typelem;
1451         bool            have_anyelement = (rettype == ANYELEMENTOID ||
1452                                                                    rettype == ANYNONARRAYOID ||
1453                                                                    rettype == ANYENUMOID);
1454         bool            have_anynonarray = (rettype == ANYNONARRAYOID);
1455         bool            have_anyenum = (rettype == ANYENUMOID);
1456
1457         /*
1458          * Loop through the arguments to see if we have any that are polymorphic.
1459          * If so, require the actual types to be consistent.
1460          */
1461         for (j = 0; j < nargs; j++)
1462         {
1463                 Oid                     decl_type = declared_arg_types[j];
1464                 Oid                     actual_type = actual_arg_types[j];
1465
1466                 if (decl_type == ANYELEMENTOID ||
1467                         decl_type == ANYNONARRAYOID ||
1468                         decl_type == ANYENUMOID)
1469                 {
1470                         have_generics = have_anyelement = true;
1471                         if (decl_type == ANYNONARRAYOID)
1472                                 have_anynonarray = true;
1473                         else if (decl_type == ANYENUMOID)
1474                                 have_anyenum = true;
1475                         if (actual_type == UNKNOWNOID)
1476                         {
1477                                 have_unknowns = true;
1478                                 continue;
1479                         }
1480                         if (allow_poly && decl_type == actual_type)
1481                                 continue;               /* no new information here */
1482                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1483                                 ereport(ERROR,
1484                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1485                                 errmsg("arguments declared \"anyelement\" are not all alike"),
1486                                                  errdetail("%s versus %s",
1487                                                                    format_type_be(elem_typeid),
1488                                                                    format_type_be(actual_type))));
1489                         elem_typeid = actual_type;
1490                 }
1491                 else if (decl_type == ANYARRAYOID)
1492                 {
1493                         have_generics = true;
1494                         if (actual_type == UNKNOWNOID)
1495                         {
1496                                 have_unknowns = true;
1497                                 continue;
1498                         }
1499                         if (allow_poly && decl_type == actual_type)
1500                                 continue;               /* no new information here */
1501                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1502                                 ereport(ERROR,
1503                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1504                                  errmsg("arguments declared \"anyarray\" are not all alike"),
1505                                                  errdetail("%s versus %s",
1506                                                                    format_type_be(array_typeid),
1507                                                                    format_type_be(actual_type))));
1508                         array_typeid = actual_type;
1509                 }
1510         }
1511
1512         /*
1513          * Fast Track: if none of the arguments are polymorphic, return the
1514          * unmodified rettype.  We assume it can't be polymorphic either.
1515          */
1516         if (!have_generics)
1517                 return rettype;
1518
1519         /* Get the element type based on the array type, if we have one */
1520         if (OidIsValid(array_typeid))
1521         {
1522                 if (array_typeid == ANYARRAYOID && !have_anyelement)
1523                 {
1524                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1525                         array_typelem = InvalidOid;
1526                 }
1527                 else
1528                 {
1529                         array_typelem = get_element_type(array_typeid);
1530                         if (!OidIsValid(array_typelem))
1531                                 ereport(ERROR,
1532                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1533                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1534                                                                 format_type_be(array_typeid))));
1535                 }
1536
1537                 if (!OidIsValid(elem_typeid))
1538                 {
1539                         /*
1540                          * if we don't have an element type yet, use the one we just got
1541                          */
1542                         elem_typeid = array_typelem;
1543                 }
1544                 else if (array_typelem != elem_typeid)
1545                 {
1546                         /* otherwise, they better match */
1547                         ereport(ERROR,
1548                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1549                                          errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1550                                          errdetail("%s versus %s",
1551                                                            format_type_be(array_typeid),
1552                                                            format_type_be(elem_typeid))));
1553                 }
1554         }
1555         else if (!OidIsValid(elem_typeid))
1556         {
1557                 if (allow_poly)
1558                 {
1559                         array_typeid = ANYARRAYOID;
1560                         elem_typeid = ANYELEMENTOID;
1561                 }
1562                 else
1563                 {
1564                         /* Only way to get here is if all the generic args are UNKNOWN */
1565                         ereport(ERROR,
1566                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1567                                          errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1568                 }
1569         }
1570
1571         if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1572         {
1573                 /* require the element type to not be an array */
1574                 if (type_is_array(elem_typeid))
1575                         ereport(ERROR,
1576                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1577                                    errmsg("type matched to anynonarray is an array type: %s",
1578                                                   format_type_be(elem_typeid))));
1579         }
1580
1581         if (have_anyenum && elem_typeid != ANYELEMENTOID)
1582         {
1583                 /* require the element type to be an enum */
1584                 if (!type_is_enum(elem_typeid))
1585                         ereport(ERROR,
1586                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1587                                          errmsg("type matched to anyenum is not an enum type: %s",
1588                                                         format_type_be(elem_typeid))));
1589         }
1590
1591         /*
1592          * If we had any unknown inputs, re-scan to assign correct types
1593          */
1594         if (have_unknowns)
1595         {
1596                 for (j = 0; j < nargs; j++)
1597                 {
1598                         Oid                     decl_type = declared_arg_types[j];
1599                         Oid                     actual_type = actual_arg_types[j];
1600
1601                         if (actual_type != UNKNOWNOID)
1602                                 continue;
1603
1604                         if (decl_type == ANYELEMENTOID ||
1605                                 decl_type == ANYNONARRAYOID ||
1606                                 decl_type == ANYENUMOID)
1607                                 declared_arg_types[j] = elem_typeid;
1608                         else if (decl_type == ANYARRAYOID)
1609                         {
1610                                 if (!OidIsValid(array_typeid))
1611                                 {
1612                                         array_typeid = get_array_type(elem_typeid);
1613                                         if (!OidIsValid(array_typeid))
1614                                                 ereport(ERROR,
1615                                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1616                                                  errmsg("could not find array type for data type %s",
1617                                                                 format_type_be(elem_typeid))));
1618                                 }
1619                                 declared_arg_types[j] = array_typeid;
1620                         }
1621                 }
1622         }
1623
1624         /* if we return ANYARRAY use the appropriate argument type */
1625         if (rettype == ANYARRAYOID)
1626         {
1627                 if (!OidIsValid(array_typeid))
1628                 {
1629                         array_typeid = get_array_type(elem_typeid);
1630                         if (!OidIsValid(array_typeid))
1631                                 ereport(ERROR,
1632                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1633                                                  errmsg("could not find array type for data type %s",
1634                                                                 format_type_be(elem_typeid))));
1635                 }
1636                 return array_typeid;
1637         }
1638
1639         /* if we return ANYELEMENT use the appropriate argument type */
1640         if (rettype == ANYELEMENTOID ||
1641                 rettype == ANYNONARRAYOID ||
1642                 rettype == ANYENUMOID)
1643                 return elem_typeid;
1644
1645         /* we don't return a generic type; send back the original return type */
1646         return rettype;
1647 }
1648
1649 /*
1650  * resolve_generic_type()
1651  *              Deduce an individual actual datatype on the assumption that
1652  *              the rules for polymorphic types are being followed.
1653  *
1654  * declared_type is the declared datatype we want to resolve.
1655  * context_actual_type is the actual input datatype to some argument
1656  * that has declared datatype context_declared_type.
1657  *
1658  * If declared_type isn't polymorphic, we just return it.  Otherwise,
1659  * context_declared_type must be polymorphic, and we deduce the correct
1660  * return type based on the relationship of the two polymorphic types.
1661  */
1662 Oid
1663 resolve_generic_type(Oid declared_type,
1664                                          Oid context_actual_type,
1665                                          Oid context_declared_type)
1666 {
1667         if (declared_type == ANYARRAYOID)
1668         {
1669                 if (context_declared_type == ANYARRAYOID)
1670                 {
1671                         /* Use actual type, but it must be an array */
1672                         Oid                     array_typelem = get_element_type(context_actual_type);
1673
1674                         if (!OidIsValid(array_typelem))
1675                                 ereport(ERROR,
1676                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1677                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1678                                                                 format_type_be(context_actual_type))));
1679                         return context_actual_type;
1680                 }
1681                 else if (context_declared_type == ANYELEMENTOID ||
1682                                  context_declared_type == ANYNONARRAYOID ||
1683                                  context_declared_type == ANYENUMOID)
1684                 {
1685                         /* Use the array type corresponding to actual type */
1686                         Oid                     array_typeid = get_array_type(context_actual_type);
1687
1688                         if (!OidIsValid(array_typeid))
1689                                 ereport(ERROR,
1690                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1691                                                  errmsg("could not find array type for data type %s",
1692                                                                 format_type_be(context_actual_type))));
1693                         return array_typeid;
1694                 }
1695         }
1696         else if (declared_type == ANYELEMENTOID ||
1697                          declared_type == ANYNONARRAYOID ||
1698                          declared_type == ANYENUMOID)
1699         {
1700                 if (context_declared_type == ANYARRAYOID)
1701                 {
1702                         /* Use the element type corresponding to actual type */
1703                         Oid                     array_typelem = get_element_type(context_actual_type);
1704
1705                         if (!OidIsValid(array_typelem))
1706                                 ereport(ERROR,
1707                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1708                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1709                                                                 format_type_be(context_actual_type))));
1710                         return array_typelem;
1711                 }
1712                 else if (context_declared_type == ANYELEMENTOID ||
1713                                  context_declared_type == ANYNONARRAYOID ||
1714                                  context_declared_type == ANYENUMOID)
1715                 {
1716                         /* Use the actual type; it doesn't matter if array or not */
1717                         return context_actual_type;
1718                 }
1719         }
1720         else
1721         {
1722                 /* declared_type isn't polymorphic, so return it as-is */
1723                 return declared_type;
1724         }
1725         /* If we get here, declared_type is polymorphic and context isn't */
1726         /* NB: this is a calling-code logic error, not a user error */
1727         elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1728         return InvalidOid;                      /* keep compiler quiet */
1729 }
1730
1731
1732 /* TypeCategory()
1733  *              Assign a category to the specified type OID.
1734  *
1735  * NB: this must not return TYPCATEGORY_INVALID.
1736  */
1737 TYPCATEGORY
1738 TypeCategory(Oid type)
1739 {
1740         char            typcategory;
1741         bool            typispreferred;
1742
1743         get_type_category_preferred(type, &typcategory, &typispreferred);
1744         Assert(typcategory != TYPCATEGORY_INVALID);
1745         return (TYPCATEGORY) typcategory;
1746 }
1747
1748
1749 /* IsPreferredType()
1750  *              Check if this type is a preferred type for the given category.
1751  *
1752  * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1753  * types of any category; otherwise, only for preferred types of that
1754  * category.
1755  */
1756 bool
1757 IsPreferredType(TYPCATEGORY category, Oid type)
1758 {
1759         char            typcategory;
1760         bool            typispreferred;
1761
1762         get_type_category_preferred(type, &typcategory, &typispreferred);
1763         if (category == typcategory || category == TYPCATEGORY_INVALID)
1764                 return typispreferred;
1765         else
1766                 return false;
1767 }
1768
1769
1770 /* IsBinaryCoercible()
1771  *              Check if srctype is binary-coercible to targettype.
1772  *
1773  * This notion allows us to cheat and directly exchange values without
1774  * going through the trouble of calling a conversion function.  Note that
1775  * in general, this should only be an implementation shortcut.  Before 7.4,
1776  * this was also used as a heuristic for resolving overloaded functions and
1777  * operators, but that's basically a bad idea.
1778  *
1779  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1780  * We consider two types binary-coercible if there is an implicitly
1781  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
1782  * binary-coercible to its base type, though *not* vice versa (in the other
1783  * direction, one must apply domain constraint checks before accepting the
1784  * value as legitimate).  We also need to special-case various polymorphic
1785  * types.
1786  *
1787  * This function replaces IsBinaryCompatible(), which was an inherently
1788  * symmetric test.      Since the pg_cast entries aren't necessarily symmetric,
1789  * the order of the operands is now significant.
1790  */
1791 bool
1792 IsBinaryCoercible(Oid srctype, Oid targettype)
1793 {
1794         HeapTuple       tuple;
1795         Form_pg_cast castForm;
1796         bool            result;
1797
1798         /* Fast path if same type */
1799         if (srctype == targettype)
1800                 return true;
1801
1802         /* If srctype is a domain, reduce to its base type */
1803         if (OidIsValid(srctype))
1804                 srctype = getBaseType(srctype);
1805
1806         /* Somewhat-fast path for domain -> base type case */
1807         if (srctype == targettype)
1808                 return true;
1809
1810         /* Also accept any array type as coercible to ANYARRAY */
1811         if (targettype == ANYARRAYOID)
1812                 if (type_is_array(srctype))
1813                         return true;
1814
1815         /* Also accept any non-array type as coercible to ANYNONARRAY */
1816         if (targettype == ANYNONARRAYOID)
1817                 if (!type_is_array(srctype))
1818                         return true;
1819
1820         /* Also accept any enum type as coercible to ANYENUM */
1821         if (targettype == ANYENUMOID)
1822                 if (type_is_enum(srctype))
1823                         return true;
1824
1825         /* Also accept any composite type as coercible to RECORD */
1826         if (targettype == RECORDOID)
1827                 if (ISCOMPLEX(srctype))
1828                         return true;
1829
1830         /* Also accept any composite array type as coercible to RECORD[] */
1831         if (targettype == RECORDARRAYOID)
1832                 if (is_complex_array(srctype))
1833                         return true;
1834
1835         /* Else look in pg_cast */
1836         tuple = SearchSysCache(CASTSOURCETARGET,
1837                                                    ObjectIdGetDatum(srctype),
1838                                                    ObjectIdGetDatum(targettype),
1839                                                    0, 0);
1840         if (!HeapTupleIsValid(tuple))
1841                 return false;                   /* no cast */
1842         castForm = (Form_pg_cast) GETSTRUCT(tuple);
1843
1844         result = (castForm->castfunc == InvalidOid &&
1845                           castForm->castcontext == COERCION_CODE_IMPLICIT);
1846
1847         ReleaseSysCache(tuple);
1848
1849         return result;
1850 }
1851
1852
1853 /*
1854  * find_coercion_pathway
1855  *              Look for a coercion pathway between two types.
1856  *
1857  * Currently, this deals only with scalar-type cases; it does not consider
1858  * polymorphic types nor casts between composite types.  (Perhaps fold
1859  * those in someday?)
1860  *
1861  * ccontext determines the set of available casts.
1862  *
1863  * The possible result codes are:
1864  *      COERCION_PATH_NONE: failed to find any coercion pathway
1865  *                              *funcid is set to InvalidOid
1866  *      COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1867  *      COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1868  *                              *funcid is set to InvalidOid
1869  *      COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1870  *                              *funcid is set to the element cast function, or InvalidOid
1871  *                              if the array elements are binary-compatible
1872  *      COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1873  *                              *funcid is set to InvalidOid
1874  *
1875  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1876  * needed to do the coercion; if the target is a domain then we may need to
1877  * apply domain constraint checking.  If you want to check for a zero-effort
1878  * conversion then use IsBinaryCoercible().
1879  */
1880 CoercionPathType
1881 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1882                                           CoercionContext ccontext,
1883                                           Oid *funcid)
1884 {
1885         CoercionPathType result = COERCION_PATH_NONE;
1886         HeapTuple       tuple;
1887
1888         *funcid = InvalidOid;
1889
1890         /* Perhaps the types are domains; if so, look at their base types */
1891         if (OidIsValid(sourceTypeId))
1892                 sourceTypeId = getBaseType(sourceTypeId);
1893         if (OidIsValid(targetTypeId))
1894                 targetTypeId = getBaseType(targetTypeId);
1895
1896         /* Domains are always coercible to and from their base type */
1897         if (sourceTypeId == targetTypeId)
1898                 return COERCION_PATH_RELABELTYPE;
1899
1900         /* Look in pg_cast */
1901         tuple = SearchSysCache(CASTSOURCETARGET,
1902                                                    ObjectIdGetDatum(sourceTypeId),
1903                                                    ObjectIdGetDatum(targetTypeId),
1904                                                    0, 0);
1905
1906         if (HeapTupleIsValid(tuple))
1907         {
1908                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1909                 CoercionContext castcontext;
1910
1911                 /* convert char value for castcontext to CoercionContext enum */
1912                 switch (castForm->castcontext)
1913                 {
1914                         case COERCION_CODE_IMPLICIT:
1915                                 castcontext = COERCION_IMPLICIT;
1916                                 break;
1917                         case COERCION_CODE_ASSIGNMENT:
1918                                 castcontext = COERCION_ASSIGNMENT;
1919                                 break;
1920                         case COERCION_CODE_EXPLICIT:
1921                                 castcontext = COERCION_EXPLICIT;
1922                                 break;
1923                         default:
1924                                 elog(ERROR, "unrecognized castcontext: %d",
1925                                          (int) castForm->castcontext);
1926                                 castcontext = 0;        /* keep compiler quiet */
1927                                 break;
1928                 }
1929
1930                 /* Rely on ordering of enum for correct behavior here */
1931                 if (ccontext >= castcontext)
1932                 {
1933                         switch (castForm->castmethod)
1934                         {
1935                                 case COERCION_METHOD_FUNCTION:
1936                                         result = COERCION_PATH_FUNC;
1937                                         *funcid = castForm->castfunc;
1938                                         break;
1939                                 case COERCION_METHOD_INOUT:
1940                                         result = COERCION_PATH_COERCEVIAIO;
1941                                         break;
1942                                 case COERCION_METHOD_BINARY:
1943                                         result = COERCION_PATH_RELABELTYPE;
1944                                         break;
1945                                 default:
1946                                         elog(ERROR, "unrecognized castmethod: %d",
1947                                                  (int) castForm->castmethod);
1948                                         break;
1949                         }
1950                 }
1951
1952                 ReleaseSysCache(tuple);
1953         }
1954         else
1955         {
1956                 /*
1957                  * If there's no pg_cast entry, perhaps we are dealing with a pair of
1958                  * array types.  If so, and if the element types have a suitable cast,
1959                  * report that we can coerce with an ArrayCoerceExpr.
1960                  *
1961                  * Hack: disallow coercions to oidvector and int2vector, which
1962                  * otherwise tend to capture coercions that should go to "real" array
1963                  * types.  We want those types to be considered "real" arrays for many
1964                  * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
1965                  * guaranteed to produce an output that meets the restrictions of
1966                  * these datatypes, such as being 1-dimensional.)
1967                  */
1968                 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
1969                 {
1970                         Oid                     targetElem;
1971                         Oid                     sourceElem;
1972
1973                         if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
1974                                 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
1975                         {
1976                                 CoercionPathType elempathtype;
1977                                 Oid                     elemfuncid;
1978
1979                                 elempathtype = find_coercion_pathway(targetElem,
1980                                                                                                          sourceElem,
1981                                                                                                          ccontext,
1982                                                                                                          &elemfuncid);
1983                                 if (elempathtype != COERCION_PATH_NONE &&
1984                                         elempathtype != COERCION_PATH_ARRAYCOERCE)
1985                                 {
1986                                         *funcid = elemfuncid;
1987                                         if (elempathtype == COERCION_PATH_COERCEVIAIO)
1988                                                 result = COERCION_PATH_COERCEVIAIO;
1989                                         else
1990                                                 result = COERCION_PATH_ARRAYCOERCE;
1991                                 }
1992                         }
1993                 }
1994
1995                 /*
1996                  * If we still haven't found a possibility, consider automatic casting
1997                  * using I/O functions.  We allow assignment casts to string types
1998                  * and explicit casts from string types to be handled this way. (The
1999                  * CoerceViaIO mechanism is a lot more general than that, but this is
2000                  * all we want to allow in the absence of a pg_cast entry.) It would
2001                  * probably be better to insist on explicit casts in both directions,
2002                  * but this is a compromise to preserve something of the pre-8.3
2003                  * behavior that many types had implicit (yipes!) casts to text.
2004                  */
2005                 if (result == COERCION_PATH_NONE)
2006                 {
2007                         if (ccontext >= COERCION_ASSIGNMENT &&
2008                                 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2009                                 result = COERCION_PATH_COERCEVIAIO;
2010                         else if (ccontext >= COERCION_EXPLICIT &&
2011                                          TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2012                                 result = COERCION_PATH_COERCEVIAIO;
2013                 }
2014         }
2015
2016         return result;
2017 }
2018
2019
2020 /*
2021  * find_typmod_coercion_function -- does the given type need length coercion?
2022  *
2023  * If the target type possesses a pg_cast function from itself to itself,
2024  * it must need length coercion.
2025  *
2026  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2027  *
2028  * If the given type is a varlena array type, we do not look for a coercion
2029  * function associated directly with the array type, but instead look for
2030  * one associated with the element type.  An ArrayCoerceExpr node must be
2031  * used to apply such a function.
2032  *
2033  * We use the same result enum as find_coercion_pathway, but the only possible
2034  * result codes are:
2035  *      COERCION_PATH_NONE: no length coercion needed
2036  *      COERCION_PATH_FUNC: apply the function returned in *funcid
2037  *      COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2038  */
2039 CoercionPathType
2040 find_typmod_coercion_function(Oid typeId,
2041                                                           Oid *funcid)
2042 {
2043         CoercionPathType result;
2044         Type            targetType;
2045         Form_pg_type typeForm;
2046         HeapTuple       tuple;
2047
2048         *funcid = InvalidOid;
2049         result = COERCION_PATH_FUNC;
2050
2051         targetType = typeidType(typeId);
2052         typeForm = (Form_pg_type) GETSTRUCT(targetType);
2053
2054         /* Check for a varlena array type (and not a domain) */
2055         if (typeForm->typelem != InvalidOid &&
2056                 typeForm->typlen == -1 &&
2057                 typeForm->typtype != TYPTYPE_DOMAIN)
2058         {
2059                 /* Yes, switch our attention to the element type */
2060                 typeId = typeForm->typelem;
2061                 result = COERCION_PATH_ARRAYCOERCE;
2062         }
2063         ReleaseSysCache(targetType);
2064
2065         /* Look in pg_cast */
2066         tuple = SearchSysCache(CASTSOURCETARGET,
2067                                                    ObjectIdGetDatum(typeId),
2068                                                    ObjectIdGetDatum(typeId),
2069                                                    0, 0);
2070
2071         if (HeapTupleIsValid(tuple))
2072         {
2073                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2074
2075                 *funcid = castForm->castfunc;
2076                 ReleaseSysCache(tuple);
2077         }
2078
2079         if (!OidIsValid(*funcid))
2080                 result = COERCION_PATH_NONE;
2081
2082         return result;
2083 }
2084
2085 /*
2086  * is_complex_array
2087  *              Is this type an array of composite?
2088  *
2089  * Note: this will not return true for record[]; check for RECORDARRAYOID
2090  * separately if needed.
2091  */
2092 static bool
2093 is_complex_array(Oid typid)
2094 {
2095         Oid                     elemtype = get_element_type(typid);
2096
2097         return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2098 }