LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_coerce.c (source / functions) Coverage Total Hit UBC GIC GNC CBC
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 92.4 % 1044 965 79 1 964
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 31 31 1 30
Baseline: lcov-20260827-baseline Branches: 76.3 % 1114 850 264 850
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 75.0 % 4 3 1 3
(30,360] days: 100.0 % 3 3 3
(360..) days: 92.5 % 1037 959 78 1 958
Function coverage date bins:
(360..) days: 100.0 % 31 31 1 30
Branch coverage date bins:
(7,30] days: 62.5 % 8 5 3 5
(360..) days: 76.4 % 1106 845 261 845

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

Generated by: LCOV version 2.0-1