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