LCOV - code coverage report
Current view: top level - src/backend/parser - parse_clause.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 885 952 93.0 %
Date: 2019-11-15 22:06:47 Functions: 40 40 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_clause.c
       4             :  *    handle clauses in parser
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/parser/parse_clause.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include "access/htup_details.h"
      19             : #include "access/nbtree.h"
      20             : #include "access/table.h"
      21             : #include "access/tsmapi.h"
      22             : #include "catalog/catalog.h"
      23             : #include "catalog/heap.h"
      24             : #include "catalog/pg_am.h"
      25             : #include "catalog/pg_amproc.h"
      26             : #include "catalog/pg_collation.h"
      27             : #include "catalog/pg_constraint.h"
      28             : #include "catalog/pg_type.h"
      29             : #include "commands/defrem.h"
      30             : #include "miscadmin.h"
      31             : #include "nodes/makefuncs.h"
      32             : #include "nodes/nodeFuncs.h"
      33             : #include "optimizer/optimizer.h"
      34             : #include "parser/analyze.h"
      35             : #include "parser/parse_clause.h"
      36             : #include "parser/parse_coerce.h"
      37             : #include "parser/parse_collate.h"
      38             : #include "parser/parse_expr.h"
      39             : #include "parser/parse_func.h"
      40             : #include "parser/parse_oper.h"
      41             : #include "parser/parse_relation.h"
      42             : #include "parser/parse_target.h"
      43             : #include "parser/parse_type.h"
      44             : #include "parser/parser.h"
      45             : #include "parser/parsetree.h"
      46             : #include "rewrite/rewriteManip.h"
      47             : #include "utils/builtins.h"
      48             : #include "utils/catcache.h"
      49             : #include "utils/guc.h"
      50             : #include "utils/lsyscache.h"
      51             : #include "utils/rel.h"
      52             : #include "utils/syscache.h"
      53             : 
      54             : /* Convenience macro for the most common makeNamespaceItem() case */
      55             : #define makeDefaultNSItem(rte)  makeNamespaceItem(rte, true, true, false, true)
      56             : 
      57             : static void extractRemainingColumns(List *common_colnames,
      58             :                                     List *src_colnames, List *src_colvars,
      59             :                                     List **res_colnames, List **res_colvars);
      60             : static Node *transformJoinUsingClause(ParseState *pstate,
      61             :                                       RangeTblEntry *leftRTE, RangeTblEntry *rightRTE,
      62             :                                       List *leftVars, List *rightVars);
      63             : static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
      64             :                                    List *namespace);
      65             : static RangeTblEntry *getRTEForSpecialRelationTypes(ParseState *pstate,
      66             :                                                     RangeVar *rv);
      67             : static RangeTblEntry *transformTableEntry(ParseState *pstate, RangeVar *r);
      68             : static RangeTblEntry *transformRangeSubselect(ParseState *pstate,
      69             :                                               RangeSubselect *r);
      70             : static RangeTblEntry *transformRangeFunction(ParseState *pstate,
      71             :                                              RangeFunction *r);
      72             : static RangeTblEntry *transformRangeTableFunc(ParseState *pstate,
      73             :                                               RangeTableFunc *t);
      74             : static TableSampleClause *transformRangeTableSample(ParseState *pstate,
      75             :                                                     RangeTableSample *rts);
      76             : static Node *transformFromClauseItem(ParseState *pstate, Node *n,
      77             :                                      RangeTblEntry **top_rte, int *top_rti,
      78             :                                      List **namespace);
      79             : static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
      80             :                                 Var *l_colvar, Var *r_colvar);
      81             : static ParseNamespaceItem *makeNamespaceItem(RangeTblEntry *rte,
      82             :                                              bool rel_visible, bool cols_visible,
      83             :                                              bool lateral_only, bool lateral_ok);
      84             : static void setNamespaceColumnVisibility(List *namespace, bool cols_visible);
      85             : static void setNamespaceLateralState(List *namespace,
      86             :                                      bool lateral_only, bool lateral_ok);
      87             : static void checkExprIsVarFree(ParseState *pstate, Node *n,
      88             :                                const char *constructName);
      89             : static TargetEntry *findTargetlistEntrySQL92(ParseState *pstate, Node *node,
      90             :                                              List **tlist, ParseExprKind exprKind);
      91             : static TargetEntry *findTargetlistEntrySQL99(ParseState *pstate, Node *node,
      92             :                                              List **tlist, ParseExprKind exprKind);
      93             : static int  get_matching_location(int sortgroupref,
      94             :                                   List *sortgrouprefs, List *exprs);
      95             : static List *resolve_unique_index_expr(ParseState *pstate, InferClause *infer,
      96             :                                        Relation heapRel);
      97             : static List *addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
      98             :                                   List *grouplist, List *targetlist, int location);
      99             : static WindowClause *findWindowClause(List *wclist, const char *name);
     100             : static Node *transformFrameOffset(ParseState *pstate, int frameOptions,
     101             :                                   Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc,
     102             :                                   Node *clause);
     103             : 
     104             : 
     105             : /*
     106             :  * transformFromClause -
     107             :  *    Process the FROM clause and add items to the query's range table,
     108             :  *    joinlist, and namespace.
     109             :  *
     110             :  * Note: we assume that the pstate's p_rtable, p_joinlist, and p_namespace
     111             :  * lists were initialized to NIL when the pstate was created.
     112             :  * We will add onto any entries already present --- this is needed for rule
     113             :  * processing, as well as for UPDATE and DELETE.
     114             :  */
     115             : void
     116      353696 : transformFromClause(ParseState *pstate, List *frmList)
     117             : {
     118             :     ListCell   *fl;
     119             : 
     120             :     /*
     121             :      * The grammar will have produced a list of RangeVars, RangeSubselects,
     122             :      * RangeFunctions, and/or JoinExprs. Transform each one (possibly adding
     123             :      * entries to the rtable), check for duplicate refnames, and then add it
     124             :      * to the joinlist and namespace.
     125             :      *
     126             :      * Note we must process the items left-to-right for proper handling of
     127             :      * LATERAL references.
     128             :      */
     129      660642 :     foreach(fl, frmList)
     130             :     {
     131      307208 :         Node       *n = lfirst(fl);
     132             :         RangeTblEntry *rte;
     133             :         int         rtindex;
     134             :         List       *namespace;
     135             : 
     136      307208 :         n = transformFromClauseItem(pstate, n,
     137             :                                     &rte,
     138             :                                     &rtindex,
     139             :                                     &namespace);
     140             : 
     141      306950 :         checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
     142             : 
     143             :         /* Mark the new namespace items as visible only to LATERAL */
     144      306946 :         setNamespaceLateralState(namespace, true, true);
     145             : 
     146      306946 :         pstate->p_joinlist = lappend(pstate->p_joinlist, n);
     147      306946 :         pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
     148             :     }
     149             : 
     150             :     /*
     151             :      * We're done parsing the FROM list, so make all namespace items
     152             :      * unconditionally visible.  Note that this will also reset lateral_only
     153             :      * for any namespace items that were already present when we were called;
     154             :      * but those should have been that way already.
     155             :      */
     156      353434 :     setNamespaceLateralState(pstate->p_namespace, false, true);
     157      353434 : }
     158             : 
     159             : /*
     160             :  * setTargetTable
     161             :  *    Add the target relation of INSERT/UPDATE/DELETE to the range table,
     162             :  *    and make the special links to it in the ParseState.
     163             :  *
     164             :  *    We also open the target relation and acquire a write lock on it.
     165             :  *    This must be done before processing the FROM list, in case the target
     166             :  *    is also mentioned as a source relation --- we want to be sure to grab
     167             :  *    the write lock before any read lock.
     168             :  *
     169             :  *    If alsoSource is true, add the target to the query's joinlist and
     170             :  *    namespace.  For INSERT, we don't want the target to be joined to;
     171             :  *    it's a destination of tuples, not a source.   For UPDATE/DELETE,
     172             :  *    we do need to scan or join the target.  (NOTE: we do not bother
     173             :  *    to check for namespace conflict; we assume that the namespace was
     174             :  *    initially empty in these cases.)
     175             :  *
     176             :  *    Finally, we mark the relation as requiring the permissions specified
     177             :  *    by requiredPerms.
     178             :  *
     179             :  *    Returns the rangetable index of the target relation.
     180             :  */
     181             : int
     182       70252 : setTargetTable(ParseState *pstate, RangeVar *relation,
     183             :                bool inh, bool alsoSource, AclMode requiredPerms)
     184             : {
     185             :     RangeTblEntry *rte;
     186             :     int         rtindex;
     187             : 
     188             :     /*
     189             :      * ENRs hide tables of the same name, so we need to check for them first.
     190             :      * In contrast, CTEs don't hide tables (for this purpose).
     191             :      */
     192      136976 :     if (relation->schemaname == NULL &&
     193       66724 :         scanNameSpaceForENR(pstate, relation->relname))
     194           4 :         ereport(ERROR,
     195             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     196             :                  errmsg("relation \"%s\" cannot be the target of a modifying statement",
     197             :                         relation->relname)));
     198             : 
     199             :     /* Close old target; this could only happen for multi-action rules */
     200       70248 :     if (pstate->p_target_relation != NULL)
     201           0 :         table_close(pstate->p_target_relation, NoLock);
     202             : 
     203             :     /*
     204             :      * Open target rel and grab suitable lock (which we will hold till end of
     205             :      * transaction).
     206             :      *
     207             :      * free_parsestate() will eventually do the corresponding table_close(),
     208             :      * but *not* release the lock.
     209             :      */
     210       70248 :     pstate->p_target_relation = parserOpenTable(pstate, relation,
     211             :                                                 RowExclusiveLock);
     212             : 
     213             :     /*
     214             :      * Now build an RTE.
     215             :      */
     216       70234 :     rte = addRangeTableEntryForRelation(pstate, pstate->p_target_relation,
     217             :                                         RowExclusiveLock,
     218             :                                         relation->alias, inh, false);
     219       70234 :     pstate->p_target_rangetblentry = rte;
     220             : 
     221             :     /* assume new rte is at end */
     222       70234 :     rtindex = list_length(pstate->p_rtable);
     223             :     Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
     224             : 
     225             :     /*
     226             :      * Override addRangeTableEntry's default ACL_SELECT permissions check, and
     227             :      * instead mark target table as requiring exactly the specified
     228             :      * permissions.
     229             :      *
     230             :      * If we find an explicit reference to the rel later during parse
     231             :      * analysis, we will add the ACL_SELECT bit back again; see
     232             :      * markVarForSelectPriv and its callers.
     233             :      */
     234       70234 :     rte->requiredPerms = requiredPerms;
     235             : 
     236             :     /*
     237             :      * If UPDATE/DELETE, add table to joinlist and namespace.
     238             :      *
     239             :      * Note: some callers know that they can find the new ParseNamespaceItem
     240             :      * at the end of the pstate->p_namespace list.  This is a bit ugly but not
     241             :      * worth complicating this function's signature for.
     242             :      */
     243       70234 :     if (alsoSource)
     244       12408 :         addRTEtoQuery(pstate, rte, true, true, true);
     245             : 
     246       70234 :     return rtindex;
     247             : }
     248             : 
     249             : /*
     250             :  * Extract all not-in-common columns from column lists of a source table
     251             :  */
     252             : static void
     253      158284 : extractRemainingColumns(List *common_colnames,
     254             :                         List *src_colnames, List *src_colvars,
     255             :                         List **res_colnames, List **res_colvars)
     256             : {
     257      158284 :     List       *new_colnames = NIL;
     258      158284 :     List       *new_colvars = NIL;
     259             :     ListCell   *lnames,
     260             :                *lvars;
     261             : 
     262             :     Assert(list_length(src_colnames) == list_length(src_colvars));
     263             : 
     264     4068304 :     forboth(lnames, src_colnames, lvars, src_colvars)
     265             :     {
     266     3910020 :         char       *colname = strVal(lfirst(lnames));
     267     3910020 :         bool        match = false;
     268             :         ListCell   *cnames;
     269             : 
     270     3915004 :         foreach(cnames, common_colnames)
     271             :         {
     272        6552 :             char       *ccolname = strVal(lfirst(cnames));
     273             : 
     274        6552 :             if (strcmp(colname, ccolname) == 0)
     275             :             {
     276        1568 :                 match = true;
     277        1568 :                 break;
     278             :             }
     279             :         }
     280             : 
     281     3910020 :         if (!match)
     282             :         {
     283     3908452 :             new_colnames = lappend(new_colnames, lfirst(lnames));
     284     3908452 :             new_colvars = lappend(new_colvars, lfirst(lvars));
     285             :         }
     286             :     }
     287             : 
     288      158284 :     *res_colnames = new_colnames;
     289      158284 :     *res_colvars = new_colvars;
     290      158284 : }
     291             : 
     292             : /* transformJoinUsingClause()
     293             :  *    Build a complete ON clause from a partially-transformed USING list.
     294             :  *    We are given lists of nodes representing left and right match columns.
     295             :  *    Result is a transformed qualification expression.
     296             :  */
     297             : static Node *
     298         688 : transformJoinUsingClause(ParseState *pstate,
     299             :                          RangeTblEntry *leftRTE, RangeTblEntry *rightRTE,
     300             :                          List *leftVars, List *rightVars)
     301             : {
     302             :     Node       *result;
     303         688 :     List       *andargs = NIL;
     304             :     ListCell   *lvars,
     305             :                *rvars;
     306             : 
     307             :     /*
     308             :      * We cheat a little bit here by building an untransformed operator tree
     309             :      * whose leaves are the already-transformed Vars.  This requires collusion
     310             :      * from transformExpr(), which normally could be expected to complain
     311             :      * about already-transformed subnodes.  However, this does mean that we
     312             :      * have to mark the columns as requiring SELECT privilege for ourselves;
     313             :      * transformExpr() won't do it.
     314             :      */
     315        1472 :     forboth(lvars, leftVars, rvars, rightVars)
     316             :     {
     317         784 :         Var        *lvar = (Var *) lfirst(lvars);
     318         784 :         Var        *rvar = (Var *) lfirst(rvars);
     319             :         A_Expr     *e;
     320             : 
     321             :         /* Require read access to the join variables */
     322         784 :         markVarForSelectPriv(pstate, lvar, leftRTE);
     323         784 :         markVarForSelectPriv(pstate, rvar, rightRTE);
     324             : 
     325             :         /* Now create the lvar = rvar join condition */
     326         784 :         e = makeSimpleA_Expr(AEXPR_OP, "=",
     327         784 :                              (Node *) copyObject(lvar), (Node *) copyObject(rvar),
     328             :                              -1);
     329             : 
     330             :         /* Prepare to combine into an AND clause, if multiple join columns */
     331         784 :         andargs = lappend(andargs, e);
     332             :     }
     333             : 
     334             :     /* Only need an AND if there's more than one join column */
     335         688 :     if (list_length(andargs) == 1)
     336         608 :         result = (Node *) linitial(andargs);
     337             :     else
     338          80 :         result = (Node *) makeBoolExpr(AND_EXPR, andargs, -1);
     339             : 
     340             :     /*
     341             :      * Since the references are already Vars, and are certainly from the input
     342             :      * relations, we don't have to go through the same pushups that
     343             :      * transformJoinOnClause() does.  Just invoke transformExpr() to fix up
     344             :      * the operators, and we're done.
     345             :      */
     346         688 :     result = transformExpr(pstate, result, EXPR_KIND_JOIN_USING);
     347             : 
     348         688 :     result = coerce_to_boolean(pstate, result, "JOIN/USING");
     349             : 
     350         688 :     return result;
     351             : }
     352             : 
     353             : /* transformJoinOnClause()
     354             :  *    Transform the qual conditions for JOIN/ON.
     355             :  *    Result is a transformed qualification expression.
     356             :  */
     357             : static Node *
     358       78326 : transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
     359             : {
     360             :     Node       *result;
     361             :     List       *save_namespace;
     362             : 
     363             :     /*
     364             :      * The namespace that the join expression should see is just the two
     365             :      * subtrees of the JOIN plus any outer references from upper pstate
     366             :      * levels.  Temporarily set this pstate's namespace accordingly.  (We need
     367             :      * not check for refname conflicts, because transformFromClauseItem()
     368             :      * already did.)  All namespace items are marked visible regardless of
     369             :      * LATERAL state.
     370             :      */
     371       78326 :     setNamespaceLateralState(namespace, false, true);
     372             : 
     373       78326 :     save_namespace = pstate->p_namespace;
     374       78326 :     pstate->p_namespace = namespace;
     375             : 
     376       78326 :     result = transformWhereClause(pstate, j->quals,
     377             :                                   EXPR_KIND_JOIN_ON, "JOIN/ON");
     378             : 
     379       78314 :     pstate->p_namespace = save_namespace;
     380             : 
     381       78314 :     return result;
     382             : }
     383             : 
     384             : /*
     385             :  * transformTableEntry --- transform a RangeVar (simple relation reference)
     386             :  */
     387             : static RangeTblEntry *
     388      325596 : transformTableEntry(ParseState *pstate, RangeVar *r)
     389             : {
     390             :     RangeTblEntry *rte;
     391             : 
     392             :     /* We need only build a range table entry */
     393      325596 :     rte = addRangeTableEntry(pstate, r, r->alias, r->inh, true);
     394             : 
     395      325506 :     return rte;
     396             : }
     397             : 
     398             : /*
     399             :  * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
     400             :  */
     401             : static RangeTblEntry *
     402       20102 : transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
     403             : {
     404             :     Query      *query;
     405             :     RangeTblEntry *rte;
     406             : 
     407             :     /*
     408             :      * We require user to supply an alias for a subselect, per SQL92. To relax
     409             :      * this, we'd have to be prepared to gin up a unique alias for an
     410             :      * unlabeled subselect.  (This is just elog, not ereport, because the
     411             :      * grammar should have enforced it already.  It'd probably be better to
     412             :      * report the error here, but we don't have a good error location here.)
     413             :      */
     414       20102 :     if (r->alias == NULL)
     415           0 :         elog(ERROR, "subquery in FROM must have an alias");
     416             : 
     417             :     /*
     418             :      * Set p_expr_kind to show this parse level is recursing to a subselect.
     419             :      * We can't be nested within any expression, so don't need save-restore
     420             :      * logic here.
     421             :      */
     422             :     Assert(pstate->p_expr_kind == EXPR_KIND_NONE);
     423       20102 :     pstate->p_expr_kind = EXPR_KIND_FROM_SUBSELECT;
     424             : 
     425             :     /*
     426             :      * If the subselect is LATERAL, make lateral_only names of this level
     427             :      * visible to it.  (LATERAL can't nest within a single pstate level, so we
     428             :      * don't need save/restore logic here.)
     429             :      */
     430             :     Assert(!pstate->p_lateral_active);
     431       20102 :     pstate->p_lateral_active = r->lateral;
     432             : 
     433             :     /*
     434             :      * Analyze and transform the subquery.
     435             :      */
     436       20102 :     query = parse_sub_analyze(r->subquery, pstate, NULL,
     437       20102 :                               isLockedRefname(pstate, r->alias->aliasname),
     438             :                               true);
     439             : 
     440             :     /* Restore state */
     441       20034 :     pstate->p_lateral_active = false;
     442       20034 :     pstate->p_expr_kind = EXPR_KIND_NONE;
     443             : 
     444             :     /*
     445             :      * Check that we got a SELECT.  Anything else should be impossible given
     446             :      * restrictions of the grammar, but check anyway.
     447             :      */
     448       40068 :     if (!IsA(query, Query) ||
     449       20034 :         query->commandType != CMD_SELECT)
     450           0 :         elog(ERROR, "unexpected non-SELECT command in subquery in FROM");
     451             : 
     452             :     /*
     453             :      * OK, build an RTE for the subquery.
     454             :      */
     455       20034 :     rte = addRangeTableEntryForSubquery(pstate,
     456             :                                         query,
     457             :                                         r->alias,
     458       20034 :                                         r->lateral,
     459             :                                         true);
     460             : 
     461       20034 :     return rte;
     462             : }
     463             : 
     464             : 
     465             : /*
     466             :  * transformRangeFunction --- transform a function call appearing in FROM
     467             :  */
     468             : static RangeTblEntry *
     469       38414 : transformRangeFunction(ParseState *pstate, RangeFunction *r)
     470             : {
     471       38414 :     List       *funcexprs = NIL;
     472       38414 :     List       *funcnames = NIL;
     473       38414 :     List       *coldeflists = NIL;
     474             :     bool        is_lateral;
     475             :     RangeTblEntry *rte;
     476             :     ListCell   *lc;
     477             : 
     478             :     /*
     479             :      * We make lateral_only names of this level visible, whether or not the
     480             :      * RangeFunction is explicitly marked LATERAL.  This is needed for SQL
     481             :      * spec compliance in the case of UNNEST(), and seems useful on
     482             :      * convenience grounds for all functions in FROM.
     483             :      *
     484             :      * (LATERAL can't nest within a single pstate level, so we don't need
     485             :      * save/restore logic here.)
     486             :      */
     487             :     Assert(!pstate->p_lateral_active);
     488       38414 :     pstate->p_lateral_active = true;
     489             : 
     490             :     /*
     491             :      * Transform the raw expressions.
     492             :      *
     493             :      * While transforming, also save function names for possible use as alias
     494             :      * and column names.  We use the same transformation rules as for a SELECT
     495             :      * output expression.  For a FuncCall node, the result will be the
     496             :      * function name, but it is possible for the grammar to hand back other
     497             :      * node types.
     498             :      *
     499             :      * We have to get this info now, because FigureColname only works on raw
     500             :      * parsetrees.  Actually deciding what to do with the names is left up to
     501             :      * addRangeTableEntryForFunction.
     502             :      *
     503             :      * Likewise, collect column definition lists if there were any.  But
     504             :      * complain if we find one here and the RangeFunction has one too.
     505             :      */
     506       76908 :     foreach(lc, r->functions)
     507             :     {
     508       38538 :         List       *pair = (List *) lfirst(lc);
     509             :         Node       *fexpr;
     510             :         List       *coldeflist;
     511             :         Node       *newfexpr;
     512             :         Node       *last_srf;
     513             : 
     514             :         /* Disassemble the function-call/column-def-list pairs */
     515             :         Assert(list_length(pair) == 2);
     516       38538 :         fexpr = (Node *) linitial(pair);
     517       38538 :         coldeflist = (List *) lsecond(pair);
     518             : 
     519             :         /*
     520             :          * If we find a function call unnest() with more than one argument and
     521             :          * no special decoration, transform it into separate unnest() calls on
     522             :          * each argument.  This is a kluge, for sure, but it's less nasty than
     523             :          * other ways of implementing the SQL-standard UNNEST() syntax.
     524             :          *
     525             :          * If there is any decoration (including a coldeflist), we don't
     526             :          * transform, which probably means a no-such-function error later.  We
     527             :          * could alternatively throw an error right now, but that doesn't seem
     528             :          * tremendously helpful.  If someone is using any such decoration,
     529             :          * then they're not using the SQL-standard syntax, and they're more
     530             :          * likely expecting an un-tweaked function call.
     531             :          *
     532             :          * Note: the transformation changes a non-schema-qualified unnest()
     533             :          * function name into schema-qualified pg_catalog.unnest().  This
     534             :          * choice is also a bit debatable, but it seems reasonable to force
     535             :          * use of built-in unnest() when we make this transformation.
     536             :          */
     537       38538 :         if (IsA(fexpr, FuncCall))
     538             :         {
     539       38518 :             FuncCall   *fc = (FuncCall *) fexpr;
     540             : 
     541       57214 :             if (list_length(fc->funcname) == 1 &&
     542       20020 :                 strcmp(strVal(linitial(fc->funcname)), "unnest") == 0 &&
     543        1360 :                 list_length(fc->args) > 1 &&
     544          72 :                 fc->agg_order == NIL &&
     545          72 :                 fc->agg_filter == NULL &&
     546          72 :                 !fc->agg_star &&
     547          72 :                 !fc->agg_distinct &&
     548          72 :                 !fc->func_variadic &&
     549          72 :                 fc->over == NULL &&
     550             :                 coldeflist == NIL)
     551             :             {
     552             :                 ListCell   *lc;
     553             : 
     554         128 :                 foreach(lc, fc->args)
     555             :                 {
     556          92 :                     Node       *arg = (Node *) lfirst(lc);
     557             :                     FuncCall   *newfc;
     558             : 
     559          92 :                     last_srf = pstate->p_last_srf;
     560             : 
     561         184 :                     newfc = makeFuncCall(SystemFuncName("unnest"),
     562          92 :                                          list_make1(arg),
     563             :                                          fc->location);
     564             : 
     565          92 :                     newfexpr = transformExpr(pstate, (Node *) newfc,
     566             :                                              EXPR_KIND_FROM_FUNCTION);
     567             : 
     568             :                     /* nodeFunctionscan.c requires SRFs to be at top level */
     569         184 :                     if (pstate->p_last_srf != last_srf &&
     570          92 :                         pstate->p_last_srf != newfexpr)
     571           0 :                         ereport(ERROR,
     572             :                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     573             :                                  errmsg("set-returning functions must appear at top level of FROM"),
     574             :                                  parser_errposition(pstate,
     575             :                                                     exprLocation(pstate->p_last_srf))));
     576             : 
     577          92 :                     funcexprs = lappend(funcexprs, newfexpr);
     578             : 
     579          92 :                     funcnames = lappend(funcnames,
     580          92 :                                         FigureColname((Node *) newfc));
     581             : 
     582             :                     /* coldeflist is empty, so no error is possible */
     583             : 
     584          92 :                     coldeflists = lappend(coldeflists, coldeflist);
     585             :                 }
     586          36 :                 continue;       /* done with this function item */
     587             :             }
     588             :         }
     589             : 
     590             :         /* normal case ... */
     591       38502 :         last_srf = pstate->p_last_srf;
     592             : 
     593       38502 :         newfexpr = transformExpr(pstate, fexpr,
     594             :                                  EXPR_KIND_FROM_FUNCTION);
     595             : 
     596             :         /* nodeFunctionscan.c requires SRFs to be at top level */
     597       73564 :         if (pstate->p_last_srf != last_srf &&
     598       35102 :             pstate->p_last_srf != newfexpr)
     599           4 :             ereport(ERROR,
     600             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     601             :                      errmsg("set-returning functions must appear at top level of FROM"),
     602             :                      parser_errposition(pstate,
     603             :                                         exprLocation(pstate->p_last_srf))));
     604             : 
     605       38458 :         funcexprs = lappend(funcexprs, newfexpr);
     606             : 
     607       38458 :         funcnames = lappend(funcnames,
     608       38458 :                             FigureColname(fexpr));
     609             : 
     610       38458 :         if (coldeflist && r->coldeflist)
     611           0 :             ereport(ERROR,
     612             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     613             :                      errmsg("multiple column definition lists are not allowed for the same function"),
     614             :                      parser_errposition(pstate,
     615             :                                         exprLocation((Node *) r->coldeflist))));
     616             : 
     617       38458 :         coldeflists = lappend(coldeflists, coldeflist);
     618             :     }
     619             : 
     620       38370 :     pstate->p_lateral_active = false;
     621             : 
     622             :     /*
     623             :      * We must assign collations now so that the RTE exposes correct collation
     624             :      * info for Vars created from it.
     625             :      */
     626       38370 :     assign_list_collations(pstate, funcexprs);
     627             : 
     628             :     /*
     629             :      * Install the top-level coldeflist if there was one (we already checked
     630             :      * that there was no conflicting per-function coldeflist).
     631             :      *
     632             :      * We only allow this when there's a single function (even after UNNEST
     633             :      * expansion) and no WITH ORDINALITY.  The reason for the latter
     634             :      * restriction is that it's not real clear whether the ordinality column
     635             :      * should be in the coldeflist, and users are too likely to make mistakes
     636             :      * in one direction or the other.  Putting the coldeflist inside ROWS
     637             :      * FROM() is much clearer in this case.
     638             :      */
     639       38370 :     if (r->coldeflist)
     640             :     {
     641         482 :         if (list_length(funcexprs) != 1)
     642             :         {
     643           0 :             if (r->is_rowsfrom)
     644           0 :                 ereport(ERROR,
     645             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     646             :                          errmsg("ROWS FROM() with multiple functions cannot have a column definition list"),
     647             :                          errhint("Put a separate column definition list for each function inside ROWS FROM()."),
     648             :                          parser_errposition(pstate,
     649             :                                             exprLocation((Node *) r->coldeflist))));
     650             :             else
     651           0 :                 ereport(ERROR,
     652             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     653             :                          errmsg("UNNEST() with multiple arguments cannot have a column definition list"),
     654             :                          errhint("Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one."),
     655             :                          parser_errposition(pstate,
     656             :                                             exprLocation((Node *) r->coldeflist))));
     657             :         }
     658         482 :         if (r->ordinality)
     659           0 :             ereport(ERROR,
     660             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     661             :                      errmsg("WITH ORDINALITY cannot be used with a column definition list"),
     662             :                      errhint("Put the column definition list inside ROWS FROM()."),
     663             :                      parser_errposition(pstate,
     664             :                                         exprLocation((Node *) r->coldeflist))));
     665             : 
     666         482 :         coldeflists = list_make1(r->coldeflist);
     667             :     }
     668             : 
     669             :     /*
     670             :      * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
     671             :      * there are any lateral cross-references in it.
     672             :      */
     673       38370 :     is_lateral = r->lateral || contain_vars_of_level((Node *) funcexprs, 0);
     674             : 
     675             :     /*
     676             :      * OK, build an RTE for the function.
     677             :      */
     678       38370 :     rte = addRangeTableEntryForFunction(pstate,
     679             :                                         funcnames, funcexprs, coldeflists,
     680             :                                         r, is_lateral, true);
     681             : 
     682       38346 :     return rte;
     683             : }
     684             : 
     685             : /*
     686             :  * transformRangeTableFunc -
     687             :  *          Transform a raw RangeTableFunc into TableFunc.
     688             :  *
     689             :  * Transform the namespace clauses, the document-generating expression, the
     690             :  * row-generating expression, the column-generating expressions, and the
     691             :  * default value expressions.
     692             :  */
     693             : static RangeTblEntry *
     694         140 : transformRangeTableFunc(ParseState *pstate, RangeTableFunc *rtf)
     695             : {
     696         140 :     TableFunc  *tf = makeNode(TableFunc);
     697             :     const char *constructName;
     698             :     Oid         docType;
     699             :     RangeTblEntry *rte;
     700             :     bool        is_lateral;
     701             :     ListCell   *col;
     702             :     char      **names;
     703             :     int         colno;
     704             : 
     705             :     /* Currently only XMLTABLE is supported */
     706         140 :     constructName = "XMLTABLE";
     707         140 :     docType = XMLOID;
     708             : 
     709             :     /*
     710             :      * We make lateral_only names of this level visible, whether or not the
     711             :      * RangeTableFunc is explicitly marked LATERAL.  This is needed for SQL
     712             :      * spec compliance and seems useful on convenience grounds for all
     713             :      * functions in FROM.
     714             :      *
     715             :      * (LATERAL can't nest within a single pstate level, so we don't need
     716             :      * save/restore logic here.)
     717             :      */
     718             :     Assert(!pstate->p_lateral_active);
     719         140 :     pstate->p_lateral_active = true;
     720             : 
     721             :     /* Transform and apply typecast to the row-generating expression ... */
     722             :     Assert(rtf->rowexpr != NULL);
     723         140 :     tf->rowexpr = coerce_to_specific_type(pstate,
     724             :                                           transformExpr(pstate, rtf->rowexpr, EXPR_KIND_FROM_FUNCTION),
     725             :                                           TEXTOID,
     726             :                                           constructName);
     727         140 :     assign_expr_collations(pstate, tf->rowexpr);
     728             : 
     729             :     /* ... and to the document itself */
     730             :     Assert(rtf->docexpr != NULL);
     731         140 :     tf->docexpr = coerce_to_specific_type(pstate,
     732             :                                           transformExpr(pstate, rtf->docexpr, EXPR_KIND_FROM_FUNCTION),
     733             :                                           docType,
     734             :                                           constructName);
     735         140 :     assign_expr_collations(pstate, tf->docexpr);
     736             : 
     737             :     /* undef ordinality column number */
     738         140 :     tf->ordinalitycol = -1;
     739             : 
     740             :     /* Process column specs */
     741         140 :     names = palloc(sizeof(char *) * list_length(rtf->columns));
     742             : 
     743         140 :     colno = 0;
     744         634 :     foreach(col, rtf->columns)
     745             :     {
     746         494 :         RangeTableFuncCol *rawc = (RangeTableFuncCol *) lfirst(col);
     747             :         Oid         typid;
     748             :         int32       typmod;
     749             :         Node       *colexpr;
     750             :         Node       *coldefexpr;
     751             :         int         j;
     752             : 
     753         494 :         tf->colnames = lappend(tf->colnames,
     754         494 :                                makeString(pstrdup(rawc->colname)));
     755             : 
     756             :         /*
     757             :          * Determine the type and typmod for the new column. FOR ORDINALITY
     758             :          * columns are INTEGER per spec; the others are user-specified.
     759             :          */
     760         494 :         if (rawc->for_ordinality)
     761             :         {
     762          42 :             if (tf->ordinalitycol != -1)
     763           0 :                 ereport(ERROR,
     764             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     765             :                          errmsg("only one FOR ORDINALITY column is allowed"),
     766             :                          parser_errposition(pstate, rawc->location)));
     767             : 
     768          42 :             typid = INT4OID;
     769          42 :             typmod = -1;
     770          42 :             tf->ordinalitycol = colno;
     771             :         }
     772             :         else
     773             :         {
     774         452 :             if (rawc->typeName->setof)
     775           0 :                 ereport(ERROR,
     776             :                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
     777             :                          errmsg("column \"%s\" cannot be declared SETOF",
     778             :                                 rawc->colname),
     779             :                          parser_errposition(pstate, rawc->location)));
     780             : 
     781         452 :             typenameTypeIdAndMod(pstate, rawc->typeName,
     782             :                                  &typid, &typmod);
     783             :         }
     784             : 
     785         494 :         tf->coltypes = lappend_oid(tf->coltypes, typid);
     786         494 :         tf->coltypmods = lappend_int(tf->coltypmods, typmod);
     787         494 :         tf->colcollations = lappend_oid(tf->colcollations,
     788             :                                         get_typcollation(typid));
     789             : 
     790             :         /* Transform the PATH and DEFAULT expressions */
     791         494 :         if (rawc->colexpr)
     792             :         {
     793         332 :             colexpr = coerce_to_specific_type(pstate,
     794             :                                               transformExpr(pstate, rawc->colexpr,
     795             :                                                             EXPR_KIND_FROM_FUNCTION),
     796             :                                               TEXTOID,
     797             :                                               constructName);
     798         332 :             assign_expr_collations(pstate, colexpr);
     799             :         }
     800             :         else
     801         162 :             colexpr = NULL;
     802             : 
     803         494 :         if (rawc->coldefexpr)
     804             :         {
     805          38 :             coldefexpr = coerce_to_specific_type_typmod(pstate,
     806             :                                                         transformExpr(pstate, rawc->coldefexpr,
     807             :                                                                       EXPR_KIND_FROM_FUNCTION),
     808             :                                                         typid, typmod,
     809             :                                                         constructName);
     810          38 :             assign_expr_collations(pstate, coldefexpr);
     811             :         }
     812             :         else
     813         456 :             coldefexpr = NULL;
     814             : 
     815         494 :         tf->colexprs = lappend(tf->colexprs, colexpr);
     816         494 :         tf->coldefexprs = lappend(tf->coldefexprs, coldefexpr);
     817             : 
     818         494 :         if (rawc->is_not_null)
     819          38 :             tf->notnulls = bms_add_member(tf->notnulls, colno);
     820             : 
     821             :         /* make sure column names are unique */
     822        1698 :         for (j = 0; j < colno; j++)
     823        1204 :             if (strcmp(names[j], rawc->colname) == 0)
     824           0 :                 ereport(ERROR,
     825             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     826             :                          errmsg("column name \"%s\" is not unique",
     827             :                                 rawc->colname),
     828             :                          parser_errposition(pstate, rawc->location)));
     829         494 :         names[colno] = rawc->colname;
     830             : 
     831         494 :         colno++;
     832             :     }
     833         140 :     pfree(names);
     834             : 
     835             :     /* Namespaces, if any, also need to be transformed */
     836         140 :     if (rtf->namespaces != NIL)
     837             :     {
     838             :         ListCell   *ns;
     839             :         ListCell   *lc2;
     840          14 :         List       *ns_uris = NIL;
     841          14 :         List       *ns_names = NIL;
     842          14 :         bool        default_ns_seen = false;
     843             : 
     844          28 :         foreach(ns, rtf->namespaces)
     845             :         {
     846          14 :             ResTarget  *r = (ResTarget *) lfirst(ns);
     847             :             Node       *ns_uri;
     848             : 
     849             :             Assert(IsA(r, ResTarget));
     850          14 :             ns_uri = transformExpr(pstate, r->val, EXPR_KIND_FROM_FUNCTION);
     851          14 :             ns_uri = coerce_to_specific_type(pstate, ns_uri,
     852             :                                              TEXTOID, constructName);
     853          14 :             assign_expr_collations(pstate, ns_uri);
     854          14 :             ns_uris = lappend(ns_uris, ns_uri);
     855             : 
     856             :             /* Verify consistency of name list: no dupes, only one DEFAULT */
     857          14 :             if (r->name != NULL)
     858             :             {
     859          10 :                 foreach(lc2, ns_names)
     860             :                 {
     861           0 :                     Value      *ns_node = (Value *) lfirst(lc2);
     862             : 
     863           0 :                     if (ns_node == NULL)
     864           0 :                         continue;
     865           0 :                     if (strcmp(strVal(ns_node), r->name) == 0)
     866           0 :                         ereport(ERROR,
     867             :                                 (errcode(ERRCODE_SYNTAX_ERROR),
     868             :                                  errmsg("namespace name \"%s\" is not unique",
     869             :                                         r->name),
     870             :                                  parser_errposition(pstate, r->location)));
     871             :                 }
     872             :             }
     873             :             else
     874             :             {
     875           4 :                 if (default_ns_seen)
     876           0 :                     ereport(ERROR,
     877             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     878             :                              errmsg("only one default namespace is allowed"),
     879             :                              parser_errposition(pstate, r->location)));
     880           4 :                 default_ns_seen = true;
     881             :             }
     882             : 
     883             :             /* We represent DEFAULT by a null pointer */
     884          24 :             ns_names = lappend(ns_names,
     885          24 :                                r->name ? makeString(r->name) : NULL);
     886             :         }
     887             : 
     888          14 :         tf->ns_uris = ns_uris;
     889          14 :         tf->ns_names = ns_names;
     890             :     }
     891             : 
     892         140 :     tf->location = rtf->location;
     893             : 
     894         140 :     pstate->p_lateral_active = false;
     895             : 
     896             :     /*
     897             :      * Mark the RTE as LATERAL if the user said LATERAL explicitly, or if
     898             :      * there are any lateral cross-references in it.
     899             :      */
     900         140 :     is_lateral = rtf->lateral || contain_vars_of_level((Node *) tf, 0);
     901             : 
     902         140 :     rte = addRangeTableEntryForTableFunc(pstate,
     903             :                                          tf, rtf->alias, is_lateral, true);
     904             : 
     905         140 :     return rte;
     906             : }
     907             : 
     908             : /*
     909             :  * transformRangeTableSample --- transform a TABLESAMPLE clause
     910             :  *
     911             :  * Caller has already transformed rts->relation, we just have to validate
     912             :  * the remaining fields and create a TableSampleClause node.
     913             :  */
     914             : static TableSampleClause *
     915         168 : transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
     916             : {
     917             :     TableSampleClause *tablesample;
     918             :     Oid         handlerOid;
     919             :     Oid         funcargtypes[1];
     920             :     TsmRoutine *tsm;
     921             :     List       *fargs;
     922             :     ListCell   *larg,
     923             :                *ltyp;
     924             : 
     925             :     /*
     926             :      * To validate the sample method name, look up the handler function, which
     927             :      * has the same name, one dummy INTERNAL argument, and a result type of
     928             :      * tsm_handler.  (Note: tablesample method names are not schema-qualified
     929             :      * in the SQL standard; but since they are just functions to us, we allow
     930             :      * schema qualification to resolve any potential ambiguity.)
     931             :      */
     932         168 :     funcargtypes[0] = INTERNALOID;
     933             : 
     934         168 :     handlerOid = LookupFuncName(rts->method, 1, funcargtypes, true);
     935             : 
     936             :     /* we want error to complain about no-such-method, not no-such-function */
     937         168 :     if (!OidIsValid(handlerOid))
     938           4 :         ereport(ERROR,
     939             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     940             :                  errmsg("tablesample method %s does not exist",
     941             :                         NameListToString(rts->method)),
     942             :                  parser_errposition(pstate, rts->location)));
     943             : 
     944             :     /* check that handler has correct return type */
     945         164 :     if (get_func_rettype(handlerOid) != TSM_HANDLEROID)
     946           0 :         ereport(ERROR,
     947             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     948             :                  errmsg("function %s must return type %s",
     949             :                         NameListToString(rts->method), "tsm_handler"),
     950             :                  parser_errposition(pstate, rts->location)));
     951             : 
     952             :     /* OK, run the handler to get TsmRoutine, for argument type info */
     953         164 :     tsm = GetTsmRoutine(handlerOid);
     954             : 
     955         164 :     tablesample = makeNode(TableSampleClause);
     956         164 :     tablesample->tsmhandler = handlerOid;
     957             : 
     958             :     /* check user provided the expected number of arguments */
     959         164 :     if (list_length(rts->args) != list_length(tsm->parameterTypes))
     960           0 :         ereport(ERROR,
     961             :                 (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
     962             :                  errmsg_plural("tablesample method %s requires %d argument, not %d",
     963             :                                "tablesample method %s requires %d arguments, not %d",
     964             :                                list_length(tsm->parameterTypes),
     965             :                                NameListToString(rts->method),
     966             :                                list_length(tsm->parameterTypes),
     967             :                                list_length(rts->args)),
     968             :                  parser_errposition(pstate, rts->location)));
     969             : 
     970             :     /*
     971             :      * Transform the arguments, typecasting them as needed.  Note we must also
     972             :      * assign collations now, because assign_query_collations() doesn't
     973             :      * examine any substructure of RTEs.
     974             :      */
     975         164 :     fargs = NIL;
     976         328 :     forboth(larg, rts->args, ltyp, tsm->parameterTypes)
     977             :     {
     978         164 :         Node       *arg = (Node *) lfirst(larg);
     979         164 :         Oid         argtype = lfirst_oid(ltyp);
     980             : 
     981         164 :         arg = transformExpr(pstate, arg, EXPR_KIND_FROM_FUNCTION);
     982         164 :         arg = coerce_to_specific_type(pstate, arg, argtype, "TABLESAMPLE");
     983         164 :         assign_expr_collations(pstate, arg);
     984         164 :         fargs = lappend(fargs, arg);
     985             :     }
     986         164 :     tablesample->args = fargs;
     987             : 
     988             :     /* Process REPEATABLE (seed) */
     989         164 :     if (rts->repeatable != NULL)
     990             :     {
     991             :         Node       *arg;
     992             : 
     993          62 :         if (!tsm->repeatable_across_queries)
     994           4 :             ereport(ERROR,
     995             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     996             :                      errmsg("tablesample method %s does not support REPEATABLE",
     997             :                             NameListToString(rts->method)),
     998             :                      parser_errposition(pstate, rts->location)));
     999             : 
    1000          58 :         arg = transformExpr(pstate, rts->repeatable, EXPR_KIND_FROM_FUNCTION);
    1001          58 :         arg = coerce_to_specific_type(pstate, arg, FLOAT8OID, "REPEATABLE");
    1002          58 :         assign_expr_collations(pstate, arg);
    1003          58 :         tablesample->repeatable = (Expr *) arg;
    1004             :     }
    1005             :     else
    1006         102 :         tablesample->repeatable = NULL;
    1007             : 
    1008         160 :     return tablesample;
    1009             : }
    1010             : 
    1011             : /*
    1012             :  * getRTEForSpecialRelationTypes
    1013             :  *
    1014             :  * If given RangeVar refers to a CTE or an EphemeralNamedRelation,
    1015             :  * build and return an appropriate RTE, otherwise return NULL
    1016             :  */
    1017             : static RangeTblEntry *
    1018      327730 : getRTEForSpecialRelationTypes(ParseState *pstate, RangeVar *rv)
    1019             : {
    1020             :     CommonTableExpr *cte;
    1021             :     Index       levelsup;
    1022             :     RangeTblEntry *rte;
    1023             : 
    1024             :     /*
    1025             :      * if it is a qualified name, it can't be a CTE or tuplestore reference
    1026             :      */
    1027      327730 :     if (rv->schemaname)
    1028      106166 :         return NULL;
    1029             : 
    1030      221564 :     cte = scanNameSpaceForCTE(pstate, rv->relname, &levelsup);
    1031      221564 :     if (cte)
    1032        1874 :         rte = addRangeTableEntryForCTE(pstate, cte, levelsup, rv, true);
    1033      219690 :     else if (scanNameSpaceForENR(pstate, rv->relname))
    1034         260 :         rte = addRangeTableEntryForENR(pstate, rv, true);
    1035             :     else
    1036      219430 :         rte = NULL;
    1037             : 
    1038      221560 :     return rte;
    1039             : }
    1040             : 
    1041             : /*
    1042             :  * transformFromClauseItem -
    1043             :  *    Transform a FROM-clause item, adding any required entries to the
    1044             :  *    range table list being built in the ParseState, and return the
    1045             :  *    transformed item ready to include in the joinlist.  Also build a
    1046             :  *    ParseNamespaceItem list describing the names exposed by this item.
    1047             :  *    This routine can recurse to handle SQL92 JOIN expressions.
    1048             :  *
    1049             :  * The function return value is the node to add to the jointree (a
    1050             :  * RangeTblRef or JoinExpr).  Additional output parameters are:
    1051             :  *
    1052             :  * *top_rte: receives the RTE corresponding to the jointree item.
    1053             :  * (We could extract this from the function return node, but it saves cycles
    1054             :  * to pass it back separately.)
    1055             :  *
    1056             :  * *top_rti: receives the rangetable index of top_rte.  (Ditto.)
    1057             :  *
    1058             :  * *namespace: receives a List of ParseNamespaceItems for the RTEs exposed
    1059             :  * as table/column names by this item.  (The lateral_only flags in these items
    1060             :  * are indeterminate and should be explicitly set by the caller before use.)
    1061             :  */
    1062             : static Node *
    1063      465740 : transformFromClauseItem(ParseState *pstate, Node *n,
    1064             :                         RangeTblEntry **top_rte, int *top_rti,
    1065             :                         List **namespace)
    1066             : {
    1067      465740 :     if (IsA(n, RangeVar))
    1068             :     {
    1069             :         /* Plain relation reference, or perhaps a CTE reference */
    1070      327730 :         RangeVar   *rv = (RangeVar *) n;
    1071             :         RangeTblRef *rtr;
    1072             :         RangeTblEntry *rte;
    1073             :         int         rtindex;
    1074             : 
    1075             :         /* Check if it's a CTE or tuplestore reference */
    1076      327730 :         rte = getRTEForSpecialRelationTypes(pstate, rv);
    1077             : 
    1078             :         /* if not found above, must be a table reference */
    1079      327726 :         if (!rte)
    1080      325596 :             rte = transformTableEntry(pstate, rv);
    1081             : 
    1082             :         /* assume new rte is at end */
    1083      327636 :         rtindex = list_length(pstate->p_rtable);
    1084             :         Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
    1085      327636 :         *top_rte = rte;
    1086      327636 :         *top_rti = rtindex;
    1087      327636 :         *namespace = list_make1(makeDefaultNSItem(rte));
    1088      327636 :         rtr = makeNode(RangeTblRef);
    1089      327636 :         rtr->rtindex = rtindex;
    1090      327636 :         return (Node *) rtr;
    1091             :     }
    1092      138010 :     else if (IsA(n, RangeSubselect))
    1093             :     {
    1094             :         /* sub-SELECT is like a plain relation */
    1095             :         RangeTblRef *rtr;
    1096             :         RangeTblEntry *rte;
    1097             :         int         rtindex;
    1098             : 
    1099       20102 :         rte = transformRangeSubselect(pstate, (RangeSubselect *) n);
    1100             :         /* assume new rte is at end */
    1101       20034 :         rtindex = list_length(pstate->p_rtable);
    1102             :         Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
    1103       20034 :         *top_rte = rte;
    1104       20034 :         *top_rti = rtindex;
    1105       20034 :         *namespace = list_make1(makeDefaultNSItem(rte));
    1106       20034 :         rtr = makeNode(RangeTblRef);
    1107       20034 :         rtr->rtindex = rtindex;
    1108       20034 :         return (Node *) rtr;
    1109             :     }
    1110      117908 :     else if (IsA(n, RangeFunction))
    1111             :     {
    1112             :         /* function is like a plain relation */
    1113             :         RangeTblRef *rtr;
    1114             :         RangeTblEntry *rte;
    1115             :         int         rtindex;
    1116             : 
    1117       38414 :         rte = transformRangeFunction(pstate, (RangeFunction *) n);
    1118             :         /* assume new rte is at end */
    1119       38346 :         rtindex = list_length(pstate->p_rtable);
    1120             :         Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
    1121       38346 :         *top_rte = rte;
    1122       38346 :         *top_rti = rtindex;
    1123       38346 :         *namespace = list_make1(makeDefaultNSItem(rte));
    1124       38346 :         rtr = makeNode(RangeTblRef);
    1125       38346 :         rtr->rtindex = rtindex;
    1126       38346 :         return (Node *) rtr;
    1127             :     }
    1128       79494 :     else if (IsA(n, RangeTableFunc))
    1129             :     {
    1130             :         /* table function is like a plain relation */
    1131             :         RangeTblRef *rtr;
    1132             :         RangeTblEntry *rte;
    1133             :         int         rtindex;
    1134             : 
    1135         140 :         rte = transformRangeTableFunc(pstate, (RangeTableFunc *) n);
    1136             :         /* assume new rte is at end */
    1137         140 :         rtindex = list_length(pstate->p_rtable);
    1138             :         Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
    1139         140 :         *top_rte = rte;
    1140         140 :         *top_rti = rtindex;
    1141         140 :         *namespace = list_make1(makeDefaultNSItem(rte));
    1142         140 :         rtr = makeNode(RangeTblRef);
    1143         140 :         rtr->rtindex = rtindex;
    1144         140 :         return (Node *) rtr;
    1145             :     }
    1146       79354 :     else if (IsA(n, RangeTableSample))
    1147             :     {
    1148             :         /* TABLESAMPLE clause (wrapping some other valid FROM node) */
    1149         176 :         RangeTableSample *rts = (RangeTableSample *) n;
    1150             :         Node       *rel;
    1151             :         RangeTblRef *rtr;
    1152             :         RangeTblEntry *rte;
    1153             : 
    1154             :         /* Recursively transform the contained relation */
    1155         176 :         rel = transformFromClauseItem(pstate, rts->relation,
    1156             :                                       top_rte, top_rti, namespace);
    1157             :         /* Currently, grammar could only return a RangeVar as contained rel */
    1158         176 :         rtr = castNode(RangeTblRef, rel);
    1159         176 :         rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
    1160             :         /* We only support this on plain relations and matviews */
    1161         188 :         if (rte->relkind != RELKIND_RELATION &&
    1162          24 :             rte->relkind != RELKIND_MATVIEW &&
    1163          12 :             rte->relkind != RELKIND_PARTITIONED_TABLE)
    1164           8 :             ereport(ERROR,
    1165             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1166             :                      errmsg("TABLESAMPLE clause can only be applied to tables and materialized views"),
    1167             :                      parser_errposition(pstate, exprLocation(rts->relation))));
    1168             : 
    1169             :         /* Transform TABLESAMPLE details and attach to the RTE */
    1170         168 :         rte->tablesample = transformRangeTableSample(pstate, rts);
    1171         160 :         return (Node *) rtr;
    1172             :     }
    1173       79178 :     else if (IsA(n, JoinExpr))
    1174             :     {
    1175             :         /* A newfangled join expression */
    1176       79178 :         JoinExpr   *j = (JoinExpr *) n;
    1177             :         RangeTblEntry *l_rte;
    1178             :         RangeTblEntry *r_rte;
    1179             :         int         l_rtindex;
    1180             :         int         r_rtindex;
    1181             :         List       *l_namespace,
    1182             :                    *r_namespace,
    1183             :                    *my_namespace,
    1184             :                    *l_colnames,
    1185             :                    *r_colnames,
    1186             :                    *res_colnames,
    1187             :                    *l_colvars,
    1188             :                    *r_colvars,
    1189             :                    *res_colvars;
    1190             :         bool        lateral_ok;
    1191             :         int         sv_namespace_length;
    1192             :         RangeTblEntry *rte;
    1193             :         int         k;
    1194             : 
    1195             :         /*
    1196             :          * Recursively process the left subtree, then the right.  We must do
    1197             :          * it in this order for correct visibility of LATERAL references.
    1198             :          */
    1199       79178 :         j->larg = transformFromClauseItem(pstate, j->larg,
    1200             :                                           &l_rte,
    1201             :                                           &l_rtindex,
    1202             :                                           &l_namespace);
    1203             : 
    1204             :         /*
    1205             :          * Make the left-side RTEs available for LATERAL access within the
    1206             :          * right side, by temporarily adding them to the pstate's namespace
    1207             :          * list.  Per SQL:2008, if the join type is not INNER or LEFT then the
    1208             :          * left-side names must still be exposed, but it's an error to
    1209             :          * reference them.  (Stupid design, but that's what it says.)  Hence,
    1210             :          * we always push them into the namespace, but mark them as not
    1211             :          * lateral_ok if the jointype is wrong.
    1212             :          *
    1213             :          * Notice that we don't require the merged namespace list to be
    1214             :          * conflict-free.  See the comments for scanNameSpaceForRefname().
    1215             :          */
    1216       79178 :         lateral_ok = (j->jointype == JOIN_INNER || j->jointype == JOIN_LEFT);
    1217       79178 :         setNamespaceLateralState(l_namespace, true, lateral_ok);
    1218             : 
    1219       79178 :         sv_namespace_length = list_length(pstate->p_namespace);
    1220       79178 :         pstate->p_namespace = list_concat(pstate->p_namespace, l_namespace);
    1221             : 
    1222             :         /* And now we can process the RHS */
    1223       79178 :         j->rarg = transformFromClauseItem(pstate, j->rarg,
    1224             :                                           &r_rte,
    1225             :                                           &r_rtindex,
    1226             :                                           &r_namespace);
    1227             : 
    1228             :         /* Remove the left-side RTEs from the namespace list again */
    1229       79154 :         pstate->p_namespace = list_truncate(pstate->p_namespace,
    1230             :                                             sv_namespace_length);
    1231             : 
    1232             :         /*
    1233             :          * Check for conflicting refnames in left and right subtrees. Must do
    1234             :          * this because higher levels will assume I hand back a self-
    1235             :          * consistent namespace list.
    1236             :          */
    1237       79154 :         checkNameSpaceConflicts(pstate, l_namespace, r_namespace);
    1238             : 
    1239             :         /*
    1240             :          * Generate combined namespace info for possible use below.
    1241             :          */
    1242       79154 :         my_namespace = list_concat(l_namespace, r_namespace);
    1243             : 
    1244             :         /*
    1245             :          * Extract column name and var lists from both subtrees
    1246             :          *
    1247             :          * Note: expandRTE returns new lists, safe for me to modify
    1248             :          */
    1249       79154 :         expandRTE(l_rte, l_rtindex, 0, -1, false,
    1250             :                   &l_colnames, &l_colvars);
    1251       79154 :         expandRTE(r_rte, r_rtindex, 0, -1, false,
    1252             :                   &r_colnames, &r_colvars);
    1253             : 
    1254             :         /*
    1255             :          * Natural join does not explicitly specify columns; must generate
    1256             :          * columns to join. Need to run through the list of columns from each
    1257             :          * table or join result and match up the column names. Use the first
    1258             :          * table, and check every column in the second table for a match.
    1259             :          * (We'll check that the matches were unique later on.) The result of
    1260             :          * this step is a list of column names just like an explicitly-written
    1261             :          * USING list.
    1262             :          */
    1263       79154 :         if (j->isNatural)
    1264             :         {
    1265         160 :             List       *rlist = NIL;
    1266             :             ListCell   *lx,
    1267             :                        *rx;
    1268             : 
    1269             :             Assert(j->usingClause == NIL);   /* shouldn't have USING() too */
    1270             : 
    1271         728 :             foreach(lx, l_colnames)
    1272             :             {
    1273         568 :                 char       *l_colname = strVal(lfirst(lx));
    1274         568 :                 Value      *m_name = NULL;
    1275             : 
    1276        1588 :                 foreach(rx, r_colnames)
    1277             :                 {
    1278        1212 :                     char       *r_colname = strVal(lfirst(rx));
    1279             : 
    1280        1212 :                     if (strcmp(l_colname, r_colname) == 0)
    1281             :                     {
    1282         192 :                         m_name = makeString(l_colname);
    1283         192 :                         break;
    1284             :                     }
    1285             :                 }
    1286             : 
    1287             :                 /* matched a right column? then keep as join column... */
    1288         568 :                 if (m_name != NULL)
    1289         192 :                     rlist = lappend(rlist, m_name);
    1290             :             }
    1291             : 
    1292         160 :             j->usingClause = rlist;
    1293             :         }
    1294             : 
    1295             :         /*
    1296             :          * Now transform the join qualifications, if any.
    1297             :          */
    1298       79154 :         res_colnames = NIL;
    1299       79154 :         res_colvars = NIL;
    1300             : 
    1301       79154 :         if (j->usingClause)
    1302             :         {
    1303             :             /*
    1304             :              * JOIN/USING (or NATURAL JOIN, as transformed above). Transform
    1305             :              * the list into an explicit ON-condition, and generate a list of
    1306             :              * merged result columns.
    1307             :              */
    1308         688 :             List       *ucols = j->usingClause;
    1309         688 :             List       *l_usingvars = NIL;
    1310         688 :             List       *r_usingvars = NIL;
    1311             :             ListCell   *ucol;
    1312             : 
    1313             :             Assert(j->quals == NULL);    /* shouldn't have ON() too */
    1314             : 
    1315        1472 :             foreach(ucol, ucols)
    1316             :             {
    1317         784 :                 char       *u_colname = strVal(lfirst(ucol));
    1318             :                 ListCell   *col;
    1319             :                 int         ndx;
    1320         784 :                 int         l_index = -1;
    1321         784 :                 int         r_index = -1;
    1322             :                 Var        *l_colvar,
    1323             :                            *r_colvar;
    1324             : 
    1325             :                 /* Check for USING(foo,foo) */
    1326         900 :                 foreach(col, res_colnames)
    1327             :                 {
    1328         116 :                     char       *res_colname = strVal(lfirst(col));
    1329             : 
    1330         116 :                     if (strcmp(res_colname, u_colname) == 0)
    1331           0 :                         ereport(ERROR,
    1332             :                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
    1333             :                                  errmsg("column name \"%s\" appears more than once in USING clause",
    1334             :                                         u_colname)));
    1335             :                 }
    1336             : 
    1337             :                 /* Find it in left input */
    1338         784 :                 ndx = 0;
    1339        3968 :                 foreach(col, l_colnames)
    1340             :                 {
    1341        3184 :                     char       *l_colname = strVal(lfirst(col));
    1342             : 
    1343        3184 :                     if (strcmp(l_colname, u_colname) == 0)
    1344             :                     {
    1345         784 :                         if (l_index >= 0)
    1346           0 :                             ereport(ERROR,
    1347             :                                     (errcode(ERRCODE_AMBIGUOUS_COLUMN),
    1348             :                                      errmsg("common column name \"%s\" appears more than once in left table",
    1349             :                                             u_colname)));
    1350         784 :                         l_index = ndx;
    1351             :                     }
    1352        3184 :                     ndx++;
    1353             :                 }
    1354         784 :                 if (l_index < 0)
    1355           0 :                     ereport(ERROR,
    1356             :                             (errcode(ERRCODE_UNDEFINED_COLUMN),
    1357             :                              errmsg("column \"%s\" specified in USING clause does not exist in left table",
    1358             :                                     u_colname)));
    1359             : 
    1360             :                 /* Find it in right input */
    1361         784 :                 ndx = 0;
    1362        4384 :                 foreach(col, r_colnames)
    1363             :                 {
    1364        3600 :                     char       *r_colname = strVal(lfirst(col));
    1365             : 
    1366        3600 :                     if (strcmp(r_colname, u_colname) == 0)
    1367             :                     {
    1368         784 :                         if (r_index >= 0)
    1369           0 :                             ereport(ERROR,
    1370             :                                     (errcode(ERRCODE_AMBIGUOUS_COLUMN),
    1371             :                                      errmsg("common column name \"%s\" appears more than once in right table",
    1372             :                                             u_colname)));
    1373         784 :                         r_index = ndx;
    1374             :                     }
    1375        3600 :                     ndx++;
    1376             :                 }
    1377         784 :                 if (r_index < 0)
    1378           0 :                     ereport(ERROR,
    1379             :                             (errcode(ERRCODE_UNDEFINED_COLUMN),
    1380             :                              errmsg("column \"%s\" specified in USING clause does not exist in right table",
    1381             :                                     u_colname)));
    1382             : 
    1383         784 :                 l_colvar = list_nth(l_colvars, l_index);
    1384         784 :                 l_usingvars = lappend(l_usingvars, l_colvar);
    1385         784 :                 r_colvar = list_nth(r_colvars, r_index);
    1386         784 :                 r_usingvars = lappend(r_usingvars, r_colvar);
    1387             : 
    1388         784 :                 res_colnames = lappend(res_colnames, lfirst(ucol));
    1389         784 :                 res_colvars = lappend(res_colvars,
    1390         784 :                                       buildMergedJoinVar(pstate,
    1391             :                                                          j->jointype,
    1392             :                                                          l_colvar,
    1393             :                                                          r_colvar));
    1394             :             }
    1395             : 
    1396         688 :             j->quals = transformJoinUsingClause(pstate,
    1397             :                                                 l_rte,
    1398             :                                                 r_rte,
    1399             :                                                 l_usingvars,
    1400             :                                                 r_usingvars);
    1401             :         }
    1402       78466 :         else if (j->quals)
    1403             :         {
    1404             :             /* User-written ON-condition; transform it */
    1405       78326 :             j->quals = transformJoinOnClause(pstate, j, my_namespace);
    1406             :         }
    1407             :         else
    1408             :         {
    1409             :             /* CROSS JOIN: no quals */
    1410             :         }
    1411             : 
    1412             :         /* Add remaining columns from each side to the output columns */
    1413       79142 :         extractRemainingColumns(res_colnames,
    1414             :                                 l_colnames, l_colvars,
    1415             :                                 &l_colnames, &l_colvars);
    1416       79142 :         extractRemainingColumns(res_colnames,
    1417             :                                 r_colnames, r_colvars,
    1418             :                                 &r_colnames, &r_colvars);
    1419       79142 :         res_colnames = list_concat(res_colnames, l_colnames);
    1420       79142 :         res_colvars = list_concat(res_colvars, l_colvars);
    1421       79142 :         res_colnames = list_concat(res_colnames, r_colnames);
    1422       79142 :         res_colvars = list_concat(res_colvars, r_colvars);
    1423             : 
    1424             :         /*
    1425             :          * Check alias (AS clause), if any.
    1426             :          */
    1427       79142 :         if (j->alias)
    1428             :         {
    1429          48 :             if (j->alias->colnames != NIL)
    1430             :             {
    1431          12 :                 if (list_length(j->alias->colnames) > list_length(res_colnames))
    1432           0 :                     ereport(ERROR,
    1433             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    1434             :                              errmsg("column alias list for \"%s\" has too many entries",
    1435             :                                     j->alias->aliasname)));
    1436             :             }
    1437             :         }
    1438             : 
    1439             :         /*
    1440             :          * Now build an RTE for the result of the join
    1441             :          */
    1442       79142 :         rte = addRangeTableEntryForJoin(pstate,
    1443             :                                         res_colnames,
    1444             :                                         j->jointype,
    1445             :                                         res_colvars,
    1446             :                                         j->alias,
    1447             :                                         true);
    1448             : 
    1449             :         /* assume new rte is at end */
    1450       79142 :         j->rtindex = list_length(pstate->p_rtable);
    1451             :         Assert(rte == rt_fetch(j->rtindex, pstate->p_rtable));
    1452             : 
    1453       79142 :         *top_rte = rte;
    1454       79142 :         *top_rti = j->rtindex;
    1455             : 
    1456             :         /* make a matching link to the JoinExpr for later use */
    1457      206440 :         for (k = list_length(pstate->p_joinexprs) + 1; k < j->rtindex; k++)
    1458      127298 :             pstate->p_joinexprs = lappend(pstate->p_joinexprs, NULL);
    1459       79142 :         pstate->p_joinexprs = lappend(pstate->p_joinexprs, j);
    1460             :         Assert(list_length(pstate->p_joinexprs) == j->rtindex);
    1461             : 
    1462             :         /*
    1463             :          * Prepare returned namespace list.  If the JOIN has an alias then it
    1464             :          * hides the contained RTEs completely; otherwise, the contained RTEs
    1465             :          * are still visible as table names, but are not visible for
    1466             :          * unqualified column-name access.
    1467             :          *
    1468             :          * Note: if there are nested alias-less JOINs, the lower-level ones
    1469             :          * will remain in the list although they have neither p_rel_visible
    1470             :          * nor p_cols_visible set.  We could delete such list items, but it's
    1471             :          * unclear that it's worth expending cycles to do so.
    1472             :          */
    1473       79142 :         if (j->alias != NULL)
    1474          48 :             my_namespace = NIL;
    1475             :         else
    1476       79094 :             setNamespaceColumnVisibility(my_namespace, false);
    1477             : 
    1478             :         /*
    1479             :          * The join RTE itself is always made visible for unqualified column
    1480             :          * names.  It's visible as a relation name only if it has an alias.
    1481             :          */
    1482       79142 :         *namespace = lappend(my_namespace,
    1483       79142 :                              makeNamespaceItem(rte,
    1484       79142 :                                                (j->alias != NULL),
    1485             :                                                true,
    1486             :                                                false,
    1487             :                                                true));
    1488             : 
    1489       79142 :         return (Node *) j;
    1490             :     }
    1491             :     else
    1492           0 :         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(n));
    1493             :     return NULL;                /* can't get here, keep compiler quiet */
    1494             : }
    1495             : 
    1496             : /*
    1497             :  * buildMergedJoinVar -
    1498             :  *    generate a suitable replacement expression for a merged join column
    1499             :  */
    1500             : static Node *
    1501         784 : buildMergedJoinVar(ParseState *pstate, JoinType jointype,
    1502             :                    Var *l_colvar, Var *r_colvar)
    1503             : {
    1504             :     Oid         outcoltype;
    1505             :     int32       outcoltypmod;
    1506             :     Node       *l_node,
    1507             :                *r_node,
    1508             :                *res_node;
    1509             : 
    1510             :     /*
    1511             :      * Choose output type if input types are dissimilar.
    1512             :      */
    1513         784 :     outcoltype = l_colvar->vartype;
    1514         784 :     outcoltypmod = l_colvar->vartypmod;
    1515         784 :     if (outcoltype != r_colvar->vartype)
    1516             :     {
    1517          44 :         outcoltype = select_common_type(pstate,
    1518          44 :                                         list_make2(l_colvar, r_colvar),
    1519             :                                         "JOIN/USING",
    1520             :                                         NULL);
    1521          44 :         outcoltypmod = -1;      /* ie, unknown */
    1522             :     }
    1523         740 :     else if (outcoltypmod != r_colvar->vartypmod)
    1524             :     {
    1525             :         /* same type, but not same typmod */
    1526           0 :         outcoltypmod = -1;      /* ie, unknown */
    1527             :     }
    1528             : 
    1529             :     /*
    1530             :      * Insert coercion functions if needed.  Note that a difference in typmod
    1531             :      * can only happen if input has typmod but outcoltypmod is -1. In that
    1532             :      * case we insert a RelabelType to clearly mark that result's typmod is
    1533             :      * not same as input.  We never need coerce_type_typmod.
    1534             :      */
    1535         784 :     if (l_colvar->vartype != outcoltype)
    1536          24 :         l_node = coerce_type(pstate, (Node *) l_colvar, l_colvar->vartype,
    1537             :                              outcoltype, outcoltypmod,
    1538             :                              COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
    1539         760 :     else if (l_colvar->vartypmod != outcoltypmod)
    1540           0 :         l_node = (Node *) makeRelabelType((Expr *) l_colvar,
    1541             :                                           outcoltype, outcoltypmod,
    1542             :                                           InvalidOid,   /* fixed below */
    1543             :                                           COERCE_IMPLICIT_CAST);
    1544             :     else
    1545         760 :         l_node = (Node *) l_colvar;
    1546             : 
    1547         784 :     if (r_colvar->vartype != outcoltype)
    1548          20 :         r_node = coerce_type(pstate, (Node *) r_colvar, r_colvar->vartype,
    1549             :                              outcoltype, outcoltypmod,
    1550             :                              COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
    1551         764 :     else if (r_colvar->vartypmod != outcoltypmod)
    1552           0 :         r_node = (Node *) makeRelabelType((Expr *) r_colvar,
    1553             :                                           outcoltype, outcoltypmod,
    1554             :                                           InvalidOid,   /* fixed below */
    1555             :                                           COERCE_IMPLICIT_CAST);
    1556             :     else
    1557         764 :         r_node = (Node *) r_colvar;
    1558             : 
    1559             :     /*
    1560             :      * Choose what to emit
    1561             :      */
    1562         784 :     switch (jointype)
    1563             :     {
    1564             :         case JOIN_INNER:
    1565             : 
    1566             :             /*
    1567             :              * We can use either var; prefer non-coerced one if available.
    1568             :              */
    1569         552 :             if (IsA(l_node, Var))
    1570         532 :                 res_node = l_node;
    1571          20 :             else if (IsA(r_node, Var))
    1572          20 :                 res_node = r_node;
    1573             :             else
    1574           0 :                 res_node = l_node;
    1575         552 :             break;
    1576             :         case JOIN_LEFT:
    1577             :             /* Always use left var */
    1578          92 :             res_node = l_node;
    1579          92 :             break;
    1580             :         case JOIN_RIGHT:
    1581             :             /* Always use right var */
    1582           8 :             res_node = r_node;
    1583           8 :             break;
    1584             :         case JOIN_FULL:
    1585             :             {
    1586             :                 /*
    1587             :                  * Here we must build a COALESCE expression to ensure that the
    1588             :                  * join output is non-null if either input is.
    1589             :                  */
    1590         132 :                 CoalesceExpr *c = makeNode(CoalesceExpr);
    1591             : 
    1592         132 :                 c->coalescetype = outcoltype;
    1593             :                 /* coalescecollid will get set below */
    1594         132 :                 c->args = list_make2(l_node, r_node);
    1595         132 :                 c->location = -1;
    1596         132 :                 res_node = (Node *) c;
    1597         132 :                 break;
    1598             :             }
    1599             :         default:
    1600           0 :             elog(ERROR, "unrecognized join type: %d", (int) jointype);
    1601             :             res_node = NULL;    /* keep compiler quiet */
    1602             :             break;
    1603             :     }
    1604             : 
    1605             :     /*
    1606             :      * Apply assign_expr_collations to fix up the collation info in the
    1607             :      * coercion and CoalesceExpr nodes, if we made any.  This must be done now
    1608             :      * so that the join node's alias vars show correct collation info.
    1609             :      */
    1610         784 :     assign_expr_collations(pstate, res_node);
    1611             : 
    1612         784 :     return res_node;
    1613             : }
    1614             : 
    1615             : /*
    1616             :  * makeNamespaceItem -
    1617             :  *    Convenience subroutine to construct a ParseNamespaceItem.
    1618             :  */
    1619             : static ParseNamespaceItem *
    1620      465298 : makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible,
    1621             :                   bool lateral_only, bool lateral_ok)
    1622             : {
    1623             :     ParseNamespaceItem *nsitem;
    1624             : 
    1625      465298 :     nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
    1626      465298 :     nsitem->p_rte = rte;
    1627      465298 :     nsitem->p_rel_visible = rel_visible;
    1628      465298 :     nsitem->p_cols_visible = cols_visible;
    1629      465298 :     nsitem->p_lateral_only = lateral_only;
    1630      465298 :     nsitem->p_lateral_ok = lateral_ok;
    1631      465298 :     return nsitem;
    1632             : }
    1633             : 
    1634             : /*
    1635             :  * setNamespaceColumnVisibility -
    1636             :  *    Convenience subroutine to update cols_visible flags in a namespace list.
    1637             :  */
    1638             : static void
    1639       79094 : setNamespaceColumnVisibility(List *namespace, bool cols_visible)
    1640             : {
    1641             :     ListCell   *lc;
    1642             : 
    1643      362498 :     foreach(lc, namespace)
    1644             :     {
    1645      283404 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
    1646             : 
    1647      283404 :         nsitem->p_cols_visible = cols_visible;
    1648             :     }
    1649       79094 : }
    1650             : 
    1651             : /*
    1652             :  * setNamespaceLateralState -
    1653             :  *    Convenience subroutine to update LATERAL flags in a namespace list.
    1654             :  */
    1655             : static void
    1656      817884 : setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
    1657             : {
    1658             :     ListCell   *lc;
    1659             : 
    1660     2237786 :     foreach(lc, namespace)
    1661             :     {
    1662     1419902 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
    1663             : 
    1664     1419902 :         nsitem->p_lateral_only = lateral_only;
    1665     1419902 :         nsitem->p_lateral_ok = lateral_ok;
    1666             :     }
    1667      817884 : }
    1668             : 
    1669             : 
    1670             : /*
    1671             :  * transformWhereClause -
    1672             :  *    Transform the qualification and make sure it is of type boolean.
    1673             :  *    Used for WHERE and allied clauses.
    1674             :  *
    1675             :  * constructName does not affect the semantics, but is used in error messages
    1676             :  */
    1677             : Node *
    1678      773002 : transformWhereClause(ParseState *pstate, Node *clause,
    1679             :                      ParseExprKind exprKind, const char *constructName)
    1680             : {
    1681             :     Node       *qual;
    1682             : 
    1683      773002 :     if (clause == NULL)
    1684      516176 :         return NULL;
    1685             : 
    1686      256826 :     qual = transformExpr(pstate, clause, exprKind);
    1687             : 
    1688      256732 :     qual = coerce_to_boolean(pstate, qual, constructName);
    1689             : 
    1690      256732 :     return qual;
    1691             : }
    1692             : 
    1693             : 
    1694             : /*
    1695             :  * transformLimitClause -
    1696             :  *    Transform the expression and make sure it is of type bigint.
    1697             :  *    Used for LIMIT and allied clauses.
    1698             :  *
    1699             :  * Note: as of Postgres 8.2, LIMIT expressions are expected to yield int8,
    1700             :  * rather than int4 as before.
    1701             :  *
    1702             :  * constructName does not affect the semantics, but is used in error messages
    1703             :  */
    1704             : Node *
    1705      701200 : transformLimitClause(ParseState *pstate, Node *clause,
    1706             :                      ParseExprKind exprKind, const char *constructName)
    1707             : {
    1708             :     Node       *qual;
    1709             : 
    1710      701200 :     if (clause == NULL)
    1711      697142 :         return NULL;
    1712             : 
    1713        4058 :     qual = transformExpr(pstate, clause, exprKind);
    1714             : 
    1715        4054 :     qual = coerce_to_specific_type(pstate, qual, INT8OID, constructName);
    1716             : 
    1717             :     /* LIMIT can't refer to any variables of the current query */
    1718        4054 :     checkExprIsVarFree(pstate, qual, constructName);
    1719             : 
    1720        4054 :     return qual;
    1721             : }
    1722             : 
    1723             : /*
    1724             :  * checkExprIsVarFree
    1725             :  *      Check that given expr has no Vars of the current query level
    1726             :  *      (aggregates and window functions should have been rejected already).
    1727             :  *
    1728             :  * This is used to check expressions that have to have a consistent value
    1729             :  * across all rows of the query, such as a LIMIT.  Arguably it should reject
    1730             :  * volatile functions, too, but we don't do that --- whatever value the
    1731             :  * function gives on first execution is what you get.
    1732             :  *
    1733             :  * constructName does not affect the semantics, but is used in error messages
    1734             :  */
    1735             : static void
    1736        4938 : checkExprIsVarFree(ParseState *pstate, Node *n, const char *constructName)
    1737             : {
    1738        4938 :     if (contain_vars_of_level(n, 0))
    1739             :     {
    1740           0 :         ereport(ERROR,
    1741             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1742             :         /* translator: %s is name of a SQL construct, eg LIMIT */
    1743             :                  errmsg("argument of %s must not contain variables",
    1744             :                         constructName),
    1745             :                  parser_errposition(pstate,
    1746             :                                     locate_var_of_level(n, 0))));
    1747             :     }
    1748        4938 : }
    1749             : 
    1750             : 
    1751             : /*
    1752             :  * checkTargetlistEntrySQL92 -
    1753             :  *    Validate a targetlist entry found by findTargetlistEntrySQL92
    1754             :  *
    1755             :  * When we select a pre-existing tlist entry as a result of syntax such
    1756             :  * as "GROUP BY 1", we have to make sure it is acceptable for use in the
    1757             :  * indicated clause type; transformExpr() will have treated it as a regular
    1758             :  * targetlist item.
    1759             :  */
    1760             : static void
    1761       26100 : checkTargetlistEntrySQL92(ParseState *pstate, TargetEntry *tle,
    1762             :                           ParseExprKind exprKind)
    1763             : {
    1764       26100 :     switch (exprKind)
    1765             :     {
    1766             :         case EXPR_KIND_GROUP_BY:
    1767             :             /* reject aggregates and window functions */
    1768         912 :             if (pstate->p_hasAggs &&
    1769         436 :                 contain_aggs_of_level((Node *) tle->expr, 0))
    1770           0 :                 ereport(ERROR,
    1771             :                         (errcode(ERRCODE_GROUPING_ERROR),
    1772             :                 /* translator: %s is name of a SQL construct, eg GROUP BY */
    1773             :                          errmsg("aggregate functions are not allowed in %s",
    1774             :                                 ParseExprKindName(exprKind)),
    1775             :                          parser_errposition(pstate,
    1776             :                                             locate_agg_of_level((Node *) tle->expr, 0))));
    1777         484 :             if (pstate->p_hasWindowFuncs &&
    1778           8 :                 contain_windowfuncs((Node *) tle->expr))
    1779           4 :                 ereport(ERROR,
    1780             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    1781             :                 /* translator: %s is name of a SQL construct, eg GROUP BY */
    1782             :                          errmsg("window functions are not allowed in %s",
    1783             :                                 ParseExprKindName(exprKind)),
    1784             :                          parser_errposition(pstate,
    1785             :                                             locate_windowfunc((Node *) tle->expr))));
    1786         472 :             break;
    1787             :         case EXPR_KIND_ORDER_BY:
    1788             :             /* no extra checks needed */
    1789       25568 :             break;
    1790             :         case EXPR_KIND_DISTINCT_ON:
    1791             :             /* no extra checks needed */
    1792          56 :             break;
    1793             :         default:
    1794           0 :             elog(ERROR, "unexpected exprKind in checkTargetlistEntrySQL92");
    1795             :             break;
    1796             :     }
    1797       26096 : }
    1798             : 
    1799             : /*
    1800             :  *  findTargetlistEntrySQL92 -
    1801             :  *    Returns the targetlist entry matching the given (untransformed) node.
    1802             :  *    If no matching entry exists, one is created and appended to the target
    1803             :  *    list as a "resjunk" node.
    1804             :  *
    1805             :  * This function supports the old SQL92 ORDER BY interpretation, where the
    1806             :  * expression is an output column name or number.  If we fail to find a
    1807             :  * match of that sort, we fall through to the SQL99 rules.  For historical
    1808             :  * reasons, Postgres also allows this interpretation for GROUP BY, though
    1809             :  * the standard never did.  However, for GROUP BY we prefer a SQL99 match.
    1810             :  * This function is *not* used for WINDOW definitions.
    1811             :  *
    1812             :  * node     the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
    1813             :  * tlist    the target list (passed by reference so we can append to it)
    1814             :  * exprKind identifies clause type being processed
    1815             :  */
    1816             : static TargetEntry *
    1817       55316 : findTargetlistEntrySQL92(ParseState *pstate, Node *node, List **tlist,
    1818             :                          ParseExprKind exprKind)
    1819             : {
    1820             :     ListCell   *tl;
    1821             : 
    1822             :     /*----------
    1823             :      * Handle two special cases as mandated by the SQL92 spec:
    1824             :      *
    1825             :      * 1. Bare ColumnName (no qualifier or subscripts)
    1826             :      *    For a bare identifier, we search for a matching column name
    1827             :      *    in the existing target list.  Multiple matches are an error
    1828             :      *    unless they refer to identical values; for example,
    1829             :      *    we allow  SELECT a, a FROM table ORDER BY a
    1830             :      *    but not   SELECT a AS b, b FROM table ORDER BY b
    1831             :      *    If no match is found, we fall through and treat the identifier
    1832             :      *    as an expression.
    1833             :      *    For GROUP BY, it is incorrect to match the grouping item against
    1834             :      *    targetlist entries: according to SQL92, an identifier in GROUP BY
    1835             :      *    is a reference to a column name exposed by FROM, not to a target
    1836             :      *    list column.  However, many implementations (including pre-7.0
    1837             :      *    PostgreSQL) accept this anyway.  So for GROUP BY, we look first
    1838             :      *    to see if the identifier matches any FROM column name, and only
    1839             :      *    try for a targetlist name if it doesn't.  This ensures that we
    1840             :      *    adhere to the spec in the case where the name could be both.
    1841             :      *    DISTINCT ON isn't in the standard, so we can do what we like there;
    1842             :      *    we choose to make it work like ORDER BY, on the rather flimsy
    1843             :      *    grounds that ordinary DISTINCT works on targetlist entries.
    1844             :      *
    1845             :      * 2. IntegerConstant
    1846             :      *    This means to use the n'th item in the existing target list.
    1847             :      *    Note that it would make no sense to order/group/distinct by an
    1848             :      *    actual constant, so this does not create a conflict with SQL99.
    1849             :      *    GROUP BY column-number is not allowed by SQL92, but since
    1850             :      *    the standard has no other behavior defined for this syntax,
    1851             :      *    we may as well accept this common extension.
    1852             :      *
    1853             :      * Note that pre-existing resjunk targets must not be used in either case,
    1854             :      * since the user didn't write them in his SELECT list.
    1855             :      *
    1856             :      * If neither special case applies, fall through to treat the item as
    1857             :      * an expression per SQL99.
    1858             :      *----------
    1859             :      */
    1860       91514 :     if (IsA(node, ColumnRef) &&
    1861       56824 :         list_length(((ColumnRef *) node)->fields) == 1 &&
    1862       20626 :         IsA(linitial(((ColumnRef *) node)->fields), String))
    1863             :     {
    1864       20626 :         char       *name = strVal(linitial(((ColumnRef *) node)->fields));
    1865       20626 :         int         location = ((ColumnRef *) node)->location;
    1866             : 
    1867       20626 :         if (exprKind == EXPR_KIND_GROUP_BY)
    1868             :         {
    1869             :             /*
    1870             :              * In GROUP BY, we must prefer a match against a FROM-clause
    1871             :              * column to one against the targetlist.  Look to see if there is
    1872             :              * a matching column.  If so, fall through to use SQL99 rules.
    1873             :              * NOTE: if name could refer ambiguously to more than one column
    1874             :              * name exposed by FROM, colNameToVar will ereport(ERROR). That's
    1875             :              * just what we want here.
    1876             :              *
    1877             :              * Small tweak for 7.4.3: ignore matches in upper query levels.
    1878             :              * This effectively changes the search order for bare names to (1)
    1879             :              * local FROM variables, (2) local targetlist aliases, (3) outer
    1880             :              * FROM variables, whereas before it was (1) (3) (2). SQL92 and
    1881             :              * SQL99 do not allow GROUPing BY an outer reference, so this
    1882             :              * breaks no cases that are legal per spec, and it seems a more
    1883             :              * self-consistent behavior.
    1884             :              */
    1885        2240 :             if (colNameToVar(pstate, name, true, location) != NULL)
    1886        2192 :                 name = NULL;
    1887             :         }
    1888             : 
    1889       20626 :         if (name != NULL)
    1890             :         {
    1891       18434 :             TargetEntry *target_result = NULL;
    1892             : 
    1893       98390 :             foreach(tl, *tlist)
    1894             :             {
    1895       79956 :                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
    1896             : 
    1897      159776 :                 if (!tle->resjunk &&
    1898       79820 :                     strcmp(tle->resname, name) == 0)
    1899             :                 {
    1900       11400 :                     if (target_result != NULL)
    1901             :                     {
    1902           4 :                         if (!equal(target_result->expr, tle->expr))
    1903           0 :                             ereport(ERROR,
    1904             :                                     (errcode(ERRCODE_AMBIGUOUS_COLUMN),
    1905             : 
    1906             :                             /*------
    1907             :                               translator: first %s is name of a SQL construct, eg ORDER BY */
    1908             :                                      errmsg("%s \"%s\" is ambiguous",
    1909             :                                             ParseExprKindName(exprKind),
    1910             :                                             name),
    1911             :                                      parser_errposition(pstate, location)));
    1912             :                     }
    1913             :                     else
    1914       11396 :                         target_result = tle;
    1915             :                     /* Stay in loop to check for ambiguity */
    1916             :                 }
    1917             :             }
    1918       18434 :             if (target_result != NULL)
    1919             :             {
    1920             :                 /* return the first match, after suitable validation */
    1921       11396 :                 checkTargetlistEntrySQL92(pstate, target_result, exprKind);
    1922       11396 :                 return target_result;
    1923             :             }
    1924             :         }
    1925             :     }
    1926       43920 :     if (IsA(node, A_Const))
    1927             :     {
    1928       14708 :         Value      *val = &((A_Const *) node)->val;
    1929       14708 :         int         location = ((A_Const *) node)->location;
    1930       14708 :         int         targetlist_pos = 0;
    1931             :         int         target_pos;
    1932             : 
    1933       14708 :         if (!IsA(val, Integer))
    1934           0 :             ereport(ERROR,
    1935             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    1936             :             /* translator: %s is name of a SQL construct, eg ORDER BY */
    1937             :                      errmsg("non-integer constant in %s",
    1938             :                             ParseExprKindName(exprKind)),
    1939             :                      parser_errposition(pstate, location)));
    1940             : 
    1941       14708 :         target_pos = intVal(val);
    1942       25804 :         foreach(tl, *tlist)
    1943             :         {
    1944       25800 :             TargetEntry *tle = (TargetEntry *) lfirst(tl);
    1945             : 
    1946       25800 :             if (!tle->resjunk)
    1947             :             {
    1948       25800 :                 if (++targetlist_pos == target_pos)
    1949             :                 {
    1950             :                     /* return the unique match, after suitable validation */
    1951       14704 :                     checkTargetlistEntrySQL92(pstate, tle, exprKind);
    1952       14700 :                     return tle;
    1953             :                 }
    1954             :             }
    1955             :         }
    1956           4 :         ereport(ERROR,
    1957             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1958             :         /* translator: %s is name of a SQL construct, eg ORDER BY */
    1959             :                  errmsg("%s position %d is not in select list",
    1960             :                         ParseExprKindName(exprKind), target_pos),
    1961             :                  parser_errposition(pstate, location)));
    1962             :     }
    1963             : 
    1964             :     /*
    1965             :      * Otherwise, we have an expression, so process it per SQL99 rules.
    1966             :      */
    1967       29212 :     return findTargetlistEntrySQL99(pstate, node, tlist, exprKind);
    1968             : }
    1969             : 
    1970             : /*
    1971             :  *  findTargetlistEntrySQL99 -
    1972             :  *    Returns the targetlist entry matching the given (untransformed) node.
    1973             :  *    If no matching entry exists, one is created and appended to the target
    1974             :  *    list as a "resjunk" node.
    1975             :  *
    1976             :  * This function supports the SQL99 interpretation, wherein the expression
    1977             :  * is just an ordinary expression referencing input column names.
    1978             :  *
    1979             :  * node     the ORDER BY, GROUP BY, etc expression to be matched
    1980             :  * tlist    the target list (passed by reference so we can append to it)
    1981             :  * exprKind identifies clause type being processed
    1982             :  */
    1983             : static TargetEntry *
    1984       41848 : findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist,
    1985             :                          ParseExprKind exprKind)
    1986             : {
    1987             :     TargetEntry *target_result;
    1988             :     ListCell   *tl;
    1989             :     Node       *expr;
    1990             : 
    1991             :     /*
    1992             :      * Convert the untransformed node to a transformed expression, and search
    1993             :      * for a match in the tlist.  NOTE: it doesn't really matter whether there
    1994             :      * is more than one match.  Also, we are willing to match an existing
    1995             :      * resjunk target here, though the SQL92 cases above must ignore resjunk
    1996             :      * targets.
    1997             :      */
    1998       41848 :     expr = transformExpr(pstate, node, exprKind);
    1999             : 
    2000      149646 :     foreach(tl, *tlist)
    2001             :     {
    2002      123146 :         TargetEntry *tle = (TargetEntry *) lfirst(tl);
    2003             :         Node       *texpr;
    2004             : 
    2005             :         /*
    2006             :          * Ignore any implicit cast on the existing tlist expression.
    2007             :          *
    2008             :          * This essentially allows the ORDER/GROUP/etc item to adopt the same
    2009             :          * datatype previously selected for a textually-equivalent tlist item.
    2010             :          * There can't be any implicit cast at top level in an ordinary SELECT
    2011             :          * tlist at this stage, but the case does arise with ORDER BY in an
    2012             :          * aggregate function.
    2013             :          */
    2014      123146 :         texpr = strip_implicit_coercions((Node *) tle->expr);
    2015             : 
    2016      123146 :         if (equal(expr, texpr))
    2017       15312 :             return tle;
    2018             :     }
    2019             : 
    2020             :     /*
    2021             :      * If no matches, construct a new target entry which is appended to the
    2022             :      * end of the target list.  This target is given resjunk = true so that it
    2023             :      * will not be projected into the final tuple.
    2024             :      */
    2025       26500 :     target_result = transformTargetEntry(pstate, node, expr, exprKind,
    2026             :                                          NULL, true);
    2027             : 
    2028       26500 :     *tlist = lappend(*tlist, target_result);
    2029             : 
    2030       26500 :     return target_result;
    2031             : }
    2032             : 
    2033             : /*-------------------------------------------------------------------------
    2034             :  * Flatten out parenthesized sublists in grouping lists, and some cases
    2035             :  * of nested grouping sets.
    2036             :  *
    2037             :  * Inside a grouping set (ROLLUP, CUBE, or GROUPING SETS), we expect the
    2038             :  * content to be nested no more than 2 deep: i.e. ROLLUP((a,b),(c,d)) is
    2039             :  * ok, but ROLLUP((a,(b,c)),d) is flattened to ((a,b,c),d), which we then
    2040             :  * (later) normalize to ((a,b,c),(d)).
    2041             :  *
    2042             :  * CUBE or ROLLUP can be nested inside GROUPING SETS (but not the reverse),
    2043             :  * and we leave that alone if we find it. But if we see GROUPING SETS inside
    2044             :  * GROUPING SETS, we can flatten and normalize as follows:
    2045             :  *   GROUPING SETS (a, (b,c), GROUPING SETS ((c,d),(e)), (f,g))
    2046             :  * becomes
    2047             :  *   GROUPING SETS ((a), (b,c), (c,d), (e), (f,g))
    2048             :  *
    2049             :  * This is per the spec's syntax transformations, but these are the only such
    2050             :  * transformations we do in parse analysis, so that queries retain the
    2051             :  * originally specified grouping set syntax for CUBE and ROLLUP as much as
    2052             :  * possible when deparsed. (Full expansion of the result into a list of
    2053             :  * grouping sets is left to the planner.)
    2054             :  *
    2055             :  * When we're done, the resulting list should contain only these possible
    2056             :  * elements:
    2057             :  *   - an expression
    2058             :  *   - a CUBE or ROLLUP with a list of expressions nested 2 deep
    2059             :  *   - a GROUPING SET containing any of:
    2060             :  *      - expression lists
    2061             :  *      - empty grouping sets
    2062             :  *      - CUBE or ROLLUP nodes with lists nested 2 deep
    2063             :  * The return is a new list, but doesn't deep-copy the old nodes except for
    2064             :  * GroupingSet nodes.
    2065             :  *
    2066             :  * As a side effect, flag whether the list has any GroupingSet nodes.
    2067             :  *-------------------------------------------------------------------------
    2068             :  */
    2069             : static Node *
    2070      350720 : flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets)
    2071             : {
    2072             :     /* just in case of pathological input */
    2073      350720 :     check_stack_depth();
    2074             : 
    2075      350720 :     if (expr == (Node *) NIL)
    2076      337150 :         return (Node *) NIL;
    2077             : 
    2078       13570 :     switch (expr->type)
    2079             :     {
    2080             :         case T_RowExpr:
    2081             :             {
    2082         192 :                 RowExpr    *r = (RowExpr *) expr;
    2083             : 
    2084         192 :                 if (r->row_format == COERCE_IMPLICIT_CAST)
    2085         192 :                     return flatten_grouping_sets((Node *) r->args,
    2086             :                                                  false, NULL);
    2087             :             }
    2088           0 :             break;
    2089             :         case T_GroupingSet:
    2090             :             {
    2091         672 :                 GroupingSet *gset = (GroupingSet *) expr;
    2092             :                 ListCell   *l2;
    2093         672 :                 List       *result_set = NIL;
    2094             : 
    2095         672 :                 if (hasGroupingSets)
    2096         460 :                     *hasGroupingSets = true;
    2097             : 
    2098             :                 /*
    2099             :                  * at the top level, we skip over all empty grouping sets; the
    2100             :                  * caller can supply the canonical GROUP BY () if nothing is
    2101             :                  * left.
    2102             :                  */
    2103             : 
    2104         672 :                 if (toplevel && gset->kind == GROUPING_SET_EMPTY)
    2105          12 :                     return (Node *) NIL;
    2106             : 
    2107        1740 :                 foreach(l2, gset->content)
    2108             :                 {
    2109        1080 :                     Node       *n1 = lfirst(l2);
    2110        1080 :                     Node       *n2 = flatten_grouping_sets(n1, false, NULL);
    2111             : 
    2112        1292 :                     if (IsA(n1, GroupingSet) &&
    2113         212 :                         ((GroupingSet *) n1)->kind == GROUPING_SET_SETS)
    2114          64 :                         result_set = list_concat(result_set, (List *) n2);
    2115             :                     else
    2116        1016 :                         result_set = lappend(result_set, n2);
    2117             :                 }
    2118             : 
    2119             :                 /*
    2120             :                  * At top level, keep the grouping set node; but if we're in a
    2121             :                  * nested grouping set, then we need to concat the flattened
    2122             :                  * result into the outer list if it's simply nested.
    2123             :                  */
    2124             : 
    2125         660 :                 if (toplevel || (gset->kind != GROUPING_SET_SETS))
    2126             :                 {
    2127         596 :                     return (Node *) makeGroupingSet(gset->kind, result_set, gset->location);
    2128             :                 }
    2129             :                 else
    2130          64 :                     return (Node *) result_set;
    2131             :             }
    2132             :         case T_List:
    2133             :             {
    2134        3884 :                 List       *result = NIL;
    2135             :                 ListCell   *l;
    2136             : 
    2137       12490 :                 foreach(l, (List *) expr)
    2138             :                 {
    2139        8606 :                     Node       *n = flatten_grouping_sets(lfirst(l), toplevel, hasGroupingSets);
    2140             : 
    2141        8606 :                     if (n != (Node *) NIL)
    2142             :                     {
    2143        8594 :                         if (IsA(n, List))
    2144          28 :                             result = list_concat(result, (List *) n);
    2145             :                         else
    2146        8566 :                             result = lappend(result, n);
    2147             :                     }
    2148             :                 }
    2149             : 
    2150        3884 :                 return (Node *) result;
    2151             :             }
    2152             :         default:
    2153        8822 :             break;
    2154             :     }
    2155             : 
    2156        8822 :     return expr;
    2157             : }
    2158             : 
    2159             : /*
    2160             :  * Transform a single expression within a GROUP BY clause or grouping set.
    2161             :  *
    2162             :  * The expression is added to the targetlist if not already present, and to the
    2163             :  * flatresult list (which will become the groupClause) if not already present
    2164             :  * there.  The sortClause is consulted for operator and sort order hints.
    2165             :  *
    2166             :  * Returns the ressortgroupref of the expression.
    2167             :  *
    2168             :  * flatresult   reference to flat list of SortGroupClause nodes
    2169             :  * seen_local   bitmapset of sortgrouprefs already seen at the local level
    2170             :  * pstate       ParseState
    2171             :  * gexpr        node to transform
    2172             :  * targetlist   reference to TargetEntry list
    2173             :  * sortClause   ORDER BY clause (SortGroupClause nodes)
    2174             :  * exprKind     expression kind
    2175             :  * useSQL99     SQL99 rather than SQL92 syntax
    2176             :  * toplevel     false if within any grouping set
    2177             :  */
    2178             : static Index
    2179        8822 : transformGroupClauseExpr(List **flatresult, Bitmapset *seen_local,
    2180             :                          ParseState *pstate, Node *gexpr,
    2181             :                          List **targetlist, List *sortClause,
    2182             :                          ParseExprKind exprKind, bool useSQL99, bool toplevel)
    2183             : {
    2184             :     TargetEntry *tle;
    2185        8822 :     bool        found = false;
    2186             : 
    2187        8822 :     if (useSQL99)
    2188        1926 :         tle = findTargetlistEntrySQL99(pstate, gexpr,
    2189             :                                        targetlist, exprKind);
    2190             :     else
    2191        6896 :         tle = findTargetlistEntrySQL92(pstate, gexpr,
    2192             :                                        targetlist, exprKind);
    2193             : 
    2194        8806 :     if (tle->ressortgroupref > 0)
    2195             :     {
    2196             :         ListCell   *sl;
    2197             : 
    2198             :         /*
    2199             :          * Eliminate duplicates (GROUP BY x, x) but only at local level.
    2200             :          * (Duplicates in grouping sets can affect the number of returned
    2201             :          * rows, so can't be dropped indiscriminately.)
    2202             :          *
    2203             :          * Since we don't care about anything except the sortgroupref, we can
    2204             :          * use a bitmapset rather than scanning lists.
    2205             :          */
    2206        1438 :         if (bms_is_member(tle->ressortgroupref, seen_local))
    2207          16 :             return 0;
    2208             : 
    2209             :         /*
    2210             :          * If we're already in the flat clause list, we don't need to consider
    2211             :          * adding ourselves again.
    2212             :          */
    2213        1422 :         found = targetIsInSortList(tle, InvalidOid, *flatresult);
    2214        1422 :         if (found)
    2215         116 :             return tle->ressortgroupref;
    2216             : 
    2217             :         /*
    2218             :          * If the GROUP BY tlist entry also appears in ORDER BY, copy operator
    2219             :          * info from the (first) matching ORDER BY item.  This means that if
    2220             :          * you write something like "GROUP BY foo ORDER BY foo USING <<<", the
    2221             :          * GROUP BY operation silently takes on the equality semantics implied
    2222             :          * by the ORDER BY.  There are two reasons to do this: it improves the
    2223             :          * odds that we can implement both GROUP BY and ORDER BY with a single
    2224             :          * sort step, and it allows the user to choose the equality semantics
    2225             :          * used by GROUP BY, should she be working with a datatype that has
    2226             :          * more than one equality operator.
    2227             :          *
    2228             :          * If we're in a grouping set, though, we force our requested ordering
    2229             :          * to be NULLS LAST, because if we have any hope of using a sorted agg
    2230             :          * for the job, we're going to be tacking on generated NULL values
    2231             :          * after the corresponding groups. If the user demands nulls first,
    2232             :          * another sort step is going to be inevitable, but that's the
    2233             :          * planner's problem.
    2234             :          */
    2235             : 
    2236        1732 :         foreach(sl, sortClause)
    2237             :         {
    2238        1688 :             SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
    2239             : 
    2240        1688 :             if (sc->tleSortGroupRef == tle->ressortgroupref)
    2241             :             {
    2242        1262 :                 SortGroupClause *grpc = copyObject(sc);
    2243             : 
    2244        1262 :                 if (!toplevel)
    2245         288 :                     grpc->nulls_first = false;
    2246        1262 :                 *flatresult = lappend(*flatresult, grpc);
    2247        1262 :                 found = true;
    2248        1262 :                 break;
    2249             :             }
    2250             :         }
    2251             :     }
    2252             : 
    2253             :     /*
    2254             :      * If no match in ORDER BY, just add it to the result using default
    2255             :      * sort/group semantics.
    2256             :      */
    2257        8674 :     if (!found)
    2258        7412 :         *flatresult = addTargetToGroupList(pstate, tle,
    2259             :                                            *flatresult, *targetlist,
    2260             :                                            exprLocation(gexpr));
    2261             : 
    2262             :     /*
    2263             :      * _something_ must have assigned us a sortgroupref by now...
    2264             :      */
    2265             : 
    2266        8674 :     return tle->ressortgroupref;
    2267             : }
    2268             : 
    2269             : /*
    2270             :  * Transform a list of expressions within a GROUP BY clause or grouping set.
    2271             :  *
    2272             :  * The list of expressions belongs to a single clause within which duplicates
    2273             :  * can be safely eliminated.
    2274             :  *
    2275             :  * Returns an integer list of ressortgroupref values.
    2276             :  *
    2277             :  * flatresult   reference to flat list of SortGroupClause nodes
    2278             :  * pstate       ParseState
    2279             :  * list         nodes to transform
    2280             :  * targetlist   reference to TargetEntry list
    2281             :  * sortClause   ORDER BY clause (SortGroupClause nodes)
    2282             :  * exprKind     expression kind
    2283             :  * useSQL99     SQL99 rather than SQL92 syntax
    2284             :  * toplevel     false if within any grouping set
    2285             :  */
    2286             : static List *
    2287         164 : transformGroupClauseList(List **flatresult,
    2288             :                          ParseState *pstate, List *list,
    2289             :                          List **targetlist, List *sortClause,
    2290             :                          ParseExprKind exprKind, bool useSQL99, bool toplevel)
    2291             : {
    2292         164 :     Bitmapset  *seen_local = NULL;
    2293         164 :     List       *result = NIL;
    2294             :     ListCell   *gl;
    2295             : 
    2296         508 :     foreach(gl, list)
    2297             :     {
    2298         344 :         Node       *gexpr = (Node *) lfirst(gl);
    2299             : 
    2300         344 :         Index       ref = transformGroupClauseExpr(flatresult,
    2301             :                                                    seen_local,
    2302             :                                                    pstate,
    2303             :                                                    gexpr,
    2304             :                                                    targetlist,
    2305             :                                                    sortClause,
    2306             :                                                    exprKind,
    2307             :                                                    useSQL99,
    2308             :                                                    toplevel);
    2309             : 
    2310         344 :         if (ref > 0)
    2311             :         {
    2312         336 :             seen_local = bms_add_member(seen_local, ref);
    2313         336 :             result = lappend_int(result, ref);
    2314             :         }
    2315             :     }
    2316             : 
    2317         164 :     return result;
    2318             : }
    2319             : 
    2320             : /*
    2321             :  * Transform a grouping set and (recursively) its content.
    2322             :  *
    2323             :  * The grouping set might be a GROUPING SETS node with other grouping sets
    2324             :  * inside it, but SETS within SETS have already been flattened out before
    2325             :  * reaching here.
    2326             :  *
    2327             :  * Returns the transformed node, which now contains SIMPLE nodes with lists
    2328             :  * of ressortgrouprefs rather than expressions.
    2329             :  *
    2330             :  * flatresult   reference to flat list of SortGroupClause nodes
    2331             :  * pstate       ParseState
    2332             :  * gset         grouping set to transform
    2333             :  * targetlist   reference to TargetEntry list
    2334             :  * sortClause   ORDER BY clause (SortGroupClause nodes)
    2335             :  * exprKind     expression kind
    2336             :  * useSQL99     SQL99 rather than SQL92 syntax
    2337             :  * toplevel     false if within any grouping set
    2338             :  */
    2339             : static Node *
    2340         596 : transformGroupingSet(List **flatresult,
    2341             :                      ParseState *pstate, GroupingSet *gset,
    2342             :                      List **targetlist, List *sortClause,
    2343             :                      ParseExprKind exprKind, bool useSQL99, bool toplevel)
    2344             : {
    2345             :     ListCell   *gl;
    2346         596 :     List       *content = NIL;
    2347             : 
    2348             :     Assert(toplevel || gset->kind != GROUPING_SET_SETS);
    2349             : 
    2350        1612 :     foreach(gl, gset->content)
    2351             :     {
    2352        1016 :         Node       *n = lfirst(gl);
    2353             : 
    2354        1016 :         if (IsA(n, List))
    2355             :         {
    2356         164 :             List       *l = transformGroupClauseList(flatresult,
    2357             :                                                      pstate, (List *) n,
    2358             :                                                      targetlist, sortClause,
    2359             :                                                      exprKind, useSQL99, false);
    2360             : 
    2361         164 :             content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
    2362             :                                                        l,
    2363             :                                                        exprLocation(n)));
    2364             :         }
    2365         852 :         else if (IsA(n, GroupingSet))
    2366             :         {
    2367         148 :             GroupingSet *gset2 = (GroupingSet *) lfirst(gl);
    2368             : 
    2369         148 :             content = lappend(content, transformGroupingSet(flatresult,
    2370             :                                                             pstate, gset2,
    2371             :                                                             targetlist, sortClause,
    2372             :                                                             exprKind, useSQL99, false));
    2373             :         }
    2374             :         else
    2375             :         {
    2376         704 :             Index       ref = transformGroupClauseExpr(flatresult,
    2377             :                                                        NULL,
    2378             :                                                        pstate,
    2379             :                                                        n,
    2380             :                                                        targetlist,
    2381             :                                                        sortClause,
    2382             :                                                        exprKind,
    2383             :                                                        useSQL99,
    2384             :                                                        false);
    2385             : 
    2386        1408 :             content = lappend(content, makeGroupingSet(GROUPING_SET_SIMPLE,
    2387         704 :                                                        list_make1_int(ref),
    2388             :                                                        exprLocation(n)));
    2389             :         }
    2390             :     }
    2391             : 
    2392             :     /* Arbitrarily cap the size of CUBE, which has exponential growth */
    2393         596 :     if (gset->kind == GROUPING_SET_CUBE)
    2394             :     {
    2395          96 :         if (list_length(content) > 12)
    2396           0 :             ereport(ERROR,
    2397             :                     (errcode(ERRCODE_TOO_MANY_COLUMNS),
    2398             :                      errmsg("CUBE is limited to 12 elements"),
    2399             :                      parser_errposition(pstate, gset->location)));
    2400             :     }
    2401             : 
    2402         596 :     return (Node *) makeGroupingSet(gset->kind, content, gset->location);
    2403             : }
    2404             : 
    2405             : 
    2406             : /*
    2407             :  * transformGroupClause -
    2408             :  *    transform a GROUP BY clause
    2409             :  *
    2410             :  * GROUP BY items will be added to the targetlist (as resjunk columns)
    2411             :  * if not already present, so the targetlist must be passed by reference.
    2412             :  *
    2413             :  * This is also used for window PARTITION BY clauses (which act almost the
    2414             :  * same, but are always interpreted per SQL99 rules).
    2415             :  *
    2416             :  * Grouping sets make this a lot more complex than it was. Our goal here is
    2417             :  * twofold: we make a flat list of SortGroupClause nodes referencing each
    2418             :  * distinct expression used for grouping, with those expressions added to the
    2419             :  * targetlist if needed. At the same time, we build the groupingSets tree,
    2420             :  * which stores only ressortgrouprefs as integer lists inside GroupingSet nodes
    2421             :  * (possibly nested, but limited in depth: a GROUPING_SET_SETS node can contain
    2422             :  * nested SIMPLE, CUBE or ROLLUP nodes, but not more sets - we flatten that
    2423             :  * out; while CUBE and ROLLUP can contain only SIMPLE nodes).
    2424             :  *
    2425             :  * We skip much of the hard work if there are no grouping sets.
    2426             :  *
    2427             :  * One subtlety is that the groupClause list can end up empty while the
    2428             :  * groupingSets list is not; this happens if there are only empty grouping
    2429             :  * sets, or an explicit GROUP BY (). This has the same effect as specifying
    2430             :  * aggregates or a HAVING clause with no GROUP BY; the output is one row per
    2431             :  * grouping set even if the input is empty.
    2432             :  *
    2433             :  * Returns the transformed (flat) groupClause.
    2434             :  *
    2435             :  * pstate       ParseState
    2436             :  * grouplist    clause to transform
    2437             :  * groupingSets reference to list to contain the grouping set tree
    2438             :  * targetlist   reference to TargetEntry list
    2439             :  * sortClause   ORDER BY clause (SortGroupClause nodes)
    2440             :  * exprKind     expression kind
    2441             :  * useSQL99     SQL99 rather than SQL92 syntax
    2442             :  */
    2443             : List *
    2444      340842 : transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets,
    2445             :                      List **targetlist, List *sortClause,
    2446             :                      ParseExprKind exprKind, bool useSQL99)
    2447             : {
    2448      340842 :     List       *result = NIL;
    2449             :     List       *flat_grouplist;
    2450      340842 :     List       *gsets = NIL;
    2451             :     ListCell   *gl;
    2452      340842 :     bool        hasGroupingSets = false;
    2453      340842 :     Bitmapset  *seen_local = NULL;
    2454             : 
    2455             :     /*
    2456             :      * Recursively flatten implicit RowExprs. (Technically this is only needed
    2457             :      * for GROUP BY, per the syntax rules for grouping sets, but we do it
    2458             :      * anyway.)
    2459             :      */
    2460      340842 :     flat_grouplist = (List *) flatten_grouping_sets((Node *) grouplist,
    2461             :                                                     true,
    2462             :                                                     &hasGroupingSets);
    2463             : 
    2464             :     /*
    2465             :      * If the list is now empty, but hasGroupingSets is true, it's because we
    2466             :      * elided redundant empty grouping sets. Restore a single empty grouping
    2467             :      * set to leave a canonical form: GROUP BY ()
    2468             :      */
    2469             : 
    2470      340842 :     if (flat_grouplist == NIL && hasGroupingSets)
    2471             :     {
    2472          12 :         flat_grouplist = list_make1(makeGroupingSet(GROUPING_SET_EMPTY,
    2473             :                                                     NIL,
    2474             :                                                     exprLocation((Node *) grouplist)));
    2475             :     }
    2476             : 
    2477      349060 :     foreach(gl, flat_grouplist)
    2478             :     {
    2479        8234 :         Node       *gexpr = (Node *) lfirst(gl);
    2480             : 
    2481        8234 :         if (IsA(gexpr, GroupingSet))
    2482             :         {
    2483         460 :             GroupingSet *gset = (GroupingSet *) gexpr;
    2484             : 
    2485         460 :             switch (gset->kind)
    2486             :             {
    2487             :                 case GROUPING_SET_EMPTY:
    2488          12 :                     gsets = lappend(gsets, gset);
    2489          12 :                     break;
    2490             :                 case GROUPING_SET_SIMPLE:
    2491             :                     /* can't happen */
    2492             :                     Assert(false);
    2493           0 :                     break;
    2494             :                 case GROUPING_SET_SETS:
    2495             :                 case GROUPING_SET_CUBE:
    2496             :                 case GROUPING_SET_ROLLUP:
    2497         448 :                     gsets = lappend(gsets,
    2498         448 :                                     transformGroupingSet(&result,
    2499             :                                                          pstate, gset,
    2500             :                                                          targetlist, sortClause,
    2501             :                                                          exprKind, useSQL99, true));
    2502         448 :                     break;
    2503             :             }
    2504             :         }
    2505             :         else
    2506             :         {
    2507        7774 :             Index       ref = transformGroupClauseExpr(&result, seen_local,
    2508             :                                                        pstate, gexpr,
    2509             :                                                        targetlist, sortClause,
    2510             :                                                        exprKind, useSQL99, true);
    2511             : 
    2512        7758 :             if (ref > 0)
    2513             :             {
    2514        7750 :                 seen_local = bms_add_member(seen_local, ref);
    2515        7750 :                 if (hasGroupingSets)
    2516          24 :                     gsets = lappend(gsets,
    2517          48 :                                     makeGroupingSet(GROUPING_SET_SIMPLE,
    2518          24 :                                                     list_make1_int(ref),
    2519             :                                                     exprLocation(gexpr)));
    2520             :             }
    2521             :         }
    2522             :     }
    2523             : 
    2524             :     /* parser should prevent this */
    2525             :     Assert(gsets == NIL || groupingSets != NULL);
    2526             : 
    2527      340826 :     if (groupingSets)
    2528      339284 :         *groupingSets = gsets;
    2529             : 
    2530      340826 :     return result;
    2531             : }
    2532             : 
    2533             : /*
    2534             :  * transformSortClause -
    2535             :  *    transform an ORDER BY clause
    2536             :  *
    2537             :  * ORDER BY items will be added to the targetlist (as resjunk columns)
    2538             :  * if not already present, so the targetlist must be passed by reference.
    2539             :  *
    2540             :  * This is also used for window and aggregate ORDER BY clauses (which act
    2541             :  * almost the same, but are always interpreted per SQL99 rules).
    2542             :  */
    2543             : List *
    2544      381932 : transformSortClause(ParseState *pstate,
    2545             :                     List *orderlist,
    2546             :                     List **targetlist,
    2547             :                     ParseExprKind exprKind,
    2548             :                     bool useSQL99)
    2549             : {
    2550      381932 :     List       *sortlist = NIL;
    2551             :     ListCell   *olitem;
    2552             : 
    2553      440974 :     foreach(olitem, orderlist)
    2554             :     {
    2555       59070 :         SortBy     *sortby = (SortBy *) lfirst(olitem);
    2556             :         TargetEntry *tle;
    2557             : 
    2558       59070 :         if (useSQL99)
    2559       10710 :             tle = findTargetlistEntrySQL99(pstate, sortby->node,
    2560             :                                            targetlist, exprKind);
    2561             :         else
    2562       48360 :             tle = findTargetlistEntrySQL92(pstate, sortby->node,
    2563             :                                            targetlist, exprKind);
    2564             : 
    2565       59046 :         sortlist = addTargetToSortList(pstate, tle,
    2566             :                                        sortlist, *targetlist, sortby);
    2567             :     }
    2568             : 
    2569      381904 :     return sortlist;
    2570             : }
    2571             : 
    2572             : /*
    2573             :  * transformWindowDefinitions -
    2574             :  *      transform window definitions (WindowDef to WindowClause)
    2575             :  */
    2576             : List *
    2577      339272 : transformWindowDefinitions(ParseState *pstate,
    2578             :                            List *windowdefs,
    2579             :                            List **targetlist)
    2580             : {
    2581      339272 :     List       *result = NIL;
    2582      339272 :     Index       winref = 0;
    2583             :     ListCell   *lc;
    2584             : 
    2585      340782 :     foreach(lc, windowdefs)
    2586             :     {
    2587        1550 :         WindowDef  *windef = (WindowDef *) lfirst(lc);
    2588        1550 :         WindowClause *refwc = NULL;
    2589             :         List       *partitionClause;
    2590             :         List       *orderClause;
    2591        1550 :         Oid         rangeopfamily = InvalidOid;
    2592        1550 :         Oid         rangeopcintype = InvalidOid;
    2593             :         WindowClause *wc;
    2594             : 
    2595        1550 :         winref++;
    2596             : 
    2597             :         /*
    2598             :          * Check for duplicate window names.
    2599             :          */
    2600        1782 :         if (windef->name &&
    2601         232 :             findWindowClause(result, windef->name) != NULL)
    2602           4 :             ereport(ERROR,
    2603             :                     (errcode(ERRCODE_WINDOWING_ERROR),
    2604             :                      errmsg("window \"%s\" is already defined", windef->name),
    2605             :                      parser_errposition(pstate, windef->location)));
    2606             : 
    2607             :         /*
    2608             :          * If it references a previous window, look that up.
    2609             :          */
    2610        1546 :         if (windef->refname)
    2611             :         {
    2612          16 :             refwc = findWindowClause(result, windef->refname);
    2613          16 :             if (refwc == NULL)
    2614           0 :                 ereport(ERROR,
    2615             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    2616             :                          errmsg("window \"%s\" does not exist",
    2617             :                                 windef->refname),
    2618             :                          parser_errposition(pstate, windef->location)));
    2619             :         }
    2620             : 
    2621             :         /*
    2622             :          * Transform PARTITION and ORDER specs, if any.  These are treated
    2623             :          * almost exactly like top-level GROUP BY and ORDER BY clauses,
    2624             :          * including the special handling of nondefault operator semantics.
    2625             :          */
    2626        1546 :         orderClause = transformSortClause(pstate,
    2627             :                                           windef->orderClause,
    2628             :                                           targetlist,
    2629             :                                           EXPR_KIND_WINDOW_ORDER,
    2630             :                                           true /* force SQL99 rules */ );
    2631        1542 :         partitionClause = transformGroupClause(pstate,
    2632             :                                                windef->partitionClause,
    2633             :                                                NULL,
    2634             :                                                targetlist,
    2635             :                                                orderClause,
    2636             :                                                EXPR_KIND_WINDOW_PARTITION,
    2637             :                                                true /* force SQL99 rules */ );
    2638             : 
    2639             :         /*
    2640             :          * And prepare the new WindowClause.
    2641             :          */
    2642        1542 :         wc = makeNode(WindowClause);
    2643        1542 :         wc->name = windef->name;
    2644        1542 :         wc->refname = windef->refname;
    2645             : 
    2646             :         /*
    2647             :          * Per spec, a windowdef that references a previous one copies the
    2648             :          * previous partition clause (and mustn't specify its own).  It can
    2649             :          * specify its own ordering clause, but only if the previous one had
    2650             :          * none.  It always specifies its own frame clause, and the previous
    2651             :          * one must not have a frame clause.  Yeah, it's bizarre that each of
    2652             :          * these cases works differently, but SQL:2008 says so; see 7.11
    2653             :          * <window clause> syntax rule 10 and general rule 1.  The frame
    2654             :          * clause rule is especially bizarre because it makes "OVER foo"
    2655             :          * different from "OVER (foo)", and requires the latter to throw an
    2656             :          * error if foo has a nondefault frame clause.  Well, ours not to
    2657             :          * reason why, but we do go out of our way to throw a useful error
    2658             :          * message for such cases.
    2659             :          */
    2660        1542 :         if (refwc)
    2661             :         {
    2662          16 :             if (partitionClause)
    2663           0 :                 ereport(ERROR,
    2664             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    2665             :                          errmsg("cannot override PARTITION BY clause of window \"%s\"",
    2666             :                                 windef->refname),
    2667             :                          parser_errposition(pstate, windef->location)));
    2668          16 :             wc->partitionClause = copyObject(refwc->partitionClause);
    2669             :         }
    2670             :         else
    2671        1526 :             wc->partitionClause = partitionClause;
    2672        1542 :         if (refwc)
    2673             :         {
    2674          16 :             if (orderClause && refwc->orderClause)
    2675           0 :                 ereport(ERROR,
    2676             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    2677             :                          errmsg("cannot override ORDER BY clause of window \"%s\"",
    2678             :                                 windef->refname),
    2679             :                          parser_errposition(pstate, windef->location)));
    2680          16 :             if (orderClause)
    2681             :             {
    2682           0 :                 wc->orderClause = orderClause;
    2683           0 :                 wc->copiedOrder = false;
    2684             :             }
    2685             :             else
    2686             :             {
    2687          16 :                 wc->orderClause = copyObject(refwc->orderClause);
    2688          16 :                 wc->copiedOrder = true;
    2689             :             }
    2690             :         }
    2691             :         else
    2692             :         {
    2693        1526 :             wc->orderClause = orderClause;
    2694        1526 :             wc->copiedOrder = false;
    2695             :         }
    2696        1542 :         if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
    2697             :         {
    2698             :             /*
    2699             :              * Use this message if this is a WINDOW clause, or if it's an OVER
    2700             :              * clause that includes ORDER BY or framing clauses.  (We already
    2701             :              * rejected PARTITION BY above, so no need to check that.)
    2702             :              */
    2703           0 :             if (windef->name ||
    2704           0 :                 orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
    2705           0 :                 ereport(ERROR,
    2706             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    2707             :                          errmsg("cannot copy window \"%s\" because it has a frame clause",
    2708             :                                 windef->refname),
    2709             :                          parser_errposition(pstate, windef->location)));
    2710             :             /* Else this clause is just OVER (foo), so say this: */
    2711           0 :             ereport(ERROR,
    2712             :                     (errcode(ERRCODE_WINDOWING_ERROR),
    2713             :                      errmsg("cannot copy window \"%s\" because it has a frame clause",
    2714             :                             windef->refname),
    2715             :                      errhint("Omit the parentheses in this OVER clause."),
    2716             :                      parser_errposition(pstate, windef->location)));
    2717             :         }
    2718        1542 :         wc->frameOptions = windef->frameOptions;
    2719             : 
    2720             :         /*
    2721             :          * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
    2722             :          * column; check that and get its sort opfamily info.
    2723             :          */
    2724        2652 :         if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
    2725        1110 :             (wc->frameOptions & (FRAMEOPTION_START_OFFSET |
    2726             :                                  FRAMEOPTION_END_OFFSET)))
    2727             :         {
    2728             :             SortGroupClause *sortcl;
    2729             :             Node       *sortkey;
    2730             :             int16       rangestrategy;
    2731             : 
    2732         296 :             if (list_length(wc->orderClause) != 1)
    2733          12 :                 ereport(ERROR,
    2734             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    2735             :                          errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
    2736             :                          parser_errposition(pstate, windef->location)));
    2737         284 :             sortcl = castNode(SortGroupClause, linitial(wc->orderClause));
    2738         284 :             sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
    2739             :             /* Find the sort operator in pg_amop */
    2740         284 :             if (!get_ordering_op_properties(sortcl->sortop,
    2741             :                                             &rangeopfamily,
    2742             :                                             &rangeopcintype,
    2743             :                                             &rangestrategy))
    2744           0 :                 elog(ERROR, "operator %u is not a valid ordering operator",
    2745             :                      sortcl->sortop);
    2746             :             /* Record properties of sort ordering */
    2747         284 :             wc->inRangeColl = exprCollation(sortkey);
    2748         284 :             wc->inRangeAsc = (rangestrategy == BTLessStrategyNumber);
    2749         284 :             wc->inRangeNullsFirst = sortcl->nulls_first;
    2750             :         }
    2751             : 
    2752             :         /* Per spec, GROUPS mode requires an ORDER BY clause */
    2753        1530 :         if (wc->frameOptions & FRAMEOPTION_GROUPS)
    2754             :         {
    2755         116 :             if (wc->orderClause == NIL)
    2756           4 :                 ereport(ERROR,
    2757             :                         (errcode(ERRCODE_WINDOWING_ERROR),
    2758             :                          errmsg("GROUPS mode requires an ORDER BY clause"),
    2759             :                          parser_errposition(pstate, windef->location)));
    2760             :         }
    2761             : 
    2762             :         /* Process frame offset expressions */
    2763        1526 :         wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
    2764             :                                                rangeopfamily, rangeopcintype,
    2765             :                                                &wc->startInRangeFunc,
    2766             :                                                windef->startOffset);
    2767        1514 :         wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
    2768             :                                              rangeopfamily, rangeopcintype,
    2769             :                                              &wc->endInRangeFunc,
    2770             :                                              windef->endOffset);
    2771        1510 :         wc->winref = winref;
    2772             : 
    2773        1510 :         result = lappend(result, wc);
    2774             :     }
    2775             : 
    2776      339232 :     return result;
    2777             : }
    2778             : 
    2779             : /*
    2780             :  * transformDistinctClause -
    2781             :  *    transform a DISTINCT clause
    2782             :  *
    2783             :  * Since we may need to add items to the query's targetlist, that list
    2784             :  * is passed by reference.
    2785             :  *
    2786             :  * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
    2787             :  * possible into the distinctClause.  This avoids a possible need to re-sort,
    2788             :  * and allows the user to choose the equality semantics used by DISTINCT,
    2789             :  * should she be working with a datatype that has more than one equality
    2790             :  * operator.
    2791             :  *
    2792             :  * is_agg is true if we are transforming an aggregate(DISTINCT ...)
    2793             :  * function call.  This does not affect any behavior, only the phrasing
    2794             :  * of error messages.
    2795             :  */
    2796             : List *
    2797        1946 : transformDistinctClause(ParseState *pstate,
    2798             :                         List **targetlist, List *sortClause, bool is_agg)
    2799             : {
    2800        1946 :     List       *result = NIL;
    2801             :     ListCell   *slitem;
    2802             :     ListCell   *tlitem;
    2803             : 
    2804             :     /*
    2805             :      * The distinctClause should consist of all ORDER BY items followed by all
    2806             :      * other non-resjunk targetlist items.  There must not be any resjunk
    2807             :      * ORDER BY items --- that would imply that we are sorting by a value that
    2808             :      * isn't necessarily unique within a DISTINCT group, so the results
    2809             :      * wouldn't be well-defined.  This construction ensures we follow the rule
    2810             :      * that sortClause and distinctClause match; in fact the sortClause will
    2811             :      * always be a prefix of distinctClause.
    2812             :      *
    2813             :      * Note a corner case: the same TLE could be in the ORDER BY list multiple
    2814             :      * times with different sortops.  We have to include it in the
    2815             :      * distinctClause the same way to preserve the prefix property. The net
    2816             :      * effect will be that the TLE value will be made unique according to both
    2817             :      * sortops.
    2818             :      */
    2819        2284 :     foreach(slitem, sortClause)
    2820             :     {
    2821         362 :         SortGroupClause *scl = (SortGroupClause *) lfirst(slitem);
    2822         362 :         TargetEntry *tle = get_sortgroupclause_tle(scl, *targetlist);
    2823             : 
    2824         362 :         if (tle->resjunk)
    2825          24 :             ereport(ERROR,
    2826             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2827             :                      is_agg ?
    2828             :                      errmsg("in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list") :
    2829             :                      errmsg("for SELECT DISTINCT, ORDER BY expressions must appear in select list"),
    2830             :                      parser_errposition(pstate,
    2831             :                                         exprLocation((Node *) tle->expr))));
    2832         338 :         result = lappend(result, copyObject(scl));
    2833             :     }
    2834             : 
    2835             :     /*
    2836             :      * Now add any remaining non-resjunk tlist items, using default sort/group
    2837             :      * semantics for their data types.
    2838             :      */
    2839       10974 :     foreach(tlitem, *targetlist)
    2840             :     {
    2841        9052 :         TargetEntry *tle = (TargetEntry *) lfirst(tlitem);
    2842             : 
    2843        9052 :         if (tle->resjunk)
    2844           4 :             continue;           /* ignore junk */
    2845        9048 :         result = addTargetToGroupList(pstate, tle,
    2846             :                                       result, *targetlist,
    2847        9048 :                                       exprLocation((Node *) tle->expr));
    2848             :     }
    2849             : 
    2850             :     /*
    2851             :      * Complain if we found nothing to make DISTINCT.  Returning an empty list
    2852             :      * would cause the parsed Query to look like it didn't have DISTINCT, with
    2853             :      * results that would probably surprise the user.  Note: this case is
    2854             :      * presently impossible for aggregates because of grammar restrictions,
    2855             :      * but we check anyway.
    2856             :      */
    2857        1922 :     if (result == NIL)
    2858           0 :         ereport(ERROR,
    2859             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2860             :                  is_agg ?
    2861             :                  errmsg("an aggregate with DISTINCT must have at least one argument") :
    2862             :                  errmsg("SELECT DISTINCT must have at least one column")));
    2863             : 
    2864        1922 :     return result;
    2865             : }
    2866             : 
    2867             : /*
    2868             :  * transformDistinctOnClause -
    2869             :  *    transform a DISTINCT ON clause
    2870             :  *
    2871             :  * Since we may need to add items to the query's targetlist, that list
    2872             :  * is passed by reference.
    2873             :  *
    2874             :  * As with GROUP BY, we absorb the sorting semantics of ORDER BY as much as
    2875             :  * possible into the distinctClause.  This avoids a possible need to re-sort,
    2876             :  * and allows the user to choose the equality semantics used by DISTINCT,
    2877             :  * should she be working with a datatype that has more than one equality
    2878             :  * operator.
    2879             :  */
    2880             : List *
    2881          44 : transformDistinctOnClause(ParseState *pstate, List *distinctlist,
    2882             :                           List **targetlist, List *sortClause)
    2883             : {
    2884          44 :     List       *result = NIL;
    2885          44 :     List       *sortgrouprefs = NIL;
    2886             :     bool        skipped_sortitem;
    2887             :     ListCell   *lc;
    2888             :     ListCell   *lc2;
    2889             : 
    2890             :     /*
    2891             :      * Add all the DISTINCT ON expressions to the tlist (if not already
    2892             :      * present, they are added as resjunk items).  Assign sortgroupref numbers
    2893             :      * to them, and make a list of these numbers.  (NB: we rely below on the
    2894             :      * sortgrouprefs list being one-for-one with the original distinctlist.
    2895             :      * Also notice that we could have duplicate DISTINCT ON expressions and
    2896             :      * hence duplicate entries in sortgrouprefs.)
    2897             :      */
    2898         100 :     foreach(lc, distinctlist)
    2899             :     {
    2900          60 :         Node       *dexpr = (Node *) lfirst(lc);
    2901             :         int         sortgroupref;
    2902             :         TargetEntry *tle;
    2903             : 
    2904          60 :         tle = findTargetlistEntrySQL92(pstate, dexpr, targetlist,
    2905             :                                        EXPR_KIND_DISTINCT_ON);
    2906          56 :         sortgroupref = assignSortGroupRef(tle, *targetlist);
    2907          56 :         sortgrouprefs = lappend_int(sortgrouprefs, sortgroupref);
    2908             :     }
    2909             : 
    2910             :     /*
    2911             :      * If the user writes both DISTINCT ON and ORDER BY, adopt the sorting
    2912             :      * semantics from ORDER BY items that match DISTINCT ON items, and also
    2913             :      * adopt their column sort order.  We insist that the distinctClause and
    2914             :      * sortClause match, so throw error if we find the need to add any more
    2915             :      * distinctClause items after we've skipped an ORDER BY item that wasn't
    2916             :      * in DISTINCT ON.
    2917             :      */
    2918          40 :     skipped_sortitem = false;
    2919         112 :     foreach(lc, sortClause)
    2920             :     {
    2921          76 :         SortGroupClause *scl = (SortGroupClause *) lfirst(lc);
    2922             : 
    2923          76 :         if (list_member_int(sortgrouprefs, scl->tleSortGroupRef))
    2924             :         {
    2925          44 :             if (skipped_sortitem)
    2926           4 :                 ereport(ERROR,
    2927             :                         (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2928             :                          errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
    2929             :                          parser_errposition(pstate,
    2930             :                                             get_matching_location(scl->tleSortGroupRef,
    2931             :                                                                   sortgrouprefs,
    2932             :                                                                   distinctlist))));
    2933             :             else
    2934          40 :                 result = lappend(result, copyObject(scl));
    2935             :         }
    2936             :         else
    2937          32 :             skipped_sortitem = true;
    2938             :     }
    2939             : 
    2940             :     /*
    2941             :      * Now add any remaining DISTINCT ON items, using default sort/group
    2942             :      * semantics for their data types.  (Note: this is pretty questionable; if
    2943             :      * the ORDER BY list doesn't include all the DISTINCT ON items and more
    2944             :      * besides, you certainly aren't using DISTINCT ON in the intended way,
    2945             :      * and you probably aren't going to get consistent results.  It might be
    2946             :      * better to throw an error or warning here.  But historically we've
    2947             :      * allowed it, so keep doing so.)
    2948             :      */
    2949          84 :     forboth(lc, distinctlist, lc2, sortgrouprefs)
    2950             :     {
    2951          48 :         Node       *dexpr = (Node *) lfirst(lc);
    2952          48 :         int         sortgroupref = lfirst_int(lc2);
    2953          48 :         TargetEntry *tle = get_sortgroupref_tle(sortgroupref, *targetlist);
    2954             : 
    2955          48 :         if (targetIsInSortList(tle, InvalidOid, result))
    2956          36 :             continue;           /* already in list (with some semantics) */
    2957          12 :         if (skipped_sortitem)
    2958           0 :             ereport(ERROR,
    2959             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2960             :                      errmsg("SELECT DISTINCT ON expressions must match initial ORDER BY expressions"),
    2961             :                      parser_errposition(pstate, exprLocation(dexpr))));
    2962          12 :         result = addTargetToGroupList(pstate, tle,
    2963             :                                       result, *targetlist,
    2964             :                                       exprLocation(dexpr));
    2965             :     }
    2966             : 
    2967             :     /*
    2968             :      * An empty result list is impossible here because of grammar
    2969             :      * restrictions.
    2970             :      */
    2971             :     Assert(result != NIL);
    2972             : 
    2973          36 :     return result;
    2974             : }
    2975             : 
    2976             : /*
    2977             :  * get_matching_location
    2978             :  *      Get the exprLocation of the exprs member corresponding to the
    2979             :  *      (first) member of sortgrouprefs that equals sortgroupref.
    2980             :  *
    2981             :  * This is used so that we can point at a troublesome DISTINCT ON entry.
    2982             :  * (Note that we need to use the original untransformed DISTINCT ON list
    2983             :  * item, as whatever TLE it corresponds to will very possibly have a
    2984             :  * parse location pointing to some matching entry in the SELECT list
    2985             :  * or ORDER BY list.)
    2986             :  */
    2987             : static int
    2988           4 : get_matching_location(int sortgroupref, List *sortgrouprefs, List *exprs)
    2989             : {
    2990             :     ListCell   *lcs;
    2991             :     ListCell   *lce;
    2992             : 
    2993           8 :     forboth(lcs, sortgrouprefs, lce, exprs)
    2994             :     {
    2995           8 :         if (lfirst_int(lcs) == sortgroupref)
    2996           4 :             return exprLocation((Node *) lfirst(lce));
    2997             :     }
    2998             :     /* if no match, caller blew it */
    2999           0 :     elog(ERROR, "get_matching_location: no matching sortgroupref");
    3000             :     return -1;                  /* keep compiler quiet */
    3001             : }
    3002             : 
    3003             : /*
    3004             :  * resolve_unique_index_expr
    3005             :  *      Infer a unique index from a list of indexElems, for ON
    3006             :  *      CONFLICT clause
    3007             :  *
    3008             :  * Perform parse analysis of expressions and columns appearing within ON
    3009             :  * CONFLICT clause.  During planning, the returned list of expressions is used
    3010             :  * to infer which unique index to use.
    3011             :  */
    3012             : static List *
    3013         836 : resolve_unique_index_expr(ParseState *pstate, InferClause *infer,
    3014             :                           Relation heapRel)
    3015             : {
    3016         836 :     List       *result = NIL;
    3017             :     ListCell   *l;
    3018             : 
    3019        1864 :     foreach(l, infer->indexElems)
    3020             :     {
    3021        1032 :         IndexElem  *ielem = (IndexElem *) lfirst(l);
    3022        1032 :         InferenceElem *pInfer = makeNode(InferenceElem);
    3023             :         Node       *parse;
    3024             : 
    3025             :         /*
    3026             :          * Raw grammar re-uses CREATE INDEX infrastructure for unique index
    3027             :          * inference clause, and so will accept opclasses by name and so on.
    3028             :          *
    3029             :          * Make no attempt to match ASC or DESC ordering or NULLS FIRST/NULLS
    3030             :          * LAST ordering, since those are not significant for inference
    3031             :          * purposes (any unique index matching the inference specification in
    3032             :          * other regards is accepted indifferently).  Actively reject this as
    3033             :          * wrong-headed.
    3034             :          */
    3035        1032 :         if (ielem->ordering != SORTBY_DEFAULT)
    3036           0 :             ereport(ERROR,
    3037             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3038             :                      errmsg("ASC/DESC is not allowed in ON CONFLICT clause"),
    3039             :                      parser_errposition(pstate,
    3040             :                                         exprLocation((Node *) infer))));
    3041        1032 :         if (ielem->nulls_ordering != SORTBY_NULLS_DEFAULT)
    3042           0 :             ereport(ERROR,
    3043             :                     (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    3044             :                      errmsg("NULLS FIRST/LAST is not allowed in ON CONFLICT clause"),
    3045             :                      parser_errposition(pstate,
    3046             :                                         exprLocation((Node *) infer))));
    3047             : 
    3048        1032 :         if (!ielem->expr)
    3049             :         {
    3050             :             /* Simple index attribute */
    3051             :             ColumnRef  *n;
    3052             : 
    3053             :             /*
    3054             :              * Grammar won't have built raw expression for us in event of
    3055             :              * plain column reference.  Create one directly, and perform
    3056             :              * expression transformation.  Planner expects this, and performs
    3057             :              * its own normalization for the purposes of matching against
    3058             :              * pg_index.
    3059             :              */
    3060         920 :             n = makeNode(ColumnRef);
    3061         920 :             n->fields = list_make1(makeString(ielem->name));
    3062             :             /* Location is approximately that of inference specification */
    3063         920 :             n->location = infer->location;
    3064         920 :             parse = (Node *) n;
    3065             :         }
    3066             :         else
    3067             :         {
    3068             :             /* Do parse transformation of the raw expression */
    3069         112 :             parse = (Node *) ielem->expr;
    3070             :         }
    3071             : 
    3072             :         /*
    3073             :          * transformExpr() will reject subqueries, aggregates, window
    3074             :          * functions, and SRFs, based on being passed
    3075             :          * EXPR_KIND_INDEX_EXPRESSION.  So we needn't worry about those
    3076             :          * further ... not that they would match any available index
    3077             :          * expression anyway.
    3078             :          */
    3079        1032 :         pInfer->expr = transformExpr(pstate, parse, EXPR_KIND_INDEX_EXPRESSION);
    3080             : 
    3081             :         /* Perform lookup of collation and operator class as required */
    3082        1028 :         if (!ielem->collation)
    3083        1000 :             pInfer->infercollid = InvalidOid;
    3084             :         else
    3085          28 :             pInfer->infercollid = LookupCollation(pstate, ielem->collation,
    3086          28 :                                                   exprLocation(pInfer->expr));
    3087             : 
    3088        1028 :         if (!ielem->opclass)
    3089        1000 :             pInfer->inferopclass = InvalidOid;
    3090             :         else
    3091          28 :             pInfer->inferopclass = get_opclass_oid(BTREE_AM_OID,
    3092             :                                                    ielem->opclass, false);
    3093             : 
    3094        1028 :         result = lappend(result, pInfer);
    3095             :     }
    3096             : 
    3097         832 :     return result;
    3098             : }
    3099             : 
    3100             : /*
    3101             :  * transformOnConflictArbiter -
    3102             :  *      transform arbiter expressions in an ON CONFLICT clause.
    3103             :  *
    3104             :  * Transformed expressions used to infer one unique index relation to serve as
    3105             :  * an ON CONFLICT arbiter.  Partial unique indexes may be inferred using WHERE
    3106             :  * clause from inference specification clause.
    3107             :  */
    3108             : void
    3109        1004 : transformOnConflictArbiter(ParseState *pstate,
    3110             :                            OnConflictClause *onConflictClause,
    3111             :                            List **arbiterExpr, Node **arbiterWhere,
    3112             :                            Oid *constraint)
    3113             : {
    3114        1004 :     InferClause *infer = onConflictClause->infer;
    3115             : 
    3116        1004 :     *arbiterExpr = NIL;
    3117        1004 :     *arbiterWhere = NULL;
    3118        1004 :     *constraint = InvalidOid;
    3119             : 
    3120        1004 :     if (onConflictClause->action == ONCONFLICT_UPDATE && !infer)
    3121           4 :         ereport(ERROR,
    3122             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3123             :                  errmsg("ON CONFLICT DO UPDATE requires inference specification or constraint name"),
    3124             :                  errhint("For example, ON CONFLICT (column_name)."),
    3125             :                  parser_errposition(pstate,
    3126             :                                     exprLocation((Node *) onConflictClause))));
    3127             : 
    3128             :     /*
    3129             :      * To simplify certain aspects of its design, speculative insertion into
    3130             :      * system catalogs is disallowed
    3131             :      */
    3132        1000 :     if (IsCatalogRelation(pstate->p_target_relation))
    3133           0 :         ereport(ERROR,
    3134             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3135             :                  errmsg("ON CONFLICT is not supported with system catalog tables"),
    3136             :                  parser_errposition(pstate,
    3137             :                                     exprLocation((Node *) onConflictClause))));
    3138             : 
    3139             :     /* Same applies to table used by logical decoding as catalog table */
    3140        1000 :     if (RelationIsUsedAsCatalogTable(pstate->p_target_relation))
    3141           0 :         ereport(ERROR,
    3142             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3143             :                  errmsg("ON CONFLICT is not supported on table \"%s\" used as a catalog table",
    3144             :                         RelationGetRelationName(pstate->p_target_relation)),
    3145             :                  parser_errposition(pstate,
    3146             :                                     exprLocation((Node *) onConflictClause))));
    3147             : 
    3148             :     /* ON CONFLICT DO NOTHING does not require an inference clause */
    3149        1000 :     if (infer)
    3150             :     {
    3151             :         List       *save_namespace;
    3152             : 
    3153             :         /*
    3154             :          * While we process the arbiter expressions, accept only non-qualified
    3155             :          * references to the target table. Hide any other relations.
    3156             :          */
    3157         868 :         save_namespace = pstate->p_namespace;
    3158         868 :         pstate->p_namespace = NIL;
    3159         868 :         addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
    3160             :                       false, false, true);
    3161             : 
    3162         868 :         if (infer->indexElems)
    3163         836 :             *arbiterExpr = resolve_unique_index_expr(pstate, infer,
    3164             :                                                      pstate->p_target_relation);
    3165             : 
    3166             :         /*
    3167             :          * Handling inference WHERE clause (for partial unique index
    3168             :          * inference)
    3169             :          */
    3170         864 :         if (infer->whereClause)
    3171          28 :             *arbiterWhere = transformExpr(pstate, infer->whereClause,
    3172             :                                           EXPR_KIND_INDEX_PREDICATE);
    3173             : 
    3174         864 :         pstate->p_namespace = save_namespace;
    3175             : 
    3176             :         /*
    3177             :          * If the arbiter is specified by constraint name, get the constraint
    3178             :          * OID and mark the constrained columns as requiring SELECT privilege,
    3179             :          * in the same way as would have happened if the arbiter had been
    3180             :          * specified by explicit reference to the constraint's index columns.
    3181             :          */
    3182         864 :         if (infer->conname)
    3183             :         {
    3184          32 :             Oid         relid = RelationGetRelid(pstate->p_target_relation);
    3185          32 :             RangeTblEntry *rte = pstate->p_target_rangetblentry;
    3186             :             Bitmapset  *conattnos;
    3187             : 
    3188          32 :             conattnos = get_relation_constraint_attnos(relid, infer->conname,
    3189             :                                                        false, constraint);
    3190             : 
    3191             :             /* Make sure the rel as a whole is marked for SELECT access */
    3192          32 :             rte->requiredPerms |= ACL_SELECT;
    3193             :             /* Mark the constrained columns as requiring SELECT access */
    3194          32 :             rte->selectedCols = bms_add_members(rte->selectedCols, conattnos);
    3195             :         }
    3196             :     }
    3197             : 
    3198             :     /*
    3199             :      * It's convenient to form a list of expressions based on the
    3200             :      * representation used by CREATE INDEX, since the same restrictions are
    3201             :      * appropriate (e.g. on subqueries).  However, from here on, a dedicated
    3202             :      * primnode representation is used for inference elements, and so
    3203             :      * assign_query_collations() can be trusted to do the right thing with the
    3204             :      * post parse analysis query tree inference clause representation.
    3205             :      */
    3206         996 : }
    3207             : 
    3208             : /*
    3209             :  * addTargetToSortList
    3210             :  *      If the given targetlist entry isn't already in the SortGroupClause
    3211             :  *      list, add it to the end of the list, using the given sort ordering
    3212             :  *      info.
    3213             :  *
    3214             :  * Returns the updated SortGroupClause list.
    3215             :  */
    3216             : List *
    3217       59304 : addTargetToSortList(ParseState *pstate, TargetEntry *tle,
    3218             :                     List *sortlist, List *targetlist, SortBy *sortby)
    3219             : {
    3220       59304 :     Oid         restype = exprType((Node *) tle->expr);
    3221             :     Oid         sortop;
    3222             :     Oid         eqop;
    3223             :     bool        hashable;
    3224             :     bool        reverse;
    3225             :     int         location;
    3226             :     ParseCallbackState pcbstate;
    3227             : 
    3228             :     /* if tlist item is an UNKNOWN literal, change it to TEXT */
    3229       59304 :     if (restype == UNKNOWNOID)
    3230             :     {
    3231           8 :         tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
    3232             :                                          restype, TEXTOID, -1,
    3233             :                                          COERCION_IMPLICIT,
    3234             :                                          COERCE_IMPLICIT_CAST,
    3235             :                                          -1);
    3236           8 :         restype = TEXTOID;
    3237             :     }
    3238             : 
    3239             :     /*
    3240             :      * Rather than clutter the API of get_sort_group_operators and the other
    3241             :      * functions we're about to use, make use of error context callback to
    3242             :      * mark any error reports with a parse position.  We point to the operator
    3243             :      * location if present, else to the expression being sorted.  (NB: use the
    3244             :      * original untransformed expression here; the TLE entry might well point
    3245             :      * at a duplicate expression in the regular SELECT list.)
    3246             :      */
    3247       59304 :     location = sortby->location;
    3248       59304 :     if (location < 0)
    3249       59158 :         location = exprLocation(sortby->node);
    3250       59304 :     setup_parser_errposition_callback(&pcbstate, pstate, location);
    3251             : 
    3252             :     /* determine the sortop, eqop, and directionality */
    3253       59304 :     switch (sortby->sortby_dir)
    3254             :     {
    3255             :         case SORTBY_DEFAULT:
    3256             :         case SORTBY_ASC:
    3257       57590 :             get_sort_group_operators(restype,
    3258             :                                      true, true, false,
    3259             :                                      &sortop, &eqop, NULL,
    3260             :                                      &hashable);
    3261       57586 :             reverse = false;
    3262       57586 :             break;
    3263             :         case SORTBY_DESC:
    3264        1568 :             get_sort_group_operators(restype,
    3265             :                                      false, true, true,
    3266             :                                      NULL, &eqop, &sortop,
    3267             :                                      &hashable);
    3268        1568 :             reverse = true;
    3269        1568 :             break;
    3270             :         case SORTBY_USING:
    3271             :             Assert(sortby->useOp != NIL);
    3272         146 :             sortop = compatible_oper_opid(sortby->useOp,
    3273             :                                           restype,
    3274             :                                           restype,
    3275             :                                           false);
    3276             : 
    3277             :             /*
    3278             :              * Verify it's a valid ordering operator, fetch the corresponding
    3279             :              * equality operator, and determine whether to consider it like
    3280             :              * ASC or DESC.
    3281             :              */
    3282         146 :             eqop = get_equality_op_for_ordering_op(sortop, &reverse);
    3283         146 :             if (!OidIsValid(eqop))
    3284           0 :                 ereport(ERROR,
    3285             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    3286             :                          errmsg("operator %s is not a valid ordering operator",
    3287             :                                 strVal(llast(sortby->useOp))),
    3288             :                          errhint("Ordering operators must be \"<\" or \">\" members of btree operator families.")));
    3289             : 
    3290             :             /*
    3291             :              * Also see if the equality operator is hashable.
    3292             :              */
    3293         146 :             hashable = op_hashjoinable(eqop, restype);
    3294         146 :             break;
    3295             :         default:
    3296           0 :             elog(ERROR, "unrecognized sortby_dir: %d", sortby->sortby_dir);
    3297             :             sortop = InvalidOid;    /* keep compiler quiet */
    3298             :             eqop = InvalidOid;
    3299             :             hashable = false;
    3300             :             reverse = false;
    3301             :             break;
    3302             :     }
    3303             : 
    3304       59300 :     cancel_parser_errposition_callback(&pcbstate);
    3305             : 
    3306             :     /* avoid making duplicate sortlist entries */
    3307       59300 :     if (!targetIsInSortList(tle, sortop, sortlist))
    3308             :     {
    3309       59300 :         SortGroupClause *sortcl = makeNode(SortGroupClause);
    3310             : 
    3311       59300 :         sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
    3312             : 
    3313       59300 :         sortcl->eqop = eqop;
    3314       59300 :         sortcl->sortop = sortop;
    3315       59300 :         sortcl->hashable = hashable;
    3316             : 
    3317       59300 :         switch (sortby->sortby_nulls)
    3318             :         {
    3319             :             case SORTBY_NULLS_DEFAULT:
    3320             :                 /* NULLS FIRST is default for DESC; other way for ASC */
    3321       58034 :                 sortcl->nulls_first = reverse;
    3322       58034 :                 break;
    3323             :             case SORTBY_NULLS_FIRST:
    3324         112 :                 sortcl->nulls_first = true;
    3325         112 :                 break;
    3326             :             case SORTBY_NULLS_LAST:
    3327        1154 :                 sortcl->nulls_first = false;
    3328        1154 :                 break;
    3329             :             default:
    3330           0 :                 elog(ERROR, "unrecognized sortby_nulls: %d",
    3331             :                      sortby->sortby_nulls);
    3332             :                 break;
    3333             :         }
    3334             : 
    3335       59300 :         sortlist = lappend(sortlist, sortcl);
    3336             :     }
    3337             : 
    3338       59300 :     return sortlist;
    3339             : }
    3340             : 
    3341             : /*
    3342             :  * addTargetToGroupList
    3343             :  *      If the given targetlist entry isn't already in the SortGroupClause
    3344             :  *      list, add it to the end of the list, using default sort/group
    3345             :  *      semantics.
    3346             :  *
    3347             :  * This is very similar to addTargetToSortList, except that we allow the
    3348             :  * case where only a grouping (equality) operator can be found, and that
    3349             :  * the TLE is considered "already in the list" if it appears there with any
    3350             :  * sorting semantics.
    3351             :  *
    3352             :  * location is the parse location to be fingered in event of trouble.  Note
    3353             :  * that we can't rely on exprLocation(tle->expr), because that might point
    3354             :  * to a SELECT item that matches the GROUP BY item; it'd be pretty confusing
    3355             :  * to report such a location.
    3356             :  *
    3357             :  * Returns the updated SortGroupClause list.
    3358             :  */
    3359             : static List *
    3360       16472 : addTargetToGroupList(ParseState *pstate, TargetEntry *tle,
    3361             :                      List *grouplist, List *targetlist, int location)
    3362             : {
    3363       16472 :     Oid         restype = exprType((Node *) tle->expr);
    3364             : 
    3365             :     /* if tlist item is an UNKNOWN literal, change it to TEXT */
    3366       16472 :     if (restype == UNKNOWNOID)
    3367             :     {
    3368           0 :         tle->expr = (Expr *) coerce_type(pstate, (Node *) tle->expr,
    3369             :                                          restype, TEXTOID, -1,
    3370             :                                          COERCION_IMPLICIT,
    3371             :                                          COERCE_IMPLICIT_CAST,
    3372             :                                          -1);
    3373           0 :         restype = TEXTOID;
    3374             :     }
    3375             : 
    3376             :     /* avoid making duplicate grouplist entries */
    3377       16472 :     if (!targetIsInSortList(tle, InvalidOid, grouplist))
    3378             :     {
    3379       16150 :         SortGroupClause *grpcl = makeNode(SortGroupClause);
    3380             :         Oid         sortop;
    3381             :         Oid         eqop;
    3382             :         bool        hashable;
    3383             :         ParseCallbackState pcbstate;
    3384             : 
    3385       16150 :         setup_parser_errposition_callback(&pcbstate, pstate, location);
    3386             : 
    3387             :         /* determine the eqop and optional sortop */
    3388       16150 :         get_sort_group_operators(restype,
    3389             :                                  false, true, false,
    3390             :                                  &sortop, &eqop, NULL,
    3391             :                                  &hashable);
    3392             : 
    3393       16150 :         cancel_parser_errposition_callback(&pcbstate);
    3394             : 
    3395       16150 :         grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
    3396       16150 :         grpcl->eqop = eqop;
    3397       16150 :         grpcl->sortop = sortop;
    3398       16150 :         grpcl->nulls_first = false; /* OK with or without sortop */
    3399       16150 :         grpcl->hashable = hashable;
    3400             : 
    3401       16150 :         grouplist = lappend(grouplist, grpcl);
    3402             :     }
    3403             : 
    3404       16472 :     return grouplist;
    3405             : }
    3406             : 
    3407             : /*
    3408             :  * assignSortGroupRef
    3409             :  *    Assign the targetentry an unused ressortgroupref, if it doesn't
    3410             :  *    already have one.  Return the assigned or pre-existing refnumber.
    3411             :  *
    3412             :  * 'tlist' is the targetlist containing (or to contain) the given targetentry.
    3413             :  */
    3414             : Index
    3415       76282 : assignSortGroupRef(TargetEntry *tle, List *tlist)
    3416             : {
    3417             :     Index       maxRef;
    3418             :     ListCell   *l;
    3419             : 
    3420       76282 :     if (tle->ressortgroupref)    /* already has one? */
    3421         228 :         return tle->ressortgroupref;
    3422             : 
    3423             :     /* easiest way to pick an unused refnumber: max used + 1 */
    3424       76054 :     maxRef = 0;
    3425      547062 :     foreach(l, tlist)
    3426             :     {
    3427      471008 :         Index       ref = ((TargetEntry *) lfirst(l))->ressortgroupref;
    3428             : 
    3429      471008 :         if (ref > maxRef)
    3430       48338 :             maxRef = ref;
    3431             :     }
    3432       76054 :     tle->ressortgroupref = maxRef + 1;
    3433       76054 :     return tle->ressortgroupref;
    3434             : }
    3435             : 
    3436             : /*
    3437             :  * targetIsInSortList
    3438             :  *      Is the given target item already in the sortlist?
    3439             :  *      If sortop is not InvalidOid, also test for a match to the sortop.
    3440             :  *
    3441             :  * It is not an oversight that this function ignores the nulls_first flag.
    3442             :  * We check sortop when determining if an ORDER BY item is redundant with
    3443             :  * earlier ORDER BY items, because it's conceivable that "ORDER BY
    3444             :  * foo USING <, foo USING <<<" is not redundant, if <<< distinguishes
    3445             :  * values that < considers equal.  We need not check nulls_first
    3446             :  * however, because a lower-order column with the same sortop but
    3447             :  * opposite nulls direction is redundant.  Also, we can consider
    3448             :  * ORDER BY foo ASC, foo DESC redundant, so check for a commutator match.
    3449             :  *
    3450             :  * Works for both ordering and grouping lists (sortop would normally be
    3451             :  * InvalidOid when considering grouping).  Note that the main reason we need
    3452             :  * this routine (and not just a quick test for nonzeroness of ressortgroupref)
    3453             :  * is that a TLE might be in only one of the lists.
    3454             :  */
    3455             : bool
    3456       77634 : targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
    3457             : {
    3458       77634 :     Index       ref = tle->ressortgroupref;
    3459             :     ListCell   *l;
    3460             : 
    3461             :     /* no need to scan list if tle has no marker */
    3462       77634 :     if (ref == 0)
    3463       75566 :         return false;
    3464             : 
    3465        2576 :     foreach(l, sortList)
    3466             :     {
    3467        1070 :         SortGroupClause *scl = (SortGroupClause *) lfirst(l);
    3468             : 
    3469        1070 :         if (scl->tleSortGroupRef == ref &&
    3470           0 :             (sortop == InvalidOid ||
    3471           0 :              sortop == scl->sortop ||
    3472           0 :              sortop == get_commutator(scl->sortop)))
    3473         562 :             return true;
    3474             :     }
    3475        1506 :     return false;
    3476             : }
    3477             : 
    3478             : /*
    3479             :  * findWindowClause
    3480             :  *      Find the named WindowClause in the list, or return NULL if not there
    3481             :  */
    3482             : static WindowClause *
    3483         248 : findWindowClause(List *wclist, const char *name)
    3484             : {
    3485             :     ListCell   *l;
    3486             : 
    3487         252 :     foreach(l, wclist)
    3488             :     {
    3489          24 :         WindowClause *wc = (WindowClause *) lfirst(l);
    3490             : 
    3491          24 :         if (wc->name && strcmp(wc->name, name) == 0)
    3492          20 :             return wc;
    3493             :     }
    3494             : 
    3495         228 :     return NULL;
    3496             : }
    3497             : 
    3498             : /*
    3499             :  * transformFrameOffset
    3500             :  *      Process a window frame offset expression
    3501             :  *
    3502             :  * In RANGE mode, rangeopfamily is the sort opfamily for the input ORDER BY
    3503             :  * column, and rangeopcintype is the input data type the sort operator is
    3504             :  * registered with.  We expect the in_range function to be registered with
    3505             :  * that same type.  (In binary-compatible cases, it might be different from
    3506             :  * the input column's actual type, so we can't use that for the lookups.)
    3507             :  * We'll return the OID of the in_range function to *inRangeFunc.
    3508             :  */
    3509             : static Node *
    3510        3040 : transformFrameOffset(ParseState *pstate, int frameOptions,
    3511             :                      Oid rangeopfamily, Oid rangeopcintype, Oid *inRangeFunc,
    3512             :                      Node *clause)
    3513             : {
    3514        3040 :     const char *constructName = NULL;
    3515             :     Node       *node;
    3516             : 
    3517        3040 :     *inRangeFunc = InvalidOid;  /* default result */
    3518             : 
    3519             :     /* Quick exit if no offset expression */
    3520        3040 :     if (clause == NULL)
    3521        2140 :         return NULL;
    3522             : 
    3523         900 :     if (frameOptions & FRAMEOPTION_ROWS)
    3524             :     {
    3525             :         /* Transform the raw expression tree */
    3526         200 :         node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_ROWS);
    3527             : 
    3528             :         /*
    3529             :          * Like LIMIT clause, simply coerce to int8
    3530             :          */
    3531         200 :         constructName = "ROWS";
    3532         200 :         node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
    3533             :     }
    3534         700 :     else if (frameOptions & FRAMEOPTION_RANGE)
    3535             :     {
    3536             :         /*
    3537             :          * We must look up the in_range support function that's to be used,
    3538             :          * possibly choosing one of several, and coerce the "offset" value to
    3539             :          * the appropriate input type.
    3540             :          */
    3541             :         Oid         nodeType;
    3542             :         Oid         preferredType;
    3543         512 :         int         nfuncs = 0;
    3544         512 :         int         nmatches = 0;
    3545         512 :         Oid         selectedType = InvalidOid;
    3546         512 :         Oid         selectedFunc = InvalidOid;
    3547             :         CatCList   *proclist;
    3548             :         int         i;
    3549             : 
    3550             :         /* Transform the raw expression tree */
    3551         512 :         node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_RANGE);
    3552         512 :         nodeType = exprType(node);
    3553             : 
    3554             :         /*
    3555             :          * If there are multiple candidates, we'll prefer the one that exactly
    3556             :          * matches nodeType; or if nodeType is as yet unknown, prefer the one
    3557             :          * that exactly matches the sort column type.  (The second rule is
    3558             :          * like what we do for "known_type operator unknown".)
    3559             :          */
    3560         512 :         preferredType = (nodeType != UNKNOWNOID) ? nodeType : rangeopcintype;
    3561             : 
    3562             :         /* Find the in_range support functions applicable to this case */
    3563         512 :         proclist = SearchSysCacheList2(AMPROCNUM,
    3564             :                                        ObjectIdGetDatum(rangeopfamily),
    3565             :                                        ObjectIdGetDatum(rangeopcintype));
    3566        3220 :         for (i = 0; i < proclist->n_members; i++)
    3567             :         {
    3568        2708 :             HeapTuple   proctup = &proclist->members[i]->tuple;
    3569        2708 :             Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
    3570             : 
    3571             :             /* The search will find all support proc types; ignore others */
    3572        2708 :             if (procform->amprocnum != BTINRANGE_PROC)
    3573        1792 :                 continue;
    3574         916 :             nfuncs++;
    3575             : 
    3576             :             /* Ignore function if given value can't be coerced to that type */
    3577         916 :             if (!can_coerce_type(1, &nodeType, &procform->amprocrighttype,
    3578             :                                  COERCION_IMPLICIT))
    3579         220 :                 continue;
    3580         696 :             nmatches++;
    3581             : 
    3582             :             /* Remember preferred match, or any match if didn't find that */
    3583         696 :             if (selectedType != preferredType)
    3584             :             {
    3585         656 :                 selectedType = procform->amprocrighttype;
    3586         656 :                 selectedFunc = procform->amproc;
    3587             :             }
    3588             :         }
    3589         512 :         ReleaseCatCacheList(proclist);
    3590             : 
    3591             :         /*
    3592             :          * Throw error if needed.  It seems worth taking the trouble to
    3593             :          * distinguish "no support at all" from "you didn't match any
    3594             :          * available offset type".
    3595             :          */
    3596         512 :         if (nfuncs == 0)
    3597           4 :             ereport(ERROR,
    3598             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3599             :                      errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s",
    3600             :                             format_type_be(rangeopcintype)),
    3601             :                      parser_errposition(pstate, exprLocation(node))));
    3602         508 :         if (nmatches == 0)
    3603          12 :             ereport(ERROR,
    3604             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3605             :                      errmsg("RANGE with offset PRECEDING/FOLLOWING is not supported for column type %s and offset type %s",
    3606             :                             format_type_be(rangeopcintype),
    3607             :                             format_type_be(nodeType)),
    3608             :                      errhint("Cast the offset value to an appropriate type."),
    3609             :                      parser_errposition(pstate, exprLocation(node))));
    3610         496 :         if (nmatches != 1 && selectedType != preferredType)
    3611           0 :             ereport(ERROR,
    3612             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3613             :                      errmsg("RANGE with offset PRECEDING/FOLLOWING has multiple interpretations for column type %s and offset type %s",
    3614             :                             format_type_be(rangeopcintype),
    3615             :                             format_type_be(nodeType)),
    3616             :                      errhint("Cast the offset value to the exact intended type."),
    3617             :                      parser_errposition(pstate, exprLocation(node))));
    3618             : 
    3619             :         /* OK, coerce the offset to the right type */
    3620         496 :         constructName = "RANGE";
    3621         496 :         node = coerce_to_specific_type(pstate, node,
    3622             :                                        selectedType, constructName);
    3623         496 :         *inRangeFunc = selectedFunc;
    3624             :     }
    3625         188 :     else if (frameOptions & FRAMEOPTION_GROUPS)
    3626             :     {
    3627             :         /* Transform the raw expression tree */
    3628         188 :         node = transformExpr(pstate, clause, EXPR_KIND_WINDOW_FRAME_GROUPS);
    3629             : 
    3630             :         /*
    3631             :          * Like LIMIT clause, simply coerce to int8
    3632             :          */
    3633         188 :         constructName = "GROUPS";
    3634         188 :         node = coerce_to_specific_type(pstate, node, INT8OID, constructName);
    3635             :     }
    3636             :     else
    3637             :     {
    3638             :         Assert(false);
    3639           0 :         node = NULL;
    3640             :     }
    3641             : 
    3642             :     /* Disallow variables in frame offsets */
    3643         884 :     checkExprIsVarFree(pstate, node, constructName);
    3644             : 
    3645         884 :     return node;
    3646             : }

Generated by: LCOV version 1.13