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

Generated by: LCOV version 1.14