LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_clause.c (source / functions) Coverage Total Hit UBC GBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 94.1 % 1123 1057 66 1 1056 1
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 43 43 1 42
Baseline: lcov-20260827-baseline Branches: 73.8 % 992 732 260 1 731
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 16 16 1 15
(30,360] days: 98.2 % 57 56 1 56
(360..) days: 93.8 % 1050 985 65 985
Function coverage date bins:
(30,360] days: 100.0 % 3 3 3
(360..) days: 100.0 % 40 40 1 39
Branch coverage date bins:
(7,30] days: 75.0 % 12 9 3 9
(30,360] days: 73.7 % 38 28 10 28
(360..) days: 73.8 % 942 695 247 1 694

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

Generated by: LCOV version 2.0-1