LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_clause.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 93.5 % 1058 989 69 5 984 2
Current Date: 2024-04-14 14:21:10 Functions: 100.0 % 41 41 2 39
Baseline: 16@8cea358b128 Branches: 73.2 % 944 691 253 6 685
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 100.0 % 5 5 5
(240..) days: 93.4 % 1053 984 69 984
Function coverage date bins:
(240..) days: 100.0 % 41 41 2 39
Branch coverage date bins:
[..60] days: 100.0 % 6 6 6
(240..) days: 73.0 % 938 685 253 685

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

Generated by: LCOV version 2.1-beta2-3-g6141622