LCOV - code coverage report
Current view: top level - src/backend/parser - parse_coerce.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 909 1000 90.9 %
Date: 2021-12-04 23:09:10 Functions: 27 27 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_coerce.c
       4             :  *      handle type coercions/conversions for parser
       5             :  *
       6             :  * Portions Copyright (c) 1996-2021, 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.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_relation.h"
      26             : #include "parser/parse_type.h"
      27             : #include "utils/builtins.h"
      28             : #include "utils/datum.h"      /* needed for datumIsEqual() */
      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             :                                 CoercionContext ccontext, CoercionForm cformat,
      38             :                                 int location,
      39             :                                 bool hideInputCoercion);
      40             : static void hide_coercion_node(Node *node);
      41             : static Node *build_coercion_expression(Node *node,
      42             :                                        CoercionPathType pathtype,
      43             :                                        Oid funcId,
      44             :                                        Oid targetTypeId, int32 targetTypMod,
      45             :                                        CoercionContext ccontext, CoercionForm cformat,
      46             :                                        int location);
      47             : static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
      48             :                                       Oid targetTypeId,
      49             :                                       CoercionContext ccontext,
      50             :                                       CoercionForm cformat,
      51             :                                       int location);
      52             : static bool is_complex_array(Oid typid);
      53             : static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
      54             : 
      55             : 
      56             : /*
      57             :  * coerce_to_target_type()
      58             :  *      Convert an expression to a target type and typmod.
      59             :  *
      60             :  * This is the general-purpose entry point for arbitrary type coercion
      61             :  * operations.  Direct use of the component operations can_coerce_type,
      62             :  * coerce_type, and coerce_type_typmod should be restricted to special
      63             :  * cases (eg, when the conversion is expected to succeed).
      64             :  *
      65             :  * Returns the possibly-transformed expression tree, or NULL if the type
      66             :  * conversion is not possible.  (We do this, rather than ereport'ing directly,
      67             :  * so that callers can generate custom error messages indicating context.)
      68             :  *
      69             :  * pstate - parse state (can be NULL, see coerce_type)
      70             :  * expr - input expression tree (already transformed by transformExpr)
      71             :  * exprtype - result type of expr
      72             :  * targettype - desired result type
      73             :  * targettypmod - desired result typmod
      74             :  * ccontext, cformat - context indicators to control coercions
      75             :  * location - parse location of the coercion request, or -1 if unknown/implicit
      76             :  */
      77             : Node *
      78     1245032 : coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
      79             :                       Oid targettype, int32 targettypmod,
      80             :                       CoercionContext ccontext,
      81             :                       CoercionForm cformat,
      82             :                       int location)
      83             : {
      84             :     Node       *result;
      85             :     Node       *origexpr;
      86             : 
      87     1245032 :     if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
      88         278 :         return NULL;
      89             : 
      90             :     /*
      91             :      * If the input has a CollateExpr at the top, strip it off, perform the
      92             :      * coercion, and put a new one back on.  This is annoying since it
      93             :      * duplicates logic in coerce_type, but if we don't do this then it's too
      94             :      * hard to tell whether coerce_type actually changed anything, and we
      95             :      * *must* know that to avoid possibly calling hide_coercion_node on
      96             :      * something that wasn't generated by coerce_type.  Note that if there are
      97             :      * multiple stacked CollateExprs, we just discard all but the topmost.
      98             :      * Also, if the target type isn't collatable, we discard the CollateExpr.
      99             :      */
     100     1244754 :     origexpr = expr;
     101     1244770 :     while (expr && IsA(expr, CollateExpr))
     102          16 :         expr = (Node *) ((CollateExpr *) expr)->arg;
     103             : 
     104     1244754 :     result = coerce_type(pstate, expr, exprtype,
     105             :                          targettype, targettypmod,
     106             :                          ccontext, cformat, location);
     107             : 
     108             :     /*
     109             :      * If the target is a fixed-length type, it may need a length coercion as
     110             :      * well as a type coercion.  If we find ourselves adding both, force the
     111             :      * inner coercion node to implicit display form.
     112             :      */
     113     1242840 :     result = coerce_type_typmod(result,
     114             :                                 targettype, targettypmod,
     115             :                                 ccontext, cformat, location,
     116     1242840 :                                 (result != expr && !IsA(result, Const)));
     117             : 
     118     1242840 :     if (expr != origexpr && type_is_collatable(targettype))
     119             :     {
     120             :         /* Reinstall top CollateExpr */
     121          12 :         CollateExpr *coll = (CollateExpr *) origexpr;
     122          12 :         CollateExpr *newcoll = makeNode(CollateExpr);
     123             : 
     124          12 :         newcoll->arg = (Expr *) result;
     125          12 :         newcoll->collOid = coll->collOid;
     126          12 :         newcoll->location = coll->location;
     127          12 :         result = (Node *) newcoll;
     128             :     }
     129             : 
     130     1242840 :     return result;
     131             : }
     132             : 
     133             : 
     134             : /*
     135             :  * coerce_type()
     136             :  *      Convert an expression to a different type.
     137             :  *
     138             :  * The caller should already have determined that the coercion is possible;
     139             :  * see can_coerce_type.
     140             :  *
     141             :  * Normally, no coercion to a typmod (length) is performed here.  The caller
     142             :  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
     143             :  * (But if the target type is a domain, it may internally contain a
     144             :  * typmod constraint, which will be applied inside coerce_to_domain.)
     145             :  * In some cases pg_cast specifies a type coercion function that also
     146             :  * applies length conversion, and in those cases only, the result will
     147             :  * already be properly coerced to the specified typmod.
     148             :  *
     149             :  * pstate is only used in the case that we are able to resolve the type of
     150             :  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
     151             :  * caller does not want type information updated for Params.
     152             :  *
     153             :  * Note: this function must not modify the given expression tree, only add
     154             :  * decoration on top of it.  See transformSetOperationTree, for example.
     155             :  */
     156             : Node *
     157     2313474 : coerce_type(ParseState *pstate, Node *node,
     158             :             Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
     159             :             CoercionContext ccontext, CoercionForm cformat, int location)
     160             : {
     161             :     Node       *result;
     162             :     CoercionPathType pathtype;
     163             :     Oid         funcId;
     164             : 
     165     2313474 :     if (targetTypeId == inputTypeId ||
     166             :         node == NULL)
     167             :     {
     168             :         /* no conversion needed */
     169      323564 :         return node;
     170             :     }
     171     1989910 :     if (targetTypeId == ANYOID ||
     172     1980150 :         targetTypeId == ANYELEMENTOID ||
     173     1938802 :         targetTypeId == ANYNONARRAYOID ||
     174     1938802 :         targetTypeId == ANYCOMPATIBLEOID ||
     175             :         targetTypeId == ANYCOMPATIBLENONARRAYOID)
     176             :     {
     177             :         /*
     178             :          * Assume can_coerce_type verified that implicit coercion is okay.
     179             :          *
     180             :          * Note: by returning the unmodified node here, we are saying that
     181             :          * it's OK to treat an UNKNOWN constant as a valid input for a
     182             :          * function accepting one of these pseudotypes.  This should be all
     183             :          * right, since an UNKNOWN value is still a perfectly valid Datum.
     184             :          *
     185             :          * NB: we do NOT want a RelabelType here: the exposed type of the
     186             :          * function argument must be its actual type, not the polymorphic
     187             :          * pseudotype.
     188             :          */
     189       51108 :         return node;
     190             :     }
     191     1938802 :     if (targetTypeId == ANYARRAYOID ||
     192     1817750 :         targetTypeId == ANYENUMOID ||
     193     1814884 :         targetTypeId == ANYRANGEOID ||
     194     1812504 :         targetTypeId == ANYMULTIRANGEOID ||
     195     1812504 :         targetTypeId == ANYCOMPATIBLEARRAYOID ||
     196     1812504 :         targetTypeId == ANYCOMPATIBLERANGEOID ||
     197             :         targetTypeId == ANYCOMPATIBLEMULTIRANGEOID)
     198             :     {
     199             :         /*
     200             :          * Assume can_coerce_type verified that implicit coercion is okay.
     201             :          *
     202             :          * These cases are unlike the ones above because the exposed type of
     203             :          * the argument must be an actual array, enum, range, or multirange
     204             :          * type.  In particular the argument must *not* be an UNKNOWN
     205             :          * constant.  If it is, we just fall through; below, we'll call the
     206             :          * pseudotype's input function, which will produce an error.  Also, if
     207             :          * what we have is a domain over array, enum, range, or multirange, we
     208             :          * have to relabel it to its base type.
     209             :          *
     210             :          * Note: currently, we can't actually see a domain-over-enum here,
     211             :          * since the other functions in this file will not match such a
     212             :          * parameter to ANYENUM.  But that should get changed eventually.
     213             :          */
     214      126298 :         if (inputTypeId != UNKNOWNOID)
     215             :         {
     216       95146 :             Oid         baseTypeId = getBaseType(inputTypeId);
     217             : 
     218       95146 :             if (baseTypeId != inputTypeId)
     219             :             {
     220          36 :                 RelabelType *r = makeRelabelType((Expr *) node,
     221             :                                                  baseTypeId, -1,
     222             :                                                  InvalidOid,
     223             :                                                  cformat);
     224             : 
     225          36 :                 r->location = location;
     226          36 :                 return (Node *) r;
     227             :             }
     228             :             /* Not a domain type, so return it as-is */
     229       95110 :             return node;
     230             :         }
     231             :     }
     232     1843656 :     if (inputTypeId == UNKNOWNOID && IsA(node, Const))
     233             :     {
     234             :         /*
     235             :          * Input is a string constant with previously undetermined type. Apply
     236             :          * the target type's typinput function to it to produce a constant of
     237             :          * the target type.
     238             :          *
     239             :          * NOTE: this case cannot be folded together with the other
     240             :          * constant-input case, since the typinput function does not
     241             :          * necessarily behave the same as a type conversion function. For
     242             :          * example, int4's typinput function will reject "1.2", whereas
     243             :          * float-to-int type conversion will round to integer.
     244             :          *
     245             :          * XXX if the typinput function is not immutable, we really ought to
     246             :          * postpone evaluation of the function call until runtime. But there
     247             :          * is no way to represent a typinput function call as an expression
     248             :          * tree, because C-string values are not Datums. (XXX This *is*
     249             :          * possible as of 7.3, do we want to do it?)
     250             :          */
     251     1161676 :         Const      *con = (Const *) node;
     252     1161676 :         Const      *newcon = makeNode(Const);
     253             :         Oid         baseTypeId;
     254             :         int32       baseTypeMod;
     255             :         int32       inputTypeMod;
     256             :         Type        baseType;
     257             :         ParseCallbackState pcbstate;
     258             : 
     259             :         /*
     260             :          * If the target type is a domain, we want to call its base type's
     261             :          * input routine, not domain_in().  This is to avoid premature failure
     262             :          * when the domain applies a typmod: existing input routines follow
     263             :          * implicit-coercion semantics for length checks, which is not always
     264             :          * what we want here.  The needed check will be applied properly
     265             :          * inside coerce_to_domain().
     266             :          */
     267     1161676 :         baseTypeMod = targetTypeMod;
     268     1161676 :         baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
     269             : 
     270             :         /*
     271             :          * For most types we pass typmod -1 to the input routine, because
     272             :          * existing input routines follow implicit-coercion semantics for
     273             :          * length checks, which is not always what we want here.  Any length
     274             :          * constraint will be applied later by our caller.  An exception
     275             :          * however is the INTERVAL type, for which we *must* pass the typmod
     276             :          * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
     277             :          * as sin, but so is this part of the spec...)
     278             :          */
     279     1161676 :         if (baseTypeId == INTERVALOID)
     280        1640 :             inputTypeMod = baseTypeMod;
     281             :         else
     282     1160036 :             inputTypeMod = -1;
     283             : 
     284     1161676 :         baseType = typeidType(baseTypeId);
     285             : 
     286     1161676 :         newcon->consttype = baseTypeId;
     287     1161676 :         newcon->consttypmod = inputTypeMod;
     288     1161676 :         newcon->constcollid = typeTypeCollation(baseType);
     289     1161676 :         newcon->constlen = typeLen(baseType);
     290     1161676 :         newcon->constbyval = typeByVal(baseType);
     291     1161676 :         newcon->constisnull = con->constisnull;
     292             : 
     293             :         /*
     294             :          * We use the original literal's location regardless of the position
     295             :          * of the coercion.  This is a change from pre-9.2 behavior, meant to
     296             :          * simplify life for pg_stat_statements.
     297             :          */
     298     1161676 :         newcon->location = con->location;
     299             : 
     300             :         /*
     301             :          * Set up to point at the constant's text if the input routine throws
     302             :          * an error.
     303             :          */
     304     1161676 :         setup_parser_errposition_callback(&pcbstate, pstate, con->location);
     305             : 
     306             :         /*
     307             :          * We assume here that UNKNOWN's internal representation is the same
     308             :          * as CSTRING.
     309             :          */
     310     1161676 :         if (!con->constisnull)
     311      965268 :             newcon->constvalue = stringTypeDatum(baseType,
     312      967294 :                                                  DatumGetCString(con->constvalue),
     313             :                                                  inputTypeMod);
     314             :         else
     315      194382 :             newcon->constvalue = stringTypeDatum(baseType,
     316             :                                                  NULL,
     317             :                                                  inputTypeMod);
     318             : 
     319             :         /*
     320             :          * If it's a varlena value, force it to be in non-expanded
     321             :          * (non-toasted) format; this avoids any possible dependency on
     322             :          * external values and improves consistency of representation.
     323             :          */
     324     1159650 :         if (!con->constisnull && newcon->constlen == -1)
     325      485378 :             newcon->constvalue =
     326      485378 :                 PointerGetDatum(PG_DETOAST_DATUM(newcon->constvalue));
     327             : 
     328             : #ifdef RANDOMIZE_ALLOCATED_MEMORY
     329             : 
     330             :         /*
     331             :          * For pass-by-reference data types, repeat the conversion to see if
     332             :          * the input function leaves any uninitialized bytes in the result. We
     333             :          * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
     334             :          * enabled, so we don't bother testing otherwise.  The reason we don't
     335             :          * want any instability in the input function is that comparison of
     336             :          * Const nodes relies on bytewise comparison of the datums, so if the
     337             :          * input function leaves garbage then subexpressions that should be
     338             :          * identical may not get recognized as such.  See pgsql-hackers
     339             :          * discussion of 2008-04-04.
     340             :          */
     341             :         if (!con->constisnull && !newcon->constbyval)
     342             :         {
     343             :             Datum       val2;
     344             : 
     345             :             val2 = stringTypeDatum(baseType,
     346             :                                    DatumGetCString(con->constvalue),
     347             :                                    inputTypeMod);
     348             :             if (newcon->constlen == -1)
     349             :                 val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
     350             :             if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
     351             :                 elog(WARNING, "type %s has unstable input conversion for \"%s\"",
     352             :                      typeTypeName(baseType), DatumGetCString(con->constvalue));
     353             :         }
     354             : #endif
     355             : 
     356     1159650 :         cancel_parser_errposition_callback(&pcbstate);
     357             : 
     358     1159650 :         result = (Node *) newcon;
     359             : 
     360             :         /* If target is a domain, apply constraints. */
     361     1159650 :         if (baseTypeId != targetTypeId)
     362      166814 :             result = coerce_to_domain(result,
     363             :                                       baseTypeId, baseTypeMod,
     364             :                                       targetTypeId,
     365             :                                       ccontext, cformat, location,
     366             :                                       false);
     367             : 
     368     1159650 :         ReleaseSysCache(baseType);
     369             : 
     370     1159650 :         return result;
     371             :     }
     372      681980 :     if (IsA(node, Param) &&
     373      162920 :         pstate != NULL && pstate->p_coerce_param_hook != NULL)
     374             :     {
     375             :         /*
     376             :          * Allow the CoerceParamHook to decide what happens.  It can return a
     377             :          * transformed node (very possibly the same Param node), or return
     378             :          * NULL to indicate we should proceed with normal coercion.
     379             :          */
     380      150802 :         result = pstate->p_coerce_param_hook(pstate,
     381             :                                              (Param *) node,
     382             :                                              targetTypeId,
     383             :                                              targetTypeMod,
     384             :                                              location);
     385      150802 :         if (result)
     386      150788 :             return result;
     387             :     }
     388      531192 :     if (IsA(node, CollateExpr))
     389             :     {
     390             :         /*
     391             :          * If we have a COLLATE clause, we have to push the coercion
     392             :          * underneath the COLLATE; or discard the COLLATE if the target type
     393             :          * isn't collatable.  This is really ugly, but there is little choice
     394             :          * because the above hacks on Consts and Params wouldn't happen
     395             :          * otherwise.  This kluge has consequences in coerce_to_target_type.
     396             :          */
     397        2942 :         CollateExpr *coll = (CollateExpr *) node;
     398             : 
     399        2942 :         result = coerce_type(pstate, (Node *) coll->arg,
     400             :                              inputTypeId, targetTypeId, targetTypeMod,
     401             :                              ccontext, cformat, location);
     402        2942 :         if (type_is_collatable(targetTypeId))
     403             :         {
     404        2942 :             CollateExpr *newcoll = makeNode(CollateExpr);
     405             : 
     406        2942 :             newcoll->arg = (Expr *) result;
     407        2942 :             newcoll->collOid = coll->collOid;
     408        2942 :             newcoll->location = coll->location;
     409        2942 :             result = (Node *) newcoll;
     410             :         }
     411        2942 :         return result;
     412             :     }
     413      528250 :     pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
     414             :                                      &funcId);
     415      528250 :     if (pathtype != COERCION_PATH_NONE)
     416             :     {
     417      526120 :         if (pathtype != COERCION_PATH_RELABELTYPE)
     418             :         {
     419             :             /*
     420             :              * Generate an expression tree representing run-time application
     421             :              * of the conversion function.  If we are dealing with a domain
     422             :              * target type, the conversion function will yield the base type,
     423             :              * and we need to extract the correct typmod to use from the
     424             :              * domain's typtypmod.
     425             :              */
     426             :             Oid         baseTypeId;
     427             :             int32       baseTypeMod;
     428             : 
     429      123960 :             baseTypeMod = targetTypeMod;
     430      123960 :             baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
     431             : 
     432      123960 :             result = build_coercion_expression(node, pathtype, funcId,
     433             :                                                baseTypeId, baseTypeMod,
     434             :                                                ccontext, cformat, location);
     435             : 
     436             :             /*
     437             :              * If domain, coerce to the domain type and relabel with domain
     438             :              * type ID, hiding the previous coercion node.
     439             :              */
     440      123960 :             if (targetTypeId != baseTypeId)
     441       13530 :                 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
     442             :                                           targetTypeId,
     443             :                                           ccontext, cformat, location,
     444             :                                           true);
     445             :         }
     446             :         else
     447             :         {
     448             :             /*
     449             :              * We don't need to do a physical conversion, but we do need to
     450             :              * attach a RelabelType node so that the expression will be seen
     451             :              * to have the intended type when inspected by higher-level code.
     452             :              *
     453             :              * Also, domains may have value restrictions beyond the base type
     454             :              * that must be accounted for.  If the destination is a domain
     455             :              * then we won't need a RelabelType node.
     456             :              */
     457      402160 :             result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
     458             :                                       ccontext, cformat, location,
     459             :                                       false);
     460      402160 :             if (result == node)
     461             :             {
     462             :                 /*
     463             :                  * XXX could we label result with exprTypmod(node) instead of
     464             :                  * default -1 typmod, to save a possible length-coercion
     465             :                  * later? Would work if both types have same interpretation of
     466             :                  * typmod, which is likely but not certain.
     467             :                  */
     468      172122 :                 RelabelType *r = makeRelabelType((Expr *) result,
     469             :                                                  targetTypeId, -1,
     470             :                                                  InvalidOid,
     471             :                                                  cformat);
     472             : 
     473      172122 :                 r->location = location;
     474      172122 :                 result = (Node *) r;
     475             :             }
     476             :         }
     477      526120 :         return result;
     478             :     }
     479        3394 :     if (inputTypeId == RECORDOID &&
     480        1264 :         ISCOMPLEX(targetTypeId))
     481             :     {
     482             :         /* Coerce a RECORD to a specific complex type */
     483        1264 :         return coerce_record_to_complex(pstate, node, targetTypeId,
     484             :                                         ccontext, cformat, location);
     485             :     }
     486        1680 :     if (targetTypeId == RECORDOID &&
     487         814 :         ISCOMPLEX(inputTypeId))
     488             :     {
     489             :         /* Coerce a specific complex type to RECORD */
     490             :         /* NB: we do NOT want a RelabelType here */
     491         814 :         return node;
     492             :     }
     493             : #ifdef NOT_USED
     494             :     if (inputTypeId == RECORDARRAYOID &&
     495             :         is_complex_array(targetTypeId))
     496             :     {
     497             :         /* Coerce record[] to a specific complex array type */
     498             :         /* not implemented yet ... */
     499             :     }
     500             : #endif
     501          64 :     if (targetTypeId == RECORDARRAYOID &&
     502          12 :         is_complex_array(inputTypeId))
     503             :     {
     504             :         /* Coerce a specific complex array type to record[] */
     505             :         /* NB: we do NOT want a RelabelType here */
     506          12 :         return node;
     507             :     }
     508          40 :     if (typeInheritsFrom(inputTypeId, targetTypeId)
     509           4 :         || typeIsOfTypedTable(inputTypeId, targetTypeId))
     510             :     {
     511             :         /*
     512             :          * Input class type is a subclass of target, so generate an
     513             :          * appropriate runtime conversion (removing unneeded columns and
     514             :          * possibly rearranging the ones that are wanted).
     515             :          *
     516             :          * We will also get here when the input is a domain over a subclass of
     517             :          * the target type.  To keep life simple for the executor, we define
     518             :          * ConvertRowtypeExpr as only working between regular composite types;
     519             :          * therefore, in such cases insert a RelabelType to smash the input
     520             :          * expression down to its base type.
     521             :          */
     522          40 :         Oid         baseTypeId = getBaseType(inputTypeId);
     523          40 :         ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
     524             : 
     525          40 :         if (baseTypeId != inputTypeId)
     526             :         {
     527           0 :             RelabelType *rt = makeRelabelType((Expr *) node,
     528             :                                               baseTypeId, -1,
     529             :                                               InvalidOid,
     530             :                                               COERCE_IMPLICIT_CAST);
     531             : 
     532           0 :             rt->location = location;
     533           0 :             node = (Node *) rt;
     534             :         }
     535          40 :         r->arg = (Expr *) node;
     536          40 :         r->resulttype = targetTypeId;
     537          40 :         r->convertformat = cformat;
     538          40 :         r->location = location;
     539          40 :         return (Node *) r;
     540             :     }
     541             :     /* If we get here, caller blew it */
     542           0 :     elog(ERROR, "failed to find conversion function from %s to %s",
     543             :          format_type_be(inputTypeId), format_type_be(targetTypeId));
     544             :     return NULL;                /* keep compiler quiet */
     545             : }
     546             : 
     547             : 
     548             : /*
     549             :  * can_coerce_type()
     550             :  *      Can input_typeids be coerced to target_typeids?
     551             :  *
     552             :  * We must be told the context (CAST construct, assignment, implicit coercion)
     553             :  * as this determines the set of available casts.
     554             :  */
     555             : bool
     556     3043810 : can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids,
     557             :                 CoercionContext ccontext)
     558             : {
     559     3043810 :     bool        have_generics = false;
     560             :     int         i;
     561             : 
     562             :     /* run through argument list... */
     563     5512346 :     for (i = 0; i < nargs; i++)
     564             :     {
     565     3418366 :         Oid         inputTypeId = input_typeids[i];
     566     3418366 :         Oid         targetTypeId = target_typeids[i];
     567             :         CoercionPathType pathtype;
     568             :         Oid         funcId;
     569             : 
     570             :         /* no problem if same type */
     571     3418366 :         if (inputTypeId == targetTypeId)
     572     2468536 :             continue;
     573             : 
     574             :         /* accept if target is ANY */
     575     2944574 :         if (targetTypeId == ANYOID)
     576        6724 :             continue;
     577             : 
     578             :         /* accept if target is polymorphic, for now */
     579     2937850 :         if (IsPolymorphicType(targetTypeId))
     580             :         {
     581      361272 :             have_generics = true;   /* do more checking later */
     582      361272 :             continue;
     583             :         }
     584             : 
     585             :         /*
     586             :          * If input is an untyped string constant, assume we can convert it to
     587             :          * anything.
     588             :          */
     589     2576578 :         if (inputTypeId == UNKNOWNOID)
     590     1102472 :             continue;
     591             : 
     592             :         /*
     593             :          * If pg_cast shows that we can coerce, accept.  This test now covers
     594             :          * both binary-compatible and coercion-function cases.
     595             :          */
     596     1474106 :         pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
     597             :                                          &funcId);
     598     1474106 :         if (pathtype != COERCION_PATH_NONE)
     599      522338 :             continue;
     600             : 
     601             :         /*
     602             :          * If input is RECORD and target is a composite type, assume we can
     603             :          * coerce (may need tighter checking here)
     604             :          */
     605      953088 :         if (inputTypeId == RECORDOID &&
     606        1320 :             ISCOMPLEX(targetTypeId))
     607        1264 :             continue;
     608             : 
     609             :         /*
     610             :          * If input is a composite type and target is RECORD, accept
     611             :          */
     612      964814 :         if (targetTypeId == RECORDOID &&
     613       14310 :             ISCOMPLEX(inputTypeId))
     614         634 :             continue;
     615             : 
     616             : #ifdef NOT_USED                 /* not implemented yet */
     617             : 
     618             :         /*
     619             :          * If input is record[] and target is a composite array type, assume
     620             :          * we can coerce (may need tighter checking here)
     621             :          */
     622             :         if (inputTypeId == RECORDARRAYOID &&
     623             :             is_complex_array(targetTypeId))
     624             :             continue;
     625             : #endif
     626             : 
     627             :         /*
     628             :          * If input is a composite array type and target is record[], accept
     629             :          */
     630      949870 :         if (targetTypeId == RECORDARRAYOID &&
     631           0 :             is_complex_array(inputTypeId))
     632           0 :             continue;
     633             : 
     634             :         /*
     635             :          * If input is a class type that inherits from target, accept
     636             :          */
     637      949870 :         if (typeInheritsFrom(inputTypeId, targetTypeId)
     638      949834 :             || typeIsOfTypedTable(inputTypeId, targetTypeId))
     639          40 :             continue;
     640             : 
     641             :         /*
     642             :          * Else, cannot coerce at this argument position
     643             :          */
     644      949830 :         return false;
     645             :     }
     646             : 
     647             :     /* If we found any generic argument types, cross-check them */
     648     2093980 :     if (have_generics)
     649             :     {
     650      293342 :         if (!check_generic_type_consistency(input_typeids, target_typeids,
     651             :                                             nargs))
     652      124190 :             return false;
     653             :     }
     654             : 
     655     1969790 :     return true;
     656             : }
     657             : 
     658             : 
     659             : /*
     660             :  * Create an expression tree to represent coercion to a domain type.
     661             :  *
     662             :  * 'arg': input expression
     663             :  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
     664             :  *      has not bothered to look this up)
     665             :  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
     666             :  *      has not bothered to look this up)
     667             :  * 'typeId': target type to coerce to
     668             :  * 'ccontext': context indicator to control coercions
     669             :  * 'cformat': coercion display format
     670             :  * 'location': coercion request location
     671             :  * 'hideInputCoercion': if true, hide the input coercion under this one.
     672             :  *
     673             :  * If the target type isn't a domain, the given 'arg' is returned as-is.
     674             :  */
     675             : Node *
     676      597216 : coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
     677             :                  CoercionContext ccontext, CoercionForm cformat, int location,
     678             :                  bool hideInputCoercion)
     679             : {
     680             :     CoerceToDomain *result;
     681             : 
     682             :     /* Get the base type if it hasn't been supplied */
     683      597216 :     if (baseTypeId == InvalidOid)
     684      416728 :         baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
     685             : 
     686             :     /* If it isn't a domain, return the node as it was passed in */
     687      597216 :     if (baseTypeId == typeId)
     688      186646 :         return arg;
     689             : 
     690             :     /* Suppress display of nested coercion steps */
     691      410570 :     if (hideInputCoercion)
     692       13530 :         hide_coercion_node(arg);
     693             : 
     694             :     /*
     695             :      * If the domain applies a typmod to its base type, build the appropriate
     696             :      * coercion step.  Mark it implicit for display purposes, because we don't
     697             :      * want it shown separately by ruleutils.c; but the isExplicit flag passed
     698             :      * to the conversion function depends on the manner in which the domain
     699             :      * coercion is invoked, so that the semantics of implicit and explicit
     700             :      * coercion differ.  (Is that really the behavior we want?)
     701             :      *
     702             :      * NOTE: because we apply this as part of the fixed expression structure,
     703             :      * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
     704             :      * would be safe to do anyway, without lots of knowledge about what the
     705             :      * base type thinks the typmod means.
     706             :      */
     707      410570 :     arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
     708             :                              ccontext, COERCE_IMPLICIT_CAST, location,
     709             :                              false);
     710             : 
     711             :     /*
     712             :      * Now build the domain coercion node.  This represents run-time checking
     713             :      * of any constraints currently attached to the domain.  This also ensures
     714             :      * that the expression is properly labeled as to result type.
     715             :      */
     716      410570 :     result = makeNode(CoerceToDomain);
     717      410570 :     result->arg = (Expr *) arg;
     718      410570 :     result->resulttype = typeId;
     719      410570 :     result->resulttypmod = -1;   /* currently, always -1 for domains */
     720             :     /* resultcollid will be set by parse_collate.c */
     721      410570 :     result->coercionformat = cformat;
     722      410570 :     result->location = location;
     723             : 
     724      410570 :     return (Node *) result;
     725             : }
     726             : 
     727             : 
     728             : /*
     729             :  * coerce_type_typmod()
     730             :  *      Force a value to a particular typmod, if meaningful and possible.
     731             :  *
     732             :  * This is applied to values that are going to be stored in a relation
     733             :  * (where we have an atttypmod for the column) as well as values being
     734             :  * explicitly CASTed (where the typmod comes from the target type spec).
     735             :  *
     736             :  * The caller must have already ensured that the value is of the correct
     737             :  * type, typically by applying coerce_type.
     738             :  *
     739             :  * ccontext may affect semantics, depending on whether the length coercion
     740             :  * function pays attention to the isExplicit flag it's passed.
     741             :  *
     742             :  * cformat determines the display properties of the generated node (if any).
     743             :  *
     744             :  * If hideInputCoercion is true *and* we generate a node, the input node is
     745             :  * forced to IMPLICIT display form, so that only the typmod coercion node will
     746             :  * be visible when displaying the expression.
     747             :  *
     748             :  * NOTE: this does not need to work on domain types, because any typmod
     749             :  * coercion for a domain is considered to be part of the type coercion
     750             :  * needed to produce the domain value in the first place.  So, no getBaseType.
     751             :  */
     752             : static Node *
     753     1653410 : coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
     754             :                    CoercionContext ccontext, CoercionForm cformat,
     755             :                    int location,
     756             :                    bool hideInputCoercion)
     757             : {
     758             :     CoercionPathType pathtype;
     759             :     Oid         funcId;
     760             : 
     761             :     /* Skip coercion if already done */
     762     1653410 :     if (targetTypMod == exprTypmod(node))
     763     1614880 :         return node;
     764             : 
     765             :     /* Suppress display of nested coercion steps */
     766       38530 :     if (hideInputCoercion)
     767         732 :         hide_coercion_node(node);
     768             : 
     769       38530 :     pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
     770             : 
     771       38530 :     if (pathtype != COERCION_PATH_NONE)
     772             :     {
     773       38522 :         node = build_coercion_expression(node, pathtype, funcId,
     774             :                                          targetTypeId, targetTypMod,
     775             :                                          ccontext, cformat, location);
     776             :     }
     777             :     else
     778             :     {
     779             :         /*
     780             :          * We don't need to perform any actual coercion step, but we should
     781             :          * apply a RelabelType to ensure that the expression exposes the
     782             :          * intended typmod.
     783             :          */
     784           8 :         node = applyRelabelType(node, targetTypeId, targetTypMod,
     785             :                                 exprCollation(node),
     786             :                                 cformat, location, false);
     787             :     }
     788             : 
     789       38530 :     return node;
     790             : }
     791             : 
     792             : /*
     793             :  * Mark a coercion node as IMPLICIT so it will never be displayed by
     794             :  * ruleutils.c.  We use this when we generate a nest of coercion nodes
     795             :  * to implement what is logically one conversion; the inner nodes are
     796             :  * forced to IMPLICIT_CAST format.  This does not change their semantics,
     797             :  * only display behavior.
     798             :  *
     799             :  * It is caller error to call this on something that doesn't have a
     800             :  * CoercionForm field.
     801             :  */
     802             : static void
     803       14262 : hide_coercion_node(Node *node)
     804             : {
     805       14262 :     if (IsA(node, FuncExpr))
     806        6746 :         ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
     807        7516 :     else if (IsA(node, RelabelType))
     808         196 :         ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
     809        7320 :     else if (IsA(node, CoerceViaIO))
     810        7312 :         ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
     811           8 :     else if (IsA(node, ArrayCoerceExpr))
     812           8 :         ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
     813           0 :     else if (IsA(node, ConvertRowtypeExpr))
     814           0 :         ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
     815           0 :     else if (IsA(node, RowExpr))
     816           0 :         ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
     817           0 :     else if (IsA(node, CoerceToDomain))
     818           0 :         ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
     819             :     else
     820           0 :         elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
     821       14262 : }
     822             : 
     823             : /*
     824             :  * build_coercion_expression()
     825             :  *      Construct an expression tree for applying a pg_cast entry.
     826             :  *
     827             :  * This is used for both type-coercion and length-coercion operations,
     828             :  * since there is no difference in terms of the calling convention.
     829             :  */
     830             : static Node *
     831      162482 : build_coercion_expression(Node *node,
     832             :                           CoercionPathType pathtype,
     833             :                           Oid funcId,
     834             :                           Oid targetTypeId, int32 targetTypMod,
     835             :                           CoercionContext ccontext, CoercionForm cformat,
     836             :                           int location)
     837             : {
     838      162482 :     int         nargs = 0;
     839             : 
     840      162482 :     if (OidIsValid(funcId))
     841             :     {
     842             :         HeapTuple   tp;
     843             :         Form_pg_proc procstruct;
     844             : 
     845      139888 :         tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
     846      139888 :         if (!HeapTupleIsValid(tp))
     847           0 :             elog(ERROR, "cache lookup failed for function %u", funcId);
     848      139888 :         procstruct = (Form_pg_proc) GETSTRUCT(tp);
     849             : 
     850             :         /*
     851             :          * These Asserts essentially check that function is a legal coercion
     852             :          * function.  We can't make the seemingly obvious tests on prorettype
     853             :          * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
     854             :          * various binary-compatibility cases.
     855             :          */
     856             :         /* Assert(targetTypeId == procstruct->prorettype); */
     857             :         Assert(!procstruct->proretset);
     858             :         Assert(procstruct->prokind == PROKIND_FUNCTION);
     859      139888 :         nargs = procstruct->pronargs;
     860             :         Assert(nargs >= 1 && nargs <= 3);
     861             :         /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
     862             :         Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
     863             :         Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
     864             : 
     865      139888 :         ReleaseSysCache(tp);
     866             :     }
     867             : 
     868      162482 :     if (pathtype == COERCION_PATH_FUNC)
     869             :     {
     870             :         /* We build an ordinary FuncExpr with special arguments */
     871             :         FuncExpr   *fexpr;
     872             :         List       *args;
     873             :         Const      *cons;
     874             : 
     875             :         Assert(OidIsValid(funcId));
     876             : 
     877      139832 :         args = list_make1(node);
     878             : 
     879      139832 :         if (nargs >= 2)
     880             :         {
     881             :             /* Pass target typmod as an int4 constant */
     882       39310 :             cons = makeConst(INT4OID,
     883             :                              -1,
     884             :                              InvalidOid,
     885             :                              sizeof(int32),
     886             :                              Int32GetDatum(targetTypMod),
     887             :                              false,
     888             :                              true);
     889             : 
     890       39310 :             args = lappend(args, cons);
     891             :         }
     892             : 
     893      139832 :         if (nargs == 3)
     894             :         {
     895             :             /* Pass it a boolean isExplicit parameter, too */
     896       32334 :             cons = makeConst(BOOLOID,
     897             :                              -1,
     898             :                              InvalidOid,
     899             :                              sizeof(bool),
     900             :                              BoolGetDatum(ccontext == COERCION_EXPLICIT),
     901             :                              false,
     902             :                              true);
     903             : 
     904       32334 :             args = lappend(args, cons);
     905             :         }
     906             : 
     907      139832 :         fexpr = makeFuncExpr(funcId, targetTypeId, args,
     908             :                              InvalidOid, InvalidOid, cformat);
     909      139832 :         fexpr->location = location;
     910      139832 :         return (Node *) fexpr;
     911             :     }
     912       22650 :     else if (pathtype == COERCION_PATH_ARRAYCOERCE)
     913             :     {
     914             :         /* We need to build an ArrayCoerceExpr */
     915        2598 :         ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
     916        2598 :         CaseTestExpr *ctest = makeNode(CaseTestExpr);
     917             :         Oid         sourceBaseTypeId;
     918             :         int32       sourceBaseTypeMod;
     919             :         Oid         targetElementType;
     920             :         Node       *elemexpr;
     921             : 
     922             :         /*
     923             :          * Look through any domain over the source array type.  Note we don't
     924             :          * expect that the target type is a domain; it must be a plain array.
     925             :          * (To get to a domain target type, we'll do coerce_to_domain later.)
     926             :          */
     927        2598 :         sourceBaseTypeMod = exprTypmod(node);
     928        2598 :         sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
     929             :                                                 &sourceBaseTypeMod);
     930             : 
     931             :         /*
     932             :          * Set up a CaseTestExpr representing one element of the source array.
     933             :          * This is an abuse of CaseTestExpr, but it's OK as long as there
     934             :          * can't be any CaseExpr or ArrayCoerceExpr within the completed
     935             :          * elemexpr.
     936             :          */
     937        2598 :         ctest->typeId = get_element_type(sourceBaseTypeId);
     938             :         Assert(OidIsValid(ctest->typeId));
     939        2598 :         ctest->typeMod = sourceBaseTypeMod;
     940        2598 :         ctest->collation = InvalidOid;   /* Assume coercions don't care */
     941             : 
     942             :         /* And coerce it to the target element type */
     943        2598 :         targetElementType = get_element_type(targetTypeId);
     944             :         Assert(OidIsValid(targetElementType));
     945             : 
     946        2598 :         elemexpr = coerce_to_target_type(NULL,
     947             :                                          (Node *) ctest,
     948             :                                          ctest->typeId,
     949             :                                          targetElementType,
     950             :                                          targetTypMod,
     951             :                                          ccontext,
     952             :                                          cformat,
     953             :                                          location);
     954        2598 :         if (elemexpr == NULL)   /* shouldn't happen */
     955           0 :             elog(ERROR, "failed to coerce array element type as expected");
     956             : 
     957        2598 :         acoerce->arg = (Expr *) node;
     958        2598 :         acoerce->elemexpr = (Expr *) elemexpr;
     959        2598 :         acoerce->resulttype = targetTypeId;
     960             : 
     961             :         /*
     962             :          * Label the output as having a particular element typmod only if we
     963             :          * ended up with a per-element expression that is labeled that way.
     964             :          */
     965        2598 :         acoerce->resulttypmod = exprTypmod(elemexpr);
     966             :         /* resultcollid will be set by parse_collate.c */
     967        2598 :         acoerce->coerceformat = cformat;
     968        2598 :         acoerce->location = location;
     969             : 
     970        2598 :         return (Node *) acoerce;
     971             :     }
     972       20052 :     else if (pathtype == COERCION_PATH_COERCEVIAIO)
     973             :     {
     974             :         /* We need to build a CoerceViaIO node */
     975       20052 :         CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
     976             : 
     977             :         Assert(!OidIsValid(funcId));
     978             : 
     979       20052 :         iocoerce->arg = (Expr *) node;
     980       20052 :         iocoerce->resulttype = targetTypeId;
     981             :         /* resultcollid will be set by parse_collate.c */
     982       20052 :         iocoerce->coerceformat = cformat;
     983       20052 :         iocoerce->location = location;
     984             : 
     985       20052 :         return (Node *) iocoerce;
     986             :     }
     987             :     else
     988             :     {
     989           0 :         elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
     990             :              (int) pathtype);
     991             :         return NULL;            /* keep compiler quiet */
     992             :     }
     993             : }
     994             : 
     995             : 
     996             : /*
     997             :  * coerce_record_to_complex
     998             :  *      Coerce a RECORD to a specific composite type.
     999             :  *
    1000             :  * Currently we only support this for inputs that are RowExprs or whole-row
    1001             :  * Vars.
    1002             :  */
    1003             : static Node *
    1004        1264 : coerce_record_to_complex(ParseState *pstate, Node *node,
    1005             :                          Oid targetTypeId,
    1006             :                          CoercionContext ccontext,
    1007             :                          CoercionForm cformat,
    1008             :                          int location)
    1009             : {
    1010             :     RowExpr    *rowexpr;
    1011             :     Oid         baseTypeId;
    1012        1264 :     int32       baseTypeMod = -1;
    1013             :     TupleDesc   tupdesc;
    1014        1264 :     List       *args = NIL;
    1015             :     List       *newargs;
    1016             :     int         i;
    1017             :     int         ucolno;
    1018             :     ListCell   *arg;
    1019             : 
    1020        1264 :     if (node && IsA(node, RowExpr))
    1021             :     {
    1022             :         /*
    1023             :          * Since the RowExpr must be of type RECORD, we needn't worry about it
    1024             :          * containing any dropped columns.
    1025             :          */
    1026        1264 :         args = ((RowExpr *) node)->args;
    1027             :     }
    1028           0 :     else if (node && IsA(node, Var) &&
    1029           0 :              ((Var *) node)->varattno == InvalidAttrNumber)
    1030           0 :     {
    1031           0 :         int         rtindex = ((Var *) node)->varno;
    1032           0 :         int         sublevels_up = ((Var *) node)->varlevelsup;
    1033           0 :         int         vlocation = ((Var *) node)->location;
    1034             :         ParseNamespaceItem *nsitem;
    1035             : 
    1036           0 :         nsitem = GetNSItemByRangeTablePosn(pstate, rtindex, sublevels_up);
    1037           0 :         args = expandNSItemVars(nsitem, sublevels_up, vlocation, NULL);
    1038             :     }
    1039             :     else
    1040           0 :         ereport(ERROR,
    1041             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1042             :                  errmsg("cannot cast type %s to %s",
    1043             :                         format_type_be(RECORDOID),
    1044             :                         format_type_be(targetTypeId)),
    1045             :                  parser_coercion_errposition(pstate, location, node)));
    1046             : 
    1047             :     /*
    1048             :      * Look up the composite type, accounting for possibility that what we are
    1049             :      * given is a domain over composite.
    1050             :      */
    1051        1264 :     baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
    1052        1264 :     tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
    1053             : 
    1054             :     /* Process the fields */
    1055        1264 :     newargs = NIL;
    1056        1264 :     ucolno = 1;
    1057        1264 :     arg = list_head(args);
    1058        4202 :     for (i = 0; i < tupdesc->natts; i++)
    1059             :     {
    1060             :         Node       *expr;
    1061             :         Node       *cexpr;
    1062             :         Oid         exprtype;
    1063        2938 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
    1064             : 
    1065             :         /* Fill in NULLs for dropped columns in rowtype */
    1066        2938 :         if (attr->attisdropped)
    1067             :         {
    1068             :             /*
    1069             :              * can't use atttypid here, but it doesn't really matter what type
    1070             :              * the Const claims to be.
    1071             :              */
    1072           6 :             newargs = lappend(newargs,
    1073           6 :                               makeNullConst(INT4OID, -1, InvalidOid));
    1074           6 :             continue;
    1075             :         }
    1076             : 
    1077        2932 :         if (arg == NULL)
    1078           0 :             ereport(ERROR,
    1079             :                     (errcode(ERRCODE_CANNOT_COERCE),
    1080             :                      errmsg("cannot cast type %s to %s",
    1081             :                             format_type_be(RECORDOID),
    1082             :                             format_type_be(targetTypeId)),
    1083             :                      errdetail("Input has too few columns."),
    1084             :                      parser_coercion_errposition(pstate, location, node)));
    1085        2932 :         expr = (Node *) lfirst(arg);
    1086        2932 :         exprtype = exprType(expr);
    1087             : 
    1088        2932 :         cexpr = coerce_to_target_type(pstate,
    1089             :                                       expr, exprtype,
    1090             :                                       attr->atttypid,
    1091             :                                       attr->atttypmod,
    1092             :                                       ccontext,
    1093             :                                       COERCE_IMPLICIT_CAST,
    1094             :                                       -1);
    1095        2932 :         if (cexpr == NULL)
    1096           0 :             ereport(ERROR,
    1097             :                     (errcode(ERRCODE_CANNOT_COERCE),
    1098             :                      errmsg("cannot cast type %s to %s",
    1099             :                             format_type_be(RECORDOID),
    1100             :                             format_type_be(targetTypeId)),
    1101             :                      errdetail("Cannot cast type %s to %s in column %d.",
    1102             :                                format_type_be(exprtype),
    1103             :                                format_type_be(attr->atttypid),
    1104             :                                ucolno),
    1105             :                      parser_coercion_errposition(pstate, location, expr)));
    1106        2932 :         newargs = lappend(newargs, cexpr);
    1107        2932 :         ucolno++;
    1108        2932 :         arg = lnext(args, arg);
    1109             :     }
    1110        1264 :     if (arg != NULL)
    1111           0 :         ereport(ERROR,
    1112             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1113             :                  errmsg("cannot cast type %s to %s",
    1114             :                         format_type_be(RECORDOID),
    1115             :                         format_type_be(targetTypeId)),
    1116             :                  errdetail("Input has too many columns."),
    1117             :                  parser_coercion_errposition(pstate, location, node)));
    1118             : 
    1119        1264 :     ReleaseTupleDesc(tupdesc);
    1120             : 
    1121        1264 :     rowexpr = makeNode(RowExpr);
    1122        1264 :     rowexpr->args = newargs;
    1123        1264 :     rowexpr->row_typeid = baseTypeId;
    1124        1264 :     rowexpr->row_format = cformat;
    1125        1264 :     rowexpr->colnames = NIL; /* not needed for named target type */
    1126        1264 :     rowexpr->location = location;
    1127             : 
    1128             :     /* If target is a domain, apply constraints */
    1129        1264 :     if (baseTypeId != targetTypeId)
    1130             :     {
    1131          76 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
    1132          76 :         return coerce_to_domain((Node *) rowexpr,
    1133             :                                 baseTypeId, baseTypeMod,
    1134             :                                 targetTypeId,
    1135             :                                 ccontext, cformat, location,
    1136             :                                 false);
    1137             :     }
    1138             : 
    1139        1188 :     return (Node *) rowexpr;
    1140             : }
    1141             : 
    1142             : /*
    1143             :  * coerce_to_boolean()
    1144             :  *      Coerce an argument of a construct that requires boolean input
    1145             :  *      (AND, OR, NOT, etc).  Also check that input is not a set.
    1146             :  *
    1147             :  * Returns the possibly-transformed node tree.
    1148             :  *
    1149             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1150             :  * processing is wanted.
    1151             :  */
    1152             : Node *
    1153     1485194 : coerce_to_boolean(ParseState *pstate, Node *node,
    1154             :                   const char *constructName)
    1155             : {
    1156     1485194 :     Oid         inputTypeId = exprType(node);
    1157             : 
    1158     1485194 :     if (inputTypeId != BOOLOID)
    1159             :     {
    1160             :         Node       *newnode;
    1161             : 
    1162           0 :         newnode = coerce_to_target_type(pstate, node, inputTypeId,
    1163             :                                         BOOLOID, -1,
    1164             :                                         COERCION_ASSIGNMENT,
    1165             :                                         COERCE_IMPLICIT_CAST,
    1166             :                                         -1);
    1167           0 :         if (newnode == NULL)
    1168           0 :             ereport(ERROR,
    1169             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1170             :             /* translator: first %s is name of a SQL construct, eg WHERE */
    1171             :                      errmsg("argument of %s must be type %s, not type %s",
    1172             :                             constructName, "boolean",
    1173             :                             format_type_be(inputTypeId)),
    1174             :                      parser_errposition(pstate, exprLocation(node))));
    1175           0 :         node = newnode;
    1176             :     }
    1177             : 
    1178     1485194 :     if (expression_returns_set(node))
    1179           0 :         ereport(ERROR,
    1180             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1181             :         /* translator: %s is name of a SQL construct, eg WHERE */
    1182             :                  errmsg("argument of %s must not return a set",
    1183             :                         constructName),
    1184             :                  parser_errposition(pstate, exprLocation(node))));
    1185             : 
    1186     1485194 :     return node;
    1187             : }
    1188             : 
    1189             : /*
    1190             :  * coerce_to_specific_type_typmod()
    1191             :  *      Coerce an argument of a construct that requires a specific data type,
    1192             :  *      with a specific typmod.  Also check that input is not a set.
    1193             :  *
    1194             :  * Returns the possibly-transformed node tree.
    1195             :  *
    1196             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1197             :  * processing is wanted.
    1198             :  */
    1199             : Node *
    1200       31748 : coerce_to_specific_type_typmod(ParseState *pstate, Node *node,
    1201             :                                Oid targetTypeId, int32 targetTypmod,
    1202             :                                const char *constructName)
    1203             : {
    1204       31748 :     Oid         inputTypeId = exprType(node);
    1205             : 
    1206       31748 :     if (inputTypeId != targetTypeId)
    1207             :     {
    1208             :         Node       *newnode;
    1209             : 
    1210       15770 :         newnode = coerce_to_target_type(pstate, node, inputTypeId,
    1211             :                                         targetTypeId, targetTypmod,
    1212             :                                         COERCION_ASSIGNMENT,
    1213             :                                         COERCE_IMPLICIT_CAST,
    1214             :                                         -1);
    1215       15762 :         if (newnode == NULL)
    1216           4 :             ereport(ERROR,
    1217             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1218             :             /* translator: first %s is name of a SQL construct, eg LIMIT */
    1219             :                      errmsg("argument of %s must be type %s, not type %s",
    1220             :                             constructName,
    1221             :                             format_type_be(targetTypeId),
    1222             :                             format_type_be(inputTypeId)),
    1223             :                      parser_errposition(pstate, exprLocation(node))));
    1224       15758 :         node = newnode;
    1225             :     }
    1226             : 
    1227       31736 :     if (expression_returns_set(node))
    1228           0 :         ereport(ERROR,
    1229             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1230             :         /* translator: %s is name of a SQL construct, eg LIMIT */
    1231             :                  errmsg("argument of %s must not return a set",
    1232             :                         constructName),
    1233             :                  parser_errposition(pstate, exprLocation(node))));
    1234             : 
    1235       31736 :     return node;
    1236             : }
    1237             : 
    1238             : /*
    1239             :  * coerce_to_specific_type()
    1240             :  *      Coerce an argument of a construct that requires a specific data type.
    1241             :  *      Also check that input is not a set.
    1242             :  *
    1243             :  * Returns the possibly-transformed node tree.
    1244             :  *
    1245             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1246             :  * processing is wanted.
    1247             :  */
    1248             : Node *
    1249       31710 : coerce_to_specific_type(ParseState *pstate, Node *node,
    1250             :                         Oid targetTypeId,
    1251             :                         const char *constructName)
    1252             : {
    1253       31710 :     return coerce_to_specific_type_typmod(pstate, node,
    1254             :                                           targetTypeId, -1,
    1255             :                                           constructName);
    1256             : }
    1257             : 
    1258             : /*
    1259             :  * parser_coercion_errposition - report coercion error location, if possible
    1260             :  *
    1261             :  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
    1262             :  * but there may be no such location in the case of an implicit coercion.
    1263             :  * In that case point at the input expression.
    1264             :  *
    1265             :  * XXX possibly this is more generally useful than coercion errors;
    1266             :  * if so, should rename and place with parser_errposition.
    1267             :  */
    1268             : int
    1269          16 : parser_coercion_errposition(ParseState *pstate,
    1270             :                             int coerce_location,
    1271             :                             Node *input_expr)
    1272             : {
    1273          16 :     if (coerce_location >= 0)
    1274          16 :         return parser_errposition(pstate, coerce_location);
    1275             :     else
    1276           0 :         return parser_errposition(pstate, exprLocation(input_expr));
    1277             : }
    1278             : 
    1279             : 
    1280             : /*
    1281             :  * select_common_type()
    1282             :  *      Determine the common supertype of a list of input expressions.
    1283             :  *      This is used for determining the output type of CASE, UNION,
    1284             :  *      and similar constructs.
    1285             :  *
    1286             :  * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
    1287             :  * in the list will be preferred if there is doubt.
    1288             :  * 'context' is a phrase to use in the error message if we fail to select
    1289             :  * a usable type.  Pass NULL to have the routine return InvalidOid
    1290             :  * rather than throwing an error on failure.
    1291             :  * 'which_expr': if not NULL, receives a pointer to the particular input
    1292             :  * expression from which the result type was taken.
    1293             :  */
    1294             : Oid
    1295      334996 : select_common_type(ParseState *pstate, List *exprs, const char *context,
    1296             :                    Node **which_expr)
    1297             : {
    1298             :     Node       *pexpr;
    1299             :     Oid         ptype;
    1300             :     TYPCATEGORY pcategory;
    1301             :     bool        pispreferred;
    1302             :     ListCell   *lc;
    1303             : 
    1304             :     Assert(exprs != NIL);
    1305      334996 :     pexpr = (Node *) linitial(exprs);
    1306      334996 :     lc = list_second_cell(exprs);
    1307      334996 :     ptype = exprType(pexpr);
    1308             : 
    1309             :     /*
    1310             :      * If all input types are valid and exactly the same, just pick that type.
    1311             :      * This is the only way that we will resolve the result as being a domain
    1312             :      * type; otherwise domains are smashed to their base types for comparison.
    1313             :      */
    1314      334996 :     if (ptype != UNKNOWNOID)
    1315             :     {
    1316      412570 :         for_each_cell(lc, exprs, lc)
    1317             :         {
    1318      258868 :             Node       *nexpr = (Node *) lfirst(lc);
    1319      258868 :             Oid         ntype = exprType(nexpr);
    1320             : 
    1321      258868 :             if (ntype != ptype)
    1322       92808 :                 break;
    1323             :         }
    1324      246510 :         if (lc == NULL)         /* got to the end of the list? */
    1325             :         {
    1326      153702 :             if (which_expr)
    1327      110758 :                 *which_expr = pexpr;
    1328      153702 :             return ptype;
    1329             :         }
    1330             :     }
    1331             : 
    1332             :     /*
    1333             :      * Nope, so set up for the full algorithm.  Note that at this point, lc
    1334             :      * points to the first list item with type different from pexpr's; we need
    1335             :      * not re-examine any items the previous loop advanced over.
    1336             :      */
    1337      181294 :     ptype = getBaseType(ptype);
    1338      181294 :     get_type_category_preferred(ptype, &pcategory, &pispreferred);
    1339             : 
    1340      534518 :     for_each_cell(lc, exprs, lc)
    1341             :     {
    1342      353232 :         Node       *nexpr = (Node *) lfirst(lc);
    1343      353232 :         Oid         ntype = getBaseType(exprType(nexpr));
    1344             : 
    1345             :         /* move on to next one if no new information... */
    1346      353232 :         if (ntype != UNKNOWNOID && ntype != ptype)
    1347             :         {
    1348             :             TYPCATEGORY ncategory;
    1349             :             bool        nispreferred;
    1350             : 
    1351       99928 :             get_type_category_preferred(ntype, &ncategory, &nispreferred);
    1352       99928 :             if (ptype == UNKNOWNOID)
    1353             :             {
    1354             :                 /* so far, only unknowns so take anything... */
    1355       57130 :                 pexpr = nexpr;
    1356       57130 :                 ptype = ntype;
    1357       57130 :                 pcategory = ncategory;
    1358       57130 :                 pispreferred = nispreferred;
    1359             :             }
    1360       42798 :             else if (ncategory != pcategory)
    1361             :             {
    1362             :                 /*
    1363             :                  * both types in different categories? then not much hope...
    1364             :                  */
    1365           8 :                 if (context == NULL)
    1366           0 :                     return InvalidOid;
    1367           8 :                 ereport(ERROR,
    1368             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1369             :                 /*------
    1370             :                   translator: first %s is name of a SQL construct, eg CASE */
    1371             :                          errmsg("%s types %s and %s cannot be matched",
    1372             :                                 context,
    1373             :                                 format_type_be(ptype),
    1374             :                                 format_type_be(ntype)),
    1375             :                          parser_errposition(pstate, exprLocation(nexpr))));
    1376             :             }
    1377       73656 :             else if (!pispreferred &&
    1378       30866 :                      can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
    1379       30358 :                      !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
    1380             :             {
    1381             :                 /*
    1382             :                  * take new type if can coerce to it implicitly but not the
    1383             :                  * other way; but if we have a preferred type, stay on it.
    1384             :                  */
    1385       29864 :                 pexpr = nexpr;
    1386       29864 :                 ptype = ntype;
    1387       29864 :                 pcategory = ncategory;
    1388       29864 :                 pispreferred = nispreferred;
    1389             :             }
    1390             :         }
    1391             :     }
    1392             : 
    1393             :     /*
    1394             :      * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
    1395             :      * then resolve as type TEXT.  This situation comes up with constructs
    1396             :      * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
    1397             :      * UNION SELECT 'bar'; It might seem desirable to leave the construct's
    1398             :      * output type as UNKNOWN, but that really doesn't work, because we'd
    1399             :      * probably end up needing a runtime coercion from UNKNOWN to something
    1400             :      * else, and we usually won't have it.  We need to coerce the unknown
    1401             :      * literals while they are still literals, so a decision has to be made
    1402             :      * now.
    1403             :      */
    1404      181286 :     if (ptype == UNKNOWNOID)
    1405       31356 :         ptype = TEXTOID;
    1406             : 
    1407      181286 :     if (which_expr)
    1408        7898 :         *which_expr = pexpr;
    1409      181286 :     return ptype;
    1410             : }
    1411             : 
    1412             : /*
    1413             :  * select_common_type_from_oids()
    1414             :  *      Determine the common supertype of an array of type OIDs.
    1415             :  *
    1416             :  * This is the same logic as select_common_type(), but working from
    1417             :  * an array of type OIDs not a list of expressions.  As in that function,
    1418             :  * earlier entries in the array have some preference over later ones.
    1419             :  * On failure, return InvalidOid if noerror is true, else throw an error.
    1420             :  *
    1421             :  * Note: neither caller will pass any UNKNOWNOID entries, so the tests
    1422             :  * for that in this function are dead code.  However, they don't cost much,
    1423             :  * and it seems better to keep this logic as close to select_common_type()
    1424             :  * as possible.
    1425             :  */
    1426             : static Oid
    1427        4850 : select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
    1428             : {
    1429             :     Oid         ptype;
    1430             :     TYPCATEGORY pcategory;
    1431             :     bool        pispreferred;
    1432        4850 :     int         i = 1;
    1433             : 
    1434             :     Assert(nargs > 0);
    1435        4850 :     ptype = typeids[0];
    1436             : 
    1437             :     /* If all input types are valid and exactly the same, pick that type. */
    1438        4850 :     if (ptype != UNKNOWNOID)
    1439             :     {
    1440        6820 :         for (; i < nargs; i++)
    1441             :         {
    1442        2626 :             if (typeids[i] != ptype)
    1443         656 :                 break;
    1444             :         }
    1445        4850 :         if (i == nargs)
    1446        4194 :             return ptype;
    1447             :     }
    1448             : 
    1449             :     /*
    1450             :      * Nope, so set up for the full algorithm.  Note that at this point, we
    1451             :      * can skip array entries before "i"; they are all equal to ptype.
    1452             :      */
    1453         656 :     ptype = getBaseType(ptype);
    1454         656 :     get_type_category_preferred(ptype, &pcategory, &pispreferred);
    1455             : 
    1456         984 :     for (; i < nargs; i++)
    1457             :     {
    1458         692 :         Oid         ntype = getBaseType(typeids[i]);
    1459             : 
    1460             :         /* move on to next one if no new information... */
    1461         692 :         if (ntype != UNKNOWNOID && ntype != ptype)
    1462             :         {
    1463             :             TYPCATEGORY ncategory;
    1464             :             bool        nispreferred;
    1465             : 
    1466         684 :             get_type_category_preferred(ntype, &ncategory, &nispreferred);
    1467         684 :             if (ptype == UNKNOWNOID)
    1468             :             {
    1469             :                 /* so far, only unknowns so take anything... */
    1470           0 :                 ptype = ntype;
    1471           0 :                 pcategory = ncategory;
    1472           0 :                 pispreferred = nispreferred;
    1473             :             }
    1474         684 :             else if (ncategory != pcategory)
    1475             :             {
    1476             :                 /*
    1477             :                  * both types in different categories? then not much hope...
    1478             :                  */
    1479         364 :                 if (noerror)
    1480         364 :                     return InvalidOid;
    1481           0 :                 ereport(ERROR,
    1482             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1483             :                          errmsg("argument types %s and %s cannot be matched",
    1484             :                                 format_type_be(ptype),
    1485             :                                 format_type_be(ntype))));
    1486             :             }
    1487         592 :             else if (!pispreferred &&
    1488         272 :                      can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
    1489         180 :                      !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
    1490             :             {
    1491             :                 /*
    1492             :                  * take new type if can coerce to it implicitly but not the
    1493             :                  * other way; but if we have a preferred type, stay on it.
    1494             :                  */
    1495         180 :                 ptype = ntype;
    1496         180 :                 pcategory = ncategory;
    1497         180 :                 pispreferred = nispreferred;
    1498             :             }
    1499             :         }
    1500             :     }
    1501             : 
    1502             :     /* Like select_common_type(), choose TEXT if all inputs were UNKNOWN */
    1503         292 :     if (ptype == UNKNOWNOID)
    1504           0 :         ptype = TEXTOID;
    1505             : 
    1506         292 :     return ptype;
    1507             : }
    1508             : 
    1509             : /*
    1510             :  * coerce_to_common_type()
    1511             :  *      Coerce an expression to the given type.
    1512             :  *
    1513             :  * This is used following select_common_type() to coerce the individual
    1514             :  * expressions to the desired type.  'context' is a phrase to use in the
    1515             :  * error message if we fail to coerce.
    1516             :  *
    1517             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1518             :  * processing is wanted.
    1519             :  */
    1520             : Node *
    1521      803704 : coerce_to_common_type(ParseState *pstate, Node *node,
    1522             :                       Oid targetTypeId, const char *context)
    1523             : {
    1524      803704 :     Oid         inputTypeId = exprType(node);
    1525             : 
    1526      803704 :     if (inputTypeId == targetTypeId)
    1527      454404 :         return node;            /* no work */
    1528      349300 :     if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
    1529      349300 :         node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
    1530             :                            COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
    1531             :     else
    1532           0 :         ereport(ERROR,
    1533             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1534             :         /* translator: first %s is name of a SQL construct, eg CASE */
    1535             :                  errmsg("%s could not convert type %s to %s",
    1536             :                         context,
    1537             :                         format_type_be(inputTypeId),
    1538             :                         format_type_be(targetTypeId)),
    1539             :                  parser_errposition(pstate, exprLocation(node))));
    1540      349296 :     return node;
    1541             : }
    1542             : 
    1543             : /*
    1544             :  * select_common_typmod()
    1545             :  *      Determine the common typmod of a list of input expressions.
    1546             :  *
    1547             :  * common_type is the selected common type of the expressions, typically
    1548             :  * computed using select_common_type().
    1549             :  */
    1550             : int32
    1551      125036 : select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
    1552             : {
    1553             :     ListCell   *lc;
    1554      125036 :     bool        first = true;
    1555      125036 :     int32       result = -1;
    1556             : 
    1557      384412 :     foreach(lc, exprs)
    1558             :     {
    1559      259510 :         Node       *expr = (Node *) lfirst(lc);
    1560             : 
    1561             :         /* Types must match */
    1562      259510 :         if (exprType(expr) != common_type)
    1563         134 :             return -1;
    1564      259406 :         else if (first)
    1565             :         {
    1566      124992 :             result = exprTypmod(expr);
    1567      124992 :             first = false;
    1568             :         }
    1569             :         else
    1570             :         {
    1571             :             /* As soon as we see a non-matching typmod, fall back to -1 */
    1572      134414 :             if (result != exprTypmod(expr))
    1573          30 :                 return -1;
    1574             :         }
    1575             :     }
    1576             : 
    1577      124902 :     return result;
    1578             : }
    1579             : 
    1580             : /*
    1581             :  * check_generic_type_consistency()
    1582             :  *      Are the actual arguments potentially compatible with a
    1583             :  *      polymorphic function?
    1584             :  *
    1585             :  * The argument consistency rules are:
    1586             :  *
    1587             :  * 1) All arguments declared ANYELEMENT must have the same datatype.
    1588             :  * 2) All arguments declared ANYARRAY must have the same datatype,
    1589             :  *    which must be a varlena array type.
    1590             :  * 3) All arguments declared ANYRANGE must be the same range type.
    1591             :  *    Similarly, all arguments declared ANYMULTIRANGE must be the same
    1592             :  *    multirange type; and if both of these appear, the ANYRANGE type
    1593             :  *    must be the element type of the ANYMULTIRANGE type.
    1594             :  * 4) If there are arguments of more than one of these polymorphic types,
    1595             :  *    the array element type and/or range subtype must be the same as each
    1596             :  *    other and the same as the ANYELEMENT type.
    1597             :  * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
    1598             :  *    (alone or in combination with plain ANYELEMENT), we add the extra
    1599             :  *    condition that the ANYELEMENT type must be an enum.
    1600             :  * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
    1601             :  *    we add the extra condition that the ANYELEMENT type must not be an array.
    1602             :  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
    1603             :  *    is an extra restriction if not.)
    1604             :  * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
    1605             :  *    to a common supertype (chosen as per select_common_type's rules).
    1606             :  *    ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
    1607             :  *    common supertype to not be an array.  If there are ANYCOMPATIBLEARRAY
    1608             :  *    or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
    1609             :  *    types or subtypes are included while making the choice of common supertype.
    1610             :  * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
    1611             :  *    type over the common supertype (which might not be the same array type
    1612             :  *    as any of the original arrays).
    1613             :  * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
    1614             :  *    (after domain flattening), since we have no preference rule that would
    1615             :  *    let us choose one over another.  Furthermore, that range's subtype
    1616             :  *    must exactly match the common supertype chosen by rule 7.
    1617             :  * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
    1618             :  *    type (after domain flattening), since we have no preference rule that
    1619             :  *    would let us choose one over another.  Furthermore, if ANYCOMPATIBLERANGE
    1620             :  *    also appears, that range type must be the multirange's element type;
    1621             :  *    otherwise, the multirange's range's subtype must exactly match the
    1622             :  *    common supertype chosen by rule 7.
    1623             :  *
    1624             :  * Domains over arrays match ANYARRAY, and are immediately flattened to their
    1625             :  * base type.  (Thus, for example, we will consider it a match if one ANYARRAY
    1626             :  * argument is a domain over int4[] while another one is just int4[].)  Also
    1627             :  * notice that such a domain does *not* match ANYNONARRAY.  The same goes
    1628             :  * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
    1629             :  *
    1630             :  * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
    1631             :  * and are immediately flattened to their base type.  Likewise, domains
    1632             :  * over multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are
    1633             :  * immediately flattened to their base type.
    1634             :  *
    1635             :  * Note that domains aren't currently considered to match ANYENUM,
    1636             :  * even if their base type would match.
    1637             :  *
    1638             :  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
    1639             :  * argument, assume it is okay.
    1640             :  *
    1641             :  * We do not ereport here, but just return false if a rule is violated.
    1642             :  */
    1643             : bool
    1644      293342 : check_generic_type_consistency(const Oid *actual_arg_types,
    1645             :                                const Oid *declared_arg_types,
    1646             :                                int nargs)
    1647             : {
    1648      293342 :     Oid         elem_typeid = InvalidOid;
    1649      293342 :     Oid         array_typeid = InvalidOid;
    1650      293342 :     Oid         range_typeid = InvalidOid;
    1651      293342 :     Oid         multirange_typeid = InvalidOid;
    1652      293342 :     Oid         anycompatible_range_typeid = InvalidOid;
    1653      293342 :     Oid         anycompatible_range_typelem = InvalidOid;
    1654      293342 :     Oid         anycompatible_multirange_typeid = InvalidOid;
    1655      293342 :     Oid         anycompatible_multirange_typelem = InvalidOid;
    1656      293342 :     Oid         range_typelem = InvalidOid;
    1657      293342 :     bool        have_anynonarray = false;
    1658      293342 :     bool        have_anyenum = false;
    1659      293342 :     bool        have_anycompatible_nonarray = false;
    1660      293342 :     int         n_anycompatible_args = 0;
    1661             :     Oid         anycompatible_actual_types[FUNC_MAX_ARGS];
    1662             : 
    1663             :     /*
    1664             :      * Loop through the arguments to see if we have any that are polymorphic.
    1665             :      * If so, require the actual types to be consistent.
    1666             :      */
    1667             :     Assert(nargs <= FUNC_MAX_ARGS);
    1668      678828 :     for (int j = 0; j < nargs; j++)
    1669             :     {
    1670      426868 :         Oid         decl_type = declared_arg_types[j];
    1671      426868 :         Oid         actual_type = actual_arg_types[j];
    1672             : 
    1673      426868 :         if (decl_type == ANYELEMENTOID ||
    1674      377800 :             decl_type == ANYNONARRAYOID ||
    1675             :             decl_type == ANYENUMOID)
    1676             :         {
    1677       76966 :             if (decl_type == ANYNONARRAYOID)
    1678       45658 :                 have_anynonarray = true;
    1679       31308 :             else if (decl_type == ANYENUMOID)
    1680       27898 :                 have_anyenum = true;
    1681       76966 :             if (actual_type == UNKNOWNOID)
    1682        3742 :                 continue;
    1683       73224 :             if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
    1684       10074 :                 return false;
    1685       63150 :             elem_typeid = actual_type;
    1686             :         }
    1687      349902 :         else if (decl_type == ANYARRAYOID)
    1688             :         {
    1689      186034 :             if (actual_type == UNKNOWNOID)
    1690       33436 :                 continue;
    1691      152598 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1692      152598 :             if (OidIsValid(array_typeid) && actual_type != array_typeid)
    1693        8736 :                 return false;
    1694      143862 :             array_typeid = actual_type;
    1695             :         }
    1696      163868 :         else if (decl_type == ANYRANGEOID)
    1697             :         {
    1698       32534 :             if (actual_type == UNKNOWNOID)
    1699        2398 :                 continue;
    1700       30136 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1701       30136 :             if (OidIsValid(range_typeid) && actual_type != range_typeid)
    1702        9198 :                 return false;
    1703       20938 :             range_typeid = actual_type;
    1704             :         }
    1705      131334 :         else if (decl_type == ANYMULTIRANGEOID)
    1706             :         {
    1707       51160 :             if (actual_type == UNKNOWNOID)
    1708        2410 :                 continue;
    1709       48750 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1710       48750 :             if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
    1711        9198 :                 return false;
    1712       39552 :             multirange_typeid = actual_type;
    1713             :         }
    1714       80174 :         else if (decl_type == ANYCOMPATIBLEOID ||
    1715             :                  decl_type == ANYCOMPATIBLENONARRAYOID)
    1716             :         {
    1717        4058 :             if (decl_type == ANYCOMPATIBLENONARRAYOID)
    1718          24 :                 have_anycompatible_nonarray = true;
    1719        4058 :             if (actual_type == UNKNOWNOID)
    1720        1156 :                 continue;
    1721             :             /* collect the actual types of non-unknown COMPATIBLE args */
    1722        2902 :             anycompatible_actual_types[n_anycompatible_args++] = actual_type;
    1723             :         }
    1724       76116 :         else if (decl_type == ANYCOMPATIBLEARRAYOID)
    1725             :         {
    1726             :             Oid         elem_type;
    1727             : 
    1728        7682 :             if (actual_type == UNKNOWNOID)
    1729        1892 :                 continue;
    1730        5790 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1731        5790 :             elem_type = get_element_type(actual_type);
    1732        5790 :             if (!OidIsValid(elem_type))
    1733        4160 :                 return false;   /* not an array */
    1734             :             /* collect the element type for common-supertype choice */
    1735        1630 :             anycompatible_actual_types[n_anycompatible_args++] = elem_type;
    1736             :         }
    1737       68434 :         else if (decl_type == ANYCOMPATIBLERANGEOID)
    1738             :         {
    1739         124 :             if (actual_type == UNKNOWNOID)
    1740           8 :                 continue;
    1741         116 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1742         116 :             if (OidIsValid(anycompatible_range_typeid))
    1743             :             {
    1744             :                 /* All ANYCOMPATIBLERANGE arguments must be the same type */
    1745           8 :                 if (anycompatible_range_typeid != actual_type)
    1746           4 :                     return false;
    1747             :             }
    1748             :             else
    1749             :             {
    1750         108 :                 anycompatible_range_typeid = actual_type;
    1751         108 :                 anycompatible_range_typelem = get_range_subtype(actual_type);
    1752         108 :                 if (!OidIsValid(anycompatible_range_typelem))
    1753           4 :                     return false;   /* not a range type */
    1754             :                 /* collect the subtype for common-supertype choice */
    1755         104 :                 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
    1756             :             }
    1757             :         }
    1758       68310 :         else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
    1759             :         {
    1760          92 :             if (actual_type == UNKNOWNOID)
    1761          12 :                 continue;
    1762          80 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1763          80 :             if (OidIsValid(anycompatible_multirange_typeid))
    1764             :             {
    1765             :                 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
    1766           8 :                 if (anycompatible_multirange_typeid != actual_type)
    1767           4 :                     return false;
    1768             :             }
    1769             :             else
    1770             :             {
    1771          72 :                 anycompatible_multirange_typeid = actual_type;
    1772          72 :                 anycompatible_multirange_typelem = get_multirange_range(actual_type);
    1773          72 :                 if (!OidIsValid(anycompatible_multirange_typelem))
    1774           4 :                     return false;   /* not a multirange type */
    1775             :                 /* we'll consider the subtype below */
    1776             :             }
    1777             :         }
    1778             :     }
    1779             : 
    1780             :     /* Get the element type based on the array type, if we have one */
    1781      251960 :     if (OidIsValid(array_typeid))
    1782             :     {
    1783      131882 :         if (array_typeid == ANYARRAYOID)
    1784             :         {
    1785             :             /*
    1786             :              * Special case for matching ANYARRAY input to an ANYARRAY
    1787             :              * argument: allow it for now.  enforce_generic_type_consistency()
    1788             :              * might complain later, depending on the presence of other
    1789             :              * polymorphic arguments or results, but it will deliver a less
    1790             :              * surprising error message than "function does not exist".
    1791             :              *
    1792             :              * (If you think to change this, note that can_coerce_type will
    1793             :              * consider such a situation as a match, so that we might not even
    1794             :              * get here.)
    1795             :              */
    1796             :         }
    1797             :         else
    1798             :         {
    1799             :             Oid         array_typelem;
    1800             : 
    1801      131882 :             array_typelem = get_element_type(array_typeid);
    1802      131882 :             if (!OidIsValid(array_typelem))
    1803       44812 :                 return false;   /* should be an array, but isn't */
    1804             : 
    1805       87070 :             if (!OidIsValid(elem_typeid))
    1806             :             {
    1807             :                 /*
    1808             :                  * if we don't have an element type yet, use the one we just
    1809             :                  * got
    1810             :                  */
    1811       86986 :                 elem_typeid = array_typelem;
    1812             :             }
    1813          84 :             else if (array_typelem != elem_typeid)
    1814             :             {
    1815             :                 /* otherwise, they better match */
    1816          32 :                 return false;
    1817             :             }
    1818             :         }
    1819             :     }
    1820             : 
    1821             :     /* Deduce range type from multirange type, or check that they agree */
    1822      207116 :     if (OidIsValid(multirange_typeid))
    1823             :     {
    1824             :         Oid         multirange_typelem;
    1825             : 
    1826       26968 :         multirange_typelem = get_multirange_range(multirange_typeid);
    1827       26968 :         if (!OidIsValid(multirange_typelem))
    1828       26132 :             return false;       /* should be a multirange, but isn't */
    1829             : 
    1830         836 :         if (!OidIsValid(range_typeid))
    1831             :         {
    1832             :             /* If we don't have a range type yet, use the one we just got */
    1833         512 :             range_typeid = multirange_typelem;
    1834         512 :             range_typelem = get_range_subtype(multirange_typelem);
    1835         512 :             if (!OidIsValid(range_typelem))
    1836           0 :                 return false;   /* should be a range, but isn't */
    1837             :         }
    1838         324 :         else if (multirange_typelem != range_typeid)
    1839             :         {
    1840             :             /* otherwise, they better match */
    1841         180 :             return false;
    1842             :         }
    1843             :     }
    1844             : 
    1845             :     /* Get the element type based on the range type, if we have one */
    1846      180804 :     if (OidIsValid(range_typeid))
    1847             :     {
    1848        7846 :         range_typelem = get_range_subtype(range_typeid);
    1849        7846 :         if (!OidIsValid(range_typelem))
    1850        6376 :             return false;       /* should be a range, but isn't */
    1851             : 
    1852        1470 :         if (!OidIsValid(elem_typeid))
    1853             :         {
    1854             :             /*
    1855             :              * If we don't have an element type yet, use the one we just got
    1856             :              */
    1857        1250 :             elem_typeid = range_typelem;
    1858             :         }
    1859         220 :         else if (range_typelem != elem_typeid)
    1860             :         {
    1861             :             /* otherwise, they better match */
    1862         108 :             return false;
    1863             :         }
    1864             :     }
    1865             : 
    1866      174320 :     if (have_anynonarray)
    1867             :     {
    1868             :         /* require the element type to not be an array or domain over array */
    1869       45306 :         if (type_is_array_domain(elem_typeid))
    1870        1012 :             return false;
    1871             :     }
    1872             : 
    1873      173308 :     if (have_anyenum)
    1874             :     {
    1875             :         /* require the element type to be an enum */
    1876        4020 :         if (!type_is_enum(elem_typeid))
    1877        3756 :             return false;
    1878             :     }
    1879             : 
    1880             :     /* Deduce range type from multirange type, or check that they agree */
    1881      169552 :     if (OidIsValid(anycompatible_multirange_typeid))
    1882             :     {
    1883          64 :         if (OidIsValid(anycompatible_range_typeid))
    1884             :         {
    1885           8 :             if (anycompatible_multirange_typelem !=
    1886             :                 anycompatible_range_typeid)
    1887           4 :                 return false;
    1888             :         }
    1889             :         else
    1890             :         {
    1891          56 :             anycompatible_range_typeid = anycompatible_multirange_typelem;
    1892          56 :             anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
    1893          56 :             if (!OidIsValid(anycompatible_range_typelem))
    1894           0 :                 return false;   /* not a range type */
    1895             :             /* collect the subtype for common-supertype choice */
    1896          56 :             anycompatible_actual_types[n_anycompatible_args++] =
    1897             :                 anycompatible_range_typelem;
    1898             :         }
    1899             :     }
    1900             : 
    1901             :     /* Check matching of ANYCOMPATIBLE-family arguments, if any */
    1902      169548 :     if (n_anycompatible_args > 0)
    1903             :     {
    1904             :         Oid         anycompatible_typeid;
    1905             : 
    1906             :         anycompatible_typeid =
    1907        2832 :             select_common_type_from_oids(n_anycompatible_args,
    1908             :                                          anycompatible_actual_types,
    1909             :                                          true);
    1910             : 
    1911        2832 :         if (!OidIsValid(anycompatible_typeid))
    1912         364 :             return false;       /* there's no common supertype */
    1913             : 
    1914        2468 :         if (have_anycompatible_nonarray)
    1915             :         {
    1916             :             /*
    1917             :              * require the anycompatible type to not be an array or domain
    1918             :              * over array
    1919             :              */
    1920          12 :             if (type_is_array_domain(anycompatible_typeid))
    1921           4 :                 return false;
    1922             :         }
    1923             : 
    1924             :         /*
    1925             :          * The anycompatible type must exactly match the range element type,
    1926             :          * if we were able to identify one. This checks compatibility for
    1927             :          * anycompatiblemultirange too since that also sets
    1928             :          * anycompatible_range_typelem above.
    1929             :          */
    1930        2464 :         if (OidIsValid(anycompatible_range_typelem) &&
    1931             :             anycompatible_range_typelem != anycompatible_typeid)
    1932          28 :             return false;
    1933             :     }
    1934             : 
    1935             :     /* Looks valid */
    1936      169152 :     return true;
    1937             : }
    1938             : 
    1939             : /*
    1940             :  * enforce_generic_type_consistency()
    1941             :  *      Make sure a polymorphic function is legally callable, and
    1942             :  *      deduce actual argument and result types.
    1943             :  *
    1944             :  * If any polymorphic pseudotype is used in a function's arguments or
    1945             :  * return type, we make sure the actual data types are consistent with
    1946             :  * each other.  The argument consistency rules are shown above for
    1947             :  * check_generic_type_consistency().
    1948             :  *
    1949             :  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
    1950             :  * argument, we attempt to deduce the actual type it should have.  If
    1951             :  * successful, we alter that position of declared_arg_types[] so that
    1952             :  * make_fn_arguments will coerce the literal to the right thing.
    1953             :  *
    1954             :  * If we have polymorphic arguments of the ANYCOMPATIBLE family,
    1955             :  * we similarly alter declared_arg_types[] entries to show the resolved
    1956             :  * common supertype, so that make_fn_arguments will coerce the actual
    1957             :  * arguments to the proper type.
    1958             :  *
    1959             :  * Rules are applied to the function's return type (possibly altering it)
    1960             :  * if it is declared as a polymorphic type and there is at least one
    1961             :  * polymorphic argument type:
    1962             :  *
    1963             :  * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
    1964             :  *    argument's actual type as the function's return type.
    1965             :  * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
    1966             :  *    argument's actual type as the function's return type.
    1967             :  * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
    1968             :  *    argument is ANYRANGE or ANYMULTIRANGE, use that argument's actual type
    1969             :  *    (or the corresponding range or multirange type) as the function's return
    1970             :  *    type.
    1971             :  * 4) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
    1972             :  *    at least one ANYELEMENT, ANYARRAY, ANYRANGE, or ANYMULTIRANGE input,
    1973             :  *    deduce the return type from those inputs, or throw error if we can't.
    1974             :  * 5) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
    1975             :  *    (We have no way to select a specific range type if the arguments don't
    1976             :  *    include ANYRANGE or ANYMULTIRANGE.)
    1977             :  * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
    1978             :  *    (alone or in combination with plain ANYELEMENT), we add the extra
    1979             :  *    condition that the ANYELEMENT type must be an enum.
    1980             :  * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
    1981             :  *    we add the extra condition that the ANYELEMENT type must not be an array.
    1982             :  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
    1983             :  *    is an extra restriction if not.)
    1984             :  * 8) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, and ANYCOMPATIBLENONARRAY are handled
    1985             :  *    by resolving the common supertype of those arguments (or their element
    1986             :  *    types, for array inputs), and then coercing all those arguments to the
    1987             :  *    common supertype, or the array type over the common supertype for
    1988             :  *    ANYCOMPATIBLEARRAY.
    1989             :  * 9) For ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE, there must be at
    1990             :  *    least one non-UNKNOWN input matching those arguments, and all such
    1991             :  *    inputs must be the same range type (or its multirange type, as
    1992             :  *    appropriate), since we cannot deduce a range type from non-range types.
    1993             :  *    Furthermore, the range type's subtype is included while choosing the
    1994             :  *    common supertype for ANYCOMPATIBLE et al, and it must exactly match
    1995             :  *    that common supertype.
    1996             :  *
    1997             :  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
    1998             :  * respectively, and are immediately flattened to their base type.  (In
    1999             :  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
    2000             :  * it to the base type not the domain type.)  The same is true for
    2001             :  * ANYMULTIRANGE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLERANGE, and
    2002             :  * ANYCOMPATIBLEMULTIRANGE.
    2003             :  *
    2004             :  * When allow_poly is false, we are not expecting any of the actual_arg_types
    2005             :  * to be polymorphic, and we should not return a polymorphic result type
    2006             :  * either.  When allow_poly is true, it is okay to have polymorphic "actual"
    2007             :  * arg types, and we can return a matching polymorphic type as the result.
    2008             :  * (This case is currently used only to check compatibility of an aggregate's
    2009             :  * declaration with the underlying transfn.)
    2010             :  *
    2011             :  * A special case is that we could see ANYARRAY as an actual_arg_type even
    2012             :  * when allow_poly is false (this is possible only because pg_statistic has
    2013             :  * columns shown as anyarray in the catalogs).  We allow this to match a
    2014             :  * declared ANYARRAY argument, but only if there is no other polymorphic
    2015             :  * argument that we would need to match it with, and no need to determine
    2016             :  * the element type to infer the result type.  Note this means that functions
    2017             :  * taking ANYARRAY had better behave sanely if applied to the pg_statistic
    2018             :  * columns; they can't just assume that successive inputs are of the same
    2019             :  * actual element type.  There is no similar logic for ANYCOMPATIBLEARRAY;
    2020             :  * there isn't a need for it since there are no catalog columns of that type,
    2021             :  * so we won't see it as input.  We could consider matching an actual ANYARRAY
    2022             :  * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
    2023             :  * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
    2024             :  * at least one other ANYCOMPATIBLE-family argument or result.
    2025             :  *
    2026             :  * Also, if there are no arguments declared to be of polymorphic types,
    2027             :  * we'll return the rettype unmodified even if it's polymorphic.  This should
    2028             :  * never occur for user-declared functions, because CREATE FUNCTION prevents
    2029             :  * it.  But it does happen for some built-in functions, such as array_in().
    2030             :  */
    2031             : Oid
    2032     1806936 : enforce_generic_type_consistency(const Oid *actual_arg_types,
    2033             :                                  Oid *declared_arg_types,
    2034             :                                  int nargs,
    2035             :                                  Oid rettype,
    2036             :                                  bool allow_poly)
    2037             : {
    2038     1806936 :     bool        have_poly_anycompatible = false;
    2039     1806936 :     bool        have_poly_unknowns = false;
    2040     1806936 :     Oid         elem_typeid = InvalidOid;
    2041     1806936 :     Oid         array_typeid = InvalidOid;
    2042     1806936 :     Oid         range_typeid = InvalidOid;
    2043     1806936 :     Oid         multirange_typeid = InvalidOid;
    2044     1806936 :     Oid         anycompatible_typeid = InvalidOid;
    2045     1806936 :     Oid         anycompatible_array_typeid = InvalidOid;
    2046     1806936 :     Oid         anycompatible_range_typeid = InvalidOid;
    2047     1806936 :     Oid         anycompatible_range_typelem = InvalidOid;
    2048     1806936 :     Oid         anycompatible_multirange_typeid = InvalidOid;
    2049     1806936 :     Oid         anycompatible_multirange_typelem = InvalidOid;
    2050     1806936 :     bool        have_anynonarray = (rettype == ANYNONARRAYOID);
    2051     1806936 :     bool        have_anyenum = (rettype == ANYENUMOID);
    2052     1806936 :     bool        have_anymultirange = (rettype == ANYMULTIRANGEOID);
    2053     1806936 :     bool        have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
    2054     1806936 :     bool        have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
    2055     1806936 :     bool        have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
    2056     1806936 :     bool        have_anycompatible_multirange = (rettype == ANYCOMPATIBLEMULTIRANGEOID);
    2057     1806936 :     int         n_poly_args = 0;    /* this counts all family-1 arguments */
    2058     1806936 :     int         n_anycompatible_args = 0;   /* this counts only non-unknowns */
    2059             :     Oid         anycompatible_actual_types[FUNC_MAX_ARGS];
    2060             : 
    2061             :     /*
    2062             :      * Loop through the arguments to see if we have any that are polymorphic.
    2063             :      * If so, require the actual types to be consistent.
    2064             :      */
    2065             :     Assert(nargs <= FUNC_MAX_ARGS);
    2066     4988148 :     for (int j = 0; j < nargs; j++)
    2067             :     {
    2068     3181212 :         Oid         decl_type = declared_arg_types[j];
    2069     3181212 :         Oid         actual_type = actual_arg_types[j];
    2070             : 
    2071     3181212 :         if (decl_type == ANYELEMENTOID ||
    2072     3135940 :             decl_type == ANYNONARRAYOID ||
    2073             :             decl_type == ANYENUMOID)
    2074             :         {
    2075       45860 :             n_poly_args++;
    2076       45860 :             if (decl_type == ANYNONARRAYOID)
    2077       41658 :                 have_anynonarray = true;
    2078        4202 :             else if (decl_type == ANYENUMOID)
    2079         588 :                 have_anyenum = true;
    2080       45860 :             if (actual_type == UNKNOWNOID)
    2081             :             {
    2082         588 :                 have_poly_unknowns = true;
    2083         588 :                 continue;
    2084             :             }
    2085       45272 :             if (allow_poly && decl_type == actual_type)
    2086         132 :                 continue;       /* no new information here */
    2087       45140 :             if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
    2088           0 :                 ereport(ERROR,
    2089             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2090             :                          errmsg("arguments declared \"%s\" are not all alike", "anyelement"),
    2091             :                          errdetail("%s versus %s",
    2092             :                                    format_type_be(elem_typeid),
    2093             :                                    format_type_be(actual_type))));
    2094       45140 :             elem_typeid = actual_type;
    2095             :         }
    2096     3135352 :         else if (decl_type == ANYARRAYOID)
    2097             :         {
    2098       92476 :             n_poly_args++;
    2099       92476 :             if (actual_type == UNKNOWNOID)
    2100             :             {
    2101        2606 :                 have_poly_unknowns = true;
    2102        2606 :                 continue;
    2103             :             }
    2104       89870 :             if (allow_poly && decl_type == actual_type)
    2105          60 :                 continue;       /* no new information here */
    2106       89810 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2107       89810 :             if (OidIsValid(array_typeid) && actual_type != array_typeid)
    2108           0 :                 ereport(ERROR,
    2109             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2110             :                          errmsg("arguments declared \"%s\" are not all alike", "anyarray"),
    2111             :                          errdetail("%s versus %s",
    2112             :                                    format_type_be(array_typeid),
    2113             :                                    format_type_be(actual_type))));
    2114       89810 :             array_typeid = actual_type;
    2115             :         }
    2116     3042876 :         else if (decl_type == ANYRANGEOID)
    2117             :         {
    2118        2928 :             n_poly_args++;
    2119        2928 :             if (actual_type == UNKNOWNOID)
    2120             :             {
    2121          50 :                 have_poly_unknowns = true;
    2122          50 :                 continue;
    2123             :             }
    2124        2878 :             if (allow_poly && decl_type == actual_type)
    2125           0 :                 continue;       /* no new information here */
    2126        2878 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2127        2878 :             if (OidIsValid(range_typeid) && actual_type != range_typeid)
    2128           0 :                 ereport(ERROR,
    2129             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2130             :                          errmsg("arguments declared \"%s\" are not all alike", "anyrange"),
    2131             :                          errdetail("%s versus %s",
    2132             :                                    format_type_be(range_typeid),
    2133             :                                    format_type_be(actual_type))));
    2134        2878 :             range_typeid = actual_type;
    2135             :         }
    2136     3039948 :         else if (decl_type == ANYMULTIRANGEOID)
    2137             :         {
    2138        2572 :             n_poly_args++;
    2139        2572 :             have_anymultirange = true;
    2140        2572 :             if (actual_type == UNKNOWNOID)
    2141             :             {
    2142         176 :                 have_poly_unknowns = true;
    2143         176 :                 continue;
    2144             :             }
    2145        2396 :             if (allow_poly && decl_type == actual_type)
    2146           0 :                 continue;       /* no new information here */
    2147        2396 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2148        2396 :             if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
    2149           0 :                 ereport(ERROR,
    2150             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2151             :                          errmsg("arguments declared \"%s\" are not all alike", "anymultirange"),
    2152             :                          errdetail("%s versus %s",
    2153             :                                    format_type_be(multirange_typeid),
    2154             :                                    format_type_be(actual_type))));
    2155        2396 :             multirange_typeid = actual_type;
    2156             :         }
    2157     3037376 :         else if (decl_type == ANYCOMPATIBLEOID ||
    2158             :                  decl_type == ANYCOMPATIBLENONARRAYOID)
    2159             :         {
    2160        1244 :             have_poly_anycompatible = true;
    2161        1244 :             if (decl_type == ANYCOMPATIBLENONARRAYOID)
    2162          16 :                 have_anycompatible_nonarray = true;
    2163        1244 :             if (actual_type == UNKNOWNOID)
    2164         480 :                 continue;
    2165         764 :             if (allow_poly && decl_type == actual_type)
    2166           6 :                 continue;       /* no new information here */
    2167             :             /* collect the actual types of non-unknown COMPATIBLE args */
    2168         758 :             anycompatible_actual_types[n_anycompatible_args++] = actual_type;
    2169             :         }
    2170     3036132 :         else if (decl_type == ANYCOMPATIBLEARRAYOID)
    2171             :         {
    2172             :             Oid         anycompatible_elem_type;
    2173             : 
    2174        2652 :             have_poly_anycompatible = true;
    2175        2652 :             have_anycompatible_array = true;
    2176        2652 :             if (actual_type == UNKNOWNOID)
    2177          20 :                 continue;
    2178        2632 :             if (allow_poly && decl_type == actual_type)
    2179           6 :                 continue;       /* no new information here */
    2180        2626 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2181        2626 :             anycompatible_elem_type = get_element_type(actual_type);
    2182        2626 :             if (!OidIsValid(anycompatible_elem_type))
    2183           0 :                 ereport(ERROR,
    2184             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2185             :                          errmsg("argument declared %s is not an array but type %s",
    2186             :                                 "anycompatiblearray",
    2187             :                                 format_type_be(actual_type))));
    2188             :             /* collect the element type for common-supertype choice */
    2189        2626 :             anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
    2190             :         }
    2191     3033480 :         else if (decl_type == ANYCOMPATIBLERANGEOID)
    2192             :         {
    2193          92 :             have_poly_anycompatible = true;
    2194          92 :             have_anycompatible_range = true;
    2195          92 :             if (actual_type == UNKNOWNOID)
    2196           8 :                 continue;
    2197          84 :             if (allow_poly && decl_type == actual_type)
    2198           0 :                 continue;       /* no new information here */
    2199          84 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2200          84 :             if (OidIsValid(anycompatible_range_typeid))
    2201             :             {
    2202             :                 /* All ANYCOMPATIBLERANGE arguments must be the same type */
    2203           4 :                 if (anycompatible_range_typeid != actual_type)
    2204           0 :                     ereport(ERROR,
    2205             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2206             :                              errmsg("arguments declared \"%s\" are not all alike", "anycompatiblerange"),
    2207             :                              errdetail("%s versus %s",
    2208             :                                        format_type_be(anycompatible_range_typeid),
    2209             :                                        format_type_be(actual_type))));
    2210             :             }
    2211             :             else
    2212             :             {
    2213          80 :                 anycompatible_range_typeid = actual_type;
    2214          80 :                 anycompatible_range_typelem = get_range_subtype(actual_type);
    2215          80 :                 if (!OidIsValid(anycompatible_range_typelem))
    2216           0 :                     ereport(ERROR,
    2217             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2218             :                              errmsg("argument declared %s is not a range type but type %s",
    2219             :                                     "anycompatiblerange",
    2220             :                                     format_type_be(actual_type))));
    2221             :                 /* collect the subtype for common-supertype choice */
    2222          80 :                 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
    2223             :             }
    2224             :         }
    2225     3033388 :         else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
    2226             :         {
    2227          64 :             have_poly_anycompatible = true;
    2228          64 :             have_anycompatible_multirange = true;
    2229          64 :             if (actual_type == UNKNOWNOID)
    2230          12 :                 continue;
    2231          52 :             if (allow_poly && decl_type == actual_type)
    2232           0 :                 continue;       /* no new information here */
    2233          52 :             actual_type = getBaseType(actual_type); /* flatten domains */
    2234          52 :             if (OidIsValid(anycompatible_multirange_typeid))
    2235             :             {
    2236             :                 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
    2237           4 :                 if (anycompatible_multirange_typeid != actual_type)
    2238           0 :                     ereport(ERROR,
    2239             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2240             :                              errmsg("arguments declared \"%s\" are not all alike", "anycompatiblemultirange"),
    2241             :                              errdetail("%s versus %s",
    2242             :                                        format_type_be(anycompatible_multirange_typeid),
    2243             :                                        format_type_be(actual_type))));
    2244             :             }
    2245             :             else
    2246             :             {
    2247          48 :                 anycompatible_multirange_typeid = actual_type;
    2248          48 :                 anycompatible_multirange_typelem = get_multirange_range(actual_type);
    2249          48 :                 if (!OidIsValid(anycompatible_multirange_typelem))
    2250           0 :                     ereport(ERROR,
    2251             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2252             :                              errmsg("argument declared %s is not a multirange type but type %s",
    2253             :                                     "anycompatiblemultirange",
    2254             :                                     format_type_be(actual_type))));
    2255             :                 /* we'll consider the subtype below */
    2256             :             }
    2257             :         }
    2258             :     }
    2259             : 
    2260             :     /*
    2261             :      * Fast Track: if none of the arguments are polymorphic, return the
    2262             :      * unmodified rettype.  Not our job to resolve it if it's polymorphic.
    2263             :      */
    2264     1806936 :     if (n_poly_args == 0 && !have_poly_anycompatible)
    2265     1667902 :         return rettype;
    2266             : 
    2267             :     /* Check matching of family-1 polymorphic arguments, if any */
    2268      139034 :     if (n_poly_args)
    2269             :     {
    2270             :         /* Get the element type based on the array type, if we have one */
    2271      137030 :         if (OidIsValid(array_typeid))
    2272             :         {
    2273             :             Oid         array_typelem;
    2274             : 
    2275       89064 :             if (array_typeid == ANYARRAYOID)
    2276             :             {
    2277             :                 /*
    2278             :                  * Special case for matching ANYARRAY input to an ANYARRAY
    2279             :                  * argument: allow it iff no other arguments are family-1
    2280             :                  * polymorphics (otherwise we couldn't be sure whether the
    2281             :                  * array element type matches up) and the result type doesn't
    2282             :                  * require us to infer a specific element type.
    2283             :                  */
    2284          28 :                 if (n_poly_args != 1 ||
    2285          12 :                     (rettype != ANYARRAYOID &&
    2286           4 :                      IsPolymorphicTypeFamily1(rettype)))
    2287           8 :                     ereport(ERROR,
    2288             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2289             :                              errmsg("cannot determine element type of \"anyarray\" argument")));
    2290          20 :                 array_typelem = ANYELEMENTOID;
    2291             :             }
    2292             :             else
    2293             :             {
    2294       89036 :                 array_typelem = get_element_type(array_typeid);
    2295       89036 :                 if (!OidIsValid(array_typelem))
    2296           0 :                     ereport(ERROR,
    2297             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2298             :                              errmsg("argument declared %s is not an array but type %s",
    2299             :                                     "anyarray", format_type_be(array_typeid))));
    2300             :             }
    2301             : 
    2302       89056 :             if (!OidIsValid(elem_typeid))
    2303             :             {
    2304             :                 /*
    2305             :                  * if we don't have an element type yet, use the one we just
    2306             :                  * got
    2307             :                  */
    2308       89004 :                 elem_typeid = array_typelem;
    2309             :             }
    2310          52 :             else if (array_typelem != elem_typeid)
    2311             :             {
    2312             :                 /* otherwise, they better match */
    2313           0 :                 ereport(ERROR,
    2314             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2315             :                          errmsg("argument declared %s is not consistent with argument declared %s",
    2316             :                                 "anyarray", "anyelement"),
    2317             :                          errdetail("%s versus %s",
    2318             :                                    format_type_be(array_typeid),
    2319             :                                    format_type_be(elem_typeid))));
    2320             :             }
    2321             :         }
    2322             : 
    2323             :         /* Deduce range type from multirange type, or vice versa */
    2324      137022 :         if (OidIsValid(multirange_typeid))
    2325             :         {
    2326             :             Oid         multirange_typelem;
    2327             : 
    2328        1828 :             multirange_typelem = get_multirange_range(multirange_typeid);
    2329        1828 :             if (!OidIsValid(multirange_typelem))
    2330           0 :                 ereport(ERROR,
    2331             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2332             :                          errmsg("argument declared %s is not a multirange type but type %s",
    2333             :                                 "anymultirange",
    2334             :                                 format_type_be(multirange_typeid))));
    2335             : 
    2336        1828 :             if (!OidIsValid(range_typeid))
    2337             :             {
    2338             :                 /* if we don't have a range type yet, use the one we just got */
    2339        1048 :                 range_typeid = multirange_typelem;
    2340             :             }
    2341         780 :             else if (multirange_typelem != range_typeid)
    2342             :             {
    2343             :                 /* otherwise, they better match */
    2344           0 :                 ereport(ERROR,
    2345             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2346             :                          errmsg("argument declared %s is not consistent with argument declared %s",
    2347             :                                 "anymultirange", "anyrange"),
    2348             :                          errdetail("%s versus %s",
    2349             :                                    format_type_be(multirange_typeid),
    2350             :                                    format_type_be(range_typeid))));
    2351             :             }
    2352             :         }
    2353      135194 :         else if (have_anymultirange && OidIsValid(range_typeid))
    2354             :         {
    2355         100 :             multirange_typeid = get_range_multirange(range_typeid);
    2356             :             /* We'll complain below if that didn't work */
    2357             :         }
    2358             : 
    2359             :         /* Get the element type based on the range type, if we have one */
    2360      137022 :         if (OidIsValid(range_typeid))
    2361             :         {
    2362             :             Oid         range_typelem;
    2363             : 
    2364        3180 :             range_typelem = get_range_subtype(range_typeid);
    2365        3180 :             if (!OidIsValid(range_typelem))
    2366           0 :                 ereport(ERROR,
    2367             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2368             :                          errmsg("argument declared %s is not a range type but type %s",
    2369             :                                 "anyrange",
    2370             :                                 format_type_be(range_typeid))));
    2371             : 
    2372        3180 :             if (!OidIsValid(elem_typeid))
    2373             :             {
    2374             :                 /*
    2375             :                  * if we don't have an element type yet, use the one we just
    2376             :                  * got
    2377             :                  */
    2378        3012 :                 elem_typeid = range_typelem;
    2379             :             }
    2380         168 :             else if (range_typelem != elem_typeid)
    2381             :             {
    2382             :                 /* otherwise, they better match */
    2383           0 :                 ereport(ERROR,
    2384             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2385             :                          errmsg("argument declared %s is not consistent with argument declared %s",
    2386             :                                 "anyrange", "anyelement"),
    2387             :                          errdetail("%s versus %s",
    2388             :                                    format_type_be(range_typeid),
    2389             :                                    format_type_be(elem_typeid))));
    2390             :             }
    2391             :         }
    2392             : 
    2393      137022 :         if (!OidIsValid(elem_typeid))
    2394             :         {
    2395         154 :             if (allow_poly)
    2396             :             {
    2397         138 :                 elem_typeid = ANYELEMENTOID;
    2398         138 :                 array_typeid = ANYARRAYOID;
    2399         138 :                 range_typeid = ANYRANGEOID;
    2400         138 :                 multirange_typeid = ANYMULTIRANGEOID;
    2401             :             }
    2402             :             else
    2403             :             {
    2404             :                 /*
    2405             :                  * Only way to get here is if all the family-1 polymorphic
    2406             :                  * arguments have UNKNOWN inputs.
    2407             :                  */
    2408          16 :                 ereport(ERROR,
    2409             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2410             :                          errmsg("could not determine polymorphic type because input has type %s",
    2411             :                                 "unknown")));
    2412             :             }
    2413             :         }
    2414             : 
    2415      137006 :         if (have_anynonarray && elem_typeid != ANYELEMENTOID)
    2416             :         {
    2417             :             /*
    2418             :              * require the element type to not be an array or domain over
    2419             :              * array
    2420             :              */
    2421       41306 :             if (type_is_array_domain(elem_typeid))
    2422           0 :                 ereport(ERROR,
    2423             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2424             :                          errmsg("type matched to anynonarray is an array type: %s",
    2425             :                                 format_type_be(elem_typeid))));
    2426             :         }
    2427             : 
    2428      137006 :         if (have_anyenum && elem_typeid != ANYELEMENTOID)
    2429             :         {
    2430             :             /* require the element type to be an enum */
    2431         396 :             if (!type_is_enum(elem_typeid))
    2432           0 :                 ereport(ERROR,
    2433             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2434             :                          errmsg("type matched to anyenum is not an enum type: %s",
    2435             :                                 format_type_be(elem_typeid))));
    2436             :         }
    2437             :     }
    2438             : 
    2439             :     /* Check matching of family-2 polymorphic arguments, if any */
    2440      139010 :     if (have_poly_anycompatible)
    2441             :     {
    2442             :         /* Deduce range type from multirange type, or vice versa */
    2443        2040 :         if (OidIsValid(anycompatible_multirange_typeid))
    2444             :         {
    2445          48 :             if (OidIsValid(anycompatible_range_typeid))
    2446             :             {
    2447           4 :                 if (anycompatible_multirange_typelem !=
    2448             :                     anycompatible_range_typeid)
    2449           0 :                     ereport(ERROR,
    2450             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2451             :                              errmsg("argument declared %s is not consistent with argument declared %s",
    2452             :                                     "anycompatiblemultirange",
    2453             :                                     "anycompatiblerange"),
    2454             :                              errdetail("%s versus %s",
    2455             :                                        format_type_be(anycompatible_multirange_typeid),
    2456             :                                        format_type_be(anycompatible_range_typeid))));
    2457             :             }
    2458             :             else
    2459             :             {
    2460          44 :                 anycompatible_range_typeid = anycompatible_multirange_typelem;
    2461          44 :                 anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
    2462          44 :                 if (!OidIsValid(anycompatible_range_typelem))
    2463           0 :                     ereport(ERROR,
    2464             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2465             :                              errmsg("argument declared %s is not a multirange type but type %s",
    2466             :                                     "anycompatiblemultirange",
    2467             :                                     format_type_be(anycompatible_multirange_typeid))));
    2468             :                 /* this enables element type matching check below */
    2469          44 :                 have_anycompatible_range = true;
    2470             :                 /* collect the subtype for common-supertype choice */
    2471          44 :                 anycompatible_actual_types[n_anycompatible_args++] =
    2472             :                     anycompatible_range_typelem;
    2473             :             }
    2474             :         }
    2475        1992 :         else if (have_anycompatible_multirange &&
    2476             :                  OidIsValid(anycompatible_range_typeid))
    2477             :         {
    2478           4 :             anycompatible_multirange_typeid = get_range_multirange(anycompatible_range_typeid);
    2479             :             /* We'll complain below if that didn't work */
    2480             :         }
    2481             : 
    2482        2040 :         if (n_anycompatible_args > 0)
    2483             :         {
    2484             :             anycompatible_typeid =
    2485        2018 :                 select_common_type_from_oids(n_anycompatible_args,
    2486             :                                              anycompatible_actual_types,
    2487             :                                              false);
    2488             : 
    2489        2018 :             if (have_anycompatible_array)
    2490             :             {
    2491        1886 :                 anycompatible_array_typeid = get_array_type(anycompatible_typeid);
    2492        1886 :                 if (!OidIsValid(anycompatible_array_typeid))
    2493           0 :                     ereport(ERROR,
    2494             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
    2495             :                              errmsg("could not find array type for data type %s",
    2496             :                                     format_type_be(anycompatible_typeid))));
    2497             :             }
    2498             : 
    2499        2018 :             if (have_anycompatible_range)
    2500             :             {
    2501             :                 /* we can't infer a range type from the others */
    2502         128 :                 if (!OidIsValid(anycompatible_range_typeid))
    2503           4 :                     ereport(ERROR,
    2504             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2505             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2506             :                                     "anycompatiblerange", "unknown")));
    2507             : 
    2508             :                 /*
    2509             :                  * the anycompatible type must exactly match the range element
    2510             :                  * type
    2511             :                  */
    2512         124 :                 if (anycompatible_range_typelem != anycompatible_typeid)
    2513           0 :                     ereport(ERROR,
    2514             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2515             :                              errmsg("anycompatiblerange type %s does not match anycompatible type %s",
    2516             :                                     format_type_be(anycompatible_range_typeid),
    2517             :                                     format_type_be(anycompatible_typeid))));
    2518             :             }
    2519             : 
    2520        2014 :             if (have_anycompatible_multirange)
    2521             :             {
    2522             :                 /* we can't infer a multirange type from the others */
    2523          56 :                 if (!OidIsValid(anycompatible_multirange_typeid))
    2524           4 :                     ereport(ERROR,
    2525             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2526             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2527             :                                     "anycompatiblemultirange", "unknown")));
    2528             : 
    2529             :                 /*
    2530             :                  * the anycompatible type must exactly match the multirange
    2531             :                  * element type
    2532             :                  */
    2533          52 :                 if (anycompatible_range_typelem != anycompatible_typeid)
    2534           0 :                     ereport(ERROR,
    2535             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2536             :                              errmsg("anycompatiblemultirange type %s does not match anycompatible type %s",
    2537             :                                     format_type_be(anycompatible_multirange_typeid),
    2538             :                                     format_type_be(anycompatible_typeid))));
    2539             :             }
    2540             : 
    2541        2010 :             if (have_anycompatible_nonarray)
    2542             :             {
    2543             :                 /*
    2544             :                  * require the element type to not be an array or domain over
    2545             :                  * array
    2546             :                  */
    2547           8 :                 if (type_is_array_domain(anycompatible_typeid))
    2548           0 :                     ereport(ERROR,
    2549             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2550             :                              errmsg("type matched to anycompatiblenonarray is an array type: %s",
    2551             :                                     format_type_be(anycompatible_typeid))));
    2552             :             }
    2553             :         }
    2554             :         else
    2555             :         {
    2556          22 :             if (allow_poly)
    2557             :             {
    2558           6 :                 anycompatible_typeid = ANYCOMPATIBLEOID;
    2559           6 :                 anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
    2560           6 :                 anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
    2561           6 :                 anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
    2562             :             }
    2563             :             else
    2564             :             {
    2565             :                 /*
    2566             :                  * Only way to get here is if all the family-2 polymorphic
    2567             :                  * arguments have UNKNOWN inputs.  Resolve to TEXT as
    2568             :                  * select_common_type() would do.  That doesn't license us to
    2569             :                  * use TEXTRANGE or TEXTMULTIRANGE, though.
    2570             :                  */
    2571          16 :                 anycompatible_typeid = TEXTOID;
    2572          16 :                 anycompatible_array_typeid = TEXTARRAYOID;
    2573          16 :                 if (have_anycompatible_range)
    2574           8 :                     ereport(ERROR,
    2575             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2576             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2577             :                                     "anycompatiblerange", "unknown")));
    2578           8 :                 if (have_anycompatible_multirange)
    2579           4 :                     ereport(ERROR,
    2580             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2581             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2582             :                                     "anycompatiblemultirange", "unknown")));
    2583             :             }
    2584             :         }
    2585             : 
    2586             :         /* replace family-2 polymorphic types by selected types */
    2587        6136 :         for (int j = 0; j < nargs; j++)
    2588             :         {
    2589        4116 :             Oid         decl_type = declared_arg_types[j];
    2590             : 
    2591        4116 :             if (decl_type == ANYCOMPATIBLEOID ||
    2592             :                 decl_type == ANYCOMPATIBLENONARRAYOID)
    2593        1236 :                 declared_arg_types[j] = anycompatible_typeid;
    2594        2880 :             else if (decl_type == ANYCOMPATIBLEARRAYOID)
    2595        2652 :                 declared_arg_types[j] = anycompatible_array_typeid;
    2596         228 :             else if (decl_type == ANYCOMPATIBLERANGEOID)
    2597          84 :                 declared_arg_types[j] = anycompatible_range_typeid;
    2598         144 :             else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
    2599          52 :                 declared_arg_types[j] = anycompatible_multirange_typeid;
    2600             :         }
    2601             :     }
    2602             : 
    2603             :     /*
    2604             :      * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
    2605             :      * re-scan to assign correct types to them.
    2606             :      *
    2607             :      * Note: we don't have to consider unknown inputs that were matched to
    2608             :      * family-2 polymorphic arguments, because we forcibly updated their
    2609             :      * declared_arg_types[] positions just above.
    2610             :      */
    2611      138990 :     if (have_poly_unknowns)
    2612             :     {
    2613       10992 :         for (int j = 0; j < nargs; j++)
    2614             :         {
    2615        7592 :             Oid         decl_type = declared_arg_types[j];
    2616        7592 :             Oid         actual_type = actual_arg_types[j];
    2617             : 
    2618        7592 :             if (actual_type != UNKNOWNOID)
    2619        3552 :                 continue;
    2620             : 
    2621        4040 :             if (decl_type == ANYELEMENTOID ||
    2622        3578 :                 decl_type == ANYNONARRAYOID ||
    2623             :                 decl_type == ANYENUMOID)
    2624         584 :                 declared_arg_types[j] = elem_typeid;
    2625        3456 :             else if (decl_type == ANYARRAYOID)
    2626             :             {
    2627        2606 :                 if (!OidIsValid(array_typeid))
    2628             :                 {
    2629          12 :                     array_typeid = get_array_type(elem_typeid);
    2630          12 :                     if (!OidIsValid(array_typeid))
    2631           0 :                         ereport(ERROR,
    2632             :                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    2633             :                                  errmsg("could not find array type for data type %s",
    2634             :                                         format_type_be(elem_typeid))));
    2635             :                 }
    2636        2606 :                 declared_arg_types[j] = array_typeid;
    2637             :             }
    2638         850 :             else if (decl_type == ANYRANGEOID)
    2639             :             {
    2640          46 :                 if (!OidIsValid(range_typeid))
    2641             :                 {
    2642             :                     /* we can't infer a range type from the others */
    2643           0 :                     ereport(ERROR,
    2644             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2645             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2646             :                                     "anyrange", "unknown")));
    2647             :                 }
    2648          46 :                 declared_arg_types[j] = range_typeid;
    2649             :             }
    2650         804 :             else if (decl_type == ANYMULTIRANGEOID)
    2651             :             {
    2652         168 :                 if (!OidIsValid(multirange_typeid))
    2653             :                 {
    2654             :                     /* we can't infer a multirange type from the others */
    2655           0 :                     ereport(ERROR,
    2656             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    2657             :                              errmsg("could not determine polymorphic type %s because input has type %s",
    2658             :                                     "anymultirange", "unknown")));
    2659             :                 }
    2660         168 :                 declared_arg_types[j] = multirange_typeid;
    2661             :             }
    2662             :         }
    2663             :     }
    2664             : 
    2665             :     /* if we return ANYELEMENT use the appropriate argument type */
    2666      138990 :     if (rettype == ANYELEMENTOID ||
    2667      117462 :         rettype == ANYNONARRAYOID ||
    2668             :         rettype == ANYENUMOID)
    2669       21680 :         return elem_typeid;
    2670             : 
    2671             :     /* if we return ANYARRAY use the appropriate argument type */
    2672      117310 :     if (rettype == ANYARRAYOID)
    2673             :     {
    2674       42220 :         if (!OidIsValid(array_typeid))
    2675             :         {
    2676       40770 :             array_typeid = get_array_type(elem_typeid);
    2677       40770 :             if (!OidIsValid(array_typeid))
    2678           0 :                 ereport(ERROR,
    2679             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    2680             :                          errmsg("could not find array type for data type %s",
    2681             :                                 format_type_be(elem_typeid))));
    2682             :         }
    2683       42220 :         return array_typeid;
    2684             :     }
    2685             : 
    2686             :     /* if we return ANYRANGE use the appropriate argument type */
    2687       75090 :     if (rettype == ANYRANGEOID)
    2688             :     {
    2689             :         /* this error is unreachable if the function signature is valid: */
    2690         120 :         if (!OidIsValid(range_typeid))
    2691           0 :             ereport(ERROR,
    2692             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2693             :                      errmsg_internal("could not determine polymorphic type %s because input has type %s",
    2694             :                                      "anyrange", "unknown")));
    2695         120 :         return range_typeid;
    2696             :     }
    2697             : 
    2698             :     /* if we return ANYMULTIRANGE use the appropriate argument type */
    2699       74970 :     if (rettype == ANYMULTIRANGEOID)
    2700             :     {
    2701             :         /* this error is unreachable if the function signature is valid: */
    2702         304 :         if (!OidIsValid(multirange_typeid))
    2703           0 :             ereport(ERROR,
    2704             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2705             :                      errmsg_internal("could not determine polymorphic type %s because input has type %s",
    2706             :                                      "anymultirange", "unknown")));
    2707         304 :         return multirange_typeid;
    2708             :     }
    2709             : 
    2710             :     /* if we return ANYCOMPATIBLE use the appropriate type */
    2711       74666 :     if (rettype == ANYCOMPATIBLEOID ||
    2712             :         rettype == ANYCOMPATIBLENONARRAYOID)
    2713             :     {
    2714             :         /* this error is unreachable if the function signature is valid: */
    2715         106 :         if (!OidIsValid(anycompatible_typeid))
    2716           0 :             ereport(ERROR,
    2717             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2718             :                      errmsg_internal("could not identify anycompatible type")));
    2719         106 :         return anycompatible_typeid;
    2720             :     }
    2721             : 
    2722             :     /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
    2723       74560 :     if (rettype == ANYCOMPATIBLEARRAYOID)
    2724             :     {
    2725             :         /* this error is unreachable if the function signature is valid: */
    2726        1658 :         if (!OidIsValid(anycompatible_array_typeid))
    2727           0 :             ereport(ERROR,
    2728             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2729             :                      errmsg_internal("could not identify anycompatiblearray type")));
    2730        1658 :         return anycompatible_array_typeid;
    2731             :     }
    2732             : 
    2733             :     /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
    2734       72902 :     if (rettype == ANYCOMPATIBLERANGEOID)
    2735             :     {
    2736             :         /* this error is unreachable if the function signature is valid: */
    2737          28 :         if (!OidIsValid(anycompatible_range_typeid))
    2738           0 :             ereport(ERROR,
    2739             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2740             :                      errmsg_internal("could not identify anycompatiblerange type")));
    2741          28 :         return anycompatible_range_typeid;
    2742             :     }
    2743             : 
    2744             :     /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
    2745       72874 :     if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
    2746             :     {
    2747             :         /* this error is unreachable if the function signature is valid: */
    2748          20 :         if (!OidIsValid(anycompatible_multirange_typeid))
    2749           0 :             ereport(ERROR,
    2750             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2751             :                      errmsg_internal("could not identify anycompatiblemultirange type")));
    2752          20 :         return anycompatible_multirange_typeid;
    2753             :     }
    2754             : 
    2755             :     /* we don't return a generic type; send back the original return type */
    2756       72854 :     return rettype;
    2757             : }
    2758             : 
    2759             : /*
    2760             :  * check_valid_polymorphic_signature()
    2761             :  *      Is a proposed function signature valid per polymorphism rules?
    2762             :  *
    2763             :  * Returns NULL if the signature is valid (either ret_type is not polymorphic,
    2764             :  * or it can be deduced from the given declared argument types).  Otherwise,
    2765             :  * returns a palloc'd, already translated errdetail string saying why not.
    2766             :  */
    2767             : char *
    2768       75602 : check_valid_polymorphic_signature(Oid ret_type,
    2769             :                                   const Oid *declared_arg_types,
    2770             :                                   int nargs)
    2771             : {
    2772       75602 :     if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
    2773             :     {
    2774             :         /*
    2775             :          * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
    2776             :          * input, else we can't tell which of several range types with the
    2777             :          * same element type to use.
    2778             :          */
    2779         158 :         for (int i = 0; i < nargs; i++)
    2780             :         {
    2781         110 :             if (declared_arg_types[i] == ANYRANGEOID ||
    2782          82 :                 declared_arg_types[i] == ANYMULTIRANGEOID)
    2783          56 :                 return NULL;    /* OK */
    2784             :         }
    2785          48 :         return psprintf(_("A result of type %s requires at least one input of type anyrange or anymultirange."),
    2786             :                         format_type_be(ret_type));
    2787             :     }
    2788       75498 :     else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
    2789             :     {
    2790             :         /*
    2791             :          * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
    2792             :          * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
    2793             :          * tell which of several range types with the same element type to
    2794             :          * use.
    2795             :          */
    2796          96 :         for (int i = 0; i < nargs; i++)
    2797             :         {
    2798          68 :             if (declared_arg_types[i] == ANYCOMPATIBLERANGEOID ||
    2799          48 :                 declared_arg_types[i] == ANYCOMPATIBLEMULTIRANGEOID)
    2800          32 :                 return NULL;    /* OK */
    2801             :         }
    2802          28 :         return psprintf(_("A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
    2803             :                         format_type_be(ret_type));
    2804             :     }
    2805       75438 :     else if (IsPolymorphicTypeFamily1(ret_type))
    2806             :     {
    2807             :         /* Otherwise, any family-1 type can be deduced from any other */
    2808        2084 :         for (int i = 0; i < nargs; i++)
    2809             :         {
    2810        2008 :             if (IsPolymorphicTypeFamily1(declared_arg_types[i]))
    2811        1938 :                 return NULL;    /* OK */
    2812             :         }
    2813             :         /* Keep this list in sync with IsPolymorphicTypeFamily1! */
    2814          76 :         return psprintf(_("A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
    2815             :                         format_type_be(ret_type));
    2816             :     }
    2817       73424 :     else if (IsPolymorphicTypeFamily2(ret_type))
    2818             :     {
    2819             :         /* Otherwise, any family-2 type can be deduced from any other */
    2820         160 :         for (int i = 0; i < nargs; i++)
    2821             :         {
    2822         156 :             if (IsPolymorphicTypeFamily2(declared_arg_types[i]))
    2823         128 :                 return NULL;    /* OK */
    2824             :         }
    2825             :         /* Keep this list in sync with IsPolymorphicTypeFamily2! */
    2826           4 :         return psprintf(_("A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, anycompatiblerange, or anycompatiblemultirange."),
    2827             :                         format_type_be(ret_type));
    2828             :     }
    2829             :     else
    2830       73292 :         return NULL;            /* OK, ret_type is not polymorphic */
    2831             : }
    2832             : 
    2833             : /*
    2834             :  * check_valid_internal_signature()
    2835             :  *      Is a proposed function signature valid per INTERNAL safety rules?
    2836             :  *
    2837             :  * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
    2838             :  * none of the declared arg types are.  (It's unsafe to create such a function
    2839             :  * since it would allow invocation of INTERNAL-consuming functions directly
    2840             :  * from SQL.)  It's overkill to return the error detail message, since there
    2841             :  * is only one possibility, but we do it like this to keep the API similar to
    2842             :  * check_valid_polymorphic_signature().
    2843             :  */
    2844             : char *
    2845       74858 : check_valid_internal_signature(Oid ret_type,
    2846             :                                const Oid *declared_arg_types,
    2847             :                                int nargs)
    2848             : {
    2849       74858 :     if (ret_type == INTERNALOID)
    2850             :     {
    2851        1862 :         for (int i = 0; i < nargs; i++)
    2852             :         {
    2853        1862 :             if (declared_arg_types[i] == ret_type)
    2854        1560 :                 return NULL;    /* OK */
    2855             :         }
    2856           0 :         return pstrdup(_("A result of type internal requires at least one input of type internal."));
    2857             :     }
    2858             :     else
    2859       73298 :         return NULL;            /* OK, ret_type is not INTERNAL */
    2860             : }
    2861             : 
    2862             : 
    2863             : /* TypeCategory()
    2864             :  *      Assign a category to the specified type OID.
    2865             :  *
    2866             :  * NB: this must not return TYPCATEGORY_INVALID.
    2867             :  */
    2868             : TYPCATEGORY
    2869      250736 : TypeCategory(Oid type)
    2870             : {
    2871             :     char        typcategory;
    2872             :     bool        typispreferred;
    2873             : 
    2874      250736 :     get_type_category_preferred(type, &typcategory, &typispreferred);
    2875             :     Assert(typcategory != TYPCATEGORY_INVALID);
    2876      250736 :     return (TYPCATEGORY) typcategory;
    2877             : }
    2878             : 
    2879             : 
    2880             : /* IsPreferredType()
    2881             :  *      Check if this type is a preferred type for the given category.
    2882             :  *
    2883             :  * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
    2884             :  * types of any category; otherwise, only for preferred types of that
    2885             :  * category.
    2886             :  */
    2887             : bool
    2888       43338 : IsPreferredType(TYPCATEGORY category, Oid type)
    2889             : {
    2890             :     char        typcategory;
    2891             :     bool        typispreferred;
    2892             : 
    2893       43338 :     get_type_category_preferred(type, &typcategory, &typispreferred);
    2894       43338 :     if (category == typcategory || category == TYPCATEGORY_INVALID)
    2895       30624 :         return typispreferred;
    2896             :     else
    2897       12714 :         return false;
    2898             : }
    2899             : 
    2900             : 
    2901             : /* IsBinaryCoercible()
    2902             :  *      Check if srctype is binary-coercible to targettype.
    2903             :  *
    2904             :  * This notion allows us to cheat and directly exchange values without
    2905             :  * going through the trouble of calling a conversion function.  Note that
    2906             :  * in general, this should only be an implementation shortcut.  Before 7.4,
    2907             :  * this was also used as a heuristic for resolving overloaded functions and
    2908             :  * operators, but that's basically a bad idea.
    2909             :  *
    2910             :  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
    2911             :  * We consider two types binary-coercible if there is an implicitly
    2912             :  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
    2913             :  * binary-coercible to its base type, though *not* vice versa (in the other
    2914             :  * direction, one must apply domain constraint checks before accepting the
    2915             :  * value as legitimate).  We also need to special-case various polymorphic
    2916             :  * types.
    2917             :  *
    2918             :  * This function replaces IsBinaryCompatible(), which was an inherently
    2919             :  * symmetric test.  Since the pg_cast entries aren't necessarily symmetric,
    2920             :  * the order of the operands is now significant.
    2921             :  */
    2922             : bool
    2923     4794170 : IsBinaryCoercible(Oid srctype, Oid targettype)
    2924             : {
    2925             :     HeapTuple   tuple;
    2926             :     Form_pg_cast castForm;
    2927             :     bool        result;
    2928             : 
    2929             :     /* Fast path if same type */
    2930     4794170 :     if (srctype == targettype)
    2931     1102298 :         return true;
    2932             : 
    2933             :     /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
    2934     3691872 :     if (targettype == ANYOID || targettype == ANYELEMENTOID ||
    2935             :         targettype == ANYCOMPATIBLEOID)
    2936         152 :         return true;
    2937             : 
    2938             :     /* If srctype is a domain, reduce to its base type */
    2939     3691720 :     if (OidIsValid(srctype))
    2940     3691720 :         srctype = getBaseType(srctype);
    2941             : 
    2942             :     /* Somewhat-fast path for domain -> base type case */
    2943     3691720 :     if (srctype == targettype)
    2944           8 :         return true;
    2945             : 
    2946             :     /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
    2947     3691712 :     if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
    2948      180824 :         if (type_is_array(srctype))
    2949        6530 :             return true;
    2950             : 
    2951             :     /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
    2952     3685182 :     if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
    2953           0 :         if (!type_is_array(srctype))
    2954           0 :             return true;
    2955             : 
    2956             :     /* Also accept any enum type as coercible to ANYENUM */
    2957     3685182 :     if (targettype == ANYENUMOID)
    2958      173184 :         if (type_is_enum(srctype))
    2959          86 :             return true;
    2960             : 
    2961             :     /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
    2962     3685096 :     if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
    2963       23082 :         if (type_is_range(srctype))
    2964         332 :             return true;
    2965             : 
    2966             :     /* Also, any multirange type is coercible to ANY[COMPATIBLE]MULTIRANGE */
    2967     3684764 :     if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
    2968      135560 :         if (type_is_multirange(srctype))
    2969          40 :             return true;
    2970             : 
    2971             :     /* Also accept any composite type as coercible to RECORD */
    2972     3684724 :     if (targettype == RECORDOID)
    2973       22510 :         if (ISCOMPLEX(srctype))
    2974        1342 :             return true;
    2975             : 
    2976             :     /* Also accept any composite array type as coercible to RECORD[] */
    2977     3683382 :     if (targettype == RECORDARRAYOID)
    2978           0 :         if (is_complex_array(srctype))
    2979           0 :             return true;
    2980             : 
    2981             :     /* Else look in pg_cast */
    2982     3683382 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    2983             :                             ObjectIdGetDatum(srctype),
    2984             :                             ObjectIdGetDatum(targettype));
    2985     3683382 :     if (!HeapTupleIsValid(tuple))
    2986     3249902 :         return false;           /* no cast */
    2987      433480 :     castForm = (Form_pg_cast) GETSTRUCT(tuple);
    2988             : 
    2989      537204 :     result = (castForm->castmethod == COERCION_METHOD_BINARY &&
    2990      103724 :               castForm->castcontext == COERCION_CODE_IMPLICIT);
    2991             : 
    2992      433480 :     ReleaseSysCache(tuple);
    2993             : 
    2994      433480 :     return result;
    2995             : }
    2996             : 
    2997             : 
    2998             : /*
    2999             :  * find_coercion_pathway
    3000             :  *      Look for a coercion pathway between two types.
    3001             :  *
    3002             :  * Currently, this deals only with scalar-type cases; it does not consider
    3003             :  * polymorphic types nor casts between composite types.  (Perhaps fold
    3004             :  * those in someday?)
    3005             :  *
    3006             :  * ccontext determines the set of available casts.
    3007             :  *
    3008             :  * The possible result codes are:
    3009             :  *  COERCION_PATH_NONE: failed to find any coercion pathway
    3010             :  *              *funcid is set to InvalidOid
    3011             :  *  COERCION_PATH_FUNC: apply the coercion function returned in *funcid
    3012             :  *  COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
    3013             :  *              *funcid is set to InvalidOid
    3014             :  *  COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
    3015             :  *              *funcid is set to InvalidOid
    3016             :  *  COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
    3017             :  *              *funcid is set to InvalidOid
    3018             :  *
    3019             :  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
    3020             :  * needed to do the coercion; if the target is a domain then we may need to
    3021             :  * apply domain constraint checking.  If you want to check for a zero-effort
    3022             :  * conversion then use IsBinaryCoercible().
    3023             :  */
    3024             : CoercionPathType
    3025     2007790 : find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
    3026             :                       CoercionContext ccontext,
    3027             :                       Oid *funcid)
    3028             : {
    3029     2007790 :     CoercionPathType result = COERCION_PATH_NONE;
    3030             :     HeapTuple   tuple;
    3031             : 
    3032     2007790 :     *funcid = InvalidOid;
    3033             : 
    3034             :     /* Perhaps the types are domains; if so, look at their base types */
    3035     2007790 :     if (OidIsValid(sourceTypeId))
    3036     2007790 :         sourceTypeId = getBaseType(sourceTypeId);
    3037     2007790 :     if (OidIsValid(targetTypeId))
    3038     2007790 :         targetTypeId = getBaseType(targetTypeId);
    3039             : 
    3040             :     /* Domains are always coercible to and from their base type */
    3041     2007790 :     if (sourceTypeId == targetTypeId)
    3042      407078 :         return COERCION_PATH_RELABELTYPE;
    3043             : 
    3044             :     /* Look in pg_cast */
    3045     1600712 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    3046             :                             ObjectIdGetDatum(sourceTypeId),
    3047             :                             ObjectIdGetDatum(targetTypeId));
    3048             : 
    3049     1600712 :     if (HeapTupleIsValid(tuple))
    3050             :     {
    3051      709760 :         Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
    3052             :         CoercionContext castcontext;
    3053             : 
    3054             :         /* convert char value for castcontext to CoercionContext enum */
    3055      709760 :         switch (castForm->castcontext)
    3056             :         {
    3057      522096 :             case COERCION_CODE_IMPLICIT:
    3058      522096 :                 castcontext = COERCION_IMPLICIT;
    3059      522096 :                 break;
    3060      180528 :             case COERCION_CODE_ASSIGNMENT:
    3061      180528 :                 castcontext = COERCION_ASSIGNMENT;
    3062      180528 :                 break;
    3063        7136 :             case COERCION_CODE_EXPLICIT:
    3064        7136 :                 castcontext = COERCION_EXPLICIT;
    3065        7136 :                 break;
    3066           0 :             default:
    3067           0 :                 elog(ERROR, "unrecognized castcontext: %d",
    3068             :                      (int) castForm->castcontext);
    3069             :                 castcontext = 0;    /* keep compiler quiet */
    3070             :                 break;
    3071             :         }
    3072             : 
    3073             :         /* Rely on ordering of enum for correct behavior here */
    3074      709760 :         if (ccontext >= castcontext)
    3075             :         {
    3076      601260 :             switch (castForm->castmethod)
    3077             :             {
    3078      233532 :                 case COERCION_METHOD_FUNCTION:
    3079      233532 :                     result = COERCION_PATH_FUNC;
    3080      233532 :                     *funcid = castForm->castfunc;
    3081      233532 :                     break;
    3082          20 :                 case COERCION_METHOD_INOUT:
    3083          20 :                     result = COERCION_PATH_COERCEVIAIO;
    3084          20 :                     break;
    3085      367708 :                 case COERCION_METHOD_BINARY:
    3086      367708 :                     result = COERCION_PATH_RELABELTYPE;
    3087      367708 :                     break;
    3088           0 :                 default:
    3089           0 :                     elog(ERROR, "unrecognized castmethod: %d",
    3090             :                          (int) castForm->castmethod);
    3091             :                     break;
    3092             :             }
    3093      108500 :         }
    3094             : 
    3095      709760 :         ReleaseSysCache(tuple);
    3096             :     }
    3097             :     else
    3098             :     {
    3099             :         /*
    3100             :          * If there's no pg_cast entry, perhaps we are dealing with a pair of
    3101             :          * array types.  If so, and if their element types have a conversion
    3102             :          * pathway, report that we can coerce with an ArrayCoerceExpr.
    3103             :          *
    3104             :          * Hack: disallow coercions to oidvector and int2vector, which
    3105             :          * otherwise tend to capture coercions that should go to "real" array
    3106             :          * types.  We want those types to be considered "real" arrays for many
    3107             :          * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
    3108             :          * guaranteed to produce an output that meets the restrictions of
    3109             :          * these datatypes, such as being 1-dimensional.)
    3110             :          */
    3111      890952 :         if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
    3112             :         {
    3113             :             Oid         targetElem;
    3114             :             Oid         sourceElem;
    3115             : 
    3116      883124 :             if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
    3117        5926 :                 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
    3118             :             {
    3119             :                 CoercionPathType elempathtype;
    3120             :                 Oid         elemfuncid;
    3121             : 
    3122        5276 :                 elempathtype = find_coercion_pathway(targetElem,
    3123             :                                                      sourceElem,
    3124             :                                                      ccontext,
    3125             :                                                      &elemfuncid);
    3126        5276 :                 if (elempathtype != COERCION_PATH_NONE)
    3127             :                 {
    3128        5168 :                     result = COERCION_PATH_ARRAYCOERCE;
    3129             :                 }
    3130             :             }
    3131             :         }
    3132             : 
    3133             :         /*
    3134             :          * If we still haven't found a possibility, consider automatic casting
    3135             :          * using I/O functions.  We allow assignment casts to string types and
    3136             :          * explicit casts from string types to be handled this way. (The
    3137             :          * CoerceViaIO mechanism is a lot more general than that, but this is
    3138             :          * all we want to allow in the absence of a pg_cast entry.) It would
    3139             :          * probably be better to insist on explicit casts in both directions,
    3140             :          * but this is a compromise to preserve something of the pre-8.3
    3141             :          * behavior that many types had implicit (yipes!) casts to text.
    3142             :          */
    3143      890952 :         if (result == COERCION_PATH_NONE)
    3144             :         {
    3145      928734 :             if (ccontext >= COERCION_ASSIGNMENT &&
    3146       42950 :                 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
    3147       36368 :                 result = COERCION_PATH_COERCEVIAIO;
    3148      855302 :             else if (ccontext >= COERCION_EXPLICIT &&
    3149        5886 :                      TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
    3150        3704 :                 result = COERCION_PATH_COERCEVIAIO;
    3151             :         }
    3152             :     }
    3153             : 
    3154             :     /*
    3155             :      * When parsing PL/pgSQL assignments, allow an I/O cast to be used
    3156             :      * whenever no normal coercion is available.
    3157             :      */
    3158     1600712 :     if (result == COERCION_PATH_NONE &&
    3159             :         ccontext == COERCION_PLPGSQL)
    3160         176 :         result = COERCION_PATH_COERCEVIAIO;
    3161             : 
    3162     1600712 :     return result;
    3163             : }
    3164             : 
    3165             : 
    3166             : /*
    3167             :  * find_typmod_coercion_function -- does the given type need length coercion?
    3168             :  *
    3169             :  * If the target type possesses a pg_cast function from itself to itself,
    3170             :  * it must need length coercion.
    3171             :  *
    3172             :  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
    3173             :  *
    3174             :  * If the given type is a varlena array type, we do not look for a coercion
    3175             :  * function associated directly with the array type, but instead look for
    3176             :  * one associated with the element type.  An ArrayCoerceExpr node must be
    3177             :  * used to apply such a function.  (Note: currently, it's pointless to
    3178             :  * return the funcid in this case, because it'll just get looked up again
    3179             :  * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
    3180             :  *
    3181             :  * We use the same result enum as find_coercion_pathway, but the only possible
    3182             :  * result codes are:
    3183             :  *  COERCION_PATH_NONE: no length coercion needed
    3184             :  *  COERCION_PATH_FUNC: apply the function returned in *funcid
    3185             :  *  COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
    3186             :  */
    3187             : CoercionPathType
    3188       38530 : find_typmod_coercion_function(Oid typeId,
    3189             :                               Oid *funcid)
    3190             : {
    3191             :     CoercionPathType result;
    3192             :     Type        targetType;
    3193             :     Form_pg_type typeForm;
    3194             :     HeapTuple   tuple;
    3195             : 
    3196       38530 :     *funcid = InvalidOid;
    3197       38530 :     result = COERCION_PATH_FUNC;
    3198             : 
    3199       38530 :     targetType = typeidType(typeId);
    3200       38530 :     typeForm = (Form_pg_type) GETSTRUCT(targetType);
    3201             : 
    3202             :     /* Check for a "true" array type */
    3203       38530 :     if (IsTrueArrayType(typeForm))
    3204             :     {
    3205             :         /* Yes, switch our attention to the element type */
    3206          56 :         typeId = typeForm->typelem;
    3207          56 :         result = COERCION_PATH_ARRAYCOERCE;
    3208             :     }
    3209       38530 :     ReleaseSysCache(targetType);
    3210             : 
    3211             :     /* Look in pg_cast */
    3212       38530 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    3213             :                             ObjectIdGetDatum(typeId),
    3214             :                             ObjectIdGetDatum(typeId));
    3215             : 
    3216       38530 :     if (HeapTupleIsValid(tuple))
    3217             :     {
    3218       38522 :         Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
    3219             : 
    3220       38522 :         *funcid = castForm->castfunc;
    3221       38522 :         ReleaseSysCache(tuple);
    3222             :     }
    3223             : 
    3224       38530 :     if (!OidIsValid(*funcid))
    3225           8 :         result = COERCION_PATH_NONE;
    3226             : 
    3227       38530 :     return result;
    3228             : }
    3229             : 
    3230             : /*
    3231             :  * is_complex_array
    3232             :  *      Is this type an array of composite?
    3233             :  *
    3234             :  * Note: this will not return true for record[]; check for RECORDARRAYOID
    3235             :  * separately if needed.
    3236             :  */
    3237             : static bool
    3238          12 : is_complex_array(Oid typid)
    3239             : {
    3240          12 :     Oid         elemtype = get_element_type(typid);
    3241             : 
    3242          12 :     return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
    3243             : }
    3244             : 
    3245             : 
    3246             : /*
    3247             :  * Check whether reltypeId is the row type of a typed table of type
    3248             :  * reloftypeId, or is a domain over such a row type.  (This is conceptually
    3249             :  * similar to the subtype relationship checked by typeInheritsFrom().)
    3250             :  */
    3251             : static bool
    3252      949838 : typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
    3253             : {
    3254      949838 :     Oid         relid = typeOrDomainTypeRelid(reltypeId);
    3255      949838 :     bool        result = false;
    3256             : 
    3257      949838 :     if (relid)
    3258             :     {
    3259             :         HeapTuple   tp;
    3260             :         Form_pg_class reltup;
    3261             : 
    3262        7414 :         tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    3263        7414 :         if (!HeapTupleIsValid(tp))
    3264           0 :             elog(ERROR, "cache lookup failed for relation %u", relid);
    3265             : 
    3266        7414 :         reltup = (Form_pg_class) GETSTRUCT(tp);
    3267        7414 :         if (reltup->reloftype == reloftypeId)
    3268           8 :             result = true;
    3269             : 
    3270        7414 :         ReleaseSysCache(tp);
    3271             :     }
    3272             : 
    3273      949838 :     return result;
    3274             : }

Generated by: LCOV version 1.14