]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Add a heuristic to transformAExprIn() to make it prefer expanding "x IN (list)"
[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-2008, 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.170 2008/10/25 17:19:09 tgl 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                 nargs = procstruct->pronargs;
750                 Assert(nargs >= 1 && nargs <= 3);
751                 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
752                 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
753                 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
754
755                 ReleaseSysCache(tp);
756         }
757
758         if (pathtype == COERCION_PATH_FUNC)
759         {
760                 /* We build an ordinary FuncExpr with special arguments */
761                 FuncExpr   *fexpr;
762                 List       *args;
763                 Const      *cons;
764
765                 Assert(OidIsValid(funcId));
766
767                 args = list_make1(node);
768
769                 if (nargs >= 2)
770                 {
771                         /* Pass target typmod as an int4 constant */
772                         cons = makeConst(INT4OID,
773                                                          -1,
774                                                          sizeof(int32),
775                                                          Int32GetDatum(targetTypMod),
776                                                          false,
777                                                          true);
778
779                         args = lappend(args, cons);
780                 }
781
782                 if (nargs == 3)
783                 {
784                         /* Pass it a boolean isExplicit parameter, too */
785                         cons = makeConst(BOOLOID,
786                                                          -1,
787                                                          sizeof(bool),
788                                                          BoolGetDatum(isExplicit),
789                                                          false,
790                                                          true);
791
792                         args = lappend(args, cons);
793                 }
794
795                 fexpr = makeFuncExpr(funcId, targetTypeId, args, cformat);
796                 fexpr->location = location;
797                 return (Node *) fexpr;
798         }
799         else if (pathtype == COERCION_PATH_ARRAYCOERCE)
800         {
801                 /* We need to build an ArrayCoerceExpr */
802                 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
803
804                 acoerce->arg = (Expr *) node;
805                 acoerce->elemfuncid = funcId;
806                 acoerce->resulttype = targetTypeId;
807
808                 /*
809                  * Label the output as having a particular typmod only if we are
810                  * really invoking a length-coercion function, ie one with more than
811                  * one argument.
812                  */
813                 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
814                 acoerce->isExplicit = isExplicit;
815                 acoerce->coerceformat = cformat;
816                 acoerce->location = location;
817
818                 return (Node *) acoerce;
819         }
820         else if (pathtype == COERCION_PATH_COERCEVIAIO)
821         {
822                 /* We need to build a CoerceViaIO node */
823                 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
824
825                 Assert(!OidIsValid(funcId));
826
827                 iocoerce->arg = (Expr *) node;
828                 iocoerce->resulttype = targetTypeId;
829                 iocoerce->coerceformat = cformat;
830                 iocoerce->location = location;
831
832                 return (Node *) iocoerce;
833         }
834         else
835         {
836                 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
837                          (int) pathtype);
838                 return NULL;                    /* keep compiler quiet */
839         }
840 }
841
842
843 /*
844  * coerce_record_to_complex
845  *              Coerce a RECORD to a specific composite type.
846  *
847  * Currently we only support this for inputs that are RowExprs or whole-row
848  * Vars.
849  */
850 static Node *
851 coerce_record_to_complex(ParseState *pstate, Node *node,
852                                                  Oid targetTypeId,
853                                                  CoercionContext ccontext,
854                                                  CoercionForm cformat,
855                                                  int location)
856 {
857         RowExpr    *rowexpr;
858         TupleDesc       tupdesc;
859         List       *args = NIL;
860         List       *newargs;
861         int                     i;
862         int                     ucolno;
863         ListCell   *arg;
864
865         if (node && IsA(node, RowExpr))
866         {
867                 /*
868                  * Since the RowExpr must be of type RECORD, we needn't worry about it
869                  * containing any dropped columns.
870                  */
871                 args = ((RowExpr *) node)->args;
872         }
873         else if (node && IsA(node, Var) &&
874                          ((Var *) node)->varattno == InvalidAttrNumber)
875         {
876                 int                     rtindex = ((Var *) node)->varno;
877                 int                     sublevels_up = ((Var *) node)->varlevelsup;
878                 int                     vlocation = ((Var *) node)->location;
879                 RangeTblEntry *rte;
880
881                 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
882                 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
883                                   NULL, &args);
884         }
885         else
886                 ereport(ERROR,
887                                 (errcode(ERRCODE_CANNOT_COERCE),
888                                  errmsg("cannot cast type %s to %s",
889                                                 format_type_be(RECORDOID),
890                                                 format_type_be(targetTypeId)),
891                                  parser_coercion_errposition(pstate, location, node)));
892
893         tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
894         newargs = NIL;
895         ucolno = 1;
896         arg = list_head(args);
897         for (i = 0; i < tupdesc->natts; i++)
898         {
899                 Node       *expr;
900                 Node       *cexpr;
901                 Oid                     exprtype;
902
903                 /* Fill in NULLs for dropped columns in rowtype */
904                 if (tupdesc->attrs[i]->attisdropped)
905                 {
906                         /*
907                          * can't use atttypid here, but it doesn't really matter what type
908                          * the Const claims to be.
909                          */
910                         newargs = lappend(newargs, makeNullConst(INT4OID, -1));
911                         continue;
912                 }
913
914                 if (arg == NULL)
915                         ereport(ERROR,
916                                         (errcode(ERRCODE_CANNOT_COERCE),
917                                          errmsg("cannot cast type %s to %s",
918                                                         format_type_be(RECORDOID),
919                                                         format_type_be(targetTypeId)),
920                                          errdetail("Input has too few columns."),
921                                          parser_coercion_errposition(pstate, location, node)));
922                 expr = (Node *) lfirst(arg);
923                 exprtype = exprType(expr);
924
925                 cexpr = coerce_to_target_type(pstate,
926                                                                           expr, exprtype,
927                                                                           tupdesc->attrs[i]->atttypid,
928                                                                           tupdesc->attrs[i]->atttypmod,
929                                                                           ccontext,
930                                                                           COERCE_IMPLICIT_CAST,
931                                                                           -1);
932                 if (cexpr == NULL)
933                         ereport(ERROR,
934                                         (errcode(ERRCODE_CANNOT_COERCE),
935                                          errmsg("cannot cast type %s to %s",
936                                                         format_type_be(RECORDOID),
937                                                         format_type_be(targetTypeId)),
938                                          errdetail("Cannot cast type %s to %s in column %d.",
939                                                            format_type_be(exprtype),
940                                                            format_type_be(tupdesc->attrs[i]->atttypid),
941                                                            ucolno),
942                                          parser_coercion_errposition(pstate, location, expr)));
943                 newargs = lappend(newargs, cexpr);
944                 ucolno++;
945                 arg = lnext(arg);
946         }
947         if (arg != NULL)
948                 ereport(ERROR,
949                                 (errcode(ERRCODE_CANNOT_COERCE),
950                                  errmsg("cannot cast type %s to %s",
951                                                 format_type_be(RECORDOID),
952                                                 format_type_be(targetTypeId)),
953                                  errdetail("Input has too many columns."),
954                                  parser_coercion_errposition(pstate, location, node)));
955
956         ReleaseTupleDesc(tupdesc);
957
958         rowexpr = makeNode(RowExpr);
959         rowexpr->args = newargs;
960         rowexpr->row_typeid = targetTypeId;
961         rowexpr->row_format = cformat;
962         rowexpr->colnames = NIL;        /* not needed for named target type */
963         rowexpr->location = location;
964         return (Node *) rowexpr;
965 }
966
967 /*
968  * coerce_to_boolean()
969  *              Coerce an argument of a construct that requires boolean input
970  *              (AND, OR, NOT, etc).  Also check that input is not a set.
971  *
972  * Returns the possibly-transformed node tree.
973  *
974  * As with coerce_type, pstate may be NULL if no special unknown-Param
975  * processing is wanted.
976  */
977 Node *
978 coerce_to_boolean(ParseState *pstate, Node *node,
979                                   const char *constructName)
980 {
981         Oid                     inputTypeId = exprType(node);
982
983         if (inputTypeId != BOOLOID)
984         {
985                 Node    *newnode;
986
987                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
988                                                                                 BOOLOID, -1,
989                                                                                 COERCION_ASSIGNMENT,
990                                                                                 COERCE_IMPLICIT_CAST,
991                                                                                 -1);
992                 if (newnode == NULL)
993                         ereport(ERROR,
994                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
995                         /* translator: first %s is name of a SQL construct, eg WHERE */
996                                          errmsg("argument of %s must be type boolean, not type %s",
997                                                         constructName, format_type_be(inputTypeId)),
998                                          parser_errposition(pstate, exprLocation(node))));
999                 node = newnode;
1000         }
1001
1002         if (expression_returns_set(node))
1003                 ereport(ERROR,
1004                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1005                 /* translator: %s is name of a SQL construct, eg WHERE */
1006                                  errmsg("argument of %s must not return a set",
1007                                                 constructName),
1008                                  parser_errposition(pstate, exprLocation(node))));
1009
1010         return node;
1011 }
1012
1013 /*
1014  * coerce_to_specific_type()
1015  *              Coerce an argument of a construct that requires a specific data type.
1016  *              Also check that input is not a set.
1017  *
1018  * Returns the possibly-transformed node tree.
1019  *
1020  * As with coerce_type, pstate may be NULL if no special unknown-Param
1021  * processing is wanted.
1022  */
1023 Node *
1024 coerce_to_specific_type(ParseState *pstate, Node *node,
1025                                                 Oid targetTypeId,
1026                                                 const char *constructName)
1027 {
1028         Oid                     inputTypeId = exprType(node);
1029
1030         if (inputTypeId != targetTypeId)
1031         {
1032                 Node    *newnode;
1033
1034                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1035                                                                                 targetTypeId, -1,
1036                                                                                 COERCION_ASSIGNMENT,
1037                                                                                 COERCE_IMPLICIT_CAST,
1038                                                                                 -1);
1039                 if (newnode == NULL)
1040                         ereport(ERROR,
1041                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1042                         /* translator: first %s is name of a SQL construct, eg LIMIT */
1043                                          errmsg("argument of %s must be type %s, not type %s",
1044                                                         constructName,
1045                                                         format_type_be(targetTypeId),
1046                                                         format_type_be(inputTypeId)),
1047                                          parser_errposition(pstate, exprLocation(node))));
1048                 node = newnode;
1049         }
1050
1051         if (expression_returns_set(node))
1052                 ereport(ERROR,
1053                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1054                 /* translator: %s is name of a SQL construct, eg LIMIT */
1055                                  errmsg("argument of %s must not return a set",
1056                                                 constructName),
1057                                  parser_errposition(pstate, exprLocation(node))));
1058
1059         return node;
1060 }
1061
1062
1063 /*
1064  * parser_coercion_errposition - report coercion error location, if possible
1065  *
1066  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1067  * but there may be no such location in the case of an implicit coercion.
1068  * In that case point at the input expression.
1069  *
1070  * XXX possibly this is more generally useful than coercion errors;
1071  * if so, should rename and place with parser_errposition.
1072  */
1073 int
1074 parser_coercion_errposition(ParseState *pstate,
1075                                                         int coerce_location,
1076                                                         Node *input_expr)
1077 {
1078         if (coerce_location >= 0)
1079                 return parser_errposition(pstate, coerce_location);
1080         else
1081                 return parser_errposition(pstate, exprLocation(input_expr));
1082 }
1083
1084
1085 /*
1086  * select_common_type()
1087  *              Determine the common supertype of a list of input expressions.
1088  *              This is used for determining the output type of CASE, UNION,
1089  *              and similar constructs.
1090  *
1091  * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
1092  * in the list will be preferred if there is doubt.
1093  * 'context' is a phrase to use in the error message if we fail to select
1094  * a usable type.  Pass NULL to have the routine return InvalidOid
1095  * rather than throwing an error on failure.
1096  * 'which_expr': if not NULL, receives a pointer to the particular input
1097  * expression from which the result type was taken.
1098  */
1099 Oid
1100 select_common_type(ParseState *pstate, List *exprs, const char *context,
1101                                    Node **which_expr)
1102 {
1103         Node       *pexpr;
1104         Oid                     ptype;
1105         TYPCATEGORY     pcategory;
1106         bool            pispreferred;
1107         ListCell   *lc;
1108
1109         Assert(exprs != NIL);
1110         pexpr = (Node *) linitial(exprs);
1111         lc = lnext(list_head(exprs));
1112         ptype = exprType(pexpr);
1113
1114         /*
1115          * If all input types are valid and exactly the same, just pick that type.
1116          * This is the only way that we will resolve the result as being a domain
1117          * type; otherwise domains are smashed to their base types for comparison.
1118          */
1119         if (ptype != UNKNOWNOID)
1120         {
1121                 for_each_cell(lc, lc)
1122                 {
1123                         Node   *nexpr = (Node *) lfirst(lc);
1124                         Oid             ntype = exprType(nexpr);
1125
1126                         if (ntype != ptype)
1127                                 break;
1128                 }
1129                 if (lc == NULL)                 /* got to the end of the list? */
1130                 {
1131                         if (which_expr)
1132                                 *which_expr = pexpr;
1133                         return ptype;
1134                 }
1135         }
1136
1137         /*
1138          * Nope, so set up for the full algorithm.  Note that at this point,
1139          * lc points to the first list item with type different from pexpr's;
1140          * we need not re-examine any items the previous loop advanced over.
1141          */
1142         ptype = getBaseType(ptype);
1143         get_type_category_preferred(ptype, &pcategory, &pispreferred);
1144
1145         for_each_cell(lc, lc)
1146         {
1147                 Node       *nexpr = (Node *) lfirst(lc);
1148                 Oid                     ntype = getBaseType(exprType(nexpr));
1149
1150                 /* move on to next one if no new information... */
1151                 if (ntype != UNKNOWNOID && ntype != ptype)
1152                 {
1153                         TYPCATEGORY     ncategory;
1154                         bool            nispreferred;
1155
1156                         get_type_category_preferred(ntype, &ncategory, &nispreferred);
1157                         if (ptype == UNKNOWNOID)
1158                         {
1159                                 /* so far, only unknowns so take anything... */
1160                                 pexpr = nexpr;
1161                                 ptype = ntype;
1162                                 pcategory = ncategory;
1163                                 pispreferred = nispreferred;
1164                         }
1165                         else if (ncategory != pcategory)
1166                         {
1167                                 /*
1168                                  * both types in different categories? then not much hope...
1169                                  */
1170                                 if (context == NULL)
1171                                         return InvalidOid;
1172                                 ereport(ERROR,
1173                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1174                                 /*------
1175                                   translator: first %s is name of a SQL construct, eg CASE */
1176                                                  errmsg("%s types %s and %s cannot be matched",
1177                                                                 context,
1178                                                                 format_type_be(ptype),
1179                                                                 format_type_be(ntype)),
1180                                                  parser_errposition(pstate, exprLocation(nexpr))));
1181                         }
1182                         else if (!pispreferred &&
1183                                          can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1184                                          !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1185                         {
1186                                 /*
1187                                  * take new type if can coerce to it implicitly but not the
1188                                  * other way; but if we have a preferred type, stay on it.
1189                                  */
1190                                 pexpr = nexpr;
1191                                 ptype = ntype;
1192                                 pcategory = ncategory;
1193                                 pispreferred = nispreferred;
1194                         }
1195                 }
1196         }
1197
1198         /*
1199          * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1200          * then resolve as type TEXT.  This situation comes up with constructs
1201          * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1202          * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1203          * output type as UNKNOWN, but that really doesn't work, because we'd
1204          * probably end up needing a runtime coercion from UNKNOWN to something
1205          * else, and we usually won't have it.  We need to coerce the unknown
1206          * literals while they are still literals, so a decision has to be made
1207          * now.
1208          */
1209         if (ptype == UNKNOWNOID)
1210                 ptype = TEXTOID;
1211
1212         if (which_expr)
1213                 *which_expr = pexpr;
1214         return ptype;
1215 }
1216
1217 /*
1218  * coerce_to_common_type()
1219  *              Coerce an expression to the given type.
1220  *
1221  * This is used following select_common_type() to coerce the individual
1222  * expressions to the desired type.  'context' is a phrase to use in the
1223  * error message if we fail to coerce.
1224  *
1225  * As with coerce_type, pstate may be NULL if no special unknown-Param
1226  * processing is wanted.
1227  */
1228 Node *
1229 coerce_to_common_type(ParseState *pstate, Node *node,
1230                                           Oid targetTypeId, const char *context)
1231 {
1232         Oid                     inputTypeId = exprType(node);
1233
1234         if (inputTypeId == targetTypeId)
1235                 return node;                    /* no work */
1236         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1237                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1238                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1239         else
1240                 ereport(ERROR,
1241                                 (errcode(ERRCODE_CANNOT_COERCE),
1242                 /* translator: first %s is name of a SQL construct, eg CASE */
1243                                  errmsg("%s could not convert type %s to %s",
1244                                                 context,
1245                                                 format_type_be(inputTypeId),
1246                                                 format_type_be(targetTypeId)),
1247                                  parser_errposition(pstate, exprLocation(node))));
1248         return node;
1249 }
1250
1251 /*
1252  * check_generic_type_consistency()
1253  *              Are the actual arguments potentially compatible with a
1254  *              polymorphic function?
1255  *
1256  * The argument consistency rules are:
1257  *
1258  * 1) All arguments declared ANYARRAY must have matching datatypes,
1259  *        and must in fact be varlena arrays.
1260  * 2) All arguments declared ANYELEMENT must have matching datatypes.
1261  * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1262  *        the actual ANYELEMENT datatype is in fact the element type for
1263  *        the actual ANYARRAY datatype.
1264  * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1265  *        (alone or in combination with plain ANYELEMENT), we add the extra
1266  *        condition that the ANYELEMENT type must be an enum.
1267  * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1268  *        we add the extra condition that the ANYELEMENT type must not be an array.
1269  *        (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1270  *        is an extra restriction if not.)
1271  *
1272  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1273  * argument, assume it is okay.
1274  *
1275  * If an input is of type ANYARRAY (ie, we know it's an array, but not
1276  * what element type), we will accept it as a match to an argument declared
1277  * ANYARRAY, so long as we don't have to determine an element type ---
1278  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
1279  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1280  *
1281  * We do not ereport here, but just return FALSE if a rule is violated.
1282  */
1283 bool
1284 check_generic_type_consistency(Oid *actual_arg_types,
1285                                                            Oid *declared_arg_types,
1286                                                            int nargs)
1287 {
1288         int                     j;
1289         Oid                     elem_typeid = InvalidOid;
1290         Oid                     array_typeid = InvalidOid;
1291         Oid                     array_typelem;
1292         bool            have_anyelement = false;
1293         bool            have_anynonarray = false;
1294         bool            have_anyenum = false;
1295
1296         /*
1297          * Loop through the arguments to see if we have any that are polymorphic.
1298          * If so, require the actual types to be consistent.
1299          */
1300         for (j = 0; j < nargs; j++)
1301         {
1302                 Oid                     decl_type = declared_arg_types[j];
1303                 Oid                     actual_type = actual_arg_types[j];
1304
1305                 if (decl_type == ANYELEMENTOID ||
1306                         decl_type == ANYNONARRAYOID ||
1307                         decl_type == ANYENUMOID)
1308                 {
1309                         have_anyelement = true;
1310                         if (decl_type == ANYNONARRAYOID)
1311                                 have_anynonarray = true;
1312                         else if (decl_type == ANYENUMOID)
1313                                 have_anyenum = true;
1314                         if (actual_type == UNKNOWNOID)
1315                                 continue;
1316                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1317                                 return false;
1318                         elem_typeid = actual_type;
1319                 }
1320                 else if (decl_type == ANYARRAYOID)
1321                 {
1322                         if (actual_type == UNKNOWNOID)
1323                                 continue;
1324                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1325                                 return false;
1326                         array_typeid = actual_type;
1327                 }
1328         }
1329
1330         /* Get the element type based on the array type, if we have one */
1331         if (OidIsValid(array_typeid))
1332         {
1333                 if (array_typeid == ANYARRAYOID)
1334                 {
1335                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1336                         if (have_anyelement)
1337                                 return false;
1338                         return true;
1339                 }
1340
1341                 array_typelem = get_element_type(array_typeid);
1342                 if (!OidIsValid(array_typelem))
1343                         return false;           /* should be an array, but isn't */
1344
1345                 if (!OidIsValid(elem_typeid))
1346                 {
1347                         /*
1348                          * if we don't have an element type yet, use the one we just got
1349                          */
1350                         elem_typeid = array_typelem;
1351                 }
1352                 else if (array_typelem != elem_typeid)
1353                 {
1354                         /* otherwise, they better match */
1355                         return false;
1356                 }
1357         }
1358
1359         if (have_anynonarray)
1360         {
1361                 /* require the element type to not be an array */
1362                 if (type_is_array(elem_typeid))
1363                         return false;
1364         }
1365
1366         if (have_anyenum)
1367         {
1368                 /* require the element type to be an enum */
1369                 if (!type_is_enum(elem_typeid))
1370                         return false;
1371         }
1372
1373         /* Looks valid */
1374         return true;
1375 }
1376
1377 /*
1378  * enforce_generic_type_consistency()
1379  *              Make sure a polymorphic function is legally callable, and
1380  *              deduce actual argument and result types.
1381  *
1382  * If any polymorphic pseudotype is used in a function's arguments or
1383  * return type, we make sure the actual data types are consistent with
1384  * each other. The argument consistency rules are shown above for
1385  * check_generic_type_consistency().
1386  *
1387  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1388  * argument, we attempt to deduce the actual type it should have.  If
1389  * successful, we alter that position of declared_arg_types[] so that
1390  * make_fn_arguments will coerce the literal to the right thing.
1391  *
1392  * Rules are applied to the function's return type (possibly altering it)
1393  * if it is declared as a polymorphic type:
1394  *
1395  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1396  *        argument's actual type as the function's return type.
1397  * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1398  *        is ANYELEMENT, use the actual type of the argument to determine
1399  *        the function's return type, i.e. the element type's corresponding
1400  *        array type.
1401  * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1402  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1403  *        and is therefore not expected here.
1404  * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1405  *        argument's actual type as the function's return type.
1406  * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1407  *        argument is ANYARRAY, use the actual type of the argument to determine
1408  *        the function's return type, i.e. the array type's corresponding
1409  *        element type.
1410  * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1411  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1412  *        and is therefore not expected here.
1413  * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1414  *        (alone or in combination with plain ANYELEMENT), we add the extra
1415  *        condition that the ANYELEMENT type must be an enum.
1416  * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1417  *        we add the extra condition that the ANYELEMENT type must not be an array.
1418  *        (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1419  *        is an extra restriction if not.)
1420  *
1421  * When allow_poly is false, we are not expecting any of the actual_arg_types
1422  * to be polymorphic, and we should not return a polymorphic result type
1423  * either.  When allow_poly is true, it is okay to have polymorphic "actual"
1424  * arg types, and we can return ANYARRAY or ANYELEMENT as the result.  (This
1425  * case is currently used only to check compatibility of an aggregate's
1426  * declaration with the underlying transfn.)
1427  */
1428 Oid
1429 enforce_generic_type_consistency(Oid *actual_arg_types,
1430                                                                  Oid *declared_arg_types,
1431                                                                  int nargs,
1432                                                                  Oid rettype,
1433                                                                  bool allow_poly)
1434 {
1435         int                     j;
1436         bool            have_generics = false;
1437         bool            have_unknowns = false;
1438         Oid                     elem_typeid = InvalidOid;
1439         Oid                     array_typeid = InvalidOid;
1440         Oid                     array_typelem;
1441         bool            have_anynonarray = (rettype == ANYNONARRAYOID);
1442         bool            have_anyenum = (rettype == ANYENUMOID);
1443
1444         /*
1445          * Loop through the arguments to see if we have any that are polymorphic.
1446          * If so, require the actual types to be consistent.
1447          */
1448         for (j = 0; j < nargs; j++)
1449         {
1450                 Oid                     decl_type = declared_arg_types[j];
1451                 Oid                     actual_type = actual_arg_types[j];
1452
1453                 if (decl_type == ANYELEMENTOID ||
1454                         decl_type == ANYNONARRAYOID ||
1455                         decl_type == ANYENUMOID)
1456                 {
1457                         have_generics = true;
1458                         if (decl_type == ANYNONARRAYOID)
1459                                 have_anynonarray = true;
1460                         else if (decl_type == ANYENUMOID)
1461                                 have_anyenum = true;
1462                         if (actual_type == UNKNOWNOID)
1463                         {
1464                                 have_unknowns = true;
1465                                 continue;
1466                         }
1467                         if (allow_poly && decl_type == actual_type)
1468                                 continue;               /* no new information here */
1469                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1470                                 ereport(ERROR,
1471                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1472                                 errmsg("arguments declared \"anyelement\" are not all alike"),
1473                                                  errdetail("%s versus %s",
1474                                                                    format_type_be(elem_typeid),
1475                                                                    format_type_be(actual_type))));
1476                         elem_typeid = actual_type;
1477                 }
1478                 else if (decl_type == ANYARRAYOID)
1479                 {
1480                         have_generics = true;
1481                         if (actual_type == UNKNOWNOID)
1482                         {
1483                                 have_unknowns = true;
1484                                 continue;
1485                         }
1486                         if (allow_poly && decl_type == actual_type)
1487                                 continue;               /* no new information here */
1488                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1489                                 ereport(ERROR,
1490                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1491                                  errmsg("arguments declared \"anyarray\" are not all alike"),
1492                                                  errdetail("%s versus %s",
1493                                                                    format_type_be(array_typeid),
1494                                                                    format_type_be(actual_type))));
1495                         array_typeid = actual_type;
1496                 }
1497         }
1498
1499         /*
1500          * Fast Track: if none of the arguments are polymorphic, return the
1501          * unmodified rettype.  We assume it can't be polymorphic either.
1502          */
1503         if (!have_generics)
1504                 return rettype;
1505
1506         /* Get the element type based on the array type, if we have one */
1507         if (OidIsValid(array_typeid))
1508         {
1509                 array_typelem = get_element_type(array_typeid);
1510                 if (!OidIsValid(array_typelem))
1511                         ereport(ERROR,
1512                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1513                                          errmsg("argument declared \"anyarray\" is not an array but type %s",
1514                                                         format_type_be(array_typeid))));
1515
1516                 if (!OidIsValid(elem_typeid))
1517                 {
1518                         /*
1519                          * if we don't have an element type yet, use the one we just got
1520                          */
1521                         elem_typeid = array_typelem;
1522                 }
1523                 else if (array_typelem != elem_typeid)
1524                 {
1525                         /* otherwise, they better match */
1526                         ereport(ERROR,
1527                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1528                                          errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1529                                          errdetail("%s versus %s",
1530                                                            format_type_be(array_typeid),
1531                                                            format_type_be(elem_typeid))));
1532                 }
1533         }
1534         else if (!OidIsValid(elem_typeid))
1535         {
1536                 if (allow_poly)
1537                 {
1538                         array_typeid = ANYARRAYOID;
1539                         elem_typeid = ANYELEMENTOID;
1540                 }
1541                 else
1542                 {
1543                         /* Only way to get here is if all the generic args are UNKNOWN */
1544                         ereport(ERROR,
1545                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1546                                          errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1547                 }
1548         }
1549
1550         if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1551         {
1552                 /* require the element type to not be an array */
1553                 if (type_is_array(elem_typeid))
1554                         ereport(ERROR,
1555                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1556                                    errmsg("type matched to anynonarray is an array type: %s",
1557                                                   format_type_be(elem_typeid))));
1558         }
1559
1560         if (have_anyenum && elem_typeid != ANYELEMENTOID)
1561         {
1562                 /* require the element type to be an enum */
1563                 if (!type_is_enum(elem_typeid))
1564                         ereport(ERROR,
1565                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1566                                          errmsg("type matched to anyenum is not an enum type: %s",
1567                                                         format_type_be(elem_typeid))));
1568         }
1569
1570         /*
1571          * If we had any unknown inputs, re-scan to assign correct types
1572          */
1573         if (have_unknowns)
1574         {
1575                 for (j = 0; j < nargs; j++)
1576                 {
1577                         Oid                     decl_type = declared_arg_types[j];
1578                         Oid                     actual_type = actual_arg_types[j];
1579
1580                         if (actual_type != UNKNOWNOID)
1581                                 continue;
1582
1583                         if (decl_type == ANYELEMENTOID ||
1584                                 decl_type == ANYNONARRAYOID ||
1585                                 decl_type == ANYENUMOID)
1586                                 declared_arg_types[j] = elem_typeid;
1587                         else if (decl_type == ANYARRAYOID)
1588                         {
1589                                 if (!OidIsValid(array_typeid))
1590                                 {
1591                                         array_typeid = get_array_type(elem_typeid);
1592                                         if (!OidIsValid(array_typeid))
1593                                                 ereport(ERROR,
1594                                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1595                                                  errmsg("could not find array type for data type %s",
1596                                                                 format_type_be(elem_typeid))));
1597                                 }
1598                                 declared_arg_types[j] = array_typeid;
1599                         }
1600                 }
1601         }
1602
1603         /* if we return ANYARRAY use the appropriate argument type */
1604         if (rettype == ANYARRAYOID)
1605         {
1606                 if (!OidIsValid(array_typeid))
1607                 {
1608                         array_typeid = get_array_type(elem_typeid);
1609                         if (!OidIsValid(array_typeid))
1610                                 ereport(ERROR,
1611                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1612                                                  errmsg("could not find array type for data type %s",
1613                                                                 format_type_be(elem_typeid))));
1614                 }
1615                 return array_typeid;
1616         }
1617
1618         /* if we return ANYELEMENT use the appropriate argument type */
1619         if (rettype == ANYELEMENTOID ||
1620                 rettype == ANYNONARRAYOID ||
1621                 rettype == ANYENUMOID)
1622                 return elem_typeid;
1623
1624         /* we don't return a generic type; send back the original return type */
1625         return rettype;
1626 }
1627
1628 /*
1629  * resolve_generic_type()
1630  *              Deduce an individual actual datatype on the assumption that
1631  *              the rules for polymorphic types are being followed.
1632  *
1633  * declared_type is the declared datatype we want to resolve.
1634  * context_actual_type is the actual input datatype to some argument
1635  * that has declared datatype context_declared_type.
1636  *
1637  * If declared_type isn't polymorphic, we just return it.  Otherwise,
1638  * context_declared_type must be polymorphic, and we deduce the correct
1639  * return type based on the relationship of the two polymorphic types.
1640  */
1641 Oid
1642 resolve_generic_type(Oid declared_type,
1643                                          Oid context_actual_type,
1644                                          Oid context_declared_type)
1645 {
1646         if (declared_type == ANYARRAYOID)
1647         {
1648                 if (context_declared_type == ANYARRAYOID)
1649                 {
1650                         /* Use actual type, but it must be an array */
1651                         Oid                     array_typelem = get_element_type(context_actual_type);
1652
1653                         if (!OidIsValid(array_typelem))
1654                                 ereport(ERROR,
1655                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1656                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1657                                                                 format_type_be(context_actual_type))));
1658                         return context_actual_type;
1659                 }
1660                 else if (context_declared_type == ANYELEMENTOID ||
1661                                  context_declared_type == ANYNONARRAYOID ||
1662                                  context_declared_type == ANYENUMOID)
1663                 {
1664                         /* Use the array type corresponding to actual type */
1665                         Oid                     array_typeid = get_array_type(context_actual_type);
1666
1667                         if (!OidIsValid(array_typeid))
1668                                 ereport(ERROR,
1669                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1670                                                  errmsg("could not find array type for data type %s",
1671                                                                 format_type_be(context_actual_type))));
1672                         return array_typeid;
1673                 }
1674         }
1675         else if (declared_type == ANYELEMENTOID ||
1676                          declared_type == ANYNONARRAYOID ||
1677                          declared_type == ANYENUMOID)
1678         {
1679                 if (context_declared_type == ANYARRAYOID)
1680                 {
1681                         /* Use the element type corresponding to actual type */
1682                         Oid                     array_typelem = get_element_type(context_actual_type);
1683
1684                         if (!OidIsValid(array_typelem))
1685                                 ereport(ERROR,
1686                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1687                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1688                                                                 format_type_be(context_actual_type))));
1689                         return array_typelem;
1690                 }
1691                 else if (context_declared_type == ANYELEMENTOID ||
1692                                  context_declared_type == ANYNONARRAYOID ||
1693                                  context_declared_type == ANYENUMOID)
1694                 {
1695                         /* Use the actual type; it doesn't matter if array or not */
1696                         return context_actual_type;
1697                 }
1698         }
1699         else
1700         {
1701                 /* declared_type isn't polymorphic, so return it as-is */
1702                 return declared_type;
1703         }
1704         /* If we get here, declared_type is polymorphic and context isn't */
1705         /* NB: this is a calling-code logic error, not a user error */
1706         elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1707         return InvalidOid;                      /* keep compiler quiet */
1708 }
1709
1710
1711 /* TypeCategory()
1712  *              Assign a category to the specified type OID.
1713  *
1714  * NB: this must not return TYPCATEGORY_INVALID.
1715  */
1716 TYPCATEGORY
1717 TypeCategory(Oid type)
1718 {
1719         char            typcategory;
1720         bool            typispreferred;
1721
1722         get_type_category_preferred(type, &typcategory, &typispreferred);
1723         Assert(typcategory != TYPCATEGORY_INVALID);
1724         return (TYPCATEGORY) typcategory;
1725 }
1726
1727
1728 /* IsPreferredType()
1729  *              Check if this type is a preferred type for the given category.
1730  *
1731  * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1732  * types of any category; otherwise, only for preferred types of that
1733  * category.
1734  */
1735 bool
1736 IsPreferredType(TYPCATEGORY category, Oid type)
1737 {
1738         char            typcategory;
1739         bool            typispreferred;
1740
1741         get_type_category_preferred(type, &typcategory, &typispreferred);
1742         if (category == typcategory || category == TYPCATEGORY_INVALID)
1743                 return typispreferred;
1744         else
1745                 return false;
1746 }
1747
1748
1749 /* IsBinaryCoercible()
1750  *              Check if srctype is binary-coercible to targettype.
1751  *
1752  * This notion allows us to cheat and directly exchange values without
1753  * going through the trouble of calling a conversion function.  Note that
1754  * in general, this should only be an implementation shortcut.  Before 7.4,
1755  * this was also used as a heuristic for resolving overloaded functions and
1756  * operators, but that's basically a bad idea.
1757  *
1758  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1759  * We consider two types binary-coercible if there is an implicitly
1760  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
1761  * binary-coercible to its base type, though *not* vice versa (in the other
1762  * direction, one must apply domain constraint checks before accepting the
1763  * value as legitimate).  We also need to special-case various polymorphic
1764  * types.
1765  *
1766  * This function replaces IsBinaryCompatible(), which was an inherently
1767  * symmetric test.      Since the pg_cast entries aren't necessarily symmetric,
1768  * the order of the operands is now significant.
1769  */
1770 bool
1771 IsBinaryCoercible(Oid srctype, Oid targettype)
1772 {
1773         HeapTuple       tuple;
1774         Form_pg_cast castForm;
1775         bool            result;
1776
1777         /* Fast path if same type */
1778         if (srctype == targettype)
1779                 return true;
1780
1781         /* If srctype is a domain, reduce to its base type */
1782         if (OidIsValid(srctype))
1783                 srctype = getBaseType(srctype);
1784
1785         /* Somewhat-fast path for domain -> base type case */
1786         if (srctype == targettype)
1787                 return true;
1788
1789         /* Also accept any array type as coercible to ANYARRAY */
1790         if (targettype == ANYARRAYOID)
1791                 if (type_is_array(srctype))
1792                         return true;
1793
1794         /* Also accept any non-array type as coercible to ANYNONARRAY */
1795         if (targettype == ANYNONARRAYOID)
1796                 if (!type_is_array(srctype))
1797                         return true;
1798
1799         /* Also accept any enum type as coercible to ANYENUM */
1800         if (targettype == ANYENUMOID)
1801                 if (type_is_enum(srctype))
1802                         return true;
1803
1804         /* Also accept any composite type as coercible to RECORD */
1805         if (targettype == RECORDOID)
1806                 if (ISCOMPLEX(srctype))
1807                         return true;
1808
1809         /* Also accept any composite array type as coercible to RECORD[] */
1810         if (targettype == RECORDARRAYOID)
1811                 if (is_complex_array(srctype))
1812                         return true;
1813
1814         /* Else look in pg_cast */
1815         tuple = SearchSysCache(CASTSOURCETARGET,
1816                                                    ObjectIdGetDatum(srctype),
1817                                                    ObjectIdGetDatum(targettype),
1818                                                    0, 0);
1819         if (!HeapTupleIsValid(tuple))
1820                 return false;                   /* no cast */
1821         castForm = (Form_pg_cast) GETSTRUCT(tuple);
1822
1823         result = (castForm->castfunc == InvalidOid &&
1824                           castForm->castcontext == COERCION_CODE_IMPLICIT);
1825
1826         ReleaseSysCache(tuple);
1827
1828         return result;
1829 }
1830
1831
1832 /*
1833  * find_coercion_pathway
1834  *              Look for a coercion pathway between two types.
1835  *
1836  * Currently, this deals only with scalar-type cases; it does not consider
1837  * polymorphic types nor casts between composite types.  (Perhaps fold
1838  * those in someday?)
1839  *
1840  * ccontext determines the set of available casts.
1841  *
1842  * The possible result codes are:
1843  *      COERCION_PATH_NONE: failed to find any coercion pathway
1844  *                              *funcid is set to InvalidOid
1845  *      COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1846  *      COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1847  *                              *funcid is set to InvalidOid
1848  *      COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1849  *                              *funcid is set to the element cast function, or InvalidOid
1850  *                              if the array elements are binary-compatible
1851  *      COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1852  *                              *funcid is set to InvalidOid
1853  *
1854  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1855  * needed to do the coercion; if the target is a domain then we may need to
1856  * apply domain constraint checking.  If you want to check for a zero-effort
1857  * conversion then use IsBinaryCoercible().
1858  */
1859 CoercionPathType
1860 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1861                                           CoercionContext ccontext,
1862                                           Oid *funcid)
1863 {
1864         CoercionPathType result = COERCION_PATH_NONE;
1865         HeapTuple       tuple;
1866
1867         *funcid = InvalidOid;
1868
1869         /* Perhaps the types are domains; if so, look at their base types */
1870         if (OidIsValid(sourceTypeId))
1871                 sourceTypeId = getBaseType(sourceTypeId);
1872         if (OidIsValid(targetTypeId))
1873                 targetTypeId = getBaseType(targetTypeId);
1874
1875         /* Domains are always coercible to and from their base type */
1876         if (sourceTypeId == targetTypeId)
1877                 return COERCION_PATH_RELABELTYPE;
1878
1879         /* Look in pg_cast */
1880         tuple = SearchSysCache(CASTSOURCETARGET,
1881                                                    ObjectIdGetDatum(sourceTypeId),
1882                                                    ObjectIdGetDatum(targetTypeId),
1883                                                    0, 0);
1884
1885         if (HeapTupleIsValid(tuple))
1886         {
1887                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1888                 CoercionContext castcontext;
1889
1890                 /* convert char value for castcontext to CoercionContext enum */
1891                 switch (castForm->castcontext)
1892                 {
1893                         case COERCION_CODE_IMPLICIT:
1894                                 castcontext = COERCION_IMPLICIT;
1895                                 break;
1896                         case COERCION_CODE_ASSIGNMENT:
1897                                 castcontext = COERCION_ASSIGNMENT;
1898                                 break;
1899                         case COERCION_CODE_EXPLICIT:
1900                                 castcontext = COERCION_EXPLICIT;
1901                                 break;
1902                         default:
1903                                 elog(ERROR, "unrecognized castcontext: %d",
1904                                          (int) castForm->castcontext);
1905                                 castcontext = 0;        /* keep compiler quiet */
1906                                 break;
1907                 }
1908
1909                 /* Rely on ordering of enum for correct behavior here */
1910                 if (ccontext >= castcontext)
1911                 {
1912                         *funcid = castForm->castfunc;
1913                         if (OidIsValid(*funcid))
1914                                 result = COERCION_PATH_FUNC;
1915                         else
1916                                 result = COERCION_PATH_RELABELTYPE;
1917                 }
1918
1919                 ReleaseSysCache(tuple);
1920         }
1921         else
1922         {
1923                 /*
1924                  * If there's no pg_cast entry, perhaps we are dealing with a pair of
1925                  * array types.  If so, and if the element types have a suitable cast,
1926                  * report that we can coerce with an ArrayCoerceExpr.
1927                  *
1928                  * Hack: disallow coercions to oidvector and int2vector, which
1929                  * otherwise tend to capture coercions that should go to "real" array
1930                  * types.  We want those types to be considered "real" arrays for many
1931                  * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
1932                  * guaranteed to produce an output that meets the restrictions of
1933                  * these datatypes, such as being 1-dimensional.)
1934                  */
1935                 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
1936                 {
1937                         Oid                     targetElem;
1938                         Oid                     sourceElem;
1939
1940                         if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
1941                                 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
1942                         {
1943                                 CoercionPathType elempathtype;
1944                                 Oid                     elemfuncid;
1945
1946                                 elempathtype = find_coercion_pathway(targetElem,
1947                                                                                                          sourceElem,
1948                                                                                                          ccontext,
1949                                                                                                          &elemfuncid);
1950                                 if (elempathtype != COERCION_PATH_NONE &&
1951                                         elempathtype != COERCION_PATH_ARRAYCOERCE)
1952                                 {
1953                                         *funcid = elemfuncid;
1954                                         if (elempathtype == COERCION_PATH_COERCEVIAIO)
1955                                                 result = COERCION_PATH_COERCEVIAIO;
1956                                         else
1957                                                 result = COERCION_PATH_ARRAYCOERCE;
1958                                 }
1959                         }
1960                 }
1961
1962                 /*
1963                  * If we still haven't found a possibility, consider automatic casting
1964                  * using I/O functions.  We allow assignment casts to string types
1965                  * and explicit casts from string types to be handled this way. (The
1966                  * CoerceViaIO mechanism is a lot more general than that, but this is
1967                  * all we want to allow in the absence of a pg_cast entry.) It would
1968                  * probably be better to insist on explicit casts in both directions,
1969                  * but this is a compromise to preserve something of the pre-8.3
1970                  * behavior that many types had implicit (yipes!) casts to text.
1971                  */
1972                 if (result == COERCION_PATH_NONE)
1973                 {
1974                         if (ccontext >= COERCION_ASSIGNMENT &&
1975                                 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
1976                                 result = COERCION_PATH_COERCEVIAIO;
1977                         else if (ccontext >= COERCION_EXPLICIT &&
1978                                          TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
1979                                 result = COERCION_PATH_COERCEVIAIO;
1980                 }
1981         }
1982
1983         return result;
1984 }
1985
1986
1987 /*
1988  * find_typmod_coercion_function -- does the given type need length coercion?
1989  *
1990  * If the target type possesses a pg_cast function from itself to itself,
1991  * it must need length coercion.
1992  *
1993  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1994  *
1995  * If the given type is a varlena array type, we do not look for a coercion
1996  * function associated directly with the array type, but instead look for
1997  * one associated with the element type.  An ArrayCoerceExpr node must be
1998  * used to apply such a function.
1999  *
2000  * We use the same result enum as find_coercion_pathway, but the only possible
2001  * result codes are:
2002  *      COERCION_PATH_NONE: no length coercion needed
2003  *      COERCION_PATH_FUNC: apply the function returned in *funcid
2004  *      COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2005  */
2006 CoercionPathType
2007 find_typmod_coercion_function(Oid typeId,
2008                                                           Oid *funcid)
2009 {
2010         CoercionPathType result;
2011         Type            targetType;
2012         Form_pg_type typeForm;
2013         HeapTuple       tuple;
2014
2015         *funcid = InvalidOid;
2016         result = COERCION_PATH_FUNC;
2017
2018         targetType = typeidType(typeId);
2019         typeForm = (Form_pg_type) GETSTRUCT(targetType);
2020
2021         /* Check for a varlena array type (and not a domain) */
2022         if (typeForm->typelem != InvalidOid &&
2023                 typeForm->typlen == -1 &&
2024                 typeForm->typtype != TYPTYPE_DOMAIN)
2025         {
2026                 /* Yes, switch our attention to the element type */
2027                 typeId = typeForm->typelem;
2028                 result = COERCION_PATH_ARRAYCOERCE;
2029         }
2030         ReleaseSysCache(targetType);
2031
2032         /* Look in pg_cast */
2033         tuple = SearchSysCache(CASTSOURCETARGET,
2034                                                    ObjectIdGetDatum(typeId),
2035                                                    ObjectIdGetDatum(typeId),
2036                                                    0, 0);
2037
2038         if (HeapTupleIsValid(tuple))
2039         {
2040                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2041
2042                 *funcid = castForm->castfunc;
2043                 ReleaseSysCache(tuple);
2044         }
2045
2046         if (!OidIsValid(*funcid))
2047                 result = COERCION_PATH_NONE;
2048
2049         return result;
2050 }
2051
2052 /*
2053  * is_complex_array
2054  *              Is this type an array of composite?
2055  *
2056  * Note: this will not return true for record[]; check for RECORDARRAYOID
2057  * separately if needed.
2058  */
2059 static bool
2060 is_complex_array(Oid typid)
2061 {
2062         Oid                     elemtype = get_element_type(typid);
2063
2064         return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2065 }