LCOV - code coverage report
Current view: top level - src/backend/parser - parse_coerce.c (source / functions) Hit Total Coverage
Test: PostgreSQL 11devel Lines: 613 692 88.6 %
Date: 2018-05-21 18:20:01 Functions: 24 24 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-2018, 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 "access/htup_details.h"
      18             : #include "catalog/pg_cast.h"
      19             : #include "catalog/pg_class.h"
      20             : #include "catalog/pg_inherits.h"
      21             : #include "catalog/pg_proc.h"
      22             : #include "catalog/pg_type.h"
      23             : #include "nodes/makefuncs.h"
      24             : #include "nodes/nodeFuncs.h"
      25             : #include "parser/parse_coerce.h"
      26             : #include "parser/parse_relation.h"
      27             : #include "parser/parse_type.h"
      28             : #include "utils/builtins.h"
      29             : #include "utils/datum.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      561288 : 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      561288 :     if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
      88         228 :         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             :      */
      99      561060 :     origexpr = expr;
     100     1122124 :     while (expr && IsA(expr, CollateExpr))
     101           4 :         expr = (Node *) ((CollateExpr *) expr)->arg;
     102             : 
     103      561060 :     result = coerce_type(pstate, expr, exprtype,
     104             :                          targettype, targettypmod,
     105             :                          ccontext, cformat, location);
     106             : 
     107             :     /*
     108             :      * If the target is a fixed-length type, it may need a length coercion as
     109             :      * well as a type coercion.  If we find ourselves adding both, force the
     110             :      * inner coercion node to implicit display form.
     111             :      */
     112      559568 :     result = coerce_type_typmod(result,
     113             :                                 targettype, targettypmod,
     114             :                                 ccontext, cformat, location,
     115      559568 :                                 (result != expr && !IsA(result, Const)));
     116             : 
     117      559568 :     if (expr != origexpr)
     118             :     {
     119             :         /* Reinstall top CollateExpr */
     120           4 :         CollateExpr *coll = (CollateExpr *) origexpr;
     121           4 :         CollateExpr *newcoll = makeNode(CollateExpr);
     122             : 
     123           4 :         newcoll->arg = (Expr *) result;
     124           4 :         newcoll->collOid = coll->collOid;
     125           4 :         newcoll->location = coll->location;
     126           4 :         result = (Node *) newcoll;
     127             :     }
     128             : 
     129      559568 :     return result;
     130             : }
     131             : 
     132             : 
     133             : /*
     134             :  * coerce_type()
     135             :  *      Convert an expression to a different type.
     136             :  *
     137             :  * The caller should already have determined that the coercion is possible;
     138             :  * see can_coerce_type.
     139             :  *
     140             :  * Normally, no coercion to a typmod (length) is performed here.  The caller
     141             :  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
     142             :  * (But if the target type is a domain, it may internally contain a
     143             :  * typmod constraint, which will be applied inside coerce_to_domain.)
     144             :  * In some cases pg_cast specifies a type coercion function that also
     145             :  * applies length conversion, and in those cases only, the result will
     146             :  * already be properly coerced to the specified typmod.
     147             :  *
     148             :  * pstate is only used in the case that we are able to resolve the type of
     149             :  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
     150             :  * caller does not want type information updated for Params.
     151             :  *
     152             :  * Note: this function must not modify the given expression tree, only add
     153             :  * decoration on top of it.  See transformSetOperationTree, for example.
     154             :  */
     155             : Node *
     156     1061492 : coerce_type(ParseState *pstate, Node *node,
     157             :             Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
     158             :             CoercionContext ccontext, CoercionForm cformat, int location)
     159             : {
     160             :     Node       *result;
     161             :     CoercionPathType pathtype;
     162             :     Oid         funcId;
     163             : 
     164     1061492 :     if (targetTypeId == inputTypeId ||
     165             :         node == NULL)
     166             :     {
     167             :         /* no conversion needed */
     168      107828 :         return node;
     169             :     }
     170      953664 :     if (targetTypeId == ANYOID ||
     171      947264 :         targetTypeId == ANYELEMENTOID ||
     172             :         targetTypeId == ANYNONARRAYOID)
     173             :     {
     174             :         /*
     175             :          * Assume can_coerce_type verified that implicit coercion is okay.
     176             :          *
     177             :          * Note: by returning the unmodified node here, we are saying that
     178             :          * it's OK to treat an UNKNOWN constant as a valid input for a
     179             :          * function accepting ANY, ANYELEMENT, or ANYNONARRAY.  This should be
     180             :          * all right, since an UNKNOWN value is still a perfectly valid Datum.
     181             :          *
     182             :          * NB: we do NOT want a RelabelType here: the exposed type of the
     183             :          * function argument must be its actual type, not the polymorphic
     184             :          * pseudotype.
     185             :          */
     186       17356 :         return node;
     187             :     }
     188      936308 :     if (targetTypeId == ANYARRAYOID ||
     189      891284 :         targetTypeId == ANYENUMOID ||
     190             :         targetTypeId == ANYRANGEOID)
     191             :     {
     192             :         /*
     193             :          * Assume can_coerce_type verified that implicit coercion is okay.
     194             :          *
     195             :          * These cases are unlike the ones above because the exposed type of
     196             :          * the argument must be an actual array, enum, or range type.  In
     197             :          * particular the argument must *not* be an UNKNOWN constant.  If it
     198             :          * is, we just fall through; below, we'll call anyarray_in,
     199             :          * anyenum_in, or anyrange_in, which will produce an error.  Also, if
     200             :          * what we have is a domain over array, enum, or range, we have to
     201             :          * relabel it to its base type.
     202             :          *
     203             :          * Note: currently, we can't actually see a domain-over-enum here,
     204             :          * since the other functions in this file will not match such a
     205             :          * parameter to ANYENUM.  But that should get changed eventually.
     206             :          */
     207       46706 :         if (inputTypeId != UNKNOWNOID)
     208             :         {
     209       45842 :             Oid         baseTypeId = getBaseType(inputTypeId);
     210             : 
     211       45842 :             if (baseTypeId != inputTypeId)
     212             :             {
     213          40 :                 RelabelType *r = makeRelabelType((Expr *) node,
     214             :                                                  baseTypeId, -1,
     215             :                                                  InvalidOid,
     216             :                                                  cformat);
     217             : 
     218          40 :                 r->location = location;
     219          40 :                 return (Node *) r;
     220             :             }
     221             :             /* Not a domain type, so return it as-is */
     222       45802 :             return node;
     223             :         }
     224             :     }
     225      890466 :     if (inputTypeId == UNKNOWNOID && IsA(node, Const))
     226             :     {
     227             :         /*
     228             :          * Input is a string constant with previously undetermined type. Apply
     229             :          * the target type's typinput function to it to produce a constant of
     230             :          * the target type.
     231             :          *
     232             :          * NOTE: this case cannot be folded together with the other
     233             :          * constant-input case, since the typinput function does not
     234             :          * necessarily behave the same as a type conversion function. For
     235             :          * example, int4's typinput function will reject "1.2", whereas
     236             :          * float-to-int type conversion will round to integer.
     237             :          *
     238             :          * XXX if the typinput function is not immutable, we really ought to
     239             :          * postpone evaluation of the function call until runtime. But there
     240             :          * is no way to represent a typinput function call as an expression
     241             :          * tree, because C-string values are not Datums. (XXX This *is*
     242             :          * possible as of 7.3, do we want to do it?)
     243             :          */
     244      598428 :         Const      *con = (Const *) node;
     245      598428 :         Const      *newcon = makeNode(Const);
     246             :         Oid         baseTypeId;
     247             :         int32       baseTypeMod;
     248             :         int32       inputTypeMod;
     249             :         Type        baseType;
     250             :         ParseCallbackState pcbstate;
     251             : 
     252             :         /*
     253             :          * If the target type is a domain, we want to call its base type's
     254             :          * input routine, not domain_in().  This is to avoid premature failure
     255             :          * when the domain applies a typmod: existing input routines follow
     256             :          * implicit-coercion semantics for length checks, which is not always
     257             :          * what we want here.  The needed check will be applied properly
     258             :          * inside coerce_to_domain().
     259             :          */
     260      598428 :         baseTypeMod = targetTypeMod;
     261      598428 :         baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
     262             : 
     263             :         /*
     264             :          * For most types we pass typmod -1 to the input routine, because
     265             :          * existing input routines follow implicit-coercion semantics for
     266             :          * length checks, which is not always what we want here.  Any length
     267             :          * constraint will be applied later by our caller.  An exception
     268             :          * however is the INTERVAL type, for which we *must* pass the typmod
     269             :          * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
     270             :          * as sin, but so is this part of the spec...)
     271             :          */
     272      598428 :         if (baseTypeId == INTERVALOID)
     273        1358 :             inputTypeMod = baseTypeMod;
     274             :         else
     275      597070 :             inputTypeMod = -1;
     276             : 
     277      598428 :         baseType = typeidType(baseTypeId);
     278             : 
     279      598428 :         newcon->consttype = baseTypeId;
     280      598428 :         newcon->consttypmod = inputTypeMod;
     281      598428 :         newcon->constcollid = typeTypeCollation(baseType);
     282      598428 :         newcon->constlen = typeLen(baseType);
     283      598428 :         newcon->constbyval = typeByVal(baseType);
     284      598428 :         newcon->constisnull = con->constisnull;
     285             : 
     286             :         /*
     287             :          * We use the original literal's location regardless of the position
     288             :          * of the coercion.  This is a change from pre-9.2 behavior, meant to
     289             :          * simplify life for pg_stat_statements.
     290             :          */
     291      598428 :         newcon->location = con->location;
     292             : 
     293             :         /*
     294             :          * Set up to point at the constant's text if the input routine throws
     295             :          * an error.
     296             :          */
     297      598428 :         setup_parser_errposition_callback(&pcbstate, pstate, con->location);
     298             : 
     299             :         /*
     300             :          * We assume here that UNKNOWN's internal representation is the same
     301             :          * as CSTRING.
     302             :          */
     303      598428 :         if (!con->constisnull)
     304      489970 :             newcon->constvalue = stringTypeDatum(baseType,
     305      489970 :                                                  DatumGetCString(con->constvalue),
     306             :                                                  inputTypeMod);
     307             :         else
     308      108458 :             newcon->constvalue = stringTypeDatum(baseType,
     309             :                                                  NULL,
     310             :                                                  inputTypeMod);
     311             : 
     312             :         /*
     313             :          * If it's a varlena value, force it to be in non-expanded
     314             :          * (non-toasted) format; this avoids any possible dependency on
     315             :          * external values and improves consistency of representation.
     316             :          */
     317      596832 :         if (!con->constisnull && newcon->constlen == -1)
     318      261520 :             newcon->constvalue =
     319      261520 :                 PointerGetDatum(PG_DETOAST_DATUM(newcon->constvalue));
     320             : 
     321             : #ifdef RANDOMIZE_ALLOCATED_MEMORY
     322             : 
     323             :         /*
     324             :          * For pass-by-reference data types, repeat the conversion to see if
     325             :          * the input function leaves any uninitialized bytes in the result. We
     326             :          * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
     327             :          * enabled, so we don't bother testing otherwise.  The reason we don't
     328             :          * want any instability in the input function is that comparison of
     329             :          * Const nodes relies on bytewise comparison of the datums, so if the
     330             :          * input function leaves garbage then subexpressions that should be
     331             :          * identical may not get recognized as such.  See pgsql-hackers
     332             :          * discussion of 2008-04-04.
     333             :          */
     334             :         if (!con->constisnull && !newcon->constbyval)
     335             :         {
     336             :             Datum       val2;
     337             : 
     338             :             val2 = stringTypeDatum(baseType,
     339             :                                    DatumGetCString(con->constvalue),
     340             :                                    inputTypeMod);
     341             :             if (newcon->constlen == -1)
     342             :                 val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
     343             :             if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
     344             :                 elog(WARNING, "type %s has unstable input conversion for \"%s\"",
     345             :                      typeTypeName(baseType), DatumGetCString(con->constvalue));
     346             :         }
     347             : #endif
     348             : 
     349      596832 :         cancel_parser_errposition_callback(&pcbstate);
     350             : 
     351      596832 :         result = (Node *) newcon;
     352             : 
     353             :         /* If target is a domain, apply constraints. */
     354      596832 :         if (baseTypeId != targetTypeId)
     355      121426 :             result = coerce_to_domain(result,
     356             :                                       baseTypeId, baseTypeMod,
     357             :                                       targetTypeId,
     358             :                                       ccontext, cformat, location,
     359             :                                       false);
     360             : 
     361      596832 :         ReleaseSysCache(baseType);
     362             : 
     363      596832 :         return result;
     364             :     }
     365      292038 :     if (IsA(node, Param) &&
     366       13972 :         pstate != NULL && pstate->p_coerce_param_hook != NULL)
     367             :     {
     368             :         /*
     369             :          * Allow the CoerceParamHook to decide what happens.  It can return a
     370             :          * transformed node (very possibly the same Param node), or return
     371             :          * NULL to indicate we should proceed with normal coercion.
     372             :          */
     373        6672 :         result = pstate->p_coerce_param_hook(pstate,
     374             :                                              (Param *) node,
     375             :                                              targetTypeId,
     376             :                                              targetTypeMod,
     377             :                                              location);
     378        6672 :         if (result)
     379        6660 :             return result;
     380             :     }
     381      285378 :     if (IsA(node, CollateExpr))
     382             :     {
     383             :         /*
     384             :          * If we have a COLLATE clause, we have to push the coercion
     385             :          * underneath the COLLATE.  This is really ugly, but there is little
     386             :          * choice because the above hacks on Consts and Params wouldn't happen
     387             :          * otherwise.  This kluge has consequences in coerce_to_target_type.
     388             :          */
     389          66 :         CollateExpr *coll = (CollateExpr *) node;
     390          66 :         CollateExpr *newcoll = makeNode(CollateExpr);
     391             : 
     392          66 :         newcoll->arg = (Expr *)
     393          66 :             coerce_type(pstate, (Node *) coll->arg,
     394             :                         inputTypeId, targetTypeId, targetTypeMod,
     395             :                         ccontext, cformat, location);
     396          66 :         newcoll->collOid = coll->collOid;
     397          66 :         newcoll->location = coll->location;
     398          66 :         return (Node *) newcoll;
     399             :     }
     400      285312 :     pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
     401             :                                      &funcId);
     402      285312 :     if (pathtype != COERCION_PATH_NONE)
     403             :     {
     404      283386 :         if (pathtype != COERCION_PATH_RELABELTYPE)
     405             :         {
     406             :             /*
     407             :              * Generate an expression tree representing run-time application
     408             :              * of the conversion function.  If we are dealing with a domain
     409             :              * target type, the conversion function will yield the base type,
     410             :              * and we need to extract the correct typmod to use from the
     411             :              * domain's typtypmod.
     412             :              */
     413             :             Oid         baseTypeId;
     414             :             int32       baseTypeMod;
     415             : 
     416      144892 :             baseTypeMod = targetTypeMod;
     417      144892 :             baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
     418             : 
     419      144892 :             result = build_coercion_expression(node, pathtype, funcId,
     420             :                                                baseTypeId, baseTypeMod,
     421             :                                                ccontext, cformat, location);
     422             : 
     423             :             /*
     424             :              * If domain, coerce to the domain type and relabel with domain
     425             :              * type ID, hiding the previous coercion node.
     426             :              */
     427      144892 :             if (targetTypeId != baseTypeId)
     428       83830 :                 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
     429             :                                           targetTypeId,
     430             :                                           ccontext, cformat, location,
     431             :                                           true);
     432             :         }
     433             :         else
     434             :         {
     435             :             /*
     436             :              * We don't need to do a physical conversion, but we do need to
     437             :              * attach a RelabelType node so that the expression will be seen
     438             :              * to have the intended type when inspected by higher-level code.
     439             :              *
     440             :              * Also, domains may have value restrictions beyond the base type
     441             :              * that must be accounted for.  If the destination is a domain
     442             :              * then we won't need a RelabelType node.
     443             :              */
     444      138494 :             result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
     445             :                                       ccontext, cformat, location,
     446             :                                       false);
     447      138494 :             if (result == node)
     448             :             {
     449             :                 /*
     450             :                  * XXX could we label result with exprTypmod(node) instead of
     451             :                  * default -1 typmod, to save a possible length-coercion
     452             :                  * later? Would work if both types have same interpretation of
     453             :                  * typmod, which is likely but not certain.
     454             :                  */
     455       88792 :                 RelabelType *r = makeRelabelType((Expr *) result,
     456             :                                                  targetTypeId, -1,
     457             :                                                  InvalidOid,
     458             :                                                  cformat);
     459             : 
     460       88792 :                 r->location = location;
     461       88792 :                 result = (Node *) r;
     462             :             }
     463             :         }
     464      283386 :         return result;
     465             :     }
     466        3084 :     if (inputTypeId == RECORDOID &&
     467        1158 :         ISCOMPLEX(targetTypeId))
     468             :     {
     469             :         /* Coerce a RECORD to a specific complex type */
     470        1158 :         return coerce_record_to_complex(pstate, node, targetTypeId,
     471             :                                         ccontext, cformat, location);
     472             :     }
     473        1500 :     if (targetTypeId == RECORDOID &&
     474         732 :         ISCOMPLEX(inputTypeId))
     475             :     {
     476             :         /* Coerce a specific complex type to RECORD */
     477             :         /* NB: we do NOT want a RelabelType here */
     478         732 :         return node;
     479             :     }
     480             : #ifdef NOT_USED
     481             :     if (inputTypeId == RECORDARRAYOID &&
     482             :         is_complex_array(targetTypeId))
     483             :     {
     484             :         /* Coerce record[] to a specific complex array type */
     485             :         /* not implemented yet ... */
     486             :     }
     487             : #endif
     488          48 :     if (targetTypeId == RECORDARRAYOID &&
     489          12 :         is_complex_array(inputTypeId))
     490             :     {
     491             :         /* Coerce a specific complex array type to record[] */
     492             :         /* NB: we do NOT want a RelabelType here */
     493          12 :         return node;
     494             :     }
     495          24 :     if (typeInheritsFrom(inputTypeId, targetTypeId)
     496           4 :         || typeIsOfTypedTable(inputTypeId, targetTypeId))
     497             :     {
     498             :         /*
     499             :          * Input class type is a subclass of target, so generate an
     500             :          * appropriate runtime conversion (removing unneeded columns and
     501             :          * possibly rearranging the ones that are wanted).
     502             :          *
     503             :          * We will also get here when the input is a domain over a subclass of
     504             :          * the target type.  To keep life simple for the executor, we define
     505             :          * ConvertRowtypeExpr as only working between regular composite types;
     506             :          * therefore, in such cases insert a RelabelType to smash the input
     507             :          * expression down to its base type.
     508             :          */
     509          24 :         Oid         baseTypeId = getBaseType(inputTypeId);
     510          24 :         ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
     511             : 
     512          24 :         if (baseTypeId != inputTypeId)
     513             :         {
     514           0 :             RelabelType *rt = makeRelabelType((Expr *) node,
     515             :                                               baseTypeId, -1,
     516             :                                               InvalidOid,
     517             :                                               COERCE_IMPLICIT_CAST);
     518             : 
     519           0 :             rt->location = location;
     520           0 :             node = (Node *) rt;
     521             :         }
     522          24 :         r->arg = (Expr *) node;
     523          24 :         r->resulttype = targetTypeId;
     524          24 :         r->convertformat = cformat;
     525          24 :         r->location = location;
     526          24 :         return (Node *) r;
     527             :     }
     528             :     /* If we get here, caller blew it */
     529           0 :     elog(ERROR, "failed to find conversion function from %s to %s",
     530             :          format_type_be(inputTypeId), format_type_be(targetTypeId));
     531             :     return NULL;                /* keep compiler quiet */
     532             : }
     533             : 
     534             : 
     535             : /*
     536             :  * can_coerce_type()
     537             :  *      Can input_typeids be coerced to target_typeids?
     538             :  *
     539             :  * We must be told the context (CAST construct, assignment, implicit coercion)
     540             :  * as this determines the set of available casts.
     541             :  */
     542             : bool
     543     1496748 : can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
     544             :                 CoercionContext ccontext)
     545             : {
     546     1496748 :     bool        have_generics = false;
     547             :     int         i;
     548             : 
     549             :     /* run through argument list... */
     550     2586388 :     for (i = 0; i < nargs; i++)
     551             :     {
     552     1670572 :         Oid         inputTypeId = input_typeids[i];
     553     1670572 :         Oid         targetTypeId = target_typeids[i];
     554             :         CoercionPathType pathtype;
     555             :         Oid         funcId;
     556             : 
     557             :         /* no problem if same type */
     558     1670572 :         if (inputTypeId == targetTypeId)
     559     1279778 :             continue;
     560             : 
     561             :         /* accept if target is ANY */
     562     1480434 :         if (targetTypeId == ANYOID)
     563        3360 :             continue;
     564             : 
     565             :         /* accept if target is polymorphic, for now */
     566     1477074 :         if (IsPolymorphicType(targetTypeId))
     567             :         {
     568      125006 :             have_generics = true;   /* do more checking later */
     569      125006 :             continue;
     570             :         }
     571             : 
     572             :         /*
     573             :          * If input is an untyped string constant, assume we can convert it to
     574             :          * anything.
     575             :          */
     576     1352068 :         if (inputTypeId == UNKNOWNOID)
     577      501282 :             continue;
     578             : 
     579             :         /*
     580             :          * If pg_cast shows that we can coerce, accept.  This test now covers
     581             :          * both binary-compatible and coercion-function cases.
     582             :          */
     583      850786 :         pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
     584             :                                          &funcId);
     585      850786 :         if (pathtype != COERCION_PATH_NONE)
     586      268120 :             continue;
     587             : 
     588             :         /*
     589             :          * If input is RECORD and target is a composite type, assume we can
     590             :          * coerce (may need tighter checking here)
     591             :          */
     592      583880 :         if (inputTypeId == RECORDOID &&
     593        1214 :             ISCOMPLEX(targetTypeId))
     594        1158 :             continue;
     595             : 
     596             :         /*
     597             :          * If input is a composite type and target is RECORD, accept
     598             :          */
     599      590450 :         if (targetTypeId == RECORDOID &&
     600        8942 :             ISCOMPLEX(inputTypeId))
     601         552 :             continue;
     602             : 
     603             : #ifdef NOT_USED                 /* not implemented yet */
     604             : 
     605             :         /*
     606             :          * If input is record[] and target is a composite array type, assume
     607             :          * we can coerce (may need tighter checking here)
     608             :          */
     609             :         if (inputTypeId == RECORDARRAYOID &&
     610             :             is_complex_array(targetTypeId))
     611             :             continue;
     612             : #endif
     613             : 
     614             :         /*
     615             :          * If input is a composite array type and target is record[], accept
     616             :          */
     617      580956 :         if (targetTypeId == RECORDARRAYOID &&
     618           0 :             is_complex_array(inputTypeId))
     619           0 :             continue;
     620             : 
     621             :         /*
     622             :          * If input is a class type that inherits from target, accept
     623             :          */
     624      580956 :         if (typeInheritsFrom(inputTypeId, targetTypeId)
     625      580936 :             || typeIsOfTypedTable(inputTypeId, targetTypeId))
     626          24 :             continue;
     627             : 
     628             :         /*
     629             :          * Else, cannot coerce at this argument position
     630             :          */
     631      580932 :         return false;
     632             :     }
     633             : 
     634             :     /* If we found any generic argument types, cross-check them */
     635      915816 :     if (have_generics)
     636             :     {
     637       92602 :         if (!check_generic_type_consistency(input_typeids, target_typeids,
     638             :                                             nargs))
     639       40040 :             return false;
     640             :     }
     641             : 
     642      875776 :     return true;
     643             : }
     644             : 
     645             : 
     646             : /*
     647             :  * Create an expression tree to represent coercion to a domain type.
     648             :  *
     649             :  * 'arg': input expression
     650             :  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
     651             :  *      has not bothered to look this up)
     652             :  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
     653             :  *      has not bothered to look this up)
     654             :  * 'typeId': target type to coerce to
     655             :  * 'ccontext': context indicator to control coercions
     656             :  * 'cformat': coercion display format
     657             :  * 'location': coercion request location
     658             :  * 'hideInputCoercion': if true, hide the input coercion under this one.
     659             :  *
     660             :  * If the target type isn't a domain, the given 'arg' is returned as-is.
     661             :  */
     662             : Node *
     663      353144 : coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
     664             :                  CoercionContext ccontext, CoercionForm cformat, int location,
     665             :                  bool hideInputCoercion)
     666             : {
     667             :     CoerceToDomain *result;
     668             : 
     669             :     /* Get the base type if it hasn't been supplied */
     670      353144 :     if (baseTypeId == InvalidOid)
     671      147756 :         baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
     672             : 
     673             :     /* If it isn't a domain, return the node as it was passed in */
     674      353144 :     if (baseTypeId == typeId)
     675       98018 :         return arg;
     676             : 
     677             :     /* Suppress display of nested coercion steps */
     678      255126 :     if (hideInputCoercion)
     679       83830 :         hide_coercion_node(arg);
     680             : 
     681             :     /*
     682             :      * If the domain applies a typmod to its base type, build the appropriate
     683             :      * coercion step.  Mark it implicit for display purposes, because we don't
     684             :      * want it shown separately by ruleutils.c; but the isExplicit flag passed
     685             :      * to the conversion function depends on the manner in which the domain
     686             :      * coercion is invoked, so that the semantics of implicit and explicit
     687             :      * coercion differ.  (Is that really the behavior we want?)
     688             :      *
     689             :      * NOTE: because we apply this as part of the fixed expression structure,
     690             :      * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
     691             :      * would be safe to do anyway, without lots of knowledge about what the
     692             :      * base type thinks the typmod means.
     693             :      */
     694      255126 :     arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
     695             :                              ccontext, COERCE_IMPLICIT_CAST, location,
     696             :                              false);
     697             : 
     698             :     /*
     699             :      * Now build the domain coercion node.  This represents run-time checking
     700             :      * of any constraints currently attached to the domain.  This also ensures
     701             :      * that the expression is properly labeled as to result type.
     702             :      */
     703      255126 :     result = makeNode(CoerceToDomain);
     704      255126 :     result->arg = (Expr *) arg;
     705      255126 :     result->resulttype = typeId;
     706      255126 :     result->resulttypmod = -1;   /* currently, always -1 for domains */
     707             :     /* resultcollid will be set by parse_collate.c */
     708      255126 :     result->coercionformat = cformat;
     709      255126 :     result->location = location;
     710             : 
     711      255126 :     return (Node *) result;
     712             : }
     713             : 
     714             : 
     715             : /*
     716             :  * coerce_type_typmod()
     717             :  *      Force a value to a particular typmod, if meaningful and possible.
     718             :  *
     719             :  * This is applied to values that are going to be stored in a relation
     720             :  * (where we have an atttypmod for the column) as well as values being
     721             :  * explicitly CASTed (where the typmod comes from the target type spec).
     722             :  *
     723             :  * The caller must have already ensured that the value is of the correct
     724             :  * type, typically by applying coerce_type.
     725             :  *
     726             :  * ccontext may affect semantics, depending on whether the length coercion
     727             :  * function pays attention to the isExplicit flag it's passed.
     728             :  *
     729             :  * cformat determines the display properties of the generated node (if any).
     730             :  *
     731             :  * If hideInputCoercion is true *and* we generate a node, the input node is
     732             :  * forced to IMPLICIT display form, so that only the typmod coercion node will
     733             :  * be visible when displaying the expression.
     734             :  *
     735             :  * NOTE: this does not need to work on domain types, because any typmod
     736             :  * coercion for a domain is considered to be part of the type coercion
     737             :  * needed to produce the domain value in the first place.  So, no getBaseType.
     738             :  */
     739             : static Node *
     740      814694 : coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
     741             :                    CoercionContext ccontext, CoercionForm cformat,
     742             :                    int location,
     743             :                    bool hideInputCoercion)
     744             : {
     745             :     CoercionPathType pathtype;
     746             :     Oid         funcId;
     747             : 
     748             :     /*
     749             :      * A negative typmod is assumed to mean that no coercion is wanted. Also,
     750             :      * skip coercion if already done.
     751             :      */
     752      814694 :     if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
     753      786020 :         return node;
     754             : 
     755       28674 :     pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
     756             : 
     757       28674 :     if (pathtype != COERCION_PATH_NONE)
     758             :     {
     759             :         /* Suppress display of nested coercion steps */
     760       28662 :         if (hideInputCoercion)
     761         518 :             hide_coercion_node(node);
     762             : 
     763       28662 :         node = build_coercion_expression(node, pathtype, funcId,
     764             :                                          targetTypeId, targetTypMod,
     765             :                                          ccontext, cformat, location);
     766             :     }
     767             : 
     768       28674 :     return node;
     769             : }
     770             : 
     771             : /*
     772             :  * Mark a coercion node as IMPLICIT so it will never be displayed by
     773             :  * ruleutils.c.  We use this when we generate a nest of coercion nodes
     774             :  * to implement what is logically one conversion; the inner nodes are
     775             :  * forced to IMPLICIT_CAST format.  This does not change their semantics,
     776             :  * only display behavior.
     777             :  *
     778             :  * It is caller error to call this on something that doesn't have a
     779             :  * CoercionForm field.
     780             :  */
     781             : static void
     782       84348 : hide_coercion_node(Node *node)
     783             : {
     784       84348 :     if (IsA(node, FuncExpr))
     785       79826 :         ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
     786        4522 :     else if (IsA(node, RelabelType))
     787         126 :         ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
     788        4396 :     else if (IsA(node, CoerceViaIO))
     789        4388 :         ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
     790           8 :     else if (IsA(node, ArrayCoerceExpr))
     791           8 :         ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
     792           0 :     else if (IsA(node, ConvertRowtypeExpr))
     793           0 :         ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
     794           0 :     else if (IsA(node, RowExpr))
     795           0 :         ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
     796           0 :     else if (IsA(node, CoerceToDomain))
     797           0 :         ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
     798             :     else
     799           0 :         elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
     800       84348 : }
     801             : 
     802             : /*
     803             :  * build_coercion_expression()
     804             :  *      Construct an expression tree for applying a pg_cast entry.
     805             :  *
     806             :  * This is used for both type-coercion and length-coercion operations,
     807             :  * since there is no difference in terms of the calling convention.
     808             :  */
     809             : static Node *
     810      173554 : build_coercion_expression(Node *node,
     811             :                           CoercionPathType pathtype,
     812             :                           Oid funcId,
     813             :                           Oid targetTypeId, int32 targetTypMod,
     814             :                           CoercionContext ccontext, CoercionForm cformat,
     815             :                           int location)
     816             : {
     817      173554 :     int         nargs = 0;
     818             : 
     819      173554 :     if (OidIsValid(funcId))
     820             :     {
     821             :         HeapTuple   tp;
     822             :         Form_pg_proc procstruct;
     823             : 
     824      158118 :         tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
     825      158118 :         if (!HeapTupleIsValid(tp))
     826           0 :             elog(ERROR, "cache lookup failed for function %u", funcId);
     827      158118 :         procstruct = (Form_pg_proc) GETSTRUCT(tp);
     828             : 
     829             :         /*
     830             :          * These Asserts essentially check that function is a legal coercion
     831             :          * function.  We can't make the seemingly obvious tests on prorettype
     832             :          * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
     833             :          * various binary-compatibility cases.
     834             :          */
     835             :         /* Assert(targetTypeId == procstruct->prorettype); */
     836             :         Assert(!procstruct->proretset);
     837             :         Assert(procstruct->prokind == PROKIND_FUNCTION);
     838      158118 :         nargs = procstruct->pronargs;
     839             :         Assert(nargs >= 1 && nargs <= 3);
     840             :         /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
     841             :         Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
     842             :         Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
     843             : 
     844      158118 :         ReleaseSysCache(tp);
     845             :     }
     846             : 
     847      173554 :     if (pathtype == COERCION_PATH_FUNC)
     848             :     {
     849             :         /* We build an ordinary FuncExpr with special arguments */
     850             :         FuncExpr   *fexpr;
     851             :         List       *args;
     852             :         Const      *cons;
     853             : 
     854             :         Assert(OidIsValid(funcId));
     855             : 
     856      158062 :         args = list_make1(node);
     857             : 
     858      158062 :         if (nargs >= 2)
     859             :         {
     860             :             /* Pass target typmod as an int4 constant */
     861       29350 :             cons = makeConst(INT4OID,
     862             :                              -1,
     863             :                              InvalidOid,
     864             :                              sizeof(int32),
     865             :                              Int32GetDatum(targetTypMod),
     866             :                              false,
     867             :                              true);
     868             : 
     869       29350 :             args = lappend(args, cons);
     870             :         }
     871             : 
     872      158062 :         if (nargs == 3)
     873             :         {
     874             :             /* Pass it a boolean isExplicit parameter, too */
     875       23494 :             cons = makeConst(BOOLOID,
     876             :                              -1,
     877             :                              InvalidOid,
     878             :                              sizeof(bool),
     879             :                              BoolGetDatum(ccontext == COERCION_EXPLICIT),
     880             :                              false,
     881             :                              true);
     882             : 
     883       23494 :             args = lappend(args, cons);
     884             :         }
     885             : 
     886      158062 :         fexpr = makeFuncExpr(funcId, targetTypeId, args,
     887             :                              InvalidOid, InvalidOid, cformat);
     888      158062 :         fexpr->location = location;
     889      158062 :         return (Node *) fexpr;
     890             :     }
     891       15492 :     else if (pathtype == COERCION_PATH_ARRAYCOERCE)
     892             :     {
     893             :         /* We need to build an ArrayCoerceExpr */
     894        1560 :         ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
     895        1560 :         CaseTestExpr *ctest = makeNode(CaseTestExpr);
     896             :         Oid         sourceBaseTypeId;
     897             :         int32       sourceBaseTypeMod;
     898             :         Oid         targetElementType;
     899             :         Node       *elemexpr;
     900             : 
     901             :         /*
     902             :          * Look through any domain over the source array type.  Note we don't
     903             :          * expect that the target type is a domain; it must be a plain array.
     904             :          * (To get to a domain target type, we'll do coerce_to_domain later.)
     905             :          */
     906        1560 :         sourceBaseTypeMod = exprTypmod(node);
     907        1560 :         sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
     908             :                                                 &sourceBaseTypeMod);
     909             : 
     910             :         /* Set up CaseTestExpr representing one element of source array */
     911        1560 :         ctest->typeId = get_element_type(sourceBaseTypeId);
     912             :         Assert(OidIsValid(ctest->typeId));
     913        1560 :         ctest->typeMod = sourceBaseTypeMod;
     914        1560 :         ctest->collation = InvalidOid;   /* Assume coercions don't care */
     915             : 
     916             :         /* And coerce it to the target element type */
     917        1560 :         targetElementType = get_element_type(targetTypeId);
     918             :         Assert(OidIsValid(targetElementType));
     919             : 
     920        1560 :         elemexpr = coerce_to_target_type(NULL,
     921             :                                          (Node *) ctest,
     922             :                                          ctest->typeId,
     923             :                                          targetElementType,
     924             :                                          targetTypMod,
     925             :                                          ccontext,
     926             :                                          cformat,
     927             :                                          location);
     928        1560 :         if (elemexpr == NULL)   /* shouldn't happen */
     929           0 :             elog(ERROR, "failed to coerce array element type as expected");
     930             : 
     931        1560 :         acoerce->arg = (Expr *) node;
     932        1560 :         acoerce->elemexpr = (Expr *) elemexpr;
     933        1560 :         acoerce->resulttype = targetTypeId;
     934             : 
     935             :         /*
     936             :          * Label the output as having a particular element typmod only if we
     937             :          * ended up with a per-element expression that is labeled that way.
     938             :          */
     939        1560 :         acoerce->resulttypmod = exprTypmod(elemexpr);
     940             :         /* resultcollid will be set by parse_collate.c */
     941        1560 :         acoerce->coerceformat = cformat;
     942        1560 :         acoerce->location = location;
     943             : 
     944        1560 :         return (Node *) acoerce;
     945             :     }
     946       13932 :     else if (pathtype == COERCION_PATH_COERCEVIAIO)
     947             :     {
     948             :         /* We need to build a CoerceViaIO node */
     949       13932 :         CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
     950             : 
     951             :         Assert(!OidIsValid(funcId));
     952             : 
     953       13932 :         iocoerce->arg = (Expr *) node;
     954       13932 :         iocoerce->resulttype = targetTypeId;
     955             :         /* resultcollid will be set by parse_collate.c */
     956       13932 :         iocoerce->coerceformat = cformat;
     957       13932 :         iocoerce->location = location;
     958             : 
     959       13932 :         return (Node *) iocoerce;
     960             :     }
     961             :     else
     962             :     {
     963           0 :         elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
     964             :              (int) pathtype);
     965             :         return NULL;            /* keep compiler quiet */
     966             :     }
     967             : }
     968             : 
     969             : 
     970             : /*
     971             :  * coerce_record_to_complex
     972             :  *      Coerce a RECORD to a specific composite type.
     973             :  *
     974             :  * Currently we only support this for inputs that are RowExprs or whole-row
     975             :  * Vars.
     976             :  */
     977             : static Node *
     978        1158 : coerce_record_to_complex(ParseState *pstate, Node *node,
     979             :                          Oid targetTypeId,
     980             :                          CoercionContext ccontext,
     981             :                          CoercionForm cformat,
     982             :                          int location)
     983             : {
     984             :     RowExpr    *rowexpr;
     985             :     Oid         baseTypeId;
     986        1158 :     int32       baseTypeMod = -1;
     987             :     TupleDesc   tupdesc;
     988        1158 :     List       *args = NIL;
     989             :     List       *newargs;
     990             :     int         i;
     991             :     int         ucolno;
     992             :     ListCell   *arg;
     993             : 
     994        1158 :     if (node && IsA(node, RowExpr))
     995             :     {
     996             :         /*
     997             :          * Since the RowExpr must be of type RECORD, we needn't worry about it
     998             :          * containing any dropped columns.
     999             :          */
    1000        1158 :         args = ((RowExpr *) node)->args;
    1001             :     }
    1002           0 :     else if (node && IsA(node, Var) &&
    1003           0 :              ((Var *) node)->varattno == InvalidAttrNumber)
    1004           0 :     {
    1005           0 :         int         rtindex = ((Var *) node)->varno;
    1006           0 :         int         sublevels_up = ((Var *) node)->varlevelsup;
    1007           0 :         int         vlocation = ((Var *) node)->location;
    1008             :         RangeTblEntry *rte;
    1009             : 
    1010           0 :         rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
    1011           0 :         expandRTE(rte, rtindex, sublevels_up, vlocation, false,
    1012             :                   NULL, &args);
    1013             :     }
    1014             :     else
    1015           0 :         ereport(ERROR,
    1016             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1017             :                  errmsg("cannot cast type %s to %s",
    1018             :                         format_type_be(RECORDOID),
    1019             :                         format_type_be(targetTypeId)),
    1020             :                  parser_coercion_errposition(pstate, location, node)));
    1021             : 
    1022             :     /*
    1023             :      * Look up the composite type, accounting for possibility that what we are
    1024             :      * given is a domain over composite.
    1025             :      */
    1026        1158 :     baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
    1027        1158 :     tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
    1028             : 
    1029             :     /* Process the fields */
    1030        1158 :     newargs = NIL;
    1031        1158 :     ucolno = 1;
    1032        1158 :     arg = list_head(args);
    1033        3926 :     for (i = 0; i < tupdesc->natts; i++)
    1034             :     {
    1035             :         Node       *expr;
    1036             :         Node       *cexpr;
    1037             :         Oid         exprtype;
    1038        2768 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
    1039             : 
    1040             :         /* Fill in NULLs for dropped columns in rowtype */
    1041        2768 :         if (attr->attisdropped)
    1042             :         {
    1043             :             /*
    1044             :              * can't use atttypid here, but it doesn't really matter what type
    1045             :              * the Const claims to be.
    1046             :              */
    1047           6 :             newargs = lappend(newargs,
    1048           6 :                               makeNullConst(INT4OID, -1, InvalidOid));
    1049           6 :             continue;
    1050             :         }
    1051             : 
    1052        2762 :         if (arg == NULL)
    1053           0 :             ereport(ERROR,
    1054             :                     (errcode(ERRCODE_CANNOT_COERCE),
    1055             :                      errmsg("cannot cast type %s to %s",
    1056             :                             format_type_be(RECORDOID),
    1057             :                             format_type_be(targetTypeId)),
    1058             :                      errdetail("Input has too few columns."),
    1059             :                      parser_coercion_errposition(pstate, location, node)));
    1060        2762 :         expr = (Node *) lfirst(arg);
    1061        2762 :         exprtype = exprType(expr);
    1062             : 
    1063        2762 :         cexpr = coerce_to_target_type(pstate,
    1064             :                                       expr, exprtype,
    1065             :                                       attr->atttypid,
    1066             :                                       attr->atttypmod,
    1067             :                                       ccontext,
    1068             :                                       COERCE_IMPLICIT_CAST,
    1069             :                                       -1);
    1070        2762 :         if (cexpr == NULL)
    1071           0 :             ereport(ERROR,
    1072             :                     (errcode(ERRCODE_CANNOT_COERCE),
    1073             :                      errmsg("cannot cast type %s to %s",
    1074             :                             format_type_be(RECORDOID),
    1075             :                             format_type_be(targetTypeId)),
    1076             :                      errdetail("Cannot cast type %s to %s in column %d.",
    1077             :                                format_type_be(exprtype),
    1078             :                                format_type_be(attr->atttypid),
    1079             :                                ucolno),
    1080             :                      parser_coercion_errposition(pstate, location, expr)));
    1081        2762 :         newargs = lappend(newargs, cexpr);
    1082        2762 :         ucolno++;
    1083        2762 :         arg = lnext(arg);
    1084             :     }
    1085        1158 :     if (arg != NULL)
    1086           0 :         ereport(ERROR,
    1087             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1088             :                  errmsg("cannot cast type %s to %s",
    1089             :                         format_type_be(RECORDOID),
    1090             :                         format_type_be(targetTypeId)),
    1091             :                  errdetail("Input has too many columns."),
    1092             :                  parser_coercion_errposition(pstate, location, node)));
    1093             : 
    1094        1158 :     ReleaseTupleDesc(tupdesc);
    1095             : 
    1096        1158 :     rowexpr = makeNode(RowExpr);
    1097        1158 :     rowexpr->args = newargs;
    1098        1158 :     rowexpr->row_typeid = baseTypeId;
    1099        1158 :     rowexpr->row_format = cformat;
    1100        1158 :     rowexpr->colnames = NIL; /* not needed for named target type */
    1101        1158 :     rowexpr->location = location;
    1102             : 
    1103             :     /* If target is a domain, apply constraints */
    1104        1158 :     if (baseTypeId != targetTypeId)
    1105             :     {
    1106          76 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
    1107          76 :         return coerce_to_domain((Node *) rowexpr,
    1108             :                                 baseTypeId, baseTypeMod,
    1109             :                                 targetTypeId,
    1110             :                                 ccontext, cformat, location,
    1111             :                                 false);
    1112             :     }
    1113             : 
    1114        1082 :     return (Node *) rowexpr;
    1115             : }
    1116             : 
    1117             : /*
    1118             :  * coerce_to_boolean()
    1119             :  *      Coerce an argument of a construct that requires boolean input
    1120             :  *      (AND, OR, NOT, etc).  Also check that input is not a set.
    1121             :  *
    1122             :  * Returns the possibly-transformed node tree.
    1123             :  *
    1124             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1125             :  * processing is wanted.
    1126             :  */
    1127             : Node *
    1128      585120 : coerce_to_boolean(ParseState *pstate, Node *node,
    1129             :                   const char *constructName)
    1130             : {
    1131      585120 :     Oid         inputTypeId = exprType(node);
    1132             : 
    1133      585120 :     if (inputTypeId != BOOLOID)
    1134             :     {
    1135             :         Node       *newnode;
    1136             : 
    1137           0 :         newnode = coerce_to_target_type(pstate, node, inputTypeId,
    1138             :                                         BOOLOID, -1,
    1139             :                                         COERCION_ASSIGNMENT,
    1140             :                                         COERCE_IMPLICIT_CAST,
    1141             :                                         -1);
    1142           0 :         if (newnode == NULL)
    1143           0 :             ereport(ERROR,
    1144             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1145             :             /* translator: first %s is name of a SQL construct, eg WHERE */
    1146             :                      errmsg("argument of %s must be type %s, not type %s",
    1147             :                             constructName, "boolean",
    1148             :                             format_type_be(inputTypeId)),
    1149             :                      parser_errposition(pstate, exprLocation(node))));
    1150           0 :         node = newnode;
    1151             :     }
    1152             : 
    1153      585120 :     if (expression_returns_set(node))
    1154           0 :         ereport(ERROR,
    1155             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1156             :         /* translator: %s is name of a SQL construct, eg WHERE */
    1157             :                  errmsg("argument of %s must not return a set",
    1158             :                         constructName),
    1159             :                  parser_errposition(pstate, exprLocation(node))));
    1160             : 
    1161      585120 :     return node;
    1162             : }
    1163             : 
    1164             : /*
    1165             :  * coerce_to_specific_type_typmod()
    1166             :  *      Coerce an argument of a construct that requires a specific data type,
    1167             :  *      with a specific typmod.  Also check that input is not a set.
    1168             :  *
    1169             :  * Returns the possibly-transformed node tree.
    1170             :  *
    1171             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1172             :  * processing is wanted.
    1173             :  */
    1174             : Node *
    1175       12058 : coerce_to_specific_type_typmod(ParseState *pstate, Node *node,
    1176             :                                Oid targetTypeId, int32 targetTypmod,
    1177             :                                const char *constructName)
    1178             : {
    1179       12058 :     Oid         inputTypeId = exprType(node);
    1180             : 
    1181       12058 :     if (inputTypeId != targetTypeId)
    1182             :     {
    1183             :         Node       *newnode;
    1184             : 
    1185        6440 :         newnode = coerce_to_target_type(pstate, node, inputTypeId,
    1186             :                                         targetTypeId, targetTypmod,
    1187             :                                         COERCION_ASSIGNMENT,
    1188             :                                         COERCE_IMPLICIT_CAST,
    1189             :                                         -1);
    1190        6432 :         if (newnode == NULL)
    1191           4 :             ereport(ERROR,
    1192             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1193             :             /* translator: first %s is name of a SQL construct, eg LIMIT */
    1194             :                      errmsg("argument of %s must be type %s, not type %s",
    1195             :                             constructName,
    1196             :                             format_type_be(targetTypeId),
    1197             :                             format_type_be(inputTypeId)),
    1198             :                      parser_errposition(pstate, exprLocation(node))));
    1199        6428 :         node = newnode;
    1200             :     }
    1201             : 
    1202       12046 :     if (expression_returns_set(node))
    1203           0 :         ereport(ERROR,
    1204             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1205             :         /* translator: %s is name of a SQL construct, eg LIMIT */
    1206             :                  errmsg("argument of %s must not return a set",
    1207             :                         constructName),
    1208             :                  parser_errposition(pstate, exprLocation(node))));
    1209             : 
    1210       12046 :     return node;
    1211             : }
    1212             : 
    1213             : /*
    1214             :  * coerce_to_specific_type()
    1215             :  *      Coerce an argument of a construct that requires a specific data type.
    1216             :  *      Also check that input is not a set.
    1217             :  *
    1218             :  * Returns the possibly-transformed node tree.
    1219             :  *
    1220             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1221             :  * processing is wanted.
    1222             :  */
    1223             : Node *
    1224       12020 : coerce_to_specific_type(ParseState *pstate, Node *node,
    1225             :                         Oid targetTypeId,
    1226             :                         const char *constructName)
    1227             : {
    1228       12020 :     return coerce_to_specific_type_typmod(pstate, node,
    1229             :                                           targetTypeId, -1,
    1230             :                                           constructName);
    1231             : }
    1232             : 
    1233             : /*
    1234             :  * parser_coercion_errposition - report coercion error location, if possible
    1235             :  *
    1236             :  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
    1237             :  * but there may be no such location in the case of an implicit coercion.
    1238             :  * In that case point at the input expression.
    1239             :  *
    1240             :  * XXX possibly this is more generally useful than coercion errors;
    1241             :  * if so, should rename and place with parser_errposition.
    1242             :  */
    1243             : int
    1244          16 : parser_coercion_errposition(ParseState *pstate,
    1245             :                             int coerce_location,
    1246             :                             Node *input_expr)
    1247             : {
    1248          16 :     if (coerce_location >= 0)
    1249          16 :         return parser_errposition(pstate, coerce_location);
    1250             :     else
    1251           0 :         return parser_errposition(pstate, exprLocation(input_expr));
    1252             : }
    1253             : 
    1254             : 
    1255             : /*
    1256             :  * select_common_type()
    1257             :  *      Determine the common supertype of a list of input expressions.
    1258             :  *      This is used for determining the output type of CASE, UNION,
    1259             :  *      and similar constructs.
    1260             :  *
    1261             :  * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
    1262             :  * in the list will be preferred if there is doubt.
    1263             :  * 'context' is a phrase to use in the error message if we fail to select
    1264             :  * a usable type.  Pass NULL to have the routine return InvalidOid
    1265             :  * rather than throwing an error on failure.
    1266             :  * 'which_expr': if not NULL, receives a pointer to the particular input
    1267             :  * expression from which the result type was taken.
    1268             :  */
    1269             : Oid
    1270      157798 : select_common_type(ParseState *pstate, List *exprs, const char *context,
    1271             :                    Node **which_expr)
    1272             : {
    1273             :     Node       *pexpr;
    1274             :     Oid         ptype;
    1275             :     TYPCATEGORY pcategory;
    1276             :     bool        pispreferred;
    1277             :     ListCell   *lc;
    1278             : 
    1279             :     Assert(exprs != NIL);
    1280      157798 :     pexpr = (Node *) linitial(exprs);
    1281      157798 :     lc = lnext(list_head(exprs));
    1282      157798 :     ptype = exprType(pexpr);
    1283             : 
    1284             :     /*
    1285             :      * If all input types are valid and exactly the same, just pick that type.
    1286             :      * This is the only way that we will resolve the result as being a domain
    1287             :      * type; otherwise domains are smashed to their base types for comparison.
    1288             :      */
    1289      157798 :     if (ptype != UNKNOWNOID)
    1290             :     {
    1291      220280 :         for_each_cell(lc, lc)
    1292             :         {
    1293      131716 :             Node       *nexpr = (Node *) lfirst(lc);
    1294      131716 :             Oid         ntype = exprType(nexpr);
    1295             : 
    1296      131716 :             if (ntype != ptype)
    1297       38514 :                 break;
    1298             :         }
    1299      127078 :         if (lc == NULL)         /* got to the end of the list? */
    1300             :         {
    1301       88564 :             if (which_expr)
    1302       61920 :                 *which_expr = pexpr;
    1303       88564 :             return ptype;
    1304             :         }
    1305             :     }
    1306             : 
    1307             :     /*
    1308             :      * Nope, so set up for the full algorithm.  Note that at this point, lc
    1309             :      * points to the first list item with type different from pexpr's; we need
    1310             :      * not re-examine any items the previous loop advanced over.
    1311             :      */
    1312       69234 :     ptype = getBaseType(ptype);
    1313       69234 :     get_type_category_preferred(ptype, &pcategory, &pispreferred);
    1314             : 
    1315      207750 :     for_each_cell(lc, lc)
    1316             :     {
    1317      138520 :         Node       *nexpr = (Node *) lfirst(lc);
    1318      138520 :         Oid         ntype = getBaseType(exprType(nexpr));
    1319             : 
    1320             :         /* move on to next one if no new information... */
    1321      138520 :         if (ntype != UNKNOWNOID && ntype != ptype)
    1322             :         {
    1323             :             TYPCATEGORY ncategory;
    1324             :             bool        nispreferred;
    1325             : 
    1326       25914 :             get_type_category_preferred(ntype, &ncategory, &nispreferred);
    1327       25914 :             if (ptype == UNKNOWNOID)
    1328             :             {
    1329             :                 /* so far, only unknowns so take anything... */
    1330       14106 :                 pexpr = nexpr;
    1331       14106 :                 ptype = ntype;
    1332       14106 :                 pcategory = ncategory;
    1333       14106 :                 pispreferred = nispreferred;
    1334             :             }
    1335       11808 :             else if (ncategory != pcategory)
    1336             :             {
    1337             :                 /*
    1338             :                  * both types in different categories? then not much hope...
    1339             :                  */
    1340           4 :                 if (context == NULL)
    1341           0 :                     return InvalidOid;
    1342           4 :                 ereport(ERROR,
    1343             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1344             :                 /*------
    1345             :                   translator: first %s is name of a SQL construct, eg CASE */
    1346             :                          errmsg("%s types %s and %s cannot be matched",
    1347             :                                 context,
    1348             :                                 format_type_be(ptype),
    1349             :                                 format_type_be(ntype)),
    1350             :                          parser_errposition(pstate, exprLocation(nexpr))));
    1351             :             }
    1352       16884 :             else if (!pispreferred &&
    1353        9852 :                      can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
    1354        4772 :                      !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
    1355             :             {
    1356             :                 /*
    1357             :                  * take new type if can coerce to it implicitly but not the
    1358             :                  * other way; but if we have a preferred type, stay on it.
    1359             :                  */
    1360        4472 :                 pexpr = nexpr;
    1361        4472 :                 ptype = ntype;
    1362        4472 :                 pcategory = ncategory;
    1363        4472 :                 pispreferred = nispreferred;
    1364             :             }
    1365             :         }
    1366             :     }
    1367             : 
    1368             :     /*
    1369             :      * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
    1370             :      * then resolve as type TEXT.  This situation comes up with constructs
    1371             :      * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
    1372             :      * UNION SELECT 'bar'; It might seem desirable to leave the construct's
    1373             :      * output type as UNKNOWN, but that really doesn't work, because we'd
    1374             :      * probably end up needing a runtime coercion from UNKNOWN to something
    1375             :      * else, and we usually won't have it.  We need to coerce the unknown
    1376             :      * literals while they are still literals, so a decision has to be made
    1377             :      * now.
    1378             :      */
    1379       69230 :     if (ptype == UNKNOWNOID)
    1380       16614 :         ptype = TEXTOID;
    1381             : 
    1382       69230 :     if (which_expr)
    1383        3702 :         *which_expr = pexpr;
    1384       69230 :     return ptype;
    1385             : }
    1386             : 
    1387             : /*
    1388             :  * coerce_to_common_type()
    1389             :  *      Coerce an expression to the given type.
    1390             :  *
    1391             :  * This is used following select_common_type() to coerce the individual
    1392             :  * expressions to the desired type.  'context' is a phrase to use in the
    1393             :  * error message if we fail to coerce.
    1394             :  *
    1395             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    1396             :  * processing is wanted.
    1397             :  */
    1398             : Node *
    1399      368126 : coerce_to_common_type(ParseState *pstate, Node *node,
    1400             :                       Oid targetTypeId, const char *context)
    1401             : {
    1402      368126 :     Oid         inputTypeId = exprType(node);
    1403             : 
    1404      368126 :     if (inputTypeId == targetTypeId)
    1405      226786 :         return node;            /* no work */
    1406      141340 :     if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
    1407      141340 :         node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
    1408             :                            COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
    1409             :     else
    1410           0 :         ereport(ERROR,
    1411             :                 (errcode(ERRCODE_CANNOT_COERCE),
    1412             :         /* translator: first %s is name of a SQL construct, eg CASE */
    1413             :                  errmsg("%s could not convert type %s to %s",
    1414             :                         context,
    1415             :                         format_type_be(inputTypeId),
    1416             :                         format_type_be(targetTypeId)),
    1417             :                  parser_errposition(pstate, exprLocation(node))));
    1418      141336 :     return node;
    1419             : }
    1420             : 
    1421             : /*
    1422             :  * check_generic_type_consistency()
    1423             :  *      Are the actual arguments potentially compatible with a
    1424             :  *      polymorphic function?
    1425             :  *
    1426             :  * The argument consistency rules are:
    1427             :  *
    1428             :  * 1) All arguments declared ANYELEMENT must have the same datatype.
    1429             :  * 2) All arguments declared ANYARRAY must have the same datatype,
    1430             :  *    which must be a varlena array type.
    1431             :  * 3) All arguments declared ANYRANGE must have the same datatype,
    1432             :  *    which must be a range type.
    1433             :  * 4) If there are arguments of both ANYELEMENT and ANYARRAY, make sure the
    1434             :  *    actual ANYELEMENT datatype is in fact the element type for the actual
    1435             :  *    ANYARRAY datatype.
    1436             :  * 5) Similarly, if there are arguments of both ANYELEMENT and ANYRANGE,
    1437             :  *    make sure the actual ANYELEMENT datatype is in fact the subtype for
    1438             :  *    the actual ANYRANGE type.
    1439             :  * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
    1440             :  *    (alone or in combination with plain ANYELEMENT), we add the extra
    1441             :  *    condition that the ANYELEMENT type must be an enum.
    1442             :  * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
    1443             :  *    we add the extra condition that the ANYELEMENT type must not be an array.
    1444             :  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
    1445             :  *    is an extra restriction if not.)
    1446             :  *
    1447             :  * Domains over arrays match ANYARRAY, and are immediately flattened to their
    1448             :  * base type.  (Thus, for example, we will consider it a match if one ANYARRAY
    1449             :  * argument is a domain over int4[] while another one is just int4[].)  Also
    1450             :  * notice that such a domain does *not* match ANYNONARRAY.
    1451             :  *
    1452             :  * Similarly, domains over ranges match ANYRANGE, and are immediately
    1453             :  * flattened to their base type.
    1454             :  *
    1455             :  * Note that domains aren't currently considered to match ANYENUM,
    1456             :  * even if their base type would match.
    1457             :  *
    1458             :  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
    1459             :  * argument, assume it is okay.
    1460             :  *
    1461             :  * If an input is of type ANYARRAY (ie, we know it's an array, but not
    1462             :  * what element type), we will accept it as a match to an argument declared
    1463             :  * ANYARRAY, so long as we don't have to determine an element type ---
    1464             :  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
    1465             :  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
    1466             :  *
    1467             :  * We do not ereport here, but just return false if a rule is violated.
    1468             :  */
    1469             : bool
    1470       92602 : check_generic_type_consistency(Oid *actual_arg_types,
    1471             :                                Oid *declared_arg_types,
    1472             :                                int nargs)
    1473             : {
    1474             :     int         j;
    1475       92602 :     Oid         elem_typeid = InvalidOid;
    1476       92602 :     Oid         array_typeid = InvalidOid;
    1477             :     Oid         array_typelem;
    1478       92602 :     Oid         range_typeid = InvalidOid;
    1479             :     Oid         range_typelem;
    1480       92602 :     bool        have_anyelement = false;
    1481       92602 :     bool        have_anynonarray = false;
    1482       92602 :     bool        have_anyenum = false;
    1483             : 
    1484             :     /*
    1485             :      * Loop through the arguments to see if we have any that are polymorphic.
    1486             :      * If so, require the actual types to be consistent.
    1487             :      */
    1488      218718 :     for (j = 0; j < nargs; j++)
    1489             :     {
    1490      144700 :         Oid         decl_type = declared_arg_types[j];
    1491      144700 :         Oid         actual_type = actual_arg_types[j];
    1492             : 
    1493      144700 :         if (decl_type == ANYELEMENTOID ||
    1494      125790 :             decl_type == ANYNONARRAYOID ||
    1495             :             decl_type == ANYENUMOID)
    1496             :         {
    1497       36230 :             have_anyelement = true;
    1498       36230 :             if (decl_type == ANYNONARRAYOID)
    1499       12838 :                 have_anynonarray = true;
    1500       23392 :             else if (decl_type == ANYENUMOID)
    1501       17320 :                 have_anyenum = true;
    1502       36230 :             if (actual_type == UNKNOWNOID)
    1503        3288 :                 continue;
    1504       32942 :             if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
    1505        6158 :                 return false;
    1506       26784 :             elem_typeid = actual_type;
    1507             :         }
    1508      108470 :         else if (decl_type == ANYARRAYOID)
    1509             :         {
    1510       68756 :             if (actual_type == UNKNOWNOID)
    1511        3782 :                 continue;
    1512       64974 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1513       64974 :             if (OidIsValid(array_typeid) && actual_type != array_typeid)
    1514        6278 :                 return false;
    1515       58696 :             array_typeid = actual_type;
    1516             :         }
    1517       39714 :         else if (decl_type == ANYRANGEOID)
    1518             :         {
    1519       19766 :             if (actual_type == UNKNOWNOID)
    1520        1404 :                 continue;
    1521       18362 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1522       18362 :             if (OidIsValid(range_typeid) && actual_type != range_typeid)
    1523        6148 :                 return false;
    1524       12214 :             range_typeid = actual_type;
    1525             :         }
    1526             :     }
    1527             : 
    1528             :     /* Get the element type based on the array type, if we have one */
    1529       74018 :     if (OidIsValid(array_typeid))
    1530             :     {
    1531       50508 :         if (array_typeid == ANYARRAYOID)
    1532             :         {
    1533             :             /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
    1534           0 :             if (have_anyelement)
    1535           0 :                 return false;
    1536           0 :             return true;
    1537             :         }
    1538             : 
    1539       50508 :         array_typelem = get_element_type(array_typeid);
    1540       50508 :         if (!OidIsValid(array_typelem))
    1541       14972 :             return false;       /* should be an array, but isn't */
    1542             : 
    1543       35536 :         if (!OidIsValid(elem_typeid))
    1544             :         {
    1545             :             /*
    1546             :              * if we don't have an element type yet, use the one we just got
    1547             :              */
    1548       34966 :             elem_typeid = array_typelem;
    1549             :         }
    1550         570 :         else if (array_typelem != elem_typeid)
    1551             :         {
    1552             :             /* otherwise, they better match */
    1553         244 :             return false;
    1554             :         }
    1555             :     }
    1556             : 
    1557             :     /* Get the element type based on the range type, if we have one */
    1558       58802 :     if (OidIsValid(range_typeid))
    1559             :     {
    1560        4172 :         range_typelem = get_range_subtype(range_typeid);
    1561        4172 :         if (!OidIsValid(range_typelem))
    1562        3752 :             return false;       /* should be a range, but isn't */
    1563             : 
    1564         420 :         if (!OidIsValid(elem_typeid))
    1565             :         {
    1566             :             /*
    1567             :              * if we don't have an element type yet, use the one we just got
    1568             :              */
    1569         336 :             elem_typeid = range_typelem;
    1570             :         }
    1571          84 :         else if (range_typelem != elem_typeid)
    1572             :         {
    1573             :             /* otherwise, they better match */
    1574          32 :             return false;
    1575             :         }
    1576             :     }
    1577             : 
    1578       55018 :     if (have_anynonarray)
    1579             :     {
    1580             :         /* require the element type to not be an array or domain over array */
    1581       12838 :         if (type_is_array_domain(elem_typeid))
    1582          40 :             return false;
    1583             :     }
    1584             : 
    1585       54978 :     if (have_anyenum)
    1586             :     {
    1587             :         /* require the element type to be an enum */
    1588        2628 :         if (!type_is_enum(elem_typeid))
    1589        2416 :             return false;
    1590             :     }
    1591             : 
    1592             :     /* Looks valid */
    1593       52562 :     return true;
    1594             : }
    1595             : 
    1596             : /*
    1597             :  * enforce_generic_type_consistency()
    1598             :  *      Make sure a polymorphic function is legally callable, and
    1599             :  *      deduce actual argument and result types.
    1600             :  *
    1601             :  * If any polymorphic pseudotype is used in a function's arguments or
    1602             :  * return type, we make sure the actual data types are consistent with
    1603             :  * each other.  The argument consistency rules are shown above for
    1604             :  * check_generic_type_consistency().
    1605             :  *
    1606             :  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
    1607             :  * argument, we attempt to deduce the actual type it should have.  If
    1608             :  * successful, we alter that position of declared_arg_types[] so that
    1609             :  * make_fn_arguments will coerce the literal to the right thing.
    1610             :  *
    1611             :  * Rules are applied to the function's return type (possibly altering it)
    1612             :  * if it is declared as a polymorphic type:
    1613             :  *
    1614             :  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
    1615             :  *    argument's actual type as the function's return type.
    1616             :  * 2) Similarly, if return type is ANYRANGE, and any argument is ANYRANGE,
    1617             :  *    use the argument's actual type as the function's return type.
    1618             :  * 3) If return type is ANYARRAY, no argument is ANYARRAY, but any argument is
    1619             :  *    ANYELEMENT, use the actual type of the argument to determine the
    1620             :  *    function's return type, i.e. the element type's corresponding array
    1621             :  *    type.  (Note: similar behavior does not exist for ANYRANGE, because it's
    1622             :  *    impossible to determine the range type from the subtype alone.)
    1623             :  * 4) If return type is ANYARRAY, but no argument is ANYARRAY or ANYELEMENT,
    1624             :  *    generate an error.  Similarly, if return type is ANYRANGE, but no
    1625             :  *    argument is ANYRANGE, generate an error.  (These conditions are
    1626             :  *    prevented by CREATE FUNCTION and therefore are not expected here.)
    1627             :  * 5) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
    1628             :  *    argument's actual type as the function's return type.
    1629             :  * 6) If return type is ANYELEMENT, no argument is ANYELEMENT, but any argument
    1630             :  *    is ANYARRAY or ANYRANGE, use the actual type of the argument to determine
    1631             :  *    the function's return type, i.e. the array type's corresponding element
    1632             :  *    type or the range type's corresponding subtype (or both, in which case
    1633             :  *    they must match).
    1634             :  * 7) If return type is ANYELEMENT, no argument is ANYELEMENT, ANYARRAY, or
    1635             :  *    ANYRANGE, generate an error.  (This condition is prevented by CREATE
    1636             :  *    FUNCTION and therefore is not expected here.)
    1637             :  * 8) ANYENUM is treated the same as ANYELEMENT except that if it is used
    1638             :  *    (alone or in combination with plain ANYELEMENT), we add the extra
    1639             :  *    condition that the ANYELEMENT type must be an enum.
    1640             :  * 9) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
    1641             :  *    we add the extra condition that the ANYELEMENT type must not be an array.
    1642             :  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
    1643             :  *    is an extra restriction if not.)
    1644             :  *
    1645             :  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
    1646             :  * respectively, and are immediately flattened to their base type. (In
    1647             :  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set it
    1648             :  * to the base type not the domain type.)
    1649             :  *
    1650             :  * When allow_poly is false, we are not expecting any of the actual_arg_types
    1651             :  * to be polymorphic, and we should not return a polymorphic result type
    1652             :  * either.  When allow_poly is true, it is okay to have polymorphic "actual"
    1653             :  * arg types, and we can return ANYARRAY, ANYRANGE, or ANYELEMENT as the
    1654             :  * result.  (This case is currently used only to check compatibility of an
    1655             :  * aggregate's declaration with the underlying transfn.)
    1656             :  *
    1657             :  * A special case is that we could see ANYARRAY as an actual_arg_type even
    1658             :  * when allow_poly is false (this is possible only because pg_statistic has
    1659             :  * columns shown as anyarray in the catalogs).  We allow this to match a
    1660             :  * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
    1661             :  * or result (since we can't determine a specific element type to match to
    1662             :  * ANYELEMENT).  Note this means that functions taking ANYARRAY had better
    1663             :  * behave sanely if applied to the pg_statistic columns; they can't just
    1664             :  * assume that successive inputs are of the same actual element type.
    1665             :  */
    1666             : Oid
    1667      783984 : enforce_generic_type_consistency(Oid *actual_arg_types,
    1668             :                                  Oid *declared_arg_types,
    1669             :                                  int nargs,
    1670             :                                  Oid rettype,
    1671             :                                  bool allow_poly)
    1672             : {
    1673             :     int         j;
    1674      783984 :     bool        have_generics = false;
    1675      783984 :     bool        have_unknowns = false;
    1676      783984 :     Oid         elem_typeid = InvalidOid;
    1677      783984 :     Oid         array_typeid = InvalidOid;
    1678      783984 :     Oid         range_typeid = InvalidOid;
    1679             :     Oid         array_typelem;
    1680             :     Oid         range_typelem;
    1681     1550996 :     bool        have_anyelement = (rettype == ANYELEMENTOID ||
    1682     1550996 :                                    rettype == ANYNONARRAYOID ||
    1683             :                                    rettype == ANYENUMOID);
    1684      783984 :     bool        have_anynonarray = (rettype == ANYNONARRAYOID);
    1685      783984 :     bool        have_anyenum = (rettype == ANYENUMOID);
    1686             : 
    1687             :     /*
    1688             :      * Loop through the arguments to see if we have any that are polymorphic.
    1689             :      * If so, require the actual types to be consistent.
    1690             :      */
    1691     2114482 :     for (j = 0; j < nargs; j++)
    1692             :     {
    1693     1330498 :         Oid         decl_type = declared_arg_types[j];
    1694     1330498 :         Oid         actual_type = actual_arg_types[j];
    1695             : 
    1696     1330498 :         if (decl_type == ANYELEMENTOID ||
    1697     1315582 :             decl_type == ANYNONARRAYOID ||
    1698             :             decl_type == ANYENUMOID)
    1699             :         {
    1700       15472 :             have_generics = have_anyelement = true;
    1701       15472 :             if (decl_type == ANYNONARRAYOID)
    1702       10956 :                 have_anynonarray = true;
    1703        4516 :             else if (decl_type == ANYENUMOID)
    1704         556 :                 have_anyenum = true;
    1705       15472 :             if (actual_type == UNKNOWNOID)
    1706             :             {
    1707         638 :                 have_unknowns = true;
    1708         638 :                 continue;
    1709             :             }
    1710       14834 :             if (allow_poly && decl_type == actual_type)
    1711         132 :                 continue;       /* no new information here */
    1712       14702 :             if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
    1713           0 :                 ereport(ERROR,
    1714             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1715             :                          errmsg("arguments declared \"anyelement\" are not all alike"),
    1716             :                          errdetail("%s versus %s",
    1717             :                                    format_type_be(elem_typeid),
    1718             :                                    format_type_be(actual_type))));
    1719       14702 :             elem_typeid = actual_type;
    1720             :         }
    1721     1315026 :         else if (decl_type == ANYARRAYOID)
    1722             :         {
    1723       49876 :             have_generics = true;
    1724       49876 :             if (actual_type == UNKNOWNOID)
    1725             :             {
    1726        5728 :                 have_unknowns = true;
    1727        5728 :                 continue;
    1728             :             }
    1729       44148 :             if (allow_poly && decl_type == actual_type)
    1730          60 :                 continue;       /* no new information here */
    1731       44088 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1732       44088 :             if (OidIsValid(array_typeid) && actual_type != array_typeid)
    1733           0 :                 ereport(ERROR,
    1734             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1735             :                          errmsg("arguments declared \"anyarray\" are not all alike"),
    1736             :                          errdetail("%s versus %s",
    1737             :                                    format_type_be(array_typeid),
    1738             :                                    format_type_be(actual_type))));
    1739       44088 :             array_typeid = actual_type;
    1740             :         }
    1741     1265150 :         else if (decl_type == ANYRANGEOID)
    1742             :         {
    1743        1712 :             have_generics = true;
    1744        1712 :             if (actual_type == UNKNOWNOID)
    1745             :             {
    1746          30 :                 have_unknowns = true;
    1747          30 :                 continue;
    1748             :             }
    1749        1682 :             if (allow_poly && decl_type == actual_type)
    1750           0 :                 continue;       /* no new information here */
    1751        1682 :             actual_type = getBaseType(actual_type); /* flatten domains */
    1752        1682 :             if (OidIsValid(range_typeid) && actual_type != range_typeid)
    1753           0 :                 ereport(ERROR,
    1754             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1755             :                          errmsg("arguments declared \"anyrange\" are not all alike"),
    1756             :                          errdetail("%s versus %s",
    1757             :                                    format_type_be(range_typeid),
    1758             :                                    format_type_be(actual_type))));
    1759        1682 :             range_typeid = actual_type;
    1760             :         }
    1761             :     }
    1762             : 
    1763             :     /*
    1764             :      * Fast Track: if none of the arguments are polymorphic, return the
    1765             :      * unmodified rettype.  We assume it can't be polymorphic either.
    1766             :      */
    1767      783984 :     if (!have_generics)
    1768      726944 :         return rettype;
    1769             : 
    1770             :     /* Get the element type based on the array type, if we have one */
    1771       57040 :     if (OidIsValid(array_typeid))
    1772             :     {
    1773       41968 :         if (array_typeid == ANYARRAYOID && !have_anyelement)
    1774             :         {
    1775             :             /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
    1776          12 :             array_typelem = ANYELEMENTOID;
    1777             :         }
    1778             :         else
    1779             :         {
    1780       41956 :             array_typelem = get_element_type(array_typeid);
    1781       41956 :             if (!OidIsValid(array_typelem))
    1782           0 :                 ereport(ERROR,
    1783             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1784             :                          errmsg("argument declared %s is not an array but type %s",
    1785             :                                 "anyarray", format_type_be(array_typeid))));
    1786             :         }
    1787             : 
    1788       41968 :         if (!OidIsValid(elem_typeid))
    1789             :         {
    1790             :             /*
    1791             :              * if we don't have an element type yet, use the one we just got
    1792             :              */
    1793       41590 :             elem_typeid = array_typelem;
    1794             :         }
    1795         378 :         else if (array_typelem != elem_typeid)
    1796             :         {
    1797             :             /* otherwise, they better match */
    1798           0 :             ereport(ERROR,
    1799             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1800             :                      errmsg("argument declared %s is not consistent with argument declared %s",
    1801             :                             "anyarray", "anyelement"),
    1802             :                      errdetail("%s versus %s",
    1803             :                                format_type_be(array_typeid),
    1804             :                                format_type_be(elem_typeid))));
    1805             :         }
    1806             :     }
    1807             : 
    1808             :     /* Get the element type based on the range type, if we have one */
    1809       57040 :     if (OidIsValid(range_typeid))
    1810             :     {
    1811         956 :         if (range_typeid == ANYRANGEOID && !have_anyelement)
    1812             :         {
    1813             :             /* Special case for ANYRANGE input: okay iff no ANYELEMENT */
    1814           0 :             range_typelem = ANYELEMENTOID;
    1815             :         }
    1816             :         else
    1817             :         {
    1818         956 :             range_typelem = get_range_subtype(range_typeid);
    1819         956 :             if (!OidIsValid(range_typelem))
    1820           0 :                 ereport(ERROR,
    1821             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1822             :                          errmsg("argument declared %s is not a range type but type %s",
    1823             :                                 "anyrange",
    1824             :                                 format_type_be(range_typeid))));
    1825             :         }
    1826             : 
    1827         956 :         if (!OidIsValid(elem_typeid))
    1828             :         {
    1829             :             /*
    1830             :              * if we don't have an element type yet, use the one we just got
    1831             :              */
    1832         864 :             elem_typeid = range_typelem;
    1833             :         }
    1834          92 :         else if (range_typelem != elem_typeid)
    1835             :         {
    1836             :             /* otherwise, they better match */
    1837           0 :             ereport(ERROR,
    1838             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1839             :                      errmsg("argument declared %s is not consistent with argument declared %s",
    1840             :                             "anyrange", "anyelement"),
    1841             :                      errdetail("%s versus %s",
    1842             :                                format_type_be(range_typeid),
    1843             :                                format_type_be(elem_typeid))));
    1844             :         }
    1845             :     }
    1846             : 
    1847       57040 :     if (!OidIsValid(elem_typeid))
    1848             :     {
    1849         142 :         if (allow_poly)
    1850             :         {
    1851         138 :             elem_typeid = ANYELEMENTOID;
    1852         138 :             array_typeid = ANYARRAYOID;
    1853         138 :             range_typeid = ANYRANGEOID;
    1854             :         }
    1855             :         else
    1856             :         {
    1857             :             /* Only way to get here is if all the generic args are UNKNOWN */
    1858           4 :             ereport(ERROR,
    1859             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1860             :                      errmsg("could not determine polymorphic type because input has type %s",
    1861             :                             "unknown")));
    1862             :         }
    1863             :     }
    1864             : 
    1865       57036 :     if (have_anynonarray && elem_typeid != ANYELEMENTOID)
    1866             :     {
    1867             :         /* require the element type to not be an array or domain over array */
    1868       10956 :         if (type_is_array_domain(elem_typeid))
    1869           0 :             ereport(ERROR,
    1870             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1871             :                      errmsg("type matched to anynonarray is an array type: %s",
    1872             :                             format_type_be(elem_typeid))));
    1873             :     }
    1874             : 
    1875       57036 :     if (have_anyenum && elem_typeid != ANYELEMENTOID)
    1876             :     {
    1877             :         /* require the element type to be an enum */
    1878         368 :         if (!type_is_enum(elem_typeid))
    1879           0 :             ereport(ERROR,
    1880             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1881             :                      errmsg("type matched to anyenum is not an enum type: %s",
    1882             :                             format_type_be(elem_typeid))));
    1883             :     }
    1884             : 
    1885             :     /*
    1886             :      * If we had any unknown inputs, re-scan to assign correct types
    1887             :      */
    1888       57036 :     if (have_unknowns)
    1889             :     {
    1890       19256 :         for (j = 0; j < nargs; j++)
    1891             :         {
    1892       12880 :             Oid         decl_type = declared_arg_types[j];
    1893       12880 :             Oid         actual_type = actual_arg_types[j];
    1894             : 
    1895       12880 :             if (actual_type != UNKNOWNOID)
    1896        6484 :                 continue;
    1897             : 
    1898        6396 :             if (decl_type == ANYELEMENTOID ||
    1899        5880 :                 decl_type == ANYNONARRAYOID ||
    1900             :                 decl_type == ANYENUMOID)
    1901         634 :                 declared_arg_types[j] = elem_typeid;
    1902        5762 :             else if (decl_type == ANYARRAYOID)
    1903             :             {
    1904        5728 :                 if (!OidIsValid(array_typeid))
    1905             :                 {
    1906          16 :                     array_typeid = get_array_type(elem_typeid);
    1907          16 :                     if (!OidIsValid(array_typeid))
    1908           0 :                         ereport(ERROR,
    1909             :                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1910             :                                  errmsg("could not find array type for data type %s",
    1911             :                                         format_type_be(elem_typeid))));
    1912             :                 }
    1913        5728 :                 declared_arg_types[j] = array_typeid;
    1914             :             }
    1915          34 :             else if (decl_type == ANYRANGEOID)
    1916             :             {
    1917          30 :                 if (!OidIsValid(range_typeid))
    1918             :                 {
    1919           0 :                     ereport(ERROR,
    1920             :                             (errcode(ERRCODE_UNDEFINED_OBJECT),
    1921             :                              errmsg("could not find range type for data type %s",
    1922             :                                     format_type_be(elem_typeid))));
    1923             :                 }
    1924          30 :                 declared_arg_types[j] = range_typeid;
    1925             :             }
    1926             :         }
    1927             :     }
    1928             : 
    1929             :     /* if we return ANYARRAY use the appropriate argument type */
    1930       57036 :     if (rettype == ANYARRAYOID)
    1931             :     {
    1932       12564 :         if (!OidIsValid(array_typeid))
    1933             :         {
    1934       10830 :             array_typeid = get_array_type(elem_typeid);
    1935       10830 :             if (!OidIsValid(array_typeid))
    1936           0 :                 ereport(ERROR,
    1937             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    1938             :                          errmsg("could not find array type for data type %s",
    1939             :                                 format_type_be(elem_typeid))));
    1940             :         }
    1941       12564 :         return array_typeid;
    1942             :     }
    1943             : 
    1944             :     /* if we return ANYRANGE use the appropriate argument type */
    1945       44472 :     if (rettype == ANYRANGEOID)
    1946             :     {
    1947          56 :         if (!OidIsValid(range_typeid))
    1948             :         {
    1949           0 :             ereport(ERROR,
    1950             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1951             :                      errmsg("could not find range type for data type %s",
    1952             :                             format_type_be(elem_typeid))));
    1953             :         }
    1954          56 :         return range_typeid;
    1955             :     }
    1956             : 
    1957             :     /* if we return ANYELEMENT use the appropriate argument type */
    1958       44416 :     if (rettype == ANYELEMENTOID ||
    1959       27444 :         rettype == ANYNONARRAYOID ||
    1960             :         rettype == ANYENUMOID)
    1961       17116 :         return elem_typeid;
    1962             : 
    1963             :     /* we don't return a generic type; send back the original return type */
    1964       27300 :     return rettype;
    1965             : }
    1966             : 
    1967             : /*
    1968             :  * resolve_generic_type()
    1969             :  *      Deduce an individual actual datatype on the assumption that
    1970             :  *      the rules for polymorphic types are being followed.
    1971             :  *
    1972             :  * declared_type is the declared datatype we want to resolve.
    1973             :  * context_actual_type is the actual input datatype to some argument
    1974             :  * that has declared datatype context_declared_type.
    1975             :  *
    1976             :  * If declared_type isn't polymorphic, we just return it.  Otherwise,
    1977             :  * context_declared_type must be polymorphic, and we deduce the correct
    1978             :  * return type based on the relationship of the two polymorphic types.
    1979             :  */
    1980             : Oid
    1981        5536 : resolve_generic_type(Oid declared_type,
    1982             :                      Oid context_actual_type,
    1983             :                      Oid context_declared_type)
    1984             : {
    1985        5536 :     if (declared_type == ANYARRAYOID)
    1986             :     {
    1987          48 :         if (context_declared_type == ANYARRAYOID)
    1988             :         {
    1989             :             /*
    1990             :              * Use actual type, but it must be an array; or if it's a domain
    1991             :              * over array, use the base array type.
    1992             :              */
    1993           0 :             Oid         context_base_type = getBaseType(context_actual_type);
    1994           0 :             Oid         array_typelem = get_element_type(context_base_type);
    1995             : 
    1996           0 :             if (!OidIsValid(array_typelem))
    1997           0 :                 ereport(ERROR,
    1998             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1999             :                          errmsg("argument declared %s is not an array but type %s",
    2000             :                                 "anyarray", format_type_be(context_base_type))));
    2001           0 :             return context_base_type;
    2002             :         }
    2003          48 :         else if (context_declared_type == ANYELEMENTOID ||
    2004           0 :                  context_declared_type == ANYNONARRAYOID ||
    2005           0 :                  context_declared_type == ANYENUMOID ||
    2006             :                  context_declared_type == ANYRANGEOID)
    2007             :         {
    2008             :             /* Use the array type corresponding to actual type */
    2009          48 :             Oid         array_typeid = get_array_type(context_actual_type);
    2010             : 
    2011          48 :             if (!OidIsValid(array_typeid))
    2012           0 :                 ereport(ERROR,
    2013             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    2014             :                          errmsg("could not find array type for data type %s",
    2015             :                                 format_type_be(context_actual_type))));
    2016          48 :             return array_typeid;
    2017             :         }
    2018             :     }
    2019        5488 :     else if (declared_type == ANYELEMENTOID ||
    2020           0 :              declared_type == ANYNONARRAYOID ||
    2021           0 :              declared_type == ANYENUMOID ||
    2022             :              declared_type == ANYRANGEOID)
    2023             :     {
    2024        5488 :         if (context_declared_type == ANYARRAYOID)
    2025             :         {
    2026             :             /* Use the element type corresponding to actual type */
    2027        5476 :             Oid         context_base_type = getBaseType(context_actual_type);
    2028        5476 :             Oid         array_typelem = get_element_type(context_base_type);
    2029             : 
    2030        5476 :             if (!OidIsValid(array_typelem))
    2031           0 :                 ereport(ERROR,
    2032             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2033             :                          errmsg("argument declared %s is not an array but type %s",
    2034             :                                 "anyarray", format_type_be(context_base_type))));
    2035        5476 :             return array_typelem;
    2036             :         }
    2037          12 :         else if (context_declared_type == ANYRANGEOID)
    2038             :         {
    2039             :             /* Use the element type corresponding to actual type */
    2040          12 :             Oid         context_base_type = getBaseType(context_actual_type);
    2041          12 :             Oid         range_typelem = get_range_subtype(context_base_type);
    2042             : 
    2043          12 :             if (!OidIsValid(range_typelem))
    2044           0 :                 ereport(ERROR,
    2045             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    2046             :                          errmsg("argument declared %s is not a range type but type %s",
    2047             :                                 "anyrange", format_type_be(context_base_type))));
    2048          12 :             return range_typelem;
    2049             :         }
    2050           0 :         else if (context_declared_type == ANYELEMENTOID ||
    2051           0 :                  context_declared_type == ANYNONARRAYOID ||
    2052             :                  context_declared_type == ANYENUMOID)
    2053             :         {
    2054             :             /* Use the actual type; it doesn't matter if array or not */
    2055           0 :             return context_actual_type;
    2056             :         }
    2057             :     }
    2058             :     else
    2059             :     {
    2060             :         /* declared_type isn't polymorphic, so return it as-is */
    2061           0 :         return declared_type;
    2062             :     }
    2063             :     /* If we get here, declared_type is polymorphic and context isn't */
    2064             :     /* NB: this is a calling-code logic error, not a user error */
    2065           0 :     elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
    2066             :     return InvalidOid;          /* keep compiler quiet */
    2067             : }
    2068             : 
    2069             : 
    2070             : /* TypeCategory()
    2071             :  *      Assign a category to the specified type OID.
    2072             :  *
    2073             :  * NB: this must not return TYPCATEGORY_INVALID.
    2074             :  */
    2075             : TYPCATEGORY
    2076       81710 : TypeCategory(Oid type)
    2077             : {
    2078             :     char        typcategory;
    2079             :     bool        typispreferred;
    2080             : 
    2081       81710 :     get_type_category_preferred(type, &typcategory, &typispreferred);
    2082             :     Assert(typcategory != TYPCATEGORY_INVALID);
    2083       81710 :     return (TYPCATEGORY) typcategory;
    2084             : }
    2085             : 
    2086             : 
    2087             : /* IsPreferredType()
    2088             :  *      Check if this type is a preferred type for the given category.
    2089             :  *
    2090             :  * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
    2091             :  * types of any category; otherwise, only for preferred types of that
    2092             :  * category.
    2093             :  */
    2094             : bool
    2095       24466 : IsPreferredType(TYPCATEGORY category, Oid type)
    2096             : {
    2097             :     char        typcategory;
    2098             :     bool        typispreferred;
    2099             : 
    2100       24466 :     get_type_category_preferred(type, &typcategory, &typispreferred);
    2101       24466 :     if (category == typcategory || category == TYPCATEGORY_INVALID)
    2102       18516 :         return typispreferred;
    2103             :     else
    2104        5950 :         return false;
    2105             : }
    2106             : 
    2107             : 
    2108             : /* IsBinaryCoercible()
    2109             :  *      Check if srctype is binary-coercible to targettype.
    2110             :  *
    2111             :  * This notion allows us to cheat and directly exchange values without
    2112             :  * going through the trouble of calling a conversion function.  Note that
    2113             :  * in general, this should only be an implementation shortcut.  Before 7.4,
    2114             :  * this was also used as a heuristic for resolving overloaded functions and
    2115             :  * operators, but that's basically a bad idea.
    2116             :  *
    2117             :  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
    2118             :  * We consider two types binary-coercible if there is an implicitly
    2119             :  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
    2120             :  * binary-coercible to its base type, though *not* vice versa (in the other
    2121             :  * direction, one must apply domain constraint checks before accepting the
    2122             :  * value as legitimate).  We also need to special-case various polymorphic
    2123             :  * types.
    2124             :  *
    2125             :  * This function replaces IsBinaryCompatible(), which was an inherently
    2126             :  * symmetric test.  Since the pg_cast entries aren't necessarily symmetric,
    2127             :  * the order of the operands is now significant.
    2128             :  */
    2129             : bool
    2130     1435472 : IsBinaryCoercible(Oid srctype, Oid targettype)
    2131             : {
    2132             :     HeapTuple   tuple;
    2133             :     Form_pg_cast castForm;
    2134             :     bool        result;
    2135             : 
    2136             :     /* Fast path if same type */
    2137     1435472 :     if (srctype == targettype)
    2138      695184 :         return true;
    2139             : 
    2140             :     /* Anything is coercible to ANY or ANYELEMENT */
    2141      740288 :     if (targettype == ANYOID || targettype == ANYELEMENTOID)
    2142         130 :         return true;
    2143             : 
    2144             :     /* If srctype is a domain, reduce to its base type */
    2145      740158 :     if (OidIsValid(srctype))
    2146      740158 :         srctype = getBaseType(srctype);
    2147             : 
    2148             :     /* Somewhat-fast path for domain -> base type case */
    2149      740158 :     if (srctype == targettype)
    2150          12 :         return true;
    2151             : 
    2152             :     /* Also accept any array type as coercible to ANYARRAY */
    2153      740146 :     if (targettype == ANYARRAYOID)
    2154       35030 :         if (type_is_array(srctype))
    2155        3114 :             return true;
    2156             : 
    2157             :     /* Also accept any non-array type as coercible to ANYNONARRAY */
    2158      737032 :     if (targettype == ANYNONARRAYOID)
    2159           0 :         if (!type_is_array(srctype))
    2160           0 :             return true;
    2161             : 
    2162             :     /* Also accept any enum type as coercible to ANYENUM */
    2163      737032 :     if (targettype == ANYENUMOID)
    2164       31362 :         if (type_is_enum(srctype))
    2165          80 :             return true;
    2166             : 
    2167             :     /* Also accept any range type as coercible to ANYRANGE */
    2168      736952 :     if (targettype == ANYRANGEOID)
    2169       12846 :         if (type_is_range(srctype))
    2170         200 :             return true;
    2171             : 
    2172             :     /* Also accept any composite type as coercible to RECORD */
    2173      736752 :     if (targettype == RECORDOID)
    2174       10086 :         if (ISCOMPLEX(srctype))
    2175         142 :             return true;
    2176             : 
    2177             :     /* Also accept any composite array type as coercible to RECORD[] */
    2178      736610 :     if (targettype == RECORDARRAYOID)
    2179           0 :         if (is_complex_array(srctype))
    2180           0 :             return true;
    2181             : 
    2182             :     /* Else look in pg_cast */
    2183      736610 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    2184             :                             ObjectIdGetDatum(srctype),
    2185             :                             ObjectIdGetDatum(targettype));
    2186      736610 :     if (!HeapTupleIsValid(tuple))
    2187      619414 :         return false;           /* no cast */
    2188      117196 :     castForm = (Form_pg_cast) GETSTRUCT(tuple);
    2189             : 
    2190      140108 :     result = (castForm->castmethod == COERCION_METHOD_BINARY &&
    2191       22912 :               castForm->castcontext == COERCION_CODE_IMPLICIT);
    2192             : 
    2193      117196 :     ReleaseSysCache(tuple);
    2194             : 
    2195      117196 :     return result;
    2196             : }
    2197             : 
    2198             : 
    2199             : /*
    2200             :  * find_coercion_pathway
    2201             :  *      Look for a coercion pathway between two types.
    2202             :  *
    2203             :  * Currently, this deals only with scalar-type cases; it does not consider
    2204             :  * polymorphic types nor casts between composite types.  (Perhaps fold
    2205             :  * those in someday?)
    2206             :  *
    2207             :  * ccontext determines the set of available casts.
    2208             :  *
    2209             :  * The possible result codes are:
    2210             :  *  COERCION_PATH_NONE: failed to find any coercion pathway
    2211             :  *              *funcid is set to InvalidOid
    2212             :  *  COERCION_PATH_FUNC: apply the coercion function returned in *funcid
    2213             :  *  COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
    2214             :  *              *funcid is set to InvalidOid
    2215             :  *  COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
    2216             :  *              *funcid is set to InvalidOid
    2217             :  *  COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
    2218             :  *              *funcid is set to InvalidOid
    2219             :  *
    2220             :  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
    2221             :  * needed to do the coercion; if the target is a domain then we may need to
    2222             :  * apply domain constraint checking.  If you want to check for a zero-effort
    2223             :  * conversion then use IsBinaryCoercible().
    2224             :  */
    2225             : CoercionPathType
    2226     1139372 : find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
    2227             :                       CoercionContext ccontext,
    2228             :                       Oid *funcid)
    2229             : {
    2230     1139372 :     CoercionPathType result = COERCION_PATH_NONE;
    2231             :     HeapTuple   tuple;
    2232             : 
    2233     1139372 :     *funcid = InvalidOid;
    2234             : 
    2235             :     /* Perhaps the types are domains; if so, look at their base types */
    2236     1139372 :     if (OidIsValid(sourceTypeId))
    2237     1139372 :         sourceTypeId = getBaseType(sourceTypeId);
    2238     1139372 :     if (OidIsValid(targetTypeId))
    2239     1139372 :         targetTypeId = getBaseType(targetTypeId);
    2240             : 
    2241             :     /* Domains are always coercible to and from their base type */
    2242     1139372 :     if (sourceTypeId == targetTypeId)
    2243       48314 :         return COERCION_PATH_RELABELTYPE;
    2244             : 
    2245             :     /* Look in pg_cast */
    2246     1091058 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    2247             :                             ObjectIdGetDatum(sourceTypeId),
    2248             :                             ObjectIdGetDatum(targetTypeId));
    2249             : 
    2250     1091058 :     if (HeapTupleIsValid(tuple))
    2251             :     {
    2252      525898 :         Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
    2253             :         CoercionContext castcontext;
    2254             : 
    2255             :         /* convert char value for castcontext to CoercionContext enum */
    2256      525898 :         switch (castForm->castcontext)
    2257             :         {
    2258             :             case COERCION_CODE_IMPLICIT:
    2259      295516 :                 castcontext = COERCION_IMPLICIT;
    2260      295516 :                 break;
    2261             :             case COERCION_CODE_ASSIGNMENT:
    2262      226236 :                 castcontext = COERCION_ASSIGNMENT;
    2263      226236 :                 break;
    2264             :             case COERCION_CODE_EXPLICIT:
    2265        4146 :                 castcontext = COERCION_EXPLICIT;
    2266        4146 :                 break;
    2267             :             default:
    2268           0 :                 elog(ERROR, "unrecognized castcontext: %d",
    2269             :                      (int) castForm->castcontext);
    2270             :                 castcontext = 0;    /* keep compiler quiet */
    2271             :                 break;
    2272             :         }
    2273             : 
    2274             :         /* Rely on ordering of enum for correct behavior here */
    2275      525898 :         if (ccontext >= castcontext)
    2276             :         {
    2277      475312 :             switch (castForm->castmethod)
    2278             :             {
    2279             :                 case COERCION_METHOD_FUNCTION:
    2280      270914 :                     result = COERCION_PATH_FUNC;
    2281      270914 :                     *funcid = castForm->castfunc;
    2282      270914 :                     break;
    2283             :                 case COERCION_METHOD_INOUT:
    2284           8 :                     result = COERCION_PATH_COERCEVIAIO;
    2285           8 :                     break;
    2286             :                 case COERCION_METHOD_BINARY:
    2287      204390 :                     result = COERCION_PATH_RELABELTYPE;
    2288      204390 :                     break;
    2289             :                 default:
    2290           0 :                     elog(ERROR, "unrecognized castmethod: %d",
    2291             :                          (int) castForm->castmethod);
    2292             :                     break;
    2293             :             }
    2294             :         }
    2295             : 
    2296      525898 :         ReleaseSysCache(tuple);
    2297             :     }
    2298             :     else
    2299             :     {
    2300             :         /*
    2301             :          * If there's no pg_cast entry, perhaps we are dealing with a pair of
    2302             :          * array types.  If so, and if their element types have a conversion
    2303             :          * pathway, report that we can coerce with an ArrayCoerceExpr.
    2304             :          *
    2305             :          * Hack: disallow coercions to oidvector and int2vector, which
    2306             :          * otherwise tend to capture coercions that should go to "real" array
    2307             :          * types.  We want those types to be considered "real" arrays for many
    2308             :          * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
    2309             :          * guaranteed to produce an output that meets the restrictions of
    2310             :          * these datatypes, such as being 1-dimensional.)
    2311             :          */
    2312      565160 :         if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
    2313             :         {
    2314             :             Oid         targetElem;
    2315             :             Oid         sourceElem;
    2316             : 
    2317      556660 :             if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
    2318             :                 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
    2319             :             {
    2320             :                 CoercionPathType elempathtype;
    2321             :                 Oid         elemfuncid;
    2322             : 
    2323        3214 :                 elempathtype = find_coercion_pathway(targetElem,
    2324             :                                                      sourceElem,
    2325             :                                                      ccontext,
    2326             :                                                      &elemfuncid);
    2327        3214 :                 if (elempathtype != COERCION_PATH_NONE)
    2328             :                 {
    2329        3134 :                     result = COERCION_PATH_ARRAYCOERCE;
    2330             :                 }
    2331             :             }
    2332             :         }
    2333             : 
    2334             :         /*
    2335             :          * If we still haven't found a possibility, consider automatic casting
    2336             :          * using I/O functions.  We allow assignment casts to string types and
    2337             :          * explicit casts from string types to be handled this way. (The
    2338             :          * CoerceViaIO mechanism is a lot more general than that, but this is
    2339             :          * all we want to allow in the absence of a pg_cast entry.) It would
    2340             :          * probably be better to insist on explicit casts in both directions,
    2341             :          * but this is a compromise to preserve something of the pre-8.3
    2342             :          * behavior that many types had implicit (yipes!) casts to text.
    2343             :          */
    2344      565160 :         if (result == COERCION_PATH_NONE)
    2345             :         {
    2346      592388 :             if (ccontext >= COERCION_ASSIGNMENT &&
    2347       30362 :                 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
    2348       27220 :                 result = COERCION_PATH_COERCEVIAIO;
    2349      537478 :             else if (ccontext >= COERCION_EXPLICIT &&
    2350        2672 :                      TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
    2351         692 :                 result = COERCION_PATH_COERCEVIAIO;
    2352             :         }
    2353             :     }
    2354             : 
    2355     1091058 :     return result;
    2356             : }
    2357             : 
    2358             : 
    2359             : /*
    2360             :  * find_typmod_coercion_function -- does the given type need length coercion?
    2361             :  *
    2362             :  * If the target type possesses a pg_cast function from itself to itself,
    2363             :  * it must need length coercion.
    2364             :  *
    2365             :  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
    2366             :  *
    2367             :  * If the given type is a varlena array type, we do not look for a coercion
    2368             :  * function associated directly with the array type, but instead look for
    2369             :  * one associated with the element type.  An ArrayCoerceExpr node must be
    2370             :  * used to apply such a function.  (Note: currently, it's pointless to
    2371             :  * return the funcid in this case, because it'll just get looked up again
    2372             :  * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
    2373             :  *
    2374             :  * We use the same result enum as find_coercion_pathway, but the only possible
    2375             :  * result codes are:
    2376             :  *  COERCION_PATH_NONE: no length coercion needed
    2377             :  *  COERCION_PATH_FUNC: apply the function returned in *funcid
    2378             :  *  COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
    2379             :  */
    2380             : CoercionPathType
    2381       28674 : find_typmod_coercion_function(Oid typeId,
    2382             :                               Oid *funcid)
    2383             : {
    2384             :     CoercionPathType result;
    2385             :     Type        targetType;
    2386             :     Form_pg_type typeForm;
    2387             :     HeapTuple   tuple;
    2388             : 
    2389       28674 :     *funcid = InvalidOid;
    2390       28674 :     result = COERCION_PATH_FUNC;
    2391             : 
    2392       28674 :     targetType = typeidType(typeId);
    2393       28674 :     typeForm = (Form_pg_type) GETSTRUCT(targetType);
    2394             : 
    2395             :     /* Check for a varlena array type */
    2396       28674 :     if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
    2397             :     {
    2398             :         /* Yes, switch our attention to the element type */
    2399          56 :         typeId = typeForm->typelem;
    2400          56 :         result = COERCION_PATH_ARRAYCOERCE;
    2401             :     }
    2402       28674 :     ReleaseSysCache(targetType);
    2403             : 
    2404             :     /* Look in pg_cast */
    2405       28674 :     tuple = SearchSysCache2(CASTSOURCETARGET,
    2406             :                             ObjectIdGetDatum(typeId),
    2407             :                             ObjectIdGetDatum(typeId));
    2408             : 
    2409       28674 :     if (HeapTupleIsValid(tuple))
    2410             :     {
    2411       28662 :         Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
    2412             : 
    2413       28662 :         *funcid = castForm->castfunc;
    2414       28662 :         ReleaseSysCache(tuple);
    2415             :     }
    2416             : 
    2417       28674 :     if (!OidIsValid(*funcid))
    2418          12 :         result = COERCION_PATH_NONE;
    2419             : 
    2420       28674 :     return result;
    2421             : }
    2422             : 
    2423             : /*
    2424             :  * is_complex_array
    2425             :  *      Is this type an array of composite?
    2426             :  *
    2427             :  * Note: this will not return true for record[]; check for RECORDARRAYOID
    2428             :  * separately if needed.
    2429             :  */
    2430             : static bool
    2431          12 : is_complex_array(Oid typid)
    2432             : {
    2433          12 :     Oid         elemtype = get_element_type(typid);
    2434             : 
    2435          12 :     return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
    2436             : }
    2437             : 
    2438             : 
    2439             : /*
    2440             :  * Check whether reltypeId is the row type of a typed table of type
    2441             :  * reloftypeId, or is a domain over such a row type.  (This is conceptually
    2442             :  * similar to the subtype relationship checked by typeInheritsFrom().)
    2443             :  */
    2444             : static bool
    2445      580940 : typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
    2446             : {
    2447      580940 :     Oid         relid = typeOrDomainTypeRelid(reltypeId);
    2448      580940 :     bool        result = false;
    2449             : 
    2450      580940 :     if (relid)
    2451             :     {
    2452             :         HeapTuple   tp;
    2453             :         Form_pg_class reltup;
    2454             : 
    2455        6450 :         tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    2456        6450 :         if (!HeapTupleIsValid(tp))
    2457           0 :             elog(ERROR, "cache lookup failed for relation %u", relid);
    2458             : 
    2459        6450 :         reltup = (Form_pg_class) GETSTRUCT(tp);
    2460        6450 :         if (reltup->reloftype == reloftypeId)
    2461           8 :             result = true;
    2462             : 
    2463        6450 :         ReleaseSysCache(tp);
    2464             :     }
    2465             : 
    2466      580940 :     return result;
    2467             : }

Generated by: LCOV version 1.13