OSDN Git Service

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