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

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_expr.c
       4             :  *    handle expressions in parser
       5             :  *
       6             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/parser/parse_expr.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include "catalog/pg_type.h"
      19             : #include "commands/dbcommands.h"
      20             : #include "miscadmin.h"
      21             : #include "nodes/makefuncs.h"
      22             : #include "nodes/nodeFuncs.h"
      23             : #include "optimizer/optimizer.h"
      24             : #include "parser/analyze.h"
      25             : #include "parser/parse_agg.h"
      26             : #include "parser/parse_clause.h"
      27             : #include "parser/parse_coerce.h"
      28             : #include "parser/parse_collate.h"
      29             : #include "parser/parse_expr.h"
      30             : #include "parser/parse_func.h"
      31             : #include "parser/parse_oper.h"
      32             : #include "parser/parse_relation.h"
      33             : #include "parser/parse_target.h"
      34             : #include "parser/parse_type.h"
      35             : #include "utils/builtins.h"
      36             : #include "utils/date.h"
      37             : #include "utils/lsyscache.h"
      38             : #include "utils/timestamp.h"
      39             : #include "utils/xml.h"
      40             : 
      41             : /* GUC parameters */
      42             : bool        Transform_null_equals = false;
      43             : 
      44             : 
      45             : static Node *transformExprRecurse(ParseState *pstate, Node *expr);
      46             : static Node *transformParamRef(ParseState *pstate, ParamRef *pref);
      47             : static Node *transformAExprOp(ParseState *pstate, A_Expr *a);
      48             : static Node *transformAExprOpAny(ParseState *pstate, A_Expr *a);
      49             : static Node *transformAExprOpAll(ParseState *pstate, A_Expr *a);
      50             : static Node *transformAExprDistinct(ParseState *pstate, A_Expr *a);
      51             : static Node *transformAExprNullIf(ParseState *pstate, A_Expr *a);
      52             : static Node *transformAExprIn(ParseState *pstate, A_Expr *a);
      53             : static Node *transformAExprBetween(ParseState *pstate, A_Expr *a);
      54             : static Node *transformBoolExpr(ParseState *pstate, BoolExpr *a);
      55             : static Node *transformFuncCall(ParseState *pstate, FuncCall *fn);
      56             : static Node *transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref);
      57             : static Node *transformCaseExpr(ParseState *pstate, CaseExpr *c);
      58             : static Node *transformSubLink(ParseState *pstate, SubLink *sublink);
      59             : static Node *transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
      60             :                                 Oid array_type, Oid element_type, int32 typmod);
      61             : static Node *transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault);
      62             : static Node *transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c);
      63             : static Node *transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m);
      64             : static Node *transformSQLValueFunction(ParseState *pstate,
      65             :                                        SQLValueFunction *svf);
      66             : static Node *transformXmlExpr(ParseState *pstate, XmlExpr *x);
      67             : static Node *transformXmlSerialize(ParseState *pstate, XmlSerialize *xs);
      68             : static Node *transformBooleanTest(ParseState *pstate, BooleanTest *b);
      69             : static Node *transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr);
      70             : static Node *transformColumnRef(ParseState *pstate, ColumnRef *cref);
      71             : static Node *transformWholeRowRef(ParseState *pstate,
      72             :                                   ParseNamespaceItem *nsitem,
      73             :                                   int sublevels_up, int location);
      74             : static Node *transformIndirection(ParseState *pstate, A_Indirection *ind);
      75             : static Node *transformTypeCast(ParseState *pstate, TypeCast *tc);
      76             : static Node *transformCollateClause(ParseState *pstate, CollateClause *c);
      77             : static Node *make_row_comparison_op(ParseState *pstate, List *opname,
      78             :                                     List *largs, List *rargs, int location);
      79             : static Node *make_row_distinct_op(ParseState *pstate, List *opname,
      80             :                                   RowExpr *lrow, RowExpr *rrow, int location);
      81             : static Expr *make_distinct_op(ParseState *pstate, List *opname,
      82             :                               Node *ltree, Node *rtree, int location);
      83             : static Node *make_nulltest_from_distinct(ParseState *pstate,
      84             :                                          A_Expr *distincta, Node *arg);
      85             : 
      86             : 
      87             : /*
      88             :  * transformExpr -
      89             :  *    Analyze and transform expressions. Type checking and type casting is
      90             :  *    done here.  This processing converts the raw grammar output into
      91             :  *    expression trees with fully determined semantics.
      92             :  */
      93             : Node *
      94     3320638 : transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
      95             : {
      96             :     Node       *result;
      97             :     ParseExprKind sv_expr_kind;
      98             : 
      99             :     /* Save and restore identity of expression type we're parsing */
     100             :     Assert(exprKind != EXPR_KIND_NONE);
     101     3320638 :     sv_expr_kind = pstate->p_expr_kind;
     102     3320638 :     pstate->p_expr_kind = exprKind;
     103             : 
     104     3320638 :     result = transformExprRecurse(pstate, expr);
     105             : 
     106     3318080 :     pstate->p_expr_kind = sv_expr_kind;
     107             : 
     108     3318080 :     return result;
     109             : }
     110             : 
     111             : static Node *
     112     8800006 : transformExprRecurse(ParseState *pstate, Node *expr)
     113             : {
     114             :     Node       *result;
     115             : 
     116     8800006 :     if (expr == NULL)
     117      120936 :         return NULL;
     118             : 
     119             :     /* Guard against stack overflow due to overly complex expressions */
     120     8679070 :     check_stack_depth();
     121             : 
     122     8679070 :     switch (nodeTag(expr))
     123             :     {
     124     3609248 :         case T_ColumnRef:
     125     3609248 :             result = transformColumnRef(pstate, (ColumnRef *) expr);
     126     3608850 :             break;
     127             : 
     128      244394 :         case T_ParamRef:
     129      244394 :             result = transformParamRef(pstate, (ParamRef *) expr);
     130      244390 :             break;
     131             : 
     132     1619794 :         case T_A_Const:
     133     1619794 :             result = (Node *) make_const(pstate, (A_Const *) expr);
     134     1619794 :             break;
     135             : 
     136       65082 :         case T_A_Indirection:
     137       65082 :             result = transformIndirection(pstate, (A_Indirection *) expr);
     138       65022 :             break;
     139             : 
     140        3940 :         case T_A_ArrayExpr:
     141        3940 :             result = transformArrayExpr(pstate, (A_ArrayExpr *) expr,
     142             :                                         InvalidOid, InvalidOid, -1);
     143        3936 :             break;
     144             : 
     145      614960 :         case T_TypeCast:
     146      614960 :             result = transformTypeCast(pstate, (TypeCast *) expr);
     147      613644 :             break;
     148             : 
     149        3348 :         case T_CollateClause:
     150        3348 :             result = transformCollateClause(pstate, (CollateClause *) expr);
     151        3340 :             break;
     152             : 
     153     1059460 :         case T_A_Expr:
     154             :             {
     155     1059460 :                 A_Expr     *a = (A_Expr *) expr;
     156             : 
     157     1059460 :                 switch (a->kind)
     158             :                 {
     159      991658 :                     case AEXPR_OP:
     160      991658 :                         result = transformAExprOp(pstate, a);
     161      991404 :                         break;
     162        8890 :                     case AEXPR_OP_ANY:
     163        8890 :                         result = transformAExprOpAny(pstate, a);
     164        8882 :                         break;
     165         206 :                     case AEXPR_OP_ALL:
     166         206 :                         result = transformAExprOpAll(pstate, a);
     167         206 :                         break;
     168         546 :                     case AEXPR_DISTINCT:
     169             :                     case AEXPR_NOT_DISTINCT:
     170         546 :                         result = transformAExprDistinct(pstate, a);
     171         546 :                         break;
     172         690 :                     case AEXPR_NULLIF:
     173         690 :                         result = transformAExprNullIf(pstate, a);
     174         690 :                         break;
     175       55212 :                     case AEXPR_IN:
     176       55212 :                         result = transformAExprIn(pstate, a);
     177       55208 :                         break;
     178        1892 :                     case AEXPR_LIKE:
     179             :                     case AEXPR_ILIKE:
     180             :                     case AEXPR_SIMILAR:
     181             :                         /* we can transform these just like AEXPR_OP */
     182        1892 :                         result = transformAExprOp(pstate, a);
     183        1888 :                         break;
     184         366 :                     case AEXPR_BETWEEN:
     185             :                     case AEXPR_NOT_BETWEEN:
     186             :                     case AEXPR_BETWEEN_SYM:
     187             :                     case AEXPR_NOT_BETWEEN_SYM:
     188         366 :                         result = transformAExprBetween(pstate, a);
     189         366 :                         break;
     190           0 :                     default:
     191           0 :                         elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
     192             :                         result = NULL;  /* keep compiler quiet */
     193             :                         break;
     194             :                 }
     195     1059190 :                 break;
     196             :             }
     197             : 
     198      333516 :         case T_BoolExpr:
     199      333516 :             result = transformBoolExpr(pstate, (BoolExpr *) expr);
     200      333502 :             break;
     201             : 
     202      723128 :         case T_FuncCall:
     203      723128 :             result = transformFuncCall(pstate, (FuncCall *) expr);
     204      722480 :             break;
     205             : 
     206         210 :         case T_MultiAssignRef:
     207         210 :             result = transformMultiAssignRef(pstate, (MultiAssignRef *) expr);
     208         206 :             break;
     209             : 
     210         180 :         case T_GroupingFunc:
     211         180 :             result = transformGroupingFunc(pstate, (GroupingFunc *) expr);
     212         180 :             break;
     213             : 
     214       34048 :         case T_NamedArgExpr:
     215             :             {
     216       34048 :                 NamedArgExpr *na = (NamedArgExpr *) expr;
     217             : 
     218       34048 :                 na->arg = (Expr *) transformExprRecurse(pstate, (Node *) na->arg);
     219       34048 :                 result = expr;
     220       34048 :                 break;
     221             :             }
     222             : 
     223      122506 :         case T_SubLink:
     224      122506 :             result = transformSubLink(pstate, (SubLink *) expr);
     225      122446 :             break;
     226             : 
     227      133038 :         case T_CaseExpr:
     228      133038 :             result = transformCaseExpr(pstate, (CaseExpr *) expr);
     229      133034 :             break;
     230             : 
     231        8276 :         case T_RowExpr:
     232        8276 :             result = transformRowExpr(pstate, (RowExpr *) expr, false);
     233        8276 :             break;
     234             : 
     235       23178 :         case T_CoalesceExpr:
     236       23178 :             result = transformCoalesceExpr(pstate, (CoalesceExpr *) expr);
     237       23174 :             break;
     238             : 
     239         132 :         case T_MinMaxExpr:
     240         132 :             result = transformMinMaxExpr(pstate, (MinMaxExpr *) expr);
     241         132 :             break;
     242             : 
     243        4172 :         case T_SQLValueFunction:
     244        4172 :             result = transformSQLValueFunction(pstate,
     245             :                                                (SQLValueFunction *) expr);
     246        4172 :             break;
     247             : 
     248         398 :         case T_XmlExpr:
     249         398 :             result = transformXmlExpr(pstate, (XmlExpr *) expr);
     250         378 :             break;
     251             : 
     252          24 :         case T_XmlSerialize:
     253          24 :             result = transformXmlSerialize(pstate, (XmlSerialize *) expr);
     254          24 :             break;
     255             : 
     256       23302 :         case T_NullTest:
     257             :             {
     258       23302 :                 NullTest   *n = (NullTest *) expr;
     259             : 
     260       23302 :                 n->arg = (Expr *) transformExprRecurse(pstate, (Node *) n->arg);
     261             :                 /* the argument can be any type, so don't coerce it */
     262       23302 :                 n->argisrow = type_is_rowtype(exprType((Node *) n->arg));
     263       23302 :                 result = expr;
     264       23302 :                 break;
     265             :             }
     266             : 
     267         130 :         case T_BooleanTest:
     268         130 :             result = transformBooleanTest(pstate, (BooleanTest *) expr);
     269         130 :             break;
     270             : 
     271         164 :         case T_CurrentOfExpr:
     272         164 :             result = transformCurrentOfExpr(pstate, (CurrentOfExpr *) expr);
     273         164 :             break;
     274             : 
     275             :             /*
     276             :              * In all places where DEFAULT is legal, the caller should have
     277             :              * processed it rather than passing it to transformExpr().
     278             :              */
     279           0 :         case T_SetToDefault:
     280           0 :             ereport(ERROR,
     281             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     282             :                      errmsg("DEFAULT is not allowed in this context"),
     283             :                      parser_errposition(pstate,
     284             :                                         ((SetToDefault *) expr)->location)));
     285             :             break;
     286             : 
     287             :             /*
     288             :              * CaseTestExpr doesn't require any processing; it is only
     289             :              * injected into parse trees in a fully-formed state.
     290             :              *
     291             :              * Ordinarily we should not see a Var here, but it is convenient
     292             :              * for transformJoinUsingClause() to create untransformed operator
     293             :              * trees containing already-transformed Vars.  The best
     294             :              * alternative would be to deconstruct and reconstruct column
     295             :              * references, which seems expensively pointless.  So allow it.
     296             :              */
     297       52442 :         case T_CaseTestExpr:
     298             :         case T_Var:
     299             :             {
     300       52442 :                 result = (Node *) expr;
     301       52442 :                 break;
     302             :             }
     303             : 
     304           0 :         default:
     305             :             /* should not reach here */
     306           0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
     307             :             result = NULL;      /* keep compiler quiet */
     308             :             break;
     309             :     }
     310             : 
     311     8676256 :     return result;
     312             : }
     313             : 
     314             : /*
     315             :  * helper routine for delivering "column does not exist" error message
     316             :  *
     317             :  * (Usually we don't have to work this hard, but the general case of field
     318             :  * selection from an arbitrary node needs it.)
     319             :  */
     320             : static void
     321          24 : unknown_attribute(ParseState *pstate, Node *relref, const char *attname,
     322             :                   int location)
     323             : {
     324             :     RangeTblEntry *rte;
     325             : 
     326          24 :     if (IsA(relref, Var) &&
     327           8 :         ((Var *) relref)->varattno == InvalidAttrNumber)
     328             :     {
     329             :         /* Reference the RTE by alias not by actual table name */
     330           0 :         rte = GetRTEByRangeTablePosn(pstate,
     331             :                                      ((Var *) relref)->varno,
     332           0 :                                      ((Var *) relref)->varlevelsup);
     333           0 :         ereport(ERROR,
     334             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
     335             :                  errmsg("column %s.%s does not exist",
     336             :                         rte->eref->aliasname, attname),
     337             :                  parser_errposition(pstate, location)));
     338             :     }
     339             :     else
     340             :     {
     341             :         /* Have to do it by reference to the type of the expression */
     342          24 :         Oid         relTypeId = exprType(relref);
     343             : 
     344          24 :         if (ISCOMPLEX(relTypeId))
     345          12 :             ereport(ERROR,
     346             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
     347             :                      errmsg("column \"%s\" not found in data type %s",
     348             :                             attname, format_type_be(relTypeId)),
     349             :                      parser_errposition(pstate, location)));
     350          12 :         else if (relTypeId == RECORDOID)
     351          12 :             ereport(ERROR,
     352             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
     353             :                      errmsg("could not identify column \"%s\" in record data type",
     354             :                             attname),
     355             :                      parser_errposition(pstate, location)));
     356             :         else
     357           0 :             ereport(ERROR,
     358             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     359             :                      errmsg("column notation .%s applied to type %s, "
     360             :                             "which is not a composite type",
     361             :                             attname, format_type_be(relTypeId)),
     362             :                      parser_errposition(pstate, location)));
     363             :     }
     364             : }
     365             : 
     366             : static Node *
     367       65082 : transformIndirection(ParseState *pstate, A_Indirection *ind)
     368             : {
     369       65082 :     Node       *last_srf = pstate->p_last_srf;
     370       65082 :     Node       *result = transformExprRecurse(pstate, ind->arg);
     371       65082 :     List       *subscripts = NIL;
     372       65082 :     int         location = exprLocation(result);
     373             :     ListCell   *i;
     374             : 
     375             :     /*
     376             :      * We have to split any field-selection operations apart from
     377             :      * subscripting.  Adjacent A_Indices nodes have to be treated as a single
     378             :      * multidimensional subscript operation.
     379             :      */
     380      128352 :     foreach(i, ind->indirection)
     381             :     {
     382       63294 :         Node       *n = lfirst(i);
     383             : 
     384       63294 :         if (IsA(n, A_Indices))
     385       11564 :             subscripts = lappend(subscripts, n);
     386       51730 :         else if (IsA(n, A_Star))
     387             :         {
     388           0 :             ereport(ERROR,
     389             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     390             :                      errmsg("row expansion via \"*\" is not supported here"),
     391             :                      parser_errposition(pstate, location)));
     392             :         }
     393             :         else
     394             :         {
     395             :             Node       *newresult;
     396             : 
     397             :             Assert(IsA(n, String));
     398             : 
     399             :             /* process subscripts before this field selection */
     400       51730 :             if (subscripts)
     401          92 :                 result = (Node *) transformContainerSubscripts(pstate,
     402             :                                                                result,
     403             :                                                                exprType(result),
     404             :                                                                exprTypmod(result),
     405             :                                                                subscripts,
     406             :                                                                false);
     407       51730 :             subscripts = NIL;
     408             : 
     409       51730 :             newresult = ParseFuncOrColumn(pstate,
     410       51730 :                                           list_make1(n),
     411       51730 :                                           list_make1(result),
     412             :                                           last_srf,
     413             :                                           NULL,
     414             :                                           false,
     415             :                                           location);
     416       51730 :             if (newresult == NULL)
     417          24 :                 unknown_attribute(pstate, result, strVal(n), location);
     418       51706 :             result = newresult;
     419             :         }
     420             :     }
     421             :     /* process trailing subscripts, if any */
     422       65058 :     if (subscripts)
     423       11262 :         result = (Node *) transformContainerSubscripts(pstate,
     424             :                                                        result,
     425             :                                                        exprType(result),
     426             :                                                        exprTypmod(result),
     427             :                                                        subscripts,
     428             :                                                        false);
     429             : 
     430       65022 :     return result;
     431             : }
     432             : 
     433             : /*
     434             :  * Transform a ColumnRef.
     435             :  *
     436             :  * If you find yourself changing this code, see also ExpandColumnRefStar.
     437             :  */
     438             : static Node *
     439     3609248 : transformColumnRef(ParseState *pstate, ColumnRef *cref)
     440             : {
     441     3609248 :     Node       *node = NULL;
     442     3609248 :     char       *nspname = NULL;
     443     3609248 :     char       *relname = NULL;
     444     3609248 :     char       *colname = NULL;
     445             :     ParseNamespaceItem *nsitem;
     446             :     int         levels_up;
     447             :     enum
     448             :     {
     449             :         CRERR_NO_COLUMN,
     450             :         CRERR_NO_RTE,
     451             :         CRERR_WRONG_DB,
     452             :         CRERR_TOO_MANY
     453     3609248 :     }           crerr = CRERR_NO_COLUMN;
     454             :     const char *err;
     455             : 
     456             :     /*
     457             :      * Check to see if the column reference is in an invalid place within the
     458             :      * query.  We allow column references in most places, except in default
     459             :      * expressions and partition bound expressions.
     460             :      */
     461     3609248 :     err = NULL;
     462     3609248 :     switch (pstate->p_expr_kind)
     463             :     {
     464           0 :         case EXPR_KIND_NONE:
     465             :             Assert(false);      /* can't happen */
     466           0 :             break;
     467     3609192 :         case EXPR_KIND_OTHER:
     468             :         case EXPR_KIND_JOIN_ON:
     469             :         case EXPR_KIND_JOIN_USING:
     470             :         case EXPR_KIND_FROM_SUBSELECT:
     471             :         case EXPR_KIND_FROM_FUNCTION:
     472             :         case EXPR_KIND_WHERE:
     473             :         case EXPR_KIND_POLICY:
     474             :         case EXPR_KIND_HAVING:
     475             :         case EXPR_KIND_FILTER:
     476             :         case EXPR_KIND_WINDOW_PARTITION:
     477             :         case EXPR_KIND_WINDOW_ORDER:
     478             :         case EXPR_KIND_WINDOW_FRAME_RANGE:
     479             :         case EXPR_KIND_WINDOW_FRAME_ROWS:
     480             :         case EXPR_KIND_WINDOW_FRAME_GROUPS:
     481             :         case EXPR_KIND_SELECT_TARGET:
     482             :         case EXPR_KIND_INSERT_TARGET:
     483             :         case EXPR_KIND_UPDATE_SOURCE:
     484             :         case EXPR_KIND_UPDATE_TARGET:
     485             :         case EXPR_KIND_GROUP_BY:
     486             :         case EXPR_KIND_ORDER_BY:
     487             :         case EXPR_KIND_DISTINCT_ON:
     488             :         case EXPR_KIND_LIMIT:
     489             :         case EXPR_KIND_OFFSET:
     490             :         case EXPR_KIND_RETURNING:
     491             :         case EXPR_KIND_VALUES:
     492             :         case EXPR_KIND_VALUES_SINGLE:
     493             :         case EXPR_KIND_CHECK_CONSTRAINT:
     494             :         case EXPR_KIND_DOMAIN_CHECK:
     495             :         case EXPR_KIND_FUNCTION_DEFAULT:
     496             :         case EXPR_KIND_INDEX_EXPRESSION:
     497             :         case EXPR_KIND_INDEX_PREDICATE:
     498             :         case EXPR_KIND_STATS_EXPRESSION:
     499             :         case EXPR_KIND_ALTER_COL_TRANSFORM:
     500             :         case EXPR_KIND_EXECUTE_PARAMETER:
     501             :         case EXPR_KIND_TRIGGER_WHEN:
     502             :         case EXPR_KIND_PARTITION_EXPRESSION:
     503             :         case EXPR_KIND_CALL_ARGUMENT:
     504             :         case EXPR_KIND_COPY_WHERE:
     505             :         case EXPR_KIND_GENERATED_COLUMN:
     506             :         case EXPR_KIND_CYCLE_MARK:
     507             :             /* okay */
     508     3609192 :             break;
     509             : 
     510          16 :         case EXPR_KIND_COLUMN_DEFAULT:
     511          16 :             err = _("cannot use column reference in DEFAULT expression");
     512          16 :             break;
     513          40 :         case EXPR_KIND_PARTITION_BOUND:
     514          40 :             err = _("cannot use column reference in partition bound expression");
     515          40 :             break;
     516             : 
     517             :             /*
     518             :              * There is intentionally no default: case here, so that the
     519             :              * compiler will warn if we add a new ParseExprKind without
     520             :              * extending this switch.  If we do see an unrecognized value at
     521             :              * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
     522             :              * which is sane anyway.
     523             :              */
     524             :     }
     525     3609248 :     if (err)
     526          56 :         ereport(ERROR,
     527             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     528             :                  errmsg_internal("%s", err),
     529             :                  parser_errposition(pstate, cref->location)));
     530             : 
     531             :     /*
     532             :      * Give the PreParseColumnRefHook, if any, first shot.  If it returns
     533             :      * non-null then that's all, folks.
     534             :      */
     535     3609192 :     if (pstate->p_pre_columnref_hook != NULL)
     536             :     {
     537       24234 :         node = pstate->p_pre_columnref_hook(pstate, cref);
     538       24234 :         if (node != NULL)
     539        1318 :             return node;
     540             :     }
     541             : 
     542             :     /*----------
     543             :      * The allowed syntaxes are:
     544             :      *
     545             :      * A        First try to resolve as unqualified column name;
     546             :      *          if no luck, try to resolve as unqualified table name (A.*).
     547             :      * A.B      A is an unqualified table name; B is either a
     548             :      *          column or function name (trying column name first).
     549             :      * A.B.C    schema A, table B, col or func name C.
     550             :      * A.B.C.D  catalog A, schema B, table C, col or func D.
     551             :      * A.*      A is an unqualified table name; means whole-row value.
     552             :      * A.B.*    whole-row value of table B in schema A.
     553             :      * A.B.C.*  whole-row value of table C in schema B in catalog A.
     554             :      *
     555             :      * We do not need to cope with bare "*"; that will only be accepted by
     556             :      * the grammar at the top level of a SELECT list, and transformTargetList
     557             :      * will take care of it before it ever gets here.  Also, "A.*" etc will
     558             :      * be expanded by transformTargetList if they appear at SELECT top level,
     559             :      * so here we are only going to see them as function or operator inputs.
     560             :      *
     561             :      * Currently, if a catalog name is given then it must equal the current
     562             :      * database name; we check it here and then discard it.
     563             :      *----------
     564             :      */
     565     3607874 :     switch (list_length(cref->fields))
     566             :     {
     567      900388 :         case 1:
     568             :             {
     569      900388 :                 Node       *field1 = (Node *) linitial(cref->fields);
     570             : 
     571             :                 Assert(IsA(field1, String));
     572      900388 :                 colname = strVal(field1);
     573             : 
     574             :                 /* Try to identify as an unqualified column */
     575      900388 :                 node = colNameToVar(pstate, colname, false, cref->location);
     576             : 
     577      900352 :                 if (node == NULL)
     578             :                 {
     579             :                     /*
     580             :                      * Not known as a column of any range-table entry.
     581             :                      *
     582             :                      * Try to find the name as a relation.  Note that only
     583             :                      * relations already entered into the rangetable will be
     584             :                      * recognized.
     585             :                      *
     586             :                      * This is a hack for backwards compatibility with
     587             :                      * PostQUEL-inspired syntax.  The preferred form now is
     588             :                      * "rel.*".
     589             :                      */
     590       47128 :                     nsitem = refnameNamespaceItem(pstate, NULL, colname,
     591             :                                                   cref->location,
     592             :                                                   &levels_up);
     593       47128 :                     if (nsitem)
     594       27974 :                         node = transformWholeRowRef(pstate, nsitem, levels_up,
     595             :                                                     cref->location);
     596             :                 }
     597      900352 :                 break;
     598             :             }
     599     2707430 :         case 2:
     600             :             {
     601     2707430 :                 Node       *field1 = (Node *) linitial(cref->fields);
     602     2707430 :                 Node       *field2 = (Node *) lsecond(cref->fields);
     603             : 
     604             :                 Assert(IsA(field1, String));
     605     2707430 :                 relname = strVal(field1);
     606             : 
     607             :                 /* Locate the referenced nsitem */
     608     2707430 :                 nsitem = refnameNamespaceItem(pstate, nspname, relname,
     609             :                                               cref->location,
     610             :                                               &levels_up);
     611     2707414 :                 if (nsitem == NULL)
     612             :                 {
     613        3348 :                     crerr = CRERR_NO_RTE;
     614        3348 :                     break;
     615             :                 }
     616             : 
     617             :                 /* Whole-row reference? */
     618     2704066 :                 if (IsA(field2, A_Star))
     619             :                 {
     620         818 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     621             :                                                 cref->location);
     622         818 :                     break;
     623             :                 }
     624             : 
     625             :                 Assert(IsA(field2, String));
     626     2703248 :                 colname = strVal(field2);
     627             : 
     628             :                 /* Try to identify as a column of the nsitem */
     629     2703248 :                 node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
     630             :                                            cref->location);
     631     2703248 :                 if (node == NULL)
     632             :                 {
     633             :                     /* Try it as a function call on the whole row */
     634         108 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     635             :                                                 cref->location);
     636         108 :                     node = ParseFuncOrColumn(pstate,
     637         108 :                                              list_make1(makeString(colname)),
     638         108 :                                              list_make1(node),
     639             :                                              pstate->p_last_srf,
     640             :                                              NULL,
     641             :                                              false,
     642             :                                              cref->location);
     643             :                 }
     644     2703248 :                 break;
     645             :             }
     646          56 :         case 3:
     647             :             {
     648          56 :                 Node       *field1 = (Node *) linitial(cref->fields);
     649          56 :                 Node       *field2 = (Node *) lsecond(cref->fields);
     650          56 :                 Node       *field3 = (Node *) lthird(cref->fields);
     651             : 
     652             :                 Assert(IsA(field1, String));
     653          56 :                 nspname = strVal(field1);
     654             :                 Assert(IsA(field2, String));
     655          56 :                 relname = strVal(field2);
     656             : 
     657             :                 /* Locate the referenced nsitem */
     658          56 :                 nsitem = refnameNamespaceItem(pstate, nspname, relname,
     659             :                                               cref->location,
     660             :                                               &levels_up);
     661          56 :                 if (nsitem == NULL)
     662             :                 {
     663          52 :                     crerr = CRERR_NO_RTE;
     664          52 :                     break;
     665             :                 }
     666             : 
     667             :                 /* Whole-row reference? */
     668           4 :                 if (IsA(field3, A_Star))
     669             :                 {
     670           0 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     671             :                                                 cref->location);
     672           0 :                     break;
     673             :                 }
     674             : 
     675             :                 Assert(IsA(field3, String));
     676           4 :                 colname = strVal(field3);
     677             : 
     678             :                 /* Try to identify as a column of the nsitem */
     679           4 :                 node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
     680             :                                            cref->location);
     681           4 :                 if (node == NULL)
     682             :                 {
     683             :                     /* Try it as a function call on the whole row */
     684           0 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     685             :                                                 cref->location);
     686           0 :                     node = ParseFuncOrColumn(pstate,
     687           0 :                                              list_make1(makeString(colname)),
     688           0 :                                              list_make1(node),
     689             :                                              pstate->p_last_srf,
     690             :                                              NULL,
     691             :                                              false,
     692             :                                              cref->location);
     693             :                 }
     694           4 :                 break;
     695             :             }
     696           0 :         case 4:
     697             :             {
     698           0 :                 Node       *field1 = (Node *) linitial(cref->fields);
     699           0 :                 Node       *field2 = (Node *) lsecond(cref->fields);
     700           0 :                 Node       *field3 = (Node *) lthird(cref->fields);
     701           0 :                 Node       *field4 = (Node *) lfourth(cref->fields);
     702             :                 char       *catname;
     703             : 
     704             :                 Assert(IsA(field1, String));
     705           0 :                 catname = strVal(field1);
     706             :                 Assert(IsA(field2, String));
     707           0 :                 nspname = strVal(field2);
     708             :                 Assert(IsA(field3, String));
     709           0 :                 relname = strVal(field3);
     710             : 
     711             :                 /*
     712             :                  * We check the catalog name and then ignore it.
     713             :                  */
     714           0 :                 if (strcmp(catname, get_database_name(MyDatabaseId)) != 0)
     715             :                 {
     716           0 :                     crerr = CRERR_WRONG_DB;
     717           0 :                     break;
     718             :                 }
     719             : 
     720             :                 /* Locate the referenced nsitem */
     721           0 :                 nsitem = refnameNamespaceItem(pstate, nspname, relname,
     722             :                                               cref->location,
     723             :                                               &levels_up);
     724           0 :                 if (nsitem == NULL)
     725             :                 {
     726           0 :                     crerr = CRERR_NO_RTE;
     727           0 :                     break;
     728             :                 }
     729             : 
     730             :                 /* Whole-row reference? */
     731           0 :                 if (IsA(field4, A_Star))
     732             :                 {
     733           0 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     734             :                                                 cref->location);
     735           0 :                     break;
     736             :                 }
     737             : 
     738             :                 Assert(IsA(field4, String));
     739           0 :                 colname = strVal(field4);
     740             : 
     741             :                 /* Try to identify as a column of the nsitem */
     742           0 :                 node = scanNSItemForColumn(pstate, nsitem, levels_up, colname,
     743             :                                            cref->location);
     744           0 :                 if (node == NULL)
     745             :                 {
     746             :                     /* Try it as a function call on the whole row */
     747           0 :                     node = transformWholeRowRef(pstate, nsitem, levels_up,
     748             :                                                 cref->location);
     749           0 :                     node = ParseFuncOrColumn(pstate,
     750           0 :                                              list_make1(makeString(colname)),
     751           0 :                                              list_make1(node),
     752             :                                              pstate->p_last_srf,
     753             :                                              NULL,
     754             :                                              false,
     755             :                                              cref->location);
     756             :                 }
     757           0 :                 break;
     758             :             }
     759           0 :         default:
     760           0 :             crerr = CRERR_TOO_MANY; /* too many dotted names */
     761           0 :             break;
     762             :     }
     763             : 
     764             :     /*
     765             :      * Now give the PostParseColumnRefHook, if any, a chance.  We pass the
     766             :      * translation-so-far so that it can throw an error if it wishes in the
     767             :      * case that it has a conflicting interpretation of the ColumnRef. (If it
     768             :      * just translates anyway, we'll throw an error, because we can't undo
     769             :      * whatever effects the preceding steps may have had on the pstate.) If it
     770             :      * returns NULL, use the standard translation, or throw a suitable error
     771             :      * if there is none.
     772             :      */
     773     3607822 :     if (pstate->p_post_columnref_hook != NULL)
     774             :     {
     775             :         Node       *hookresult;
     776             : 
     777       52592 :         hookresult = pstate->p_post_columnref_hook(pstate, cref, node);
     778       52568 :         if (node == NULL)
     779       22332 :             node = hookresult;
     780       30236 :         else if (hookresult != NULL)
     781           0 :             ereport(ERROR,
     782             :                     (errcode(ERRCODE_AMBIGUOUS_COLUMN),
     783             :                      errmsg("column reference \"%s\" is ambiguous",
     784             :                             NameListToString(cref->fields)),
     785             :                      parser_errposition(pstate, cref->location)));
     786             :     }
     787             : 
     788             :     /*
     789             :      * Throw error if no translation found.
     790             :      */
     791     3607798 :     if (node == NULL)
     792             :     {
     793         266 :         switch (crerr)
     794             :         {
     795         214 :             case CRERR_NO_COLUMN:
     796         214 :                 errorMissingColumn(pstate, relname, colname, cref->location);
     797             :                 break;
     798          52 :             case CRERR_NO_RTE:
     799          52 :                 errorMissingRTE(pstate, makeRangeVar(nspname, relname,
     800             :                                                      cref->location));
     801             :                 break;
     802           0 :             case CRERR_WRONG_DB:
     803           0 :                 ereport(ERROR,
     804             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     805             :                          errmsg("cross-database references are not implemented: %s",
     806             :                                 NameListToString(cref->fields)),
     807             :                          parser_errposition(pstate, cref->location)));
     808             :                 break;
     809           0 :             case CRERR_TOO_MANY:
     810           0 :                 ereport(ERROR,
     811             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     812             :                          errmsg("improper qualified name (too many dotted names): %s",
     813             :                                 NameListToString(cref->fields)),
     814             :                          parser_errposition(pstate, cref->location)));
     815             :                 break;
     816             :         }
     817     3607532 :     }
     818             : 
     819     3607532 :     return node;
     820             : }
     821             : 
     822             : static Node *
     823      244394 : transformParamRef(ParseState *pstate, ParamRef *pref)
     824             : {
     825             :     Node       *result;
     826             : 
     827             :     /*
     828             :      * The core parser knows nothing about Params.  If a hook is supplied,
     829             :      * call it.  If not, or if the hook returns NULL, throw a generic error.
     830             :      */
     831      244394 :     if (pstate->p_paramref_hook != NULL)
     832      244394 :         result = pstate->p_paramref_hook(pstate, pref);
     833             :     else
     834           0 :         result = NULL;
     835             : 
     836      244394 :     if (result == NULL)
     837           4 :         ereport(ERROR,
     838             :                 (errcode(ERRCODE_UNDEFINED_PARAMETER),
     839             :                  errmsg("there is no parameter $%d", pref->number),
     840             :                  parser_errposition(pstate, pref->location)));
     841             : 
     842      244390 :     return result;
     843             : }
     844             : 
     845             : /* Test whether an a_expr is a plain NULL constant or not */
     846             : static bool
     847        1072 : exprIsNullConstant(Node *arg)
     848             : {
     849        1072 :     if (arg && IsA(arg, A_Const))
     850             :     {
     851          68 :         A_Const    *con = (A_Const *) arg;
     852             : 
     853          68 :         if (con->isnull)
     854          20 :             return true;
     855             :     }
     856        1052 :     return false;
     857             : }
     858             : 
     859             : static Node *
     860      993550 : transformAExprOp(ParseState *pstate, A_Expr *a)
     861             : {
     862      993550 :     Node       *lexpr = a->lexpr;
     863      993550 :     Node       *rexpr = a->rexpr;
     864             :     Node       *result;
     865             : 
     866             :     /*
     867             :      * Special-case "foo = NULL" and "NULL = foo" for compatibility with
     868             :      * standards-broken products (like Microsoft's).  Turn these into IS NULL
     869             :      * exprs. (If either side is a CaseTestExpr, then the expression was
     870             :      * generated internally from a CASE-WHEN expression, and
     871             :      * transform_null_equals does not apply.)
     872             :      */
     873      993550 :     if (Transform_null_equals &&
     874           0 :         list_length(a->name) == 1 &&
     875           0 :         strcmp(strVal(linitial(a->name)), "=") == 0 &&
     876           0 :         (exprIsNullConstant(lexpr) || exprIsNullConstant(rexpr)) &&
     877           0 :         (!IsA(lexpr, CaseTestExpr) && !IsA(rexpr, CaseTestExpr)))
     878           0 :     {
     879           0 :         NullTest   *n = makeNode(NullTest);
     880             : 
     881           0 :         n->nulltesttype = IS_NULL;
     882           0 :         n->location = a->location;
     883             : 
     884           0 :         if (exprIsNullConstant(lexpr))
     885           0 :             n->arg = (Expr *) rexpr;
     886             :         else
     887           0 :             n->arg = (Expr *) lexpr;
     888             : 
     889           0 :         result = transformExprRecurse(pstate, (Node *) n);
     890             :     }
     891      993550 :     else if (lexpr && IsA(lexpr, RowExpr) &&
     892        2538 :              rexpr && IsA(rexpr, SubLink) &&
     893           0 :              ((SubLink *) rexpr)->subLinkType == EXPR_SUBLINK)
     894           0 :     {
     895             :         /*
     896             :          * Convert "row op subselect" into a ROWCOMPARE sublink. Formerly the
     897             :          * grammar did this, but now that a row construct is allowed anywhere
     898             :          * in expressions, it's easier to do it here.
     899             :          */
     900           0 :         SubLink    *s = (SubLink *) rexpr;
     901             : 
     902           0 :         s->subLinkType = ROWCOMPARE_SUBLINK;
     903           0 :         s->testexpr = lexpr;
     904           0 :         s->operName = a->name;
     905           0 :         s->location = a->location;
     906           0 :         result = transformExprRecurse(pstate, (Node *) s);
     907             :     }
     908      993550 :     else if (lexpr && IsA(lexpr, RowExpr) &&
     909        2538 :              rexpr && IsA(rexpr, RowExpr))
     910             :     {
     911             :         /* ROW() op ROW() is handled specially */
     912        2538 :         lexpr = transformExprRecurse(pstate, lexpr);
     913        2538 :         rexpr = transformExprRecurse(pstate, rexpr);
     914             : 
     915        2538 :         result = make_row_comparison_op(pstate,
     916             :                                         a->name,
     917             :                                         castNode(RowExpr, lexpr)->args,
     918             :                                         castNode(RowExpr, rexpr)->args,
     919             :                                         a->location);
     920             :     }
     921             :     else
     922             :     {
     923             :         /* Ordinary scalar operator */
     924      991012 :         Node       *last_srf = pstate->p_last_srf;
     925             : 
     926      991012 :         lexpr = transformExprRecurse(pstate, lexpr);
     927      990880 :         rexpr = transformExprRecurse(pstate, rexpr);
     928             : 
     929      990826 :         result = (Node *) make_op(pstate,
     930             :                                   a->name,
     931             :                                   lexpr,
     932             :                                   rexpr,
     933             :                                   last_srf,
     934             :                                   a->location);
     935             :     }
     936             : 
     937      993292 :     return result;
     938             : }
     939             : 
     940             : static Node *
     941        8890 : transformAExprOpAny(ParseState *pstate, A_Expr *a)
     942             : {
     943        8890 :     Node       *lexpr = transformExprRecurse(pstate, a->lexpr);
     944        8890 :     Node       *rexpr = transformExprRecurse(pstate, a->rexpr);
     945             : 
     946        8890 :     return (Node *) make_scalar_array_op(pstate,
     947             :                                          a->name,
     948             :                                          true,
     949             :                                          lexpr,
     950             :                                          rexpr,
     951             :                                          a->location);
     952             : }
     953             : 
     954             : static Node *
     955         206 : transformAExprOpAll(ParseState *pstate, A_Expr *a)
     956             : {
     957         206 :     Node       *lexpr = transformExprRecurse(pstate, a->lexpr);
     958         206 :     Node       *rexpr = transformExprRecurse(pstate, a->rexpr);
     959             : 
     960         206 :     return (Node *) make_scalar_array_op(pstate,
     961             :                                          a->name,
     962             :                                          false,
     963             :                                          lexpr,
     964             :                                          rexpr,
     965             :                                          a->location);
     966             : }
     967             : 
     968             : static Node *
     969         546 : transformAExprDistinct(ParseState *pstate, A_Expr *a)
     970             : {
     971         546 :     Node       *lexpr = a->lexpr;
     972         546 :     Node       *rexpr = a->rexpr;
     973             :     Node       *result;
     974             : 
     975             :     /*
     976             :      * If either input is an undecorated NULL literal, transform to a NullTest
     977             :      * on the other input. That's simpler to process than a full DistinctExpr,
     978             :      * and it avoids needing to require that the datatype have an = operator.
     979             :      */
     980         546 :     if (exprIsNullConstant(rexpr))
     981          20 :         return make_nulltest_from_distinct(pstate, a, lexpr);
     982         526 :     if (exprIsNullConstant(lexpr))
     983           0 :         return make_nulltest_from_distinct(pstate, a, rexpr);
     984             : 
     985         526 :     lexpr = transformExprRecurse(pstate, lexpr);
     986         526 :     rexpr = transformExprRecurse(pstate, rexpr);
     987             : 
     988         526 :     if (lexpr && IsA(lexpr, RowExpr) &&
     989           4 :         rexpr && IsA(rexpr, RowExpr))
     990             :     {
     991             :         /* ROW() op ROW() is handled specially */
     992           4 :         result = make_row_distinct_op(pstate, a->name,
     993             :                                       (RowExpr *) lexpr,
     994             :                                       (RowExpr *) rexpr,
     995             :                                       a->location);
     996             :     }
     997             :     else
     998             :     {
     999             :         /* Ordinary scalar operator */
    1000         522 :         result = (Node *) make_distinct_op(pstate,
    1001             :                                            a->name,
    1002             :                                            lexpr,
    1003             :                                            rexpr,
    1004             :                                            a->location);
    1005             :     }
    1006             : 
    1007             :     /*
    1008             :      * If it's NOT DISTINCT, we first build a DistinctExpr and then stick a
    1009             :      * NOT on top.
    1010             :      */
    1011         526 :     if (a->kind == AEXPR_NOT_DISTINCT)
    1012          32 :         result = (Node *) makeBoolExpr(NOT_EXPR,
    1013          32 :                                        list_make1(result),
    1014             :                                        a->location);
    1015             : 
    1016         526 :     return result;
    1017             : }
    1018             : 
    1019             : static Node *
    1020         690 : transformAExprNullIf(ParseState *pstate, A_Expr *a)
    1021             : {
    1022         690 :     Node       *lexpr = transformExprRecurse(pstate, a->lexpr);
    1023         690 :     Node       *rexpr = transformExprRecurse(pstate, a->rexpr);
    1024             :     OpExpr     *result;
    1025             : 
    1026         690 :     result = (OpExpr *) make_op(pstate,
    1027             :                                 a->name,
    1028             :                                 lexpr,
    1029             :                                 rexpr,
    1030             :                                 pstate->p_last_srf,
    1031             :                                 a->location);
    1032             : 
    1033             :     /*
    1034             :      * The comparison operator itself should yield boolean ...
    1035             :      */
    1036         690 :     if (result->opresulttype != BOOLOID)
    1037           0 :         ereport(ERROR,
    1038             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1039             :                  errmsg("NULLIF requires = operator to yield boolean"),
    1040             :                  parser_errposition(pstate, a->location)));
    1041         690 :     if (result->opretset)
    1042           0 :         ereport(ERROR,
    1043             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1044             :         /* translator: %s is name of a SQL construct, eg NULLIF */
    1045             :                  errmsg("%s must not return a set", "NULLIF"),
    1046             :                  parser_errposition(pstate, a->location)));
    1047             : 
    1048             :     /*
    1049             :      * ... but the NullIfExpr will yield the first operand's type.
    1050             :      */
    1051         690 :     result->opresulttype = exprType((Node *) linitial(result->args));
    1052             : 
    1053             :     /*
    1054             :      * We rely on NullIfExpr and OpExpr being the same struct
    1055             :      */
    1056         690 :     NodeSetTag(result, T_NullIfExpr);
    1057             : 
    1058         690 :     return (Node *) result;
    1059             : }
    1060             : 
    1061             : static Node *
    1062       55212 : transformAExprIn(ParseState *pstate, A_Expr *a)
    1063             : {
    1064       55212 :     Node       *result = NULL;
    1065             :     Node       *lexpr;
    1066             :     List       *rexprs;
    1067             :     List       *rvars;
    1068             :     List       *rnonvars;
    1069             :     bool        useOr;
    1070             :     ListCell   *l;
    1071             : 
    1072             :     /*
    1073             :      * If the operator is <>, combine with AND not OR.
    1074             :      */
    1075       55212 :     if (strcmp(strVal(linitial(a->name)), "<>") == 0)
    1076        4214 :         useOr = false;
    1077             :     else
    1078       50998 :         useOr = true;
    1079             : 
    1080             :     /*
    1081             :      * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
    1082             :      * possible if there is a suitable array type available.  If not, we fall
    1083             :      * back to a boolean condition tree with multiple copies of the lefthand
    1084             :      * expression.  Also, any IN-list items that contain Vars are handled as
    1085             :      * separate boolean conditions, because that gives the planner more scope
    1086             :      * for optimization on such clauses.
    1087             :      *
    1088             :      * First step: transform all the inputs, and detect whether any contain
    1089             :      * Vars.
    1090             :      */
    1091       55212 :     lexpr = transformExprRecurse(pstate, a->lexpr);
    1092       55212 :     rexprs = rvars = rnonvars = NIL;
    1093      203824 :     foreach(l, (List *) a->rexpr)
    1094             :     {
    1095      148616 :         Node       *rexpr = transformExprRecurse(pstate, lfirst(l));
    1096             : 
    1097      148612 :         rexprs = lappend(rexprs, rexpr);
    1098      148612 :         if (contain_vars_of_level(rexpr, 0))
    1099           0 :             rvars = lappend(rvars, rexpr);
    1100             :         else
    1101      148612 :             rnonvars = lappend(rnonvars, rexpr);
    1102             :     }
    1103             : 
    1104             :     /*
    1105             :      * ScalarArrayOpExpr is only going to be useful if there's more than one
    1106             :      * non-Var righthand item.
    1107             :      */
    1108       55208 :     if (list_length(rnonvars) > 1)
    1109             :     {
    1110             :         List       *allexprs;
    1111             :         Oid         scalar_type;
    1112             :         Oid         array_type;
    1113             : 
    1114             :         /*
    1115             :          * Try to select a common type for the array elements.  Note that
    1116             :          * since the LHS' type is first in the list, it will be preferred when
    1117             :          * there is doubt (eg, when all the RHS items are unknown literals).
    1118             :          *
    1119             :          * Note: use list_concat here not lcons, to avoid damaging rnonvars.
    1120             :          */
    1121       49140 :         allexprs = list_concat(list_make1(lexpr), rnonvars);
    1122       49140 :         scalar_type = select_common_type(pstate, allexprs, NULL, NULL);
    1123             : 
    1124             :         /*
    1125             :          * Do we have an array type to use?  Aside from the case where there
    1126             :          * isn't one, we don't risk using ScalarArrayOpExpr when the common
    1127             :          * type is RECORD, because the RowExpr comparison logic below can cope
    1128             :          * with some cases of non-identical row types.
    1129             :          */
    1130       49140 :         if (OidIsValid(scalar_type) && scalar_type != RECORDOID)
    1131       49128 :             array_type = get_array_type(scalar_type);
    1132             :         else
    1133          12 :             array_type = InvalidOid;
    1134       49140 :         if (array_type != InvalidOid)
    1135             :         {
    1136             :             /*
    1137             :              * OK: coerce all the right-hand non-Var inputs to the common type
    1138             :              * and build an ArrayExpr for them.
    1139             :              */
    1140             :             List       *aexprs;
    1141             :             ArrayExpr  *newa;
    1142             : 
    1143       49120 :             aexprs = NIL;
    1144      191624 :             foreach(l, rnonvars)
    1145             :             {
    1146      142504 :                 Node       *rexpr = (Node *) lfirst(l);
    1147             : 
    1148      142504 :                 rexpr = coerce_to_common_type(pstate, rexpr,
    1149             :                                               scalar_type,
    1150             :                                               "IN");
    1151      142504 :                 aexprs = lappend(aexprs, rexpr);
    1152             :             }
    1153       49120 :             newa = makeNode(ArrayExpr);
    1154       49120 :             newa->array_typeid = array_type;
    1155             :             /* array_collid will be set by parse_collate.c */
    1156       49120 :             newa->element_typeid = scalar_type;
    1157       49120 :             newa->elements = aexprs;
    1158       49120 :             newa->multidims = false;
    1159       49120 :             newa->location = -1;
    1160             : 
    1161       49120 :             result = (Node *) make_scalar_array_op(pstate,
    1162             :                                                    a->name,
    1163             :                                                    useOr,
    1164             :                                                    lexpr,
    1165             :                                                    (Node *) newa,
    1166             :                                                    a->location);
    1167             : 
    1168             :             /* Consider only the Vars (if any) in the loop below */
    1169       49120 :             rexprs = rvars;
    1170             :         }
    1171             :     }
    1172             : 
    1173             :     /*
    1174             :      * Must do it the hard way, ie, with a boolean expression tree.
    1175             :      */
    1176       61316 :     foreach(l, rexprs)
    1177             :     {
    1178        6108 :         Node       *rexpr = (Node *) lfirst(l);
    1179             :         Node       *cmp;
    1180             : 
    1181        6108 :         if (IsA(lexpr, RowExpr) &&
    1182          24 :             IsA(rexpr, RowExpr))
    1183             :         {
    1184             :             /* ROW() op ROW() is handled specially */
    1185          24 :             cmp = make_row_comparison_op(pstate,
    1186             :                                          a->name,
    1187          24 :                                          copyObject(((RowExpr *) lexpr)->args),
    1188             :                                          ((RowExpr *) rexpr)->args,
    1189             :                                          a->location);
    1190             :         }
    1191             :         else
    1192             :         {
    1193             :             /* Ordinary scalar operator */
    1194        6084 :             cmp = (Node *) make_op(pstate,
    1195             :                                    a->name,
    1196        6084 :                                    copyObject(lexpr),
    1197             :                                    rexpr,
    1198             :                                    pstate->p_last_srf,
    1199             :                                    a->location);
    1200             :         }
    1201             : 
    1202        6108 :         cmp = coerce_to_boolean(pstate, cmp, "IN");
    1203        6108 :         if (result == NULL)
    1204        6088 :             result = cmp;
    1205             :         else
    1206          20 :             result = (Node *) makeBoolExpr(useOr ? OR_EXPR : AND_EXPR,
    1207          20 :                                            list_make2(result, cmp),
    1208             :                                            a->location);
    1209             :     }
    1210             : 
    1211       55208 :     return result;
    1212             : }
    1213             : 
    1214             : static Node *
    1215         366 : transformAExprBetween(ParseState *pstate, A_Expr *a)
    1216             : {
    1217             :     Node       *aexpr;
    1218             :     Node       *bexpr;
    1219             :     Node       *cexpr;
    1220             :     Node       *result;
    1221             :     Node       *sub1;
    1222             :     Node       *sub2;
    1223             :     List       *args;
    1224             : 
    1225             :     /* Deconstruct A_Expr into three subexprs */
    1226         366 :     aexpr = a->lexpr;
    1227         366 :     args = castNode(List, a->rexpr);
    1228             :     Assert(list_length(args) == 2);
    1229         366 :     bexpr = (Node *) linitial(args);
    1230         366 :     cexpr = (Node *) lsecond(args);
    1231             : 
    1232             :     /*
    1233             :      * Build the equivalent comparison expression.  Make copies of
    1234             :      * multiply-referenced subexpressions for safety.  (XXX this is really
    1235             :      * wrong since it results in multiple runtime evaluations of what may be
    1236             :      * volatile expressions ...)
    1237             :      *
    1238             :      * Ideally we would not use hard-wired operators here but instead use
    1239             :      * opclasses.  However, mixed data types and other issues make this
    1240             :      * difficult:
    1241             :      * http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
    1242             :      */
    1243         366 :     switch (a->kind)
    1244             :     {
    1245         338 :         case AEXPR_BETWEEN:
    1246         338 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
    1247             :                                                aexpr, bexpr,
    1248             :                                                a->location),
    1249             :                               makeSimpleA_Expr(AEXPR_OP, "<=",
    1250             :                                                copyObject(aexpr), cexpr,
    1251             :                                                a->location));
    1252         338 :             result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
    1253         338 :             break;
    1254          12 :         case AEXPR_NOT_BETWEEN:
    1255          12 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
    1256             :                                                aexpr, bexpr,
    1257             :                                                a->location),
    1258             :                               makeSimpleA_Expr(AEXPR_OP, ">",
    1259             :                                                copyObject(aexpr), cexpr,
    1260             :                                                a->location));
    1261          12 :             result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
    1262          12 :             break;
    1263           8 :         case AEXPR_BETWEEN_SYM:
    1264           8 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
    1265             :                                                aexpr, bexpr,
    1266             :                                                a->location),
    1267             :                               makeSimpleA_Expr(AEXPR_OP, "<=",
    1268             :                                                copyObject(aexpr), cexpr,
    1269             :                                                a->location));
    1270           8 :             sub1 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
    1271           8 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, ">=",
    1272             :                                                copyObject(aexpr), copyObject(cexpr),
    1273             :                                                a->location),
    1274             :                               makeSimpleA_Expr(AEXPR_OP, "<=",
    1275             :                                                copyObject(aexpr), copyObject(bexpr),
    1276             :                                                a->location));
    1277           8 :             sub2 = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
    1278           8 :             args = list_make2(sub1, sub2);
    1279           8 :             result = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
    1280           8 :             break;
    1281           8 :         case AEXPR_NOT_BETWEEN_SYM:
    1282           8 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
    1283             :                                                aexpr, bexpr,
    1284             :                                                a->location),
    1285             :                               makeSimpleA_Expr(AEXPR_OP, ">",
    1286             :                                                copyObject(aexpr), cexpr,
    1287             :                                                a->location));
    1288           8 :             sub1 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
    1289           8 :             args = list_make2(makeSimpleA_Expr(AEXPR_OP, "<",
    1290             :                                                copyObject(aexpr), copyObject(cexpr),
    1291             :                                                a->location),
    1292             :                               makeSimpleA_Expr(AEXPR_OP, ">",
    1293             :                                                copyObject(aexpr), copyObject(bexpr),
    1294             :                                                a->location));
    1295           8 :             sub2 = (Node *) makeBoolExpr(OR_EXPR, args, a->location);
    1296           8 :             args = list_make2(sub1, sub2);
    1297           8 :             result = (Node *) makeBoolExpr(AND_EXPR, args, a->location);
    1298           8 :             break;
    1299           0 :         default:
    1300           0 :             elog(ERROR, "unrecognized A_Expr kind: %d", a->kind);
    1301             :             result = NULL;      /* keep compiler quiet */
    1302             :             break;
    1303             :     }
    1304             : 
    1305         366 :     return transformExprRecurse(pstate, result);
    1306             : }
    1307             : 
    1308             : static Node *
    1309      333516 : transformBoolExpr(ParseState *pstate, BoolExpr *a)
    1310             : {
    1311      333516 :     List       *args = NIL;
    1312             :     const char *opname;
    1313             :     ListCell   *lc;
    1314             : 
    1315      333516 :     switch (a->boolop)
    1316             :     {
    1317      229684 :         case AND_EXPR:
    1318      229684 :             opname = "AND";
    1319      229684 :             break;
    1320       44832 :         case OR_EXPR:
    1321       44832 :             opname = "OR";
    1322       44832 :             break;
    1323       59000 :         case NOT_EXPR:
    1324       59000 :             opname = "NOT";
    1325       59000 :             break;
    1326           0 :         default:
    1327           0 :             elog(ERROR, "unrecognized boolop: %d", (int) a->boolop);
    1328             :             opname = NULL;      /* keep compiler quiet */
    1329             :             break;
    1330             :     }
    1331             : 
    1332     1129622 :     foreach(lc, a->args)
    1333             :     {
    1334      796120 :         Node       *arg = (Node *) lfirst(lc);
    1335             : 
    1336      796120 :         arg = transformExprRecurse(pstate, arg);
    1337      796106 :         arg = coerce_to_boolean(pstate, arg, opname);
    1338      796106 :         args = lappend(args, arg);
    1339             :     }
    1340             : 
    1341      333502 :     return (Node *) makeBoolExpr(a->boolop, args, a->location);
    1342             : }
    1343             : 
    1344             : static Node *
    1345      723128 : transformFuncCall(ParseState *pstate, FuncCall *fn)
    1346             : {
    1347      723128 :     Node       *last_srf = pstate->p_last_srf;
    1348             :     List       *targs;
    1349             :     ListCell   *args;
    1350             : 
    1351             :     /* Transform the list of arguments ... */
    1352      723128 :     targs = NIL;
    1353     1697172 :     foreach(args, fn->args)
    1354             :     {
    1355      974044 :         targs = lappend(targs, transformExprRecurse(pstate,
    1356      974084 :                                                     (Node *) lfirst(args)));
    1357             :     }
    1358             : 
    1359             :     /*
    1360             :      * When WITHIN GROUP is used, we treat its ORDER BY expressions as
    1361             :      * additional arguments to the function, for purposes of function lookup
    1362             :      * and argument type coercion.  So, transform each such expression and add
    1363             :      * them to the targs list.  We don't explicitly mark where each argument
    1364             :      * came from, but ParseFuncOrColumn can tell what's what by reference to
    1365             :      * list_length(fn->agg_order).
    1366             :      */
    1367      723088 :     if (fn->agg_within_group)
    1368             :     {
    1369             :         Assert(fn->agg_order != NIL);
    1370         514 :         foreach(args, fn->agg_order)
    1371             :         {
    1372         278 :             SortBy     *arg = (SortBy *) lfirst(args);
    1373             : 
    1374         278 :             targs = lappend(targs, transformExpr(pstate, arg->node,
    1375             :                                                  EXPR_KIND_ORDER_BY));
    1376             :         }
    1377             :     }
    1378             : 
    1379             :     /* ... and hand off to ParseFuncOrColumn */
    1380      723088 :     return ParseFuncOrColumn(pstate,
    1381             :                              fn->funcname,
    1382             :                              targs,
    1383             :                              last_srf,
    1384             :                              fn,
    1385             :                              false,
    1386             :                              fn->location);
    1387             : }
    1388             : 
    1389             : static Node *
    1390         210 : transformMultiAssignRef(ParseState *pstate, MultiAssignRef *maref)
    1391             : {
    1392             :     SubLink    *sublink;
    1393             :     RowExpr    *rexpr;
    1394             :     Query      *qtree;
    1395             :     TargetEntry *tle;
    1396             : 
    1397             :     /* We should only see this in first-stage processing of UPDATE tlists */
    1398             :     Assert(pstate->p_expr_kind == EXPR_KIND_UPDATE_SOURCE);
    1399             : 
    1400             :     /* We only need to transform the source if this is the first column */
    1401         210 :     if (maref->colno == 1)
    1402             :     {
    1403             :         /*
    1404             :          * For now, we only allow EXPR SubLinks and RowExprs as the source of
    1405             :          * an UPDATE multiassignment.  This is sufficient to cover interesting
    1406             :          * cases; at worst, someone would have to write (SELECT * FROM expr)
    1407             :          * to expand a composite-returning expression of another form.
    1408             :          */
    1409         102 :         if (IsA(maref->source, SubLink) &&
    1410          70 :             ((SubLink *) maref->source)->subLinkType == EXPR_SUBLINK)
    1411             :         {
    1412             :             /* Relabel it as a MULTIEXPR_SUBLINK */
    1413          70 :             sublink = (SubLink *) maref->source;
    1414          70 :             sublink->subLinkType = MULTIEXPR_SUBLINK;
    1415             :             /* And transform it */
    1416          70 :             sublink = (SubLink *) transformExprRecurse(pstate,
    1417             :                                                        (Node *) sublink);
    1418             : 
    1419          70 :             qtree = castNode(Query, sublink->subselect);
    1420             : 
    1421             :             /* Check subquery returns required number of columns */
    1422          70 :             if (count_nonjunk_tlist_entries(qtree->targetList) != maref->ncolumns)
    1423           0 :                 ereport(ERROR,
    1424             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1425             :                          errmsg("number of columns does not match number of values"),
    1426             :                          parser_errposition(pstate, sublink->location)));
    1427             : 
    1428             :             /*
    1429             :              * Build a resjunk tlist item containing the MULTIEXPR SubLink,
    1430             :              * and add it to pstate->p_multiassign_exprs, whence it will later
    1431             :              * get appended to the completed targetlist.  We needn't worry
    1432             :              * about selecting a resno for it; transformUpdateStmt will do
    1433             :              * that.
    1434             :              */
    1435          70 :             tle = makeTargetEntry((Expr *) sublink, 0, NULL, true);
    1436          70 :             pstate->p_multiassign_exprs = lappend(pstate->p_multiassign_exprs,
    1437             :                                                   tle);
    1438             : 
    1439             :             /*
    1440             :              * Assign a unique-within-this-targetlist ID to the MULTIEXPR
    1441             :              * SubLink.  We can just use its position in the
    1442             :              * p_multiassign_exprs list.
    1443             :              */
    1444          70 :             sublink->subLinkId = list_length(pstate->p_multiassign_exprs);
    1445             :         }
    1446          32 :         else if (IsA(maref->source, RowExpr))
    1447             :         {
    1448             :             /* Transform the RowExpr, allowing SetToDefault items */
    1449          28 :             rexpr = (RowExpr *) transformRowExpr(pstate,
    1450          28 :                                                  (RowExpr *) maref->source,
    1451             :                                                  true);
    1452             : 
    1453             :             /* Check it returns required number of columns */
    1454          28 :             if (list_length(rexpr->args) != maref->ncolumns)
    1455           0 :                 ereport(ERROR,
    1456             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1457             :                          errmsg("number of columns does not match number of values"),
    1458             :                          parser_errposition(pstate, rexpr->location)));
    1459             : 
    1460             :             /*
    1461             :              * Temporarily append it to p_multiassign_exprs, so we can get it
    1462             :              * back when we come back here for additional columns.
    1463             :              */
    1464          28 :             tle = makeTargetEntry((Expr *) rexpr, 0, NULL, true);
    1465          28 :             pstate->p_multiassign_exprs = lappend(pstate->p_multiassign_exprs,
    1466             :                                                   tle);
    1467             :         }
    1468             :         else
    1469           4 :             ereport(ERROR,
    1470             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1471             :                      errmsg("source for a multiple-column UPDATE item must be a sub-SELECT or ROW() expression"),
    1472             :                      parser_errposition(pstate, exprLocation(maref->source))));
    1473             :     }
    1474             :     else
    1475             :     {
    1476             :         /*
    1477             :          * Second or later column in a multiassignment.  Re-fetch the
    1478             :          * transformed SubLink or RowExpr, which we assume is still the last
    1479             :          * entry in p_multiassign_exprs.
    1480             :          */
    1481             :         Assert(pstate->p_multiassign_exprs != NIL);
    1482         108 :         tle = (TargetEntry *) llast(pstate->p_multiassign_exprs);
    1483             :     }
    1484             : 
    1485             :     /*
    1486             :      * Emit the appropriate output expression for the current column
    1487             :      */
    1488         206 :     if (IsA(tle->expr, SubLink))
    1489             :     {
    1490             :         Param      *param;
    1491             : 
    1492         142 :         sublink = (SubLink *) tle->expr;
    1493             :         Assert(sublink->subLinkType == MULTIEXPR_SUBLINK);
    1494         142 :         qtree = castNode(Query, sublink->subselect);
    1495             : 
    1496             :         /* Build a Param representing the current subquery output column */
    1497         142 :         tle = (TargetEntry *) list_nth(qtree->targetList, maref->colno - 1);
    1498             :         Assert(!tle->resjunk);
    1499             : 
    1500         142 :         param = makeNode(Param);
    1501         142 :         param->paramkind = PARAM_MULTIEXPR;
    1502         142 :         param->paramid = (sublink->subLinkId << 16) | maref->colno;
    1503         142 :         param->paramtype = exprType((Node *) tle->expr);
    1504         142 :         param->paramtypmod = exprTypmod((Node *) tle->expr);
    1505         142 :         param->paramcollid = exprCollation((Node *) tle->expr);
    1506         142 :         param->location = exprLocation((Node *) tle->expr);
    1507             : 
    1508         142 :         return (Node *) param;
    1509             :     }
    1510             : 
    1511          64 :     if (IsA(tle->expr, RowExpr))
    1512             :     {
    1513             :         Node       *result;
    1514             : 
    1515          64 :         rexpr = (RowExpr *) tle->expr;
    1516             : 
    1517             :         /* Just extract and return the next element of the RowExpr */
    1518          64 :         result = (Node *) list_nth(rexpr->args, maref->colno - 1);
    1519             : 
    1520             :         /*
    1521             :          * If we're at the last column, delete the RowExpr from
    1522             :          * p_multiassign_exprs; we don't need it anymore, and don't want it in
    1523             :          * the finished UPDATE tlist.  We assume this is still the last entry
    1524             :          * in p_multiassign_exprs.
    1525             :          */
    1526          64 :         if (maref->colno == maref->ncolumns)
    1527          28 :             pstate->p_multiassign_exprs =
    1528          28 :                 list_delete_last(pstate->p_multiassign_exprs);
    1529             : 
    1530          64 :         return result;
    1531             :     }
    1532             : 
    1533           0 :     elog(ERROR, "unexpected expr type in multiassign list");
    1534             :     return NULL;                /* keep compiler quiet */
    1535             : }
    1536             : 
    1537             : static Node *
    1538      133038 : transformCaseExpr(ParseState *pstate, CaseExpr *c)
    1539             : {
    1540      133038 :     CaseExpr   *newc = makeNode(CaseExpr);
    1541      133038 :     Node       *last_srf = pstate->p_last_srf;
    1542             :     Node       *arg;
    1543             :     CaseTestExpr *placeholder;
    1544             :     List       *newargs;
    1545             :     List       *resultexprs;
    1546             :     ListCell   *l;
    1547             :     Node       *defresult;
    1548             :     Oid         ptype;
    1549             : 
    1550             :     /* transform the test expression, if any */
    1551      133038 :     arg = transformExprRecurse(pstate, (Node *) c->arg);
    1552             : 
    1553             :     /* generate placeholder for test expression */
    1554      133038 :     if (arg)
    1555             :     {
    1556             :         /*
    1557             :          * If test expression is an untyped literal, force it to text. We have
    1558             :          * to do something now because we won't be able to do this coercion on
    1559             :          * the placeholder.  This is not as flexible as what was done in 7.4
    1560             :          * and before, but it's good enough to handle the sort of silly coding
    1561             :          * commonly seen.
    1562             :          */
    1563       12810 :         if (exprType(arg) == UNKNOWNOID)
    1564           4 :             arg = coerce_to_common_type(pstate, arg, TEXTOID, "CASE");
    1565             : 
    1566             :         /*
    1567             :          * Run collation assignment on the test expression so that we know
    1568             :          * what collation to mark the placeholder with.  In principle we could
    1569             :          * leave it to parse_collate.c to do that later, but propagating the
    1570             :          * result to the CaseTestExpr would be unnecessarily complicated.
    1571             :          */
    1572       12810 :         assign_expr_collations(pstate, arg);
    1573             : 
    1574       12810 :         placeholder = makeNode(CaseTestExpr);
    1575       12810 :         placeholder->typeId = exprType(arg);
    1576       12810 :         placeholder->typeMod = exprTypmod(arg);
    1577       12810 :         placeholder->collation = exprCollation(arg);
    1578             :     }
    1579             :     else
    1580      120228 :         placeholder = NULL;
    1581             : 
    1582      133038 :     newc->arg = (Expr *) arg;
    1583             : 
    1584             :     /* transform the list of arguments */
    1585      133038 :     newargs = NIL;
    1586      133038 :     resultexprs = NIL;
    1587      345762 :     foreach(l, c->args)
    1588             :     {
    1589      212724 :         CaseWhen   *w = lfirst_node(CaseWhen, l);
    1590      212724 :         CaseWhen   *neww = makeNode(CaseWhen);
    1591             :         Node       *warg;
    1592             : 
    1593      212724 :         warg = (Node *) w->expr;
    1594      212724 :         if (placeholder)
    1595             :         {
    1596             :             /* shorthand form was specified, so expand... */
    1597       50382 :             warg = (Node *) makeSimpleA_Expr(AEXPR_OP, "=",
    1598             :                                              (Node *) placeholder,
    1599             :                                              warg,
    1600             :                                              w->location);
    1601             :         }
    1602      212724 :         neww->expr = (Expr *) transformExprRecurse(pstate, warg);
    1603             : 
    1604      425448 :         neww->expr = (Expr *) coerce_to_boolean(pstate,
    1605      212724 :                                                 (Node *) neww->expr,
    1606             :                                                 "CASE/WHEN");
    1607             : 
    1608      212724 :         warg = (Node *) w->result;
    1609      212724 :         neww->result = (Expr *) transformExprRecurse(pstate, warg);
    1610      212724 :         neww->location = w->location;
    1611             : 
    1612      212724 :         newargs = lappend(newargs, neww);
    1613      212724 :         resultexprs = lappend(resultexprs, neww->result);
    1614             :     }
    1615             : 
    1616      133038 :     newc->args = newargs;
    1617             : 
    1618             :     /* transform the default clause */
    1619      133038 :     defresult = (Node *) c->defresult;
    1620      133038 :     if (defresult == NULL)
    1621             :     {
    1622       22782 :         A_Const    *n = makeNode(A_Const);
    1623             : 
    1624       22782 :         n->isnull = true;
    1625       22782 :         n->location = -1;
    1626       22782 :         defresult = (Node *) n;
    1627             :     }
    1628      133038 :     newc->defresult = (Expr *) transformExprRecurse(pstate, defresult);
    1629             : 
    1630             :     /*
    1631             :      * Note: default result is considered the most significant type in
    1632             :      * determining preferred type. This is how the code worked before, but it
    1633             :      * seems a little bogus to me --- tgl
    1634             :      */
    1635      133038 :     resultexprs = lcons(newc->defresult, resultexprs);
    1636             : 
    1637      133038 :     ptype = select_common_type(pstate, resultexprs, "CASE", NULL);
    1638             :     Assert(OidIsValid(ptype));
    1639      133038 :     newc->casetype = ptype;
    1640             :     /* casecollid will be set by parse_collate.c */
    1641             : 
    1642             :     /* Convert default result clause, if necessary */
    1643      133038 :     newc->defresult = (Expr *)
    1644      133038 :         coerce_to_common_type(pstate,
    1645      133038 :                               (Node *) newc->defresult,
    1646             :                               ptype,
    1647             :                               "CASE/ELSE");
    1648             : 
    1649             :     /* Convert when-clause results, if necessary */
    1650      345762 :     foreach(l, newc->args)
    1651             :     {
    1652      212724 :         CaseWhen   *w = (CaseWhen *) lfirst(l);
    1653             : 
    1654      212724 :         w->result = (Expr *)
    1655      212724 :             coerce_to_common_type(pstate,
    1656      212724 :                                   (Node *) w->result,
    1657             :                                   ptype,
    1658             :                                   "CASE/WHEN");
    1659             :     }
    1660             : 
    1661             :     /* if any subexpression contained a SRF, complain */
    1662      133038 :     if (pstate->p_last_srf != last_srf)
    1663           4 :         ereport(ERROR,
    1664             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1665             :         /* translator: %s is name of a SQL construct, eg GROUP BY */
    1666             :                  errmsg("set-returning functions are not allowed in %s",
    1667             :                         "CASE"),
    1668             :                  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
    1669             :                  parser_errposition(pstate,
    1670             :                                     exprLocation(pstate->p_last_srf))));
    1671             : 
    1672      133034 :     newc->location = c->location;
    1673             : 
    1674      133034 :     return (Node *) newc;
    1675             : }
    1676             : 
    1677             : static Node *
    1678      122506 : transformSubLink(ParseState *pstate, SubLink *sublink)
    1679             : {
    1680      122506 :     Node       *result = (Node *) sublink;
    1681             :     Query      *qtree;
    1682             :     const char *err;
    1683             : 
    1684             :     /*
    1685             :      * Check to see if the sublink is in an invalid place within the query. We
    1686             :      * allow sublinks everywhere in SELECT/INSERT/UPDATE/DELETE, but generally
    1687             :      * not in utility statements.
    1688             :      */
    1689      122506 :     err = NULL;
    1690      122506 :     switch (pstate->p_expr_kind)
    1691             :     {
    1692           0 :         case EXPR_KIND_NONE:
    1693             :             Assert(false);      /* can't happen */
    1694           0 :             break;
    1695           0 :         case EXPR_KIND_OTHER:
    1696             :             /* Accept sublink here; caller must throw error if wanted */
    1697           0 :             break;
    1698      122482 :         case EXPR_KIND_JOIN_ON:
    1699             :         case EXPR_KIND_JOIN_USING:
    1700             :         case EXPR_KIND_FROM_SUBSELECT:
    1701             :         case EXPR_KIND_FROM_FUNCTION:
    1702             :         case EXPR_KIND_WHERE:
    1703             :         case EXPR_KIND_POLICY:
    1704             :         case EXPR_KIND_HAVING:
    1705             :         case EXPR_KIND_FILTER:
    1706             :         case EXPR_KIND_WINDOW_PARTITION:
    1707             :         case EXPR_KIND_WINDOW_ORDER:
    1708             :         case EXPR_KIND_WINDOW_FRAME_RANGE:
    1709             :         case EXPR_KIND_WINDOW_FRAME_ROWS:
    1710             :         case EXPR_KIND_WINDOW_FRAME_GROUPS:
    1711             :         case EXPR_KIND_SELECT_TARGET:
    1712             :         case EXPR_KIND_INSERT_TARGET:
    1713             :         case EXPR_KIND_UPDATE_SOURCE:
    1714             :         case EXPR_KIND_UPDATE_TARGET:
    1715             :         case EXPR_KIND_GROUP_BY:
    1716             :         case EXPR_KIND_ORDER_BY:
    1717             :         case EXPR_KIND_DISTINCT_ON:
    1718             :         case EXPR_KIND_LIMIT:
    1719             :         case EXPR_KIND_OFFSET:
    1720             :         case EXPR_KIND_RETURNING:
    1721             :         case EXPR_KIND_VALUES:
    1722             :         case EXPR_KIND_VALUES_SINGLE:
    1723             :         case EXPR_KIND_CYCLE_MARK:
    1724             :             /* okay */
    1725      122482 :             break;
    1726           0 :         case EXPR_KIND_CHECK_CONSTRAINT:
    1727             :         case EXPR_KIND_DOMAIN_CHECK:
    1728           0 :             err = _("cannot use subquery in check constraint");
    1729           0 :             break;
    1730           4 :         case EXPR_KIND_COLUMN_DEFAULT:
    1731             :         case EXPR_KIND_FUNCTION_DEFAULT:
    1732           4 :             err = _("cannot use subquery in DEFAULT expression");
    1733           4 :             break;
    1734           0 :         case EXPR_KIND_INDEX_EXPRESSION:
    1735           0 :             err = _("cannot use subquery in index expression");
    1736           0 :             break;
    1737           0 :         case EXPR_KIND_INDEX_PREDICATE:
    1738           0 :             err = _("cannot use subquery in index predicate");
    1739           0 :             break;
    1740           0 :         case EXPR_KIND_STATS_EXPRESSION:
    1741           0 :             err = _("cannot use subquery in statistics expression");
    1742           0 :             break;
    1743           0 :         case EXPR_KIND_ALTER_COL_TRANSFORM:
    1744           0 :             err = _("cannot use subquery in transform expression");
    1745           0 :             break;
    1746           0 :         case EXPR_KIND_EXECUTE_PARAMETER:
    1747           0 :             err = _("cannot use subquery in EXECUTE parameter");
    1748           0 :             break;
    1749           0 :         case EXPR_KIND_TRIGGER_WHEN:
    1750           0 :             err = _("cannot use subquery in trigger WHEN condition");
    1751           0 :             break;
    1752           8 :         case EXPR_KIND_PARTITION_BOUND:
    1753           8 :             err = _("cannot use subquery in partition bound");
    1754           8 :             break;
    1755           4 :         case EXPR_KIND_PARTITION_EXPRESSION:
    1756           4 :             err = _("cannot use subquery in partition key expression");
    1757           4 :             break;
    1758           0 :         case EXPR_KIND_CALL_ARGUMENT:
    1759           0 :             err = _("cannot use subquery in CALL argument");
    1760           0 :             break;
    1761           4 :         case EXPR_KIND_COPY_WHERE:
    1762           4 :             err = _("cannot use subquery in COPY FROM WHERE condition");
    1763           4 :             break;
    1764           4 :         case EXPR_KIND_GENERATED_COLUMN:
    1765           4 :             err = _("cannot use subquery in column generation expression");
    1766           4 :             break;
    1767             : 
    1768             :             /*
    1769             :              * There is intentionally no default: case here, so that the
    1770             :              * compiler will warn if we add a new ParseExprKind without
    1771             :              * extending this switch.  If we do see an unrecognized value at
    1772             :              * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
    1773             :              * which is sane anyway.
    1774             :              */
    1775             :     }
    1776      122506 :     if (err)
    1777          24 :         ereport(ERROR,
    1778             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1779             :                  errmsg_internal("%s", err),
    1780             :                  parser_errposition(pstate, sublink->location)));
    1781             : 
    1782      122482 :     pstate->p_hasSubLinks = true;
    1783             : 
    1784             :     /*
    1785             :      * OK, let's transform the sub-SELECT.
    1786             :      */
    1787      122482 :     qtree = parse_sub_analyze(sublink->subselect, pstate, NULL, false, true);
    1788             : 
    1789             :     /*
    1790             :      * Check that we got a SELECT.  Anything else should be impossible given
    1791             :      * restrictions of the grammar, but check anyway.
    1792             :      */
    1793      122454 :     if (!IsA(qtree, Query) ||
    1794      122454 :         qtree->commandType != CMD_SELECT)
    1795           0 :         elog(ERROR, "unexpected non-SELECT command in SubLink");
    1796             : 
    1797      122454 :     sublink->subselect = (Node *) qtree;
    1798             : 
    1799      122454 :     if (sublink->subLinkType == EXISTS_SUBLINK)
    1800             :     {
    1801             :         /*
    1802             :          * EXISTS needs no test expression or combining operator. These fields
    1803             :          * should be null already, but make sure.
    1804             :          */
    1805       13922 :         sublink->testexpr = NULL;
    1806       13922 :         sublink->operName = NIL;
    1807             :     }
    1808      108532 :     else if (sublink->subLinkType == EXPR_SUBLINK ||
    1809       39498 :              sublink->subLinkType == ARRAY_SUBLINK)
    1810             :     {
    1811             :         /*
    1812             :          * Make sure the subselect delivers a single column (ignoring resjunk
    1813             :          * targets).
    1814             :          */
    1815      102262 :         if (count_nonjunk_tlist_entries(qtree->targetList) != 1)
    1816           0 :             ereport(ERROR,
    1817             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1818             :                      errmsg("subquery must return only one column"),
    1819             :                      parser_errposition(pstate, sublink->location)));
    1820             : 
    1821             :         /*
    1822             :          * EXPR and ARRAY need no test expression or combining operator. These
    1823             :          * fields should be null already, but make sure.
    1824             :          */
    1825      102262 :         sublink->testexpr = NULL;
    1826      102262 :         sublink->operName = NIL;
    1827             :     }
    1828        6270 :     else if (sublink->subLinkType == MULTIEXPR_SUBLINK)
    1829             :     {
    1830             :         /* Same as EXPR case, except no restriction on number of columns */
    1831          70 :         sublink->testexpr = NULL;
    1832          70 :         sublink->operName = NIL;
    1833             :     }
    1834             :     else
    1835             :     {
    1836             :         /* ALL, ANY, or ROWCOMPARE: generate row-comparing expression */
    1837             :         Node       *lefthand;
    1838             :         List       *left_list;
    1839             :         List       *right_list;
    1840             :         ListCell   *l;
    1841             : 
    1842             :         /*
    1843             :          * If the source was "x IN (select)", convert to "x = ANY (select)".
    1844             :          */
    1845        6200 :         if (sublink->operName == NIL)
    1846        6122 :             sublink->operName = list_make1(makeString("="));
    1847             : 
    1848             :         /*
    1849             :          * Transform lefthand expression, and convert to a list
    1850             :          */
    1851        6200 :         lefthand = transformExprRecurse(pstate, sublink->testexpr);
    1852        6200 :         if (lefthand && IsA(lefthand, RowExpr))
    1853         550 :             left_list = ((RowExpr *) lefthand)->args;
    1854             :         else
    1855        5650 :             left_list = list_make1(lefthand);
    1856             : 
    1857             :         /*
    1858             :          * Build a list of PARAM_SUBLINK nodes representing the output columns
    1859             :          * of the subquery.
    1860             :          */
    1861        6200 :         right_list = NIL;
    1862       13922 :         foreach(l, qtree->targetList)
    1863             :         {
    1864        7722 :             TargetEntry *tent = (TargetEntry *) lfirst(l);
    1865             :             Param      *param;
    1866             : 
    1867        7722 :             if (tent->resjunk)
    1868           8 :                 continue;
    1869             : 
    1870        7714 :             param = makeNode(Param);
    1871        7714 :             param->paramkind = PARAM_SUBLINK;
    1872        7714 :             param->paramid = tent->resno;
    1873        7714 :             param->paramtype = exprType((Node *) tent->expr);
    1874        7714 :             param->paramtypmod = exprTypmod((Node *) tent->expr);
    1875        7714 :             param->paramcollid = exprCollation((Node *) tent->expr);
    1876        7714 :             param->location = -1;
    1877             : 
    1878        7714 :             right_list = lappend(right_list, param);
    1879             :         }
    1880             : 
    1881             :         /*
    1882             :          * We could rely on make_row_comparison_op to complain if the list
    1883             :          * lengths differ, but we prefer to generate a more specific error
    1884             :          * message.
    1885             :          */
    1886        6200 :         if (list_length(left_list) < list_length(right_list))
    1887           0 :             ereport(ERROR,
    1888             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1889             :                      errmsg("subquery has too many columns"),
    1890             :                      parser_errposition(pstate, sublink->location)));
    1891        6200 :         if (list_length(left_list) > list_length(right_list))
    1892           0 :             ereport(ERROR,
    1893             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1894             :                      errmsg("subquery has too few columns"),
    1895             :                      parser_errposition(pstate, sublink->location)));
    1896             : 
    1897             :         /*
    1898             :          * Identify the combining operator(s) and generate a suitable
    1899             :          * row-comparison expression.
    1900             :          */
    1901        6200 :         sublink->testexpr = make_row_comparison_op(pstate,
    1902             :                                                    sublink->operName,
    1903             :                                                    left_list,
    1904             :                                                    right_list,
    1905             :                                                    sublink->location);
    1906             :     }
    1907             : 
    1908      122446 :     return result;
    1909             : }
    1910             : 
    1911             : /*
    1912             :  * transformArrayExpr
    1913             :  *
    1914             :  * If the caller specifies the target type, the resulting array will
    1915             :  * be of exactly that type.  Otherwise we try to infer a common type
    1916             :  * for the elements using select_common_type().
    1917             :  */
    1918             : static Node *
    1919        5434 : transformArrayExpr(ParseState *pstate, A_ArrayExpr *a,
    1920             :                    Oid array_type, Oid element_type, int32 typmod)
    1921             : {
    1922        5434 :     ArrayExpr  *newa = makeNode(ArrayExpr);
    1923        5434 :     List       *newelems = NIL;
    1924        5434 :     List       *newcoercedelems = NIL;
    1925             :     ListCell   *element;
    1926             :     Oid         coerce_type;
    1927             :     bool        coerce_hard;
    1928             : 
    1929             :     /*
    1930             :      * Transform the element expressions
    1931             :      *
    1932             :      * Assume that the array is one-dimensional unless we find an array-type
    1933             :      * element expression.
    1934             :      */
    1935        5434 :     newa->multidims = false;
    1936       18232 :     foreach(element, a->elements)
    1937             :     {
    1938       12798 :         Node       *e = (Node *) lfirst(element);
    1939             :         Node       *newe;
    1940             : 
    1941             :         /*
    1942             :          * If an element is itself an A_ArrayExpr, recurse directly so that we
    1943             :          * can pass down any target type we were given.
    1944             :          */
    1945       12798 :         if (IsA(e, A_ArrayExpr))
    1946             :         {
    1947         622 :             newe = transformArrayExpr(pstate,
    1948             :                                       (A_ArrayExpr *) e,
    1949             :                                       array_type,
    1950             :                                       element_type,
    1951             :                                       typmod);
    1952             :             /* we certainly have an array here */
    1953             :             Assert(array_type == InvalidOid || array_type == exprType(newe));
    1954         622 :             newa->multidims = true;
    1955             :         }
    1956             :         else
    1957             :         {
    1958       12176 :             newe = transformExprRecurse(pstate, e);
    1959             : 
    1960             :             /*
    1961             :              * Check for sub-array expressions, if we haven't already found
    1962             :              * one.
    1963             :              */
    1964       12176 :             if (!newa->multidims && type_is_array(exprType(newe)))
    1965           4 :                 newa->multidims = true;
    1966             :         }
    1967             : 
    1968       12798 :         newelems = lappend(newelems, newe);
    1969             :     }
    1970             : 
    1971             :     /*
    1972             :      * Select a target type for the elements.
    1973             :      *
    1974             :      * If we haven't been given a target array type, we must try to deduce a
    1975             :      * common type based on the types of the individual elements present.
    1976             :      */
    1977        5434 :     if (OidIsValid(array_type))
    1978             :     {
    1979             :         /* Caller must ensure array_type matches element_type */
    1980             :         Assert(OidIsValid(element_type));
    1981         970 :         coerce_type = (newa->multidims ? array_type : element_type);
    1982         970 :         coerce_hard = true;
    1983             :     }
    1984             :     else
    1985             :     {
    1986             :         /* Can't handle an empty array without a target type */
    1987        4464 :         if (newelems == NIL)
    1988           4 :             ereport(ERROR,
    1989             :                     (errcode(ERRCODE_INDETERMINATE_DATATYPE),
    1990             :                      errmsg("cannot determine type of empty array"),
    1991             :                      errhint("Explicitly cast to the desired type, "
    1992             :                              "for example ARRAY[]::integer[]."),
    1993             :                      parser_errposition(pstate, a->location)));
    1994             : 
    1995             :         /* Select a common type for the elements */
    1996        4460 :         coerce_type = select_common_type(pstate, newelems, "ARRAY", NULL);
    1997             : 
    1998        4460 :         if (newa->multidims)
    1999             :         {
    2000         294 :             array_type = coerce_type;
    2001         294 :             element_type = get_element_type(array_type);
    2002         294 :             if (!OidIsValid(element_type))
    2003           0 :                 ereport(ERROR,
    2004             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    2005             :                          errmsg("could not find element type for data type %s",
    2006             :                                 format_type_be(array_type)),
    2007             :                          parser_errposition(pstate, a->location)));
    2008             :         }
    2009             :         else
    2010             :         {
    2011        4166 :             element_type = coerce_type;
    2012        4166 :             array_type = get_array_type(element_type);
    2013        4166 :             if (!OidIsValid(array_type))
    2014           0 :                 ereport(ERROR,
    2015             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    2016             :                          errmsg("could not find array type for data type %s",
    2017             :                                 format_type_be(element_type)),
    2018             :                          parser_errposition(pstate, a->location)));
    2019             :         }
    2020        4460 :         coerce_hard = false;
    2021             :     }
    2022             : 
    2023             :     /*
    2024             :      * Coerce elements to target type
    2025             :      *
    2026             :      * If the array has been explicitly cast, then the elements are in turn
    2027             :      * explicitly coerced.
    2028             :      *
    2029             :      * If the array's type was merely derived from the common type of its
    2030             :      * elements, then the elements are implicitly coerced to the common type.
    2031             :      * This is consistent with other uses of select_common_type().
    2032             :      */
    2033       18228 :     foreach(element, newelems)
    2034             :     {
    2035       12798 :         Node       *e = (Node *) lfirst(element);
    2036             :         Node       *newe;
    2037             : 
    2038       12798 :         if (coerce_hard)
    2039             :         {
    2040        2182 :             newe = coerce_to_target_type(pstate, e,
    2041             :                                          exprType(e),
    2042             :                                          coerce_type,
    2043             :                                          typmod,
    2044             :                                          COERCION_EXPLICIT,
    2045             :                                          COERCE_EXPLICIT_CAST,
    2046             :                                          -1);
    2047        2182 :             if (newe == NULL)
    2048           0 :                 ereport(ERROR,
    2049             :                         (errcode(ERRCODE_CANNOT_COERCE),
    2050             :                          errmsg("cannot cast type %s to %s",
    2051             :                                 format_type_be(exprType(e)),
    2052             :                                 format_type_be(coerce_type)),
    2053             :                          parser_errposition(pstate, exprLocation(e))));
    2054             :         }
    2055             :         else
    2056       10616 :             newe = coerce_to_common_type(pstate, e,
    2057             :                                          coerce_type,
    2058             :                                          "ARRAY");
    2059       12798 :         newcoercedelems = lappend(newcoercedelems, newe);
    2060             :     }
    2061             : 
    2062        5430 :     newa->array_typeid = array_type;
    2063             :     /* array_collid will be set by parse_collate.c */
    2064        5430 :     newa->element_typeid = element_type;
    2065        5430 :     newa->elements = newcoercedelems;
    2066        5430 :     newa->location = a->location;
    2067             : 
    2068        5430 :     return (Node *) newa;
    2069             : }
    2070             : 
    2071             : static Node *
    2072        8304 : transformRowExpr(ParseState *pstate, RowExpr *r, bool allowDefault)
    2073             : {
    2074             :     RowExpr    *newr;
    2075             :     char        fname[16];
    2076             :     int         fnum;
    2077             : 
    2078        8304 :     newr = makeNode(RowExpr);
    2079             : 
    2080             :     /* Transform the field expressions */
    2081        8304 :     newr->args = transformExpressionList(pstate, r->args,
    2082             :                                          pstate->p_expr_kind, allowDefault);
    2083             : 
    2084             :     /* Barring later casting, we consider the type RECORD */
    2085        8304 :     newr->row_typeid = RECORDOID;
    2086        8304 :     newr->row_format = COERCE_IMPLICIT_CAST;
    2087             : 
    2088             :     /* ROW() has anonymous columns, so invent some field names */
    2089        8304 :     newr->colnames = NIL;
    2090       27946 :     for (fnum = 1; fnum <= list_length(newr->args); fnum++)
    2091             :     {
    2092       19642 :         snprintf(fname, sizeof(fname), "f%d", fnum);
    2093       19642 :         newr->colnames = lappend(newr->colnames, makeString(pstrdup(fname)));
    2094             :     }
    2095             : 
    2096        8304 :     newr->location = r->location;
    2097             : 
    2098        8304 :     return (Node *) newr;
    2099             : }
    2100             : 
    2101             : static Node *
    2102       23178 : transformCoalesceExpr(ParseState *pstate, CoalesceExpr *c)
    2103             : {
    2104       23178 :     CoalesceExpr *newc = makeNode(CoalesceExpr);
    2105       23178 :     Node       *last_srf = pstate->p_last_srf;
    2106       23178 :     List       *newargs = NIL;
    2107       23178 :     List       *newcoercedargs = NIL;
    2108             :     ListCell   *args;
    2109             : 
    2110       69526 :     foreach(args, c->args)
    2111             :     {
    2112       46348 :         Node       *e = (Node *) lfirst(args);
    2113             :         Node       *newe;
    2114             : 
    2115       46348 :         newe = transformExprRecurse(pstate, e);
    2116       46348 :         newargs = lappend(newargs, newe);
    2117             :     }
    2118             : 
    2119       23178 :     newc->coalescetype = select_common_type(pstate, newargs, "COALESCE", NULL);
    2120             :     /* coalescecollid will be set by parse_collate.c */
    2121             : 
    2122             :     /* Convert arguments if necessary */
    2123       69526 :     foreach(args, newargs)
    2124             :     {
    2125       46348 :         Node       *e = (Node *) lfirst(args);
    2126             :         Node       *newe;
    2127             : 
    2128       46348 :         newe = coerce_to_common_type(pstate, e,
    2129             :                                      newc->coalescetype,
    2130             :                                      "COALESCE");
    2131       46348 :         newcoercedargs = lappend(newcoercedargs, newe);
    2132             :     }
    2133             : 
    2134             :     /* if any subexpression contained a SRF, complain */
    2135       23178 :     if (pstate->p_last_srf != last_srf)
    2136           4 :         ereport(ERROR,
    2137             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2138             :         /* translator: %s is name of a SQL construct, eg GROUP BY */
    2139             :                  errmsg("set-returning functions are not allowed in %s",
    2140             :                         "COALESCE"),
    2141             :                  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
    2142             :                  parser_errposition(pstate,
    2143             :                                     exprLocation(pstate->p_last_srf))));
    2144             : 
    2145       23174 :     newc->args = newcoercedargs;
    2146       23174 :     newc->location = c->location;
    2147       23174 :     return (Node *) newc;
    2148             : }
    2149             : 
    2150             : static Node *
    2151         132 : transformMinMaxExpr(ParseState *pstate, MinMaxExpr *m)
    2152             : {
    2153         132 :     MinMaxExpr *newm = makeNode(MinMaxExpr);
    2154         132 :     List       *newargs = NIL;
    2155         132 :     List       *newcoercedargs = NIL;
    2156         132 :     const char *funcname = (m->op == IS_GREATEST) ? "GREATEST" : "LEAST";
    2157             :     ListCell   *args;
    2158             : 
    2159         132 :     newm->op = m->op;
    2160         432 :     foreach(args, m->args)
    2161             :     {
    2162         300 :         Node       *e = (Node *) lfirst(args);
    2163             :         Node       *newe;
    2164             : 
    2165         300 :         newe = transformExprRecurse(pstate, e);
    2166         300 :         newargs = lappend(newargs, newe);
    2167             :     }
    2168             : 
    2169         132 :     newm->minmaxtype = select_common_type(pstate, newargs, funcname, NULL);
    2170             :     /* minmaxcollid and inputcollid will be set by parse_collate.c */
    2171             : 
    2172             :     /* Convert arguments if necessary */
    2173         432 :     foreach(args, newargs)
    2174             :     {
    2175         300 :         Node       *e = (Node *) lfirst(args);
    2176             :         Node       *newe;
    2177             : 
    2178         300 :         newe = coerce_to_common_type(pstate, e,
    2179             :                                      newm->minmaxtype,
    2180             :                                      funcname);
    2181         300 :         newcoercedargs = lappend(newcoercedargs, newe);
    2182             :     }
    2183             : 
    2184         132 :     newm->args = newcoercedargs;
    2185         132 :     newm->location = m->location;
    2186         132 :     return (Node *) newm;
    2187             : }
    2188             : 
    2189             : static Node *
    2190        4172 : transformSQLValueFunction(ParseState *pstate, SQLValueFunction *svf)
    2191             : {
    2192             :     /*
    2193             :      * All we need to do is insert the correct result type and (where needed)
    2194             :      * validate the typmod, so we just modify the node in-place.
    2195             :      */
    2196        4172 :     switch (svf->op)
    2197             :     {
    2198         994 :         case SVFOP_CURRENT_DATE:
    2199         994 :             svf->type = DATEOID;
    2200         994 :             break;
    2201           4 :         case SVFOP_CURRENT_TIME:
    2202           4 :             svf->type = TIMETZOID;
    2203           4 :             break;
    2204           4 :         case SVFOP_CURRENT_TIME_N:
    2205           4 :             svf->type = TIMETZOID;
    2206           4 :             svf->typmod = anytime_typmod_check(true, svf->typmod);
    2207           4 :             break;
    2208         248 :         case SVFOP_CURRENT_TIMESTAMP:
    2209         248 :             svf->type = TIMESTAMPTZOID;
    2210         248 :             break;
    2211         490 :         case SVFOP_CURRENT_TIMESTAMP_N:
    2212         490 :             svf->type = TIMESTAMPTZOID;
    2213         490 :             svf->typmod = anytimestamp_typmod_check(true, svf->typmod);
    2214         490 :             break;
    2215           4 :         case SVFOP_LOCALTIME:
    2216           4 :             svf->type = TIMEOID;
    2217           4 :             break;
    2218           4 :         case SVFOP_LOCALTIME_N:
    2219           4 :             svf->type = TIMEOID;
    2220           4 :             svf->typmod = anytime_typmod_check(false, svf->typmod);
    2221           4 :             break;
    2222          12 :         case SVFOP_LOCALTIMESTAMP:
    2223          12 :             svf->type = TIMESTAMPOID;
    2224          12 :             break;
    2225           4 :         case SVFOP_LOCALTIMESTAMP_N:
    2226           4 :             svf->type = TIMESTAMPOID;
    2227           4 :             svf->typmod = anytimestamp_typmod_check(false, svf->typmod);
    2228           4 :             break;
    2229        2408 :         case SVFOP_CURRENT_ROLE:
    2230             :         case SVFOP_CURRENT_USER:
    2231             :         case SVFOP_USER:
    2232             :         case SVFOP_SESSION_USER:
    2233             :         case SVFOP_CURRENT_CATALOG:
    2234             :         case SVFOP_CURRENT_SCHEMA:
    2235        2408 :             svf->type = NAMEOID;
    2236        2408 :             break;
    2237             :     }
    2238             : 
    2239        4172 :     return (Node *) svf;
    2240             : }
    2241             : 
    2242             : static Node *
    2243         398 : transformXmlExpr(ParseState *pstate, XmlExpr *x)
    2244             : {
    2245             :     XmlExpr    *newx;
    2246             :     ListCell   *lc;
    2247             :     int         i;
    2248             : 
    2249         398 :     newx = makeNode(XmlExpr);
    2250         398 :     newx->op = x->op;
    2251         398 :     if (x->name)
    2252         174 :         newx->name = map_sql_identifier_to_xml_name(x->name, false, false);
    2253             :     else
    2254         224 :         newx->name = NULL;
    2255         398 :     newx->xmloption = x->xmloption;
    2256         398 :     newx->type = XMLOID;     /* this just marks the node as transformed */
    2257         398 :     newx->typmod = -1;
    2258         398 :     newx->location = x->location;
    2259             : 
    2260             :     /*
    2261             :      * gram.y built the named args as a list of ResTarget.  Transform each,
    2262             :      * and break the names out as a separate list.
    2263             :      */
    2264         398 :     newx->named_args = NIL;
    2265         398 :     newx->arg_names = NIL;
    2266             : 
    2267         548 :     foreach(lc, x->named_args)
    2268             :     {
    2269         158 :         ResTarget  *r = lfirst_node(ResTarget, lc);
    2270             :         Node       *expr;
    2271             :         char       *argname;
    2272             : 
    2273         158 :         expr = transformExprRecurse(pstate, r->val);
    2274             : 
    2275         158 :         if (r->name)
    2276          74 :             argname = map_sql_identifier_to_xml_name(r->name, false, false);
    2277          84 :         else if (IsA(r->val, ColumnRef))
    2278          80 :             argname = map_sql_identifier_to_xml_name(FigureColname(r->val),
    2279             :                                                      true, false);
    2280             :         else
    2281             :         {
    2282           4 :             ereport(ERROR,
    2283             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2284             :                      x->op == IS_XMLELEMENT
    2285             :                      ? errmsg("unnamed XML attribute value must be a column reference")
    2286             :                      : errmsg("unnamed XML element value must be a column reference"),
    2287             :                      parser_errposition(pstate, r->location)));
    2288             :             argname = NULL;     /* keep compiler quiet */
    2289             :         }
    2290             : 
    2291             :         /* reject duplicate argnames in XMLELEMENT only */
    2292         154 :         if (x->op == IS_XMLELEMENT)
    2293             :         {
    2294             :             ListCell   *lc2;
    2295             : 
    2296          82 :             foreach(lc2, newx->arg_names)
    2297             :             {
    2298          26 :                 if (strcmp(argname, strVal(lfirst(lc2))) == 0)
    2299           4 :                     ereport(ERROR,
    2300             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    2301             :                              errmsg("XML attribute name \"%s\" appears more than once",
    2302             :                                     argname),
    2303             :                              parser_errposition(pstate, r->location)));
    2304             :             }
    2305             :         }
    2306             : 
    2307         150 :         newx->named_args = lappend(newx->named_args, expr);
    2308         150 :         newx->arg_names = lappend(newx->arg_names, makeString(argname));
    2309             :     }
    2310             : 
    2311             :     /* The other arguments are of varying types depending on the function */
    2312         390 :     newx->args = NIL;
    2313         390 :     i = 0;
    2314         938 :     foreach(lc, x->args)
    2315             :     {
    2316         560 :         Node       *e = (Node *) lfirst(lc);
    2317             :         Node       *newe;
    2318             : 
    2319         560 :         newe = transformExprRecurse(pstate, e);
    2320         560 :         switch (x->op)
    2321             :         {
    2322          88 :             case IS_XMLCONCAT:
    2323          88 :                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
    2324             :                                                "XMLCONCAT");
    2325          80 :                 break;
    2326          92 :             case IS_XMLELEMENT:
    2327             :                 /* no coercion necessary */
    2328          92 :                 break;
    2329           0 :             case IS_XMLFOREST:
    2330           0 :                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
    2331             :                                                "XMLFOREST");
    2332           0 :                 break;
    2333         188 :             case IS_XMLPARSE:
    2334         188 :                 if (i == 0)
    2335          94 :                     newe = coerce_to_specific_type(pstate, newe, TEXTOID,
    2336             :                                                    "XMLPARSE");
    2337             :                 else
    2338          94 :                     newe = coerce_to_boolean(pstate, newe, "XMLPARSE");
    2339         188 :                 break;
    2340          34 :             case IS_XMLPI:
    2341          34 :                 newe = coerce_to_specific_type(pstate, newe, TEXTOID,
    2342             :                                                "XMLPI");
    2343          34 :                 break;
    2344         138 :             case IS_XMLROOT:
    2345         138 :                 if (i == 0)
    2346          46 :                     newe = coerce_to_specific_type(pstate, newe, XMLOID,
    2347             :                                                    "XMLROOT");
    2348          92 :                 else if (i == 1)
    2349          46 :                     newe = coerce_to_specific_type(pstate, newe, TEXTOID,
    2350             :                                                    "XMLROOT");
    2351             :                 else
    2352          46 :                     newe = coerce_to_specific_type(pstate, newe, INT4OID,
    2353             :                                                    "XMLROOT");
    2354         138 :                 break;
    2355           0 :             case IS_XMLSERIALIZE:
    2356             :                 /* not handled here */
    2357             :                 Assert(false);
    2358           0 :                 break;
    2359          20 :             case IS_DOCUMENT:
    2360          20 :                 newe = coerce_to_specific_type(pstate, newe, XMLOID,
    2361             :                                                "IS DOCUMENT");
    2362          16 :                 break;
    2363             :         }
    2364         548 :         newx->args = lappend(newx->args, newe);
    2365         548 :         i++;
    2366             :     }
    2367             : 
    2368         378 :     return (Node *) newx;
    2369             : }
    2370             : 
    2371             : static Node *
    2372          24 : transformXmlSerialize(ParseState *pstate, XmlSerialize *xs)
    2373             : {
    2374             :     Node       *result;
    2375             :     XmlExpr    *xexpr;
    2376             :     Oid         targetType;
    2377             :     int32       targetTypmod;
    2378             : 
    2379          24 :     xexpr = makeNode(XmlExpr);
    2380          24 :     xexpr->op = IS_XMLSERIALIZE;
    2381          24 :     xexpr->args = list_make1(coerce_to_specific_type(pstate,
    2382             :                                                      transformExprRecurse(pstate, xs->expr),
    2383             :                                                      XMLOID,
    2384             :                                                      "XMLSERIALIZE"));
    2385             : 
    2386          24 :     typenameTypeIdAndMod(pstate, xs->typeName, &targetType, &targetTypmod);
    2387             : 
    2388          24 :     xexpr->xmloption = xs->xmloption;
    2389          24 :     xexpr->location = xs->location;
    2390             :     /* We actually only need these to be able to parse back the expression. */
    2391          24 :     xexpr->type = targetType;
    2392          24 :     xexpr->typmod = targetTypmod;
    2393             : 
    2394             :     /*
    2395             :      * The actual target type is determined this way.  SQL allows char and
    2396             :      * varchar as target types.  We allow anything that can be cast implicitly
    2397             :      * from text.  This way, user-defined text-like data types automatically
    2398             :      * fit in.
    2399             :      */
    2400          24 :     result = coerce_to_target_type(pstate, (Node *) xexpr,
    2401             :                                    TEXTOID, targetType, targetTypmod,
    2402             :                                    COERCION_IMPLICIT,
    2403             :                                    COERCE_IMPLICIT_CAST,
    2404             :                                    -1);
    2405          24 :     if (result == NULL)
    2406           0 :         ereport(ERROR,
    2407             :                 (errcode(ERRCODE_CANNOT_COERCE),
    2408             :                  errmsg("cannot cast XMLSERIALIZE result to %s",
    2409             :                         format_type_be(targetType)),
    2410             :                  parser_errposition(pstate, xexpr->location)));
    2411          24 :     return result;
    2412             : }
    2413             : 
    2414             : static Node *
    2415         130 : transformBooleanTest(ParseState *pstate, BooleanTest *b)
    2416             : {
    2417             :     const char *clausename;
    2418             : 
    2419         130 :     switch (b->booltesttype)
    2420             :     {
    2421          28 :         case IS_TRUE:
    2422          28 :             clausename = "IS TRUE";
    2423          28 :             break;
    2424          34 :         case IS_NOT_TRUE:
    2425          34 :             clausename = "IS NOT TRUE";
    2426          34 :             break;
    2427          28 :         case IS_FALSE:
    2428          28 :             clausename = "IS FALSE";
    2429          28 :             break;
    2430          20 :         case IS_NOT_FALSE:
    2431          20 :             clausename = "IS NOT FALSE";
    2432          20 :             break;
    2433          12 :         case IS_UNKNOWN:
    2434          12 :             clausename = "IS UNKNOWN";
    2435          12 :             break;
    2436           8 :         case IS_NOT_UNKNOWN:
    2437           8 :             clausename = "IS NOT UNKNOWN";
    2438           8 :             break;
    2439           0 :         default:
    2440           0 :             elog(ERROR, "unrecognized booltesttype: %d",
    2441             :                  (int) b->booltesttype);
    2442             :             clausename = NULL;  /* keep compiler quiet */
    2443             :     }
    2444             : 
    2445         130 :     b->arg = (Expr *) transformExprRecurse(pstate, (Node *) b->arg);
    2446             : 
    2447         260 :     b->arg = (Expr *) coerce_to_boolean(pstate,
    2448         130 :                                         (Node *) b->arg,
    2449             :                                         clausename);
    2450             : 
    2451         130 :     return (Node *) b;
    2452             : }
    2453             : 
    2454             : static Node *
    2455         164 : transformCurrentOfExpr(ParseState *pstate, CurrentOfExpr *cexpr)
    2456             : {
    2457             :     /* CURRENT OF can only appear at top level of UPDATE/DELETE */
    2458             :     Assert(pstate->p_target_nsitem != NULL);
    2459         164 :     cexpr->cvarno = pstate->p_target_nsitem->p_rtindex;
    2460             : 
    2461             :     /*
    2462             :      * Check to see if the cursor name matches a parameter of type REFCURSOR.
    2463             :      * If so, replace the raw name reference with a parameter reference. (This
    2464             :      * is a hack for the convenience of plpgsql.)
    2465             :      */
    2466         164 :     if (cexpr->cursor_name != NULL) /* in case already transformed */
    2467             :     {
    2468         164 :         ColumnRef  *cref = makeNode(ColumnRef);
    2469         164 :         Node       *node = NULL;
    2470             : 
    2471             :         /* Build an unqualified ColumnRef with the given name */
    2472         164 :         cref->fields = list_make1(makeString(cexpr->cursor_name));
    2473         164 :         cref->location = -1;
    2474             : 
    2475             :         /* See if there is a translation available from a parser hook */
    2476         164 :         if (pstate->p_pre_columnref_hook != NULL)
    2477           8 :             node = pstate->p_pre_columnref_hook(pstate, cref);
    2478         164 :         if (node == NULL && pstate->p_post_columnref_hook != NULL)
    2479           8 :             node = pstate->p_post_columnref_hook(pstate, cref, NULL);
    2480             : 
    2481             :         /*
    2482             :          * XXX Should we throw an error if we get a translation that isn't a
    2483             :          * refcursor Param?  For now it seems best to silently ignore false
    2484             :          * matches.
    2485             :          */
    2486         164 :         if (node != NULL && IsA(node, Param))
    2487             :         {
    2488           8 :             Param      *p = (Param *) node;
    2489             : 
    2490           8 :             if (p->paramkind == PARAM_EXTERN &&
    2491           8 :                 p->paramtype == REFCURSOROID)
    2492             :             {
    2493             :                 /* Matches, so convert CURRENT OF to a param reference */
    2494           8 :                 cexpr->cursor_name = NULL;
    2495           8 :                 cexpr->cursor_param = p->paramid;
    2496             :             }
    2497             :         }
    2498             :     }
    2499             : 
    2500         164 :     return (Node *) cexpr;
    2501             : }
    2502             : 
    2503             : /*
    2504             :  * Construct a whole-row reference to represent the notation "relation.*".
    2505             :  */
    2506             : static Node *
    2507       28900 : transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem,
    2508             :                      int sublevels_up, int location)
    2509             : {
    2510             :     /*
    2511             :      * Build the appropriate referencing node.  Normally this can be a
    2512             :      * whole-row Var, but if the nsitem is a JOIN USING alias then it contains
    2513             :      * only a subset of the columns of the underlying join RTE, so that will
    2514             :      * not work.  Instead we immediately expand the reference into a RowExpr.
    2515             :      * Since the JOIN USING's common columns are fully determined at this
    2516             :      * point, there seems no harm in expanding it now rather than during
    2517             :      * planning.
    2518             :      *
    2519             :      * Note that if the RTE is a function returning scalar, we create just a
    2520             :      * plain reference to the function value, not a composite containing a
    2521             :      * single column.  This is pretty inconsistent at first sight, but it's
    2522             :      * what we've done historically.  One argument for it is that "rel" and
    2523             :      * "rel.*" mean the same thing for composite relations, so why not for
    2524             :      * scalar functions...
    2525             :      */
    2526       28900 :     if (nsitem->p_names == nsitem->p_rte->eref)
    2527             :     {
    2528             :         Var        *result;
    2529             : 
    2530       28892 :         result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex,
    2531             :                                  sublevels_up, true);
    2532             : 
    2533             :         /* location is not filled in by makeWholeRowVar */
    2534       28892 :         result->location = location;
    2535             : 
    2536             :         /* mark relation as requiring whole-row SELECT access */
    2537       28892 :         markVarForSelectPriv(pstate, result);
    2538             : 
    2539       28892 :         return (Node *) result;
    2540             :     }
    2541             :     else
    2542             :     {
    2543             :         RowExpr    *rowexpr;
    2544             :         List       *fields;
    2545             : 
    2546             :         /*
    2547             :          * We want only as many columns as are listed in p_names->colnames,
    2548             :          * and we should use those names not whatever possibly-aliased names
    2549             :          * are in the RTE.  We needn't worry about marking the RTE for SELECT
    2550             :          * access, as the common columns are surely so marked already.
    2551             :          */
    2552           8 :         expandRTE(nsitem->p_rte, nsitem->p_rtindex,
    2553             :                   sublevels_up, location, false,
    2554             :                   NULL, &fields);
    2555           8 :         rowexpr = makeNode(RowExpr);
    2556           8 :         rowexpr->args = list_truncate(fields,
    2557           8 :                                       list_length(nsitem->p_names->colnames));
    2558           8 :         rowexpr->row_typeid = RECORDOID;
    2559           8 :         rowexpr->row_format = COERCE_IMPLICIT_CAST;
    2560           8 :         rowexpr->colnames = copyObject(nsitem->p_names->colnames);
    2561           8 :         rowexpr->location = location;
    2562             : 
    2563           8 :         return (Node *) rowexpr;
    2564             :     }
    2565             : }
    2566             : 
    2567             : /*
    2568             :  * Handle an explicit CAST construct.
    2569             :  *
    2570             :  * Transform the argument, look up the type name, and apply any necessary
    2571             :  * coercion function(s).
    2572             :  */
    2573             : static Node *
    2574      614960 : transformTypeCast(ParseState *pstate, TypeCast *tc)
    2575             : {
    2576             :     Node       *result;
    2577      614960 :     Node       *arg = tc->arg;
    2578             :     Node       *expr;
    2579             :     Oid         inputType;
    2580             :     Oid         targetType;
    2581             :     int32       targetTypmod;
    2582             :     int         location;
    2583             : 
    2584             :     /* Look up the type name first */
    2585      614960 :     typenameTypeIdAndMod(pstate, tc->typeName, &targetType, &targetTypmod);
    2586             : 
    2587             :     /*
    2588             :      * If the subject of the typecast is an ARRAY[] construct and the target
    2589             :      * type is an array type, we invoke transformArrayExpr() directly so that
    2590             :      * we can pass down the type information.  This avoids some cases where
    2591             :      * transformArrayExpr() might not infer the correct type.  Otherwise, just
    2592             :      * transform the argument normally.
    2593             :      */
    2594      614960 :     if (IsA(arg, A_ArrayExpr))
    2595             :     {
    2596             :         Oid         targetBaseType;
    2597             :         int32       targetBaseTypmod;
    2598             :         Oid         elementType;
    2599             : 
    2600             :         /*
    2601             :          * If target is a domain over array, work with the base array type
    2602             :          * here.  Below, we'll cast the array type to the domain.  In the
    2603             :          * usual case that the target is not a domain, the remaining steps
    2604             :          * will be a no-op.
    2605             :          */
    2606         882 :         targetBaseTypmod = targetTypmod;
    2607         882 :         targetBaseType = getBaseTypeAndTypmod(targetType, &targetBaseTypmod);
    2608         882 :         elementType = get_element_type(targetBaseType);
    2609         882 :         if (OidIsValid(elementType))
    2610             :         {
    2611         872 :             expr = transformArrayExpr(pstate,
    2612             :                                       (A_ArrayExpr *) arg,
    2613             :                                       targetBaseType,
    2614             :                                       elementType,
    2615             :                                       targetBaseTypmod);
    2616             :         }
    2617             :         else
    2618          10 :             expr = transformExprRecurse(pstate, arg);
    2619             :     }
    2620             :     else
    2621      614078 :         expr = transformExprRecurse(pstate, arg);
    2622             : 
    2623      614948 :     inputType = exprType(expr);
    2624      614948 :     if (inputType == InvalidOid)
    2625           0 :         return expr;            /* do nothing if NULL input */
    2626             : 
    2627             :     /*
    2628             :      * Location of the coercion is preferentially the location of the :: or
    2629             :      * CAST symbol, but if there is none then use the location of the type
    2630             :      * name (this can happen in TypeName 'string' syntax, for instance).
    2631             :      */
    2632      614948 :     location = tc->location;
    2633      614948 :     if (location < 0)
    2634       67786 :         location = tc->typeName->location;
    2635             : 
    2636      614948 :     result = coerce_to_target_type(pstate, expr, inputType,
    2637             :                                    targetType, targetTypmod,
    2638             :                                    COERCION_EXPLICIT,
    2639             :                                    COERCE_EXPLICIT_CAST,
    2640             :                                    location);
    2641      613660 :     if (result == NULL)
    2642          16 :         ereport(ERROR,
    2643             :                 (errcode(ERRCODE_CANNOT_COERCE),
    2644             :                  errmsg("cannot cast type %s to %s",
    2645             :                         format_type_be(inputType),
    2646             :                         format_type_be(targetType)),
    2647             :                  parser_coercion_errposition(pstate, location, expr)));
    2648             : 
    2649      613644 :     return result;
    2650             : }
    2651             : 
    2652             : /*
    2653             :  * Handle an explicit COLLATE clause.
    2654             :  *
    2655             :  * Transform the argument, and look up the collation name.
    2656             :  */
    2657             : static Node *
    2658        3348 : transformCollateClause(ParseState *pstate, CollateClause *c)
    2659             : {
    2660             :     CollateExpr *newc;
    2661             :     Oid         argtype;
    2662             : 
    2663        3348 :     newc = makeNode(CollateExpr);
    2664        3348 :     newc->arg = (Expr *) transformExprRecurse(pstate, c->arg);
    2665             : 
    2666        3348 :     argtype = exprType((Node *) newc->arg);
    2667             : 
    2668             :     /*
    2669             :      * The unknown type is not collatable, but coerce_type() takes care of it
    2670             :      * separately, so we'll let it go here.
    2671             :      */
    2672        3348 :     if (!type_is_collatable(argtype) && argtype != UNKNOWNOID)
    2673           8 :         ereport(ERROR,
    2674             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2675             :                  errmsg("collations are not supported by type %s",
    2676             :                         format_type_be(argtype)),
    2677             :                  parser_errposition(pstate, c->location)));
    2678             : 
    2679        3340 :     newc->collOid = LookupCollation(pstate, c->collname, c->location);
    2680        3340 :     newc->location = c->location;
    2681             : 
    2682        3340 :     return (Node *) newc;
    2683             : }
    2684             : 
    2685             : /*
    2686             :  * Transform a "row compare-op row" construct
    2687             :  *
    2688             :  * The inputs are lists of already-transformed expressions.
    2689             :  * As with coerce_type, pstate may be NULL if no special unknown-Param
    2690             :  * processing is wanted.
    2691             :  *
    2692             :  * The output may be a single OpExpr, an AND or OR combination of OpExprs,
    2693             :  * or a RowCompareExpr.  In all cases it is guaranteed to return boolean.
    2694             :  * The AND, OR, and RowCompareExpr cases further imply things about the
    2695             :  * behavior of the operators (ie, they behave as =, <>, or < <= > >=).
    2696             :  */
    2697             : static Node *
    2698        8762 : make_row_comparison_op(ParseState *pstate, List *opname,
    2699             :                        List *largs, List *rargs, int location)
    2700             : {
    2701             :     RowCompareExpr *rcexpr;
    2702             :     RowCompareType rctype;
    2703             :     List       *opexprs;
    2704             :     List       *opnos;
    2705             :     List       *opfamilies;
    2706             :     ListCell   *l,
    2707             :                *r;
    2708             :     List      **opinfo_lists;
    2709             :     Bitmapset  *strats;
    2710             :     int         nopers;
    2711             :     int         i;
    2712             : 
    2713        8762 :     nopers = list_length(largs);
    2714        8762 :     if (nopers != list_length(rargs))
    2715           0 :         ereport(ERROR,
    2716             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2717             :                  errmsg("unequal number of entries in row expressions"),
    2718             :                  parser_errposition(pstate, location)));
    2719             : 
    2720             :     /*
    2721             :      * We can't compare zero-length rows because there is no principled basis
    2722             :      * for figuring out what the operator is.
    2723             :      */
    2724        8762 :     if (nopers == 0)
    2725           4 :         ereport(ERROR,
    2726             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2727             :                  errmsg("cannot compare rows of zero length"),
    2728             :                  parser_errposition(pstate, location)));
    2729             : 
    2730             :     /*
    2731             :      * Identify all the pairwise operators, using make_op so that behavior is
    2732             :      * the same as in the simple scalar case.
    2733             :      */
    2734        8758 :     opexprs = NIL;
    2735       21624 :     forboth(l, largs, r, rargs)
    2736             :     {
    2737       12874 :         Node       *larg = (Node *) lfirst(l);
    2738       12874 :         Node       *rarg = (Node *) lfirst(r);
    2739             :         OpExpr     *cmp;
    2740             : 
    2741       12874 :         cmp = castNode(OpExpr, make_op(pstate, opname, larg, rarg,
    2742             :                                        pstate->p_last_srf, location));
    2743             : 
    2744             :         /*
    2745             :          * We don't use coerce_to_boolean here because we insist on the
    2746             :          * operator yielding boolean directly, not via coercion.  If it
    2747             :          * doesn't yield bool it won't be in any index opfamilies...
    2748             :          */
    2749       12866 :         if (cmp->opresulttype != BOOLOID)
    2750           0 :             ereport(ERROR,
    2751             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2752             :                      errmsg("row comparison operator must yield type boolean, "
    2753             :                             "not type %s",
    2754             :                             format_type_be(cmp->opresulttype)),
    2755             :                      parser_errposition(pstate, location)));
    2756       12866 :         if (expression_returns_set((Node *) cmp))
    2757           0 :             ereport(ERROR,
    2758             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2759             :                      errmsg("row comparison operator must not return a set"),
    2760             :                      parser_errposition(pstate, location)));
    2761       12866 :         opexprs = lappend(opexprs, cmp);
    2762             :     }
    2763             : 
    2764             :     /*
    2765             :      * If rows are length 1, just return the single operator.  In this case we
    2766             :      * don't insist on identifying btree semantics for the operator (but we
    2767             :      * still require it to return boolean).
    2768             :      */
    2769        8750 :     if (nopers == 1)
    2770        5646 :         return (Node *) linitial(opexprs);
    2771             : 
    2772             :     /*
    2773             :      * Now we must determine which row comparison semantics (= <> < <= > >=)
    2774             :      * apply to this set of operators.  We look for btree opfamilies
    2775             :      * containing the operators, and see which interpretations (strategy
    2776             :      * numbers) exist for each operator.
    2777             :      */
    2778        3104 :     opinfo_lists = (List **) palloc(nopers * sizeof(List *));
    2779        3104 :     strats = NULL;
    2780        3104 :     i = 0;
    2781       10324 :     foreach(l, opexprs)
    2782             :     {
    2783        7220 :         Oid         opno = ((OpExpr *) lfirst(l))->opno;
    2784             :         Bitmapset  *this_strats;
    2785             :         ListCell   *j;
    2786             : 
    2787        7220 :         opinfo_lists[i] = get_op_btree_interpretation(opno);
    2788             : 
    2789             :         /*
    2790             :          * convert strategy numbers into a Bitmapset to make the intersection
    2791             :          * calculation easy.
    2792             :          */
    2793        7220 :         this_strats = NULL;
    2794       14954 :         foreach(j, opinfo_lists[i])
    2795             :         {
    2796        7734 :             OpBtreeInterpretation *opinfo = lfirst(j);
    2797             : 
    2798        7734 :             this_strats = bms_add_member(this_strats, opinfo->strategy);
    2799             :         }
    2800        7220 :         if (i == 0)
    2801        3104 :             strats = this_strats;
    2802             :         else
    2803        4116 :             strats = bms_int_members(strats, this_strats);
    2804        7220 :         i++;
    2805             :     }
    2806             : 
    2807             :     /*
    2808             :      * If there are multiple common interpretations, we may use any one of
    2809             :      * them ... this coding arbitrarily picks the lowest btree strategy
    2810             :      * number.
    2811             :      */
    2812        3104 :     i = bms_first_member(strats);
    2813        3104 :     if (i < 0)
    2814             :     {
    2815             :         /* No common interpretation, so fail */
    2816           4 :         ereport(ERROR,
    2817             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2818             :                  errmsg("could not determine interpretation of row comparison operator %s",
    2819             :                         strVal(llast(opname))),
    2820             :                  errhint("Row comparison operators must be associated with btree operator families."),
    2821             :                  parser_errposition(pstate, location)));
    2822             :     }
    2823        3100 :     rctype = (RowCompareType) i;
    2824             : 
    2825             :     /*
    2826             :      * For = and <> cases, we just combine the pairwise operators with AND or
    2827             :      * OR respectively.
    2828             :      */
    2829        3100 :     if (rctype == ROWCOMPARE_EQ)
    2830        1056 :         return (Node *) makeBoolExpr(AND_EXPR, opexprs, location);
    2831        2044 :     if (rctype == ROWCOMPARE_NE)
    2832        1936 :         return (Node *) makeBoolExpr(OR_EXPR, opexprs, location);
    2833             : 
    2834             :     /*
    2835             :      * Otherwise we need to choose exactly which opfamily to associate with
    2836             :      * each operator.
    2837             :      */
    2838         108 :     opfamilies = NIL;
    2839         360 :     for (i = 0; i < nopers; i++)
    2840             :     {
    2841         252 :         Oid         opfamily = InvalidOid;
    2842             :         ListCell   *j;
    2843             : 
    2844         252 :         foreach(j, opinfo_lists[i])
    2845             :         {
    2846         252 :             OpBtreeInterpretation *opinfo = lfirst(j);
    2847             : 
    2848         252 :             if (opinfo->strategy == rctype)
    2849             :             {
    2850         252 :                 opfamily = opinfo->opfamily_id;
    2851         252 :                 break;
    2852             :             }
    2853             :         }
    2854         252 :         if (OidIsValid(opfamily))
    2855         252 :             opfamilies = lappend_oid(opfamilies, opfamily);
    2856             :         else                    /* should not happen */
    2857           0 :             ereport(ERROR,
    2858             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2859             :                      errmsg("could not determine interpretation of row comparison operator %s",
    2860             :                             strVal(llast(opname))),
    2861             :                      errdetail("There are multiple equally-plausible candidates."),
    2862             :                      parser_errposition(pstate, location)));
    2863             :     }
    2864             : 
    2865             :     /*
    2866             :      * Now deconstruct the OpExprs and create a RowCompareExpr.
    2867             :      *
    2868             :      * Note: can't just reuse the passed largs/rargs lists, because of
    2869             :      * possibility that make_op inserted coercion operations.
    2870             :      */
    2871         108 :     opnos = NIL;
    2872         108 :     largs = NIL;
    2873         108 :     rargs = NIL;
    2874         360 :     foreach(l, opexprs)
    2875             :     {
    2876         252 :         OpExpr     *cmp = (OpExpr *) lfirst(l);
    2877             : 
    2878         252 :         opnos = lappend_oid(opnos, cmp->opno);
    2879         252 :         largs = lappend(largs, linitial(cmp->args));
    2880         252 :         rargs = lappend(rargs, lsecond(cmp->args));
    2881             :     }
    2882             : 
    2883         108 :     rcexpr = makeNode(RowCompareExpr);
    2884         108 :     rcexpr->rctype = rctype;
    2885         108 :     rcexpr->opnos = opnos;
    2886         108 :     rcexpr->opfamilies = opfamilies;
    2887         108 :     rcexpr->inputcollids = NIL; /* assign_expr_collations will fix this */
    2888         108 :     rcexpr->largs = largs;
    2889         108 :     rcexpr->rargs = rargs;
    2890             : 
    2891         108 :     return (Node *) rcexpr;
    2892             : }
    2893             : 
    2894             : /*
    2895             :  * Transform a "row IS DISTINCT FROM row" construct
    2896             :  *
    2897             :  * The input RowExprs are already transformed
    2898             :  */
    2899             : static Node *
    2900           4 : make_row_distinct_op(ParseState *pstate, List *opname,
    2901             :                      RowExpr *lrow, RowExpr *rrow,
    2902             :                      int location)
    2903             : {
    2904           4 :     Node       *result = NULL;
    2905           4 :     List       *largs = lrow->args;
    2906           4 :     List       *rargs = rrow->args;
    2907             :     ListCell   *l,
    2908             :                *r;
    2909             : 
    2910           4 :     if (list_length(largs) != list_length(rargs))
    2911           0 :         ereport(ERROR,
    2912             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2913             :                  errmsg("unequal number of entries in row expressions"),
    2914             :                  parser_errposition(pstate, location)));
    2915             : 
    2916          16 :     forboth(l, largs, r, rargs)
    2917             :     {
    2918          12 :         Node       *larg = (Node *) lfirst(l);
    2919          12 :         Node       *rarg = (Node *) lfirst(r);
    2920             :         Node       *cmp;
    2921             : 
    2922          12 :         cmp = (Node *) make_distinct_op(pstate, opname, larg, rarg, location);
    2923          12 :         if (result == NULL)
    2924           4 :             result = cmp;
    2925             :         else
    2926           8 :             result = (Node *) makeBoolExpr(OR_EXPR,
    2927           8 :                                            list_make2(result, cmp),
    2928             :                                            location);
    2929             :     }
    2930             : 
    2931           4 :     if (result == NULL)
    2932             :     {
    2933             :         /* zero-length rows?  Generate constant FALSE */
    2934           0 :         result = makeBoolConst(false, false);
    2935             :     }
    2936             : 
    2937           4 :     return result;
    2938             : }
    2939             : 
    2940             : /*
    2941             :  * make the node for an IS DISTINCT FROM operator
    2942             :  */
    2943             : static Expr *
    2944         534 : make_distinct_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree,
    2945             :                  int location)
    2946             : {
    2947             :     Expr       *result;
    2948             : 
    2949         534 :     result = make_op(pstate, opname, ltree, rtree,
    2950             :                      pstate->p_last_srf, location);
    2951         534 :     if (((OpExpr *) result)->opresulttype != BOOLOID)
    2952           0 :         ereport(ERROR,
    2953             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2954             :                  errmsg("IS DISTINCT FROM requires = operator to yield boolean"),
    2955             :                  parser_errposition(pstate, location)));
    2956         534 :     if (((OpExpr *) result)->opretset)
    2957           0 :         ereport(ERROR,
    2958             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    2959             :         /* translator: %s is name of a SQL construct, eg NULLIF */
    2960             :                  errmsg("%s must not return a set", "IS DISTINCT FROM"),
    2961             :                  parser_errposition(pstate, location)));
    2962             : 
    2963             :     /*
    2964             :      * We rely on DistinctExpr and OpExpr being same struct
    2965             :      */
    2966         534 :     NodeSetTag(result, T_DistinctExpr);
    2967             : 
    2968         534 :     return result;
    2969             : }
    2970             : 
    2971             : /*
    2972             :  * Produce a NullTest node from an IS [NOT] DISTINCT FROM NULL construct
    2973             :  *
    2974             :  * "arg" is the untransformed other argument
    2975             :  */
    2976             : static Node *
    2977          20 : make_nulltest_from_distinct(ParseState *pstate, A_Expr *distincta, Node *arg)
    2978             : {
    2979          20 :     NullTest   *nt = makeNode(NullTest);
    2980             : 
    2981          20 :     nt->arg = (Expr *) transformExprRecurse(pstate, arg);
    2982             :     /* the argument can be any type, so don't coerce it */
    2983          20 :     if (distincta->kind == AEXPR_NOT_DISTINCT)
    2984           8 :         nt->nulltesttype = IS_NULL;
    2985             :     else
    2986          12 :         nt->nulltesttype = IS_NOT_NULL;
    2987             :     /* argisrow = false is correct whether or not arg is composite */
    2988          20 :     nt->argisrow = false;
    2989          20 :     nt->location = distincta->location;
    2990          20 :     return (Node *) nt;
    2991             : }
    2992             : 
    2993             : /*
    2994             :  * Produce a string identifying an expression by kind.
    2995             :  *
    2996             :  * Note: when practical, use a simple SQL keyword for the result.  If that
    2997             :  * doesn't work well, check call sites to see whether custom error message
    2998             :  * strings are required.
    2999             :  */
    3000             : const char *
    3001          48 : ParseExprKindName(ParseExprKind exprKind)
    3002             : {
    3003          48 :     switch (exprKind)
    3004             :     {
    3005           0 :         case EXPR_KIND_NONE:
    3006           0 :             return "invalid expression context";
    3007           0 :         case EXPR_KIND_OTHER:
    3008           0 :             return "extension expression";
    3009           0 :         case EXPR_KIND_JOIN_ON:
    3010           0 :             return "JOIN/ON";
    3011           0 :         case EXPR_KIND_JOIN_USING:
    3012           0 :             return "JOIN/USING";
    3013           0 :         case EXPR_KIND_FROM_SUBSELECT:
    3014           0 :             return "sub-SELECT in FROM";
    3015           0 :         case EXPR_KIND_FROM_FUNCTION:
    3016           0 :             return "function in FROM";
    3017          12 :         case EXPR_KIND_WHERE:
    3018          12 :             return "WHERE";
    3019           0 :         case EXPR_KIND_POLICY:
    3020           0 :             return "POLICY";
    3021           0 :         case EXPR_KIND_HAVING:
    3022           0 :             return "HAVING";
    3023           8 :         case EXPR_KIND_FILTER:
    3024           8 :             return "FILTER";
    3025           0 :         case EXPR_KIND_WINDOW_PARTITION:
    3026           0 :             return "window PARTITION BY";
    3027           0 :         case EXPR_KIND_WINDOW_ORDER:
    3028           0 :             return "window ORDER BY";
    3029           0 :         case EXPR_KIND_WINDOW_FRAME_RANGE:
    3030           0 :             return "window RANGE";
    3031           0 :         case EXPR_KIND_WINDOW_FRAME_ROWS:
    3032           0 :             return "window ROWS";
    3033           0 :         case EXPR_KIND_WINDOW_FRAME_GROUPS:
    3034           0 :             return "window GROUPS";
    3035           0 :         case EXPR_KIND_SELECT_TARGET:
    3036           0 :             return "SELECT";
    3037           0 :         case EXPR_KIND_INSERT_TARGET:
    3038           0 :             return "INSERT";
    3039           4 :         case EXPR_KIND_UPDATE_SOURCE:
    3040             :         case EXPR_KIND_UPDATE_TARGET:
    3041           4 :             return "UPDATE";
    3042           8 :         case EXPR_KIND_GROUP_BY:
    3043           8 :             return "GROUP BY";
    3044           0 :         case EXPR_KIND_ORDER_BY:
    3045           0 :             return "ORDER BY";
    3046           0 :         case EXPR_KIND_DISTINCT_ON:
    3047           0 :             return "DISTINCT ON";
    3048           4 :         case EXPR_KIND_LIMIT:
    3049           4 :             return "LIMIT";
    3050           0 :         case EXPR_KIND_OFFSET:
    3051           0 :             return "OFFSET";
    3052           8 :         case EXPR_KIND_RETURNING:
    3053           8 :             return "RETURNING";
    3054           4 :         case EXPR_KIND_VALUES:
    3055             :         case EXPR_KIND_VALUES_SINGLE:
    3056           4 :             return "VALUES";
    3057           0 :         case EXPR_KIND_CHECK_CONSTRAINT:
    3058             :         case EXPR_KIND_DOMAIN_CHECK:
    3059           0 :             return "CHECK";
    3060           0 :         case EXPR_KIND_COLUMN_DEFAULT:
    3061             :         case EXPR_KIND_FUNCTION_DEFAULT:
    3062           0 :             return "DEFAULT";
    3063           0 :         case EXPR_KIND_INDEX_EXPRESSION:
    3064           0 :             return "index expression";
    3065           0 :         case EXPR_KIND_INDEX_PREDICATE:
    3066           0 :             return "index predicate";
    3067           0 :         case EXPR_KIND_STATS_EXPRESSION:
    3068           0 :             return "statistics expression";
    3069           0 :         case EXPR_KIND_ALTER_COL_TRANSFORM:
    3070           0 :             return "USING";
    3071           0 :         case EXPR_KIND_EXECUTE_PARAMETER:
    3072           0 :             return "EXECUTE";
    3073           0 :         case EXPR_KIND_TRIGGER_WHEN:
    3074           0 :             return "WHEN";
    3075           0 :         case EXPR_KIND_PARTITION_BOUND:
    3076           0 :             return "partition bound";
    3077           0 :         case EXPR_KIND_PARTITION_EXPRESSION:
    3078           0 :             return "PARTITION BY";
    3079           0 :         case EXPR_KIND_CALL_ARGUMENT:
    3080           0 :             return "CALL";
    3081           0 :         case EXPR_KIND_COPY_WHERE:
    3082           0 :             return "WHERE";
    3083           0 :         case EXPR_KIND_GENERATED_COLUMN:
    3084           0 :             return "GENERATED AS";
    3085           0 :         case EXPR_KIND_CYCLE_MARK:
    3086           0 :             return "CYCLE";
    3087             : 
    3088             :             /*
    3089             :              * There is intentionally no default: case here, so that the
    3090             :              * compiler will warn if we add a new ParseExprKind without
    3091             :              * extending this switch.  If we do see an unrecognized value at
    3092             :              * runtime, we'll fall through to the "unrecognized" return.
    3093             :              */
    3094             :     }
    3095           0 :     return "unrecognized expression kind";
    3096             : }

Generated by: LCOV version 1.14