LCOV - code coverage report
Current view: top level - src/backend/parser - parse_relation.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 969 1121 86.4 %
Date: 2020-05-25 06:06:29 Functions: 53 53 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_relation.c
       4             :  *    parser support routines dealing with relations
       5             :  *
       6             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/parser/parse_relation.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include <ctype.h>
      18             : 
      19             : #include "access/htup_details.h"
      20             : #include "access/relation.h"
      21             : #include "access/sysattr.h"
      22             : #include "access/table.h"
      23             : #include "catalog/heap.h"
      24             : #include "catalog/namespace.h"
      25             : #include "catalog/pg_type.h"
      26             : #include "funcapi.h"
      27             : #include "nodes/makefuncs.h"
      28             : #include "nodes/nodeFuncs.h"
      29             : #include "parser/parse_enr.h"
      30             : #include "parser/parse_relation.h"
      31             : #include "parser/parse_type.h"
      32             : #include "parser/parsetree.h"
      33             : #include "storage/lmgr.h"
      34             : #include "utils/builtins.h"
      35             : #include "utils/lsyscache.h"
      36             : #include "utils/rel.h"
      37             : #include "utils/syscache.h"
      38             : #include "utils/varlena.h"
      39             : 
      40             : 
      41             : /*
      42             :  * Support for fuzzily matching columns.
      43             :  *
      44             :  * This is for building diagnostic messages, where non-exact matching
      45             :  * attributes are suggested to the user.  The struct's fields may be facets of
      46             :  * a particular RTE, or of an entire range table, depending on context.
      47             :  */
      48             : typedef struct
      49             : {
      50             :     int         distance;       /* Weighted distance (lowest so far) */
      51             :     RangeTblEntry *rfirst;      /* RTE of first */
      52             :     AttrNumber  first;          /* Closest attribute so far */
      53             :     RangeTblEntry *rsecond;     /* RTE of second */
      54             :     AttrNumber  second;         /* Second closest attribute so far */
      55             : } FuzzyAttrMatchState;
      56             : 
      57             : #define MAX_FUZZY_DISTANCE              3
      58             : 
      59             : 
      60             : static ParseNamespaceItem *scanNameSpaceForRefname(ParseState *pstate,
      61             :                                                    const char *refname,
      62             :                                                    int location);
      63             : static ParseNamespaceItem *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
      64             :                                                  int location);
      65             : static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
      66             :                                  int location);
      67             : static int  scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
      68             :                              const char *colname, int location,
      69             :                              int fuzzy_rte_penalty,
      70             :                              FuzzyAttrMatchState *fuzzystate);
      71             : static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
      72             :                                  int rtindex, AttrNumber col);
      73             : static void expandRelation(Oid relid, Alias *eref,
      74             :                            int rtindex, int sublevels_up,
      75             :                            int location, bool include_dropped,
      76             :                            List **colnames, List **colvars);
      77             : static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
      78             :                             int count, int offset,
      79             :                             int rtindex, int sublevels_up,
      80             :                             int location, bool include_dropped,
      81             :                             List **colnames, List **colvars);
      82             : static int  specialAttNum(const char *attname);
      83             : static bool isQueryUsingTempRelation_walker(Node *node, void *context);
      84             : 
      85             : 
      86             : /*
      87             :  * refnameNamespaceItem
      88             :  *    Given a possibly-qualified refname, look to see if it matches any visible
      89             :  *    namespace item.  If so, return a pointer to the nsitem; else return NULL.
      90             :  *
      91             :  *    Optionally get nsitem's nesting depth (0 = current) into *sublevels_up.
      92             :  *    If sublevels_up is NULL, only consider items at the current nesting
      93             :  *    level.
      94             :  *
      95             :  * An unqualified refname (schemaname == NULL) can match any item with matching
      96             :  * alias, or matching unqualified relname in the case of alias-less relation
      97             :  * items.  It is possible that such a refname matches multiple items in the
      98             :  * nearest nesting level that has a match; if so, we report an error via
      99             :  * ereport().
     100             :  *
     101             :  * A qualified refname (schemaname != NULL) can only match a relation item
     102             :  * that (a) has no alias and (b) is for the same relation identified by
     103             :  * schemaname.refname.  In this case we convert schemaname.refname to a
     104             :  * relation OID and search by relid, rather than by alias name.  This is
     105             :  * peculiar, but it's what SQL says to do.
     106             :  */
     107             : ParseNamespaceItem *
     108     1282344 : refnameNamespaceItem(ParseState *pstate,
     109             :                      const char *schemaname,
     110             :                      const char *refname,
     111             :                      int location,
     112             :                      int *sublevels_up)
     113             : {
     114     1282344 :     Oid         relId = InvalidOid;
     115             : 
     116     1282344 :     if (sublevels_up)
     117     1282344 :         *sublevels_up = 0;
     118             : 
     119     1282344 :     if (schemaname != NULL)
     120             :     {
     121             :         Oid         namespaceId;
     122             : 
     123             :         /*
     124             :          * We can use LookupNamespaceNoError() here because we are only
     125             :          * interested in finding existing RTEs.  Checking USAGE permission on
     126             :          * the schema is unnecessary since it would have already been checked
     127             :          * when the RTE was made.  Furthermore, we want to report "RTE not
     128             :          * found", not "no permissions for schema", if the name happens to
     129             :          * match a schema name the user hasn't got access to.
     130             :          */
     131          32 :         namespaceId = LookupNamespaceNoError(schemaname);
     132          32 :         if (!OidIsValid(namespaceId))
     133          28 :             return NULL;
     134           4 :         relId = get_relname_relid(refname, namespaceId);
     135           4 :         if (!OidIsValid(relId))
     136           0 :             return NULL;
     137             :     }
     138             : 
     139     1389122 :     while (pstate != NULL)
     140             :     {
     141             :         ParseNamespaceItem *result;
     142             : 
     143     1372516 :         if (OidIsValid(relId))
     144           8 :             result = scanNameSpaceForRelid(pstate, relId, location);
     145             :         else
     146     1372508 :             result = scanNameSpaceForRefname(pstate, refname, location);
     147             : 
     148     1372500 :         if (result)
     149     1265694 :             return result;
     150             : 
     151      106806 :         if (sublevels_up)
     152      106806 :             (*sublevels_up)++;
     153             :         else
     154           0 :             break;
     155             : 
     156      106806 :         pstate = pstate->parentParseState;
     157             :     }
     158       16606 :     return NULL;
     159             : }
     160             : 
     161             : /*
     162             :  * Search the query's table namespace for an item matching the
     163             :  * given unqualified refname.  Return the nsitem if a unique match, or NULL
     164             :  * if no match.  Raise error if multiple matches.
     165             :  *
     166             :  * Note: it might seem that we shouldn't have to worry about the possibility
     167             :  * of multiple matches; after all, the SQL standard disallows duplicate table
     168             :  * aliases within a given SELECT level.  Historically, however, Postgres has
     169             :  * been laxer than that.  For example, we allow
     170             :  *      SELECT ... FROM tab1 x CROSS JOIN (tab2 x CROSS JOIN tab3 y) z
     171             :  * on the grounds that the aliased join (z) hides the aliases within it,
     172             :  * therefore there is no conflict between the two RTEs named "x".  However,
     173             :  * if tab3 is a LATERAL subquery, then from within the subquery both "x"es
     174             :  * are visible.  Rather than rejecting queries that used to work, we allow
     175             :  * this situation, and complain only if there's actually an ambiguous
     176             :  * reference to "x".
     177             :  */
     178             : static ParseNamespaceItem *
     179     1372508 : scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
     180             : {
     181     1372508 :     ParseNamespaceItem *result = NULL;
     182             :     ListCell   *l;
     183             : 
     184     7121670 :     foreach(l, pstate->p_namespace)
     185             :     {
     186     5749178 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
     187     5749178 :         RangeTblEntry *rte = nsitem->p_rte;
     188             : 
     189             :         /* Ignore columns-only items */
     190     5749178 :         if (!nsitem->p_rel_visible)
     191     1655226 :             continue;
     192             :         /* If not inside LATERAL, ignore lateral-only items */
     193     4093952 :         if (nsitem->p_lateral_only && !pstate->p_lateral_active)
     194          32 :             continue;
     195             : 
     196     4093920 :         if (strcmp(rte->eref->aliasname, refname) == 0)
     197             :         {
     198     1265714 :             if (result)
     199           8 :                 ereport(ERROR,
     200             :                         (errcode(ERRCODE_AMBIGUOUS_ALIAS),
     201             :                          errmsg("table reference \"%s\" is ambiguous",
     202             :                                 refname),
     203             :                          parser_errposition(pstate, location)));
     204     1265706 :             check_lateral_ref_ok(pstate, nsitem, location);
     205     1265698 :             result = nsitem;
     206             :         }
     207             :     }
     208     1372492 :     return result;
     209             : }
     210             : 
     211             : /*
     212             :  * Search the query's table namespace for a relation item matching the
     213             :  * given relation OID.  Return the nsitem if a unique match, or NULL
     214             :  * if no match.  Raise error if multiple matches.
     215             :  *
     216             :  * See the comments for refnameNamespaceItem to understand why this
     217             :  * acts the way it does.
     218             :  */
     219             : static ParseNamespaceItem *
     220           8 : scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
     221             : {
     222           8 :     ParseNamespaceItem *result = NULL;
     223             :     ListCell   *l;
     224             : 
     225          16 :     foreach(l, pstate->p_namespace)
     226             :     {
     227           8 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
     228           8 :         RangeTblEntry *rte = nsitem->p_rte;
     229             : 
     230             :         /* Ignore columns-only items */
     231           8 :         if (!nsitem->p_rel_visible)
     232           0 :             continue;
     233             :         /* If not inside LATERAL, ignore lateral-only items */
     234           8 :         if (nsitem->p_lateral_only && !pstate->p_lateral_active)
     235           0 :             continue;
     236             : 
     237             :         /* yes, the test for alias == NULL should be there... */
     238           8 :         if (rte->rtekind == RTE_RELATION &&
     239           8 :             rte->relid == relid &&
     240           4 :             rte->alias == NULL)
     241             :         {
     242           4 :             if (result)
     243           0 :                 ereport(ERROR,
     244             :                         (errcode(ERRCODE_AMBIGUOUS_ALIAS),
     245             :                          errmsg("table reference %u is ambiguous",
     246             :                                 relid),
     247             :                          parser_errposition(pstate, location)));
     248           4 :             check_lateral_ref_ok(pstate, nsitem, location);
     249           4 :             result = nsitem;
     250             :         }
     251             :     }
     252           8 :     return result;
     253             : }
     254             : 
     255             : /*
     256             :  * Search the query's CTE namespace for a CTE matching the given unqualified
     257             :  * refname.  Return the CTE (and its levelsup count) if a match, or NULL
     258             :  * if no match.  We need not worry about multiple matches, since parse_cte.c
     259             :  * rejects WITH lists containing duplicate CTE names.
     260             :  */
     261             : CommonTableExpr *
     262      241950 : scanNameSpaceForCTE(ParseState *pstate, const char *refname,
     263             :                     Index *ctelevelsup)
     264             : {
     265             :     Index       levelsup;
     266             : 
     267      585792 :     for (levelsup = 0;
     268             :          pstate != NULL;
     269      343842 :          pstate = pstate->parentParseState, levelsup++)
     270             :     {
     271             :         ListCell   *lc;
     272             : 
     273      348106 :         foreach(lc, pstate->p_ctenamespace)
     274             :         {
     275        4264 :             CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
     276             : 
     277        4264 :             if (strcmp(cte->ctename, refname) == 0)
     278             :             {
     279        1942 :                 *ctelevelsup = levelsup;
     280        1942 :                 return cte;
     281             :             }
     282             :         }
     283             :     }
     284      240008 :     return NULL;
     285             : }
     286             : 
     287             : /*
     288             :  * Search for a possible "future CTE", that is one that is not yet in scope
     289             :  * according to the WITH scoping rules.  This has nothing to do with valid
     290             :  * SQL semantics, but it's important for error reporting purposes.
     291             :  */
     292             : static bool
     293         104 : isFutureCTE(ParseState *pstate, const char *refname)
     294             : {
     295         216 :     for (; pstate != NULL; pstate = pstate->parentParseState)
     296             :     {
     297             :         ListCell   *lc;
     298             : 
     299         116 :         foreach(lc, pstate->p_future_ctes)
     300             :         {
     301           4 :             CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
     302             : 
     303           4 :             if (strcmp(cte->ctename, refname) == 0)
     304           4 :                 return true;
     305             :         }
     306             :     }
     307         100 :     return false;
     308             : }
     309             : 
     310             : /*
     311             :  * Search the query's ephemeral named relation namespace for a relation
     312             :  * matching the given unqualified refname.
     313             :  */
     314             : bool
     315      310220 : scanNameSpaceForENR(ParseState *pstate, const char *refname)
     316             : {
     317      310220 :     return name_matches_visible_ENR(pstate, refname);
     318             : }
     319             : 
     320             : /*
     321             :  * searchRangeTableForRel
     322             :  *    See if any RangeTblEntry could possibly match the RangeVar.
     323             :  *    If so, return a pointer to the RangeTblEntry; else return NULL.
     324             :  *
     325             :  * This is different from refnameNamespaceItem in that it considers every
     326             :  * entry in the ParseState's rangetable(s), not only those that are currently
     327             :  * visible in the p_namespace list(s).  This behavior is invalid per the SQL
     328             :  * spec, and it may give ambiguous results (there might be multiple equally
     329             :  * valid matches, but only one will be returned).  This must be used ONLY
     330             :  * as a heuristic in giving suitable error messages.  See errorMissingRTE.
     331             :  *
     332             :  * Notice that we consider both matches on actual relation (or CTE) name
     333             :  * and matches on alias.
     334             :  */
     335             : static RangeTblEntry *
     336          48 : searchRangeTableForRel(ParseState *pstate, RangeVar *relation)
     337             : {
     338          48 :     const char *refname = relation->relname;
     339          48 :     Oid         relId = InvalidOid;
     340          48 :     CommonTableExpr *cte = NULL;
     341          48 :     bool        isenr = false;
     342          48 :     Index       ctelevelsup = 0;
     343             :     Index       levelsup;
     344             : 
     345             :     /*
     346             :      * If it's an unqualified name, check for possible CTE matches. A CTE
     347             :      * hides any real relation matches.  If no CTE, look for a matching
     348             :      * relation.
     349             :      *
     350             :      * NB: It's not critical that RangeVarGetRelid return the correct answer
     351             :      * here in the face of concurrent DDL.  If it doesn't, the worst case
     352             :      * scenario is a less-clear error message.  Also, the tables involved in
     353             :      * the query are already locked, which reduces the number of cases in
     354             :      * which surprising behavior can occur.  So we do the name lookup
     355             :      * unlocked.
     356             :      */
     357          48 :     if (!relation->schemaname)
     358             :     {
     359          48 :         cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
     360          48 :         if (!cte)
     361          48 :             isenr = scanNameSpaceForENR(pstate, refname);
     362             :     }
     363             : 
     364          48 :     if (!cte && !isenr)
     365          48 :         relId = RangeVarGetRelid(relation, NoLock, true);
     366             : 
     367             :     /* Now look for RTEs matching either the relation/CTE/ENR or the alias */
     368          72 :     for (levelsup = 0;
     369             :          pstate != NULL;
     370          24 :          pstate = pstate->parentParseState, levelsup++)
     371             :     {
     372             :         ListCell   *l;
     373             : 
     374          92 :         foreach(l, pstate->p_rtable)
     375             :         {
     376          68 :             RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
     377             : 
     378          68 :             if (rte->rtekind == RTE_RELATION &&
     379          52 :                 OidIsValid(relId) &&
     380          52 :                 rte->relid == relId)
     381          40 :                 return rte;
     382          44 :             if (rte->rtekind == RTE_CTE &&
     383           0 :                 cte != NULL &&
     384           0 :                 rte->ctelevelsup + levelsup == ctelevelsup &&
     385           0 :                 strcmp(rte->ctename, refname) == 0)
     386           0 :                 return rte;
     387          44 :             if (rte->rtekind == RTE_NAMEDTUPLESTORE &&
     388           0 :                 isenr &&
     389           0 :                 strcmp(rte->enrname, refname) == 0)
     390           0 :                 return rte;
     391          44 :             if (strcmp(rte->eref->aliasname, refname) == 0)
     392          16 :                 return rte;
     393             :         }
     394             :     }
     395           8 :     return NULL;
     396             : }
     397             : 
     398             : /*
     399             :  * Check for relation-name conflicts between two namespace lists.
     400             :  * Raise an error if any is found.
     401             :  *
     402             :  * Note: we assume that each given argument does not contain conflicts
     403             :  * itself; we just want to know if the two can be merged together.
     404             :  *
     405             :  * Per SQL, two alias-less plain relation RTEs do not conflict even if
     406             :  * they have the same eref->aliasname (ie, same relation name), if they
     407             :  * are for different relation OIDs (implying they are in different schemas).
     408             :  *
     409             :  * We ignore the lateral-only flags in the namespace items: the lists must
     410             :  * not conflict, even when all items are considered visible.  However,
     411             :  * columns-only items should be ignored.
     412             :  */
     413             : void
     414      419996 : checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
     415             :                         List *namespace2)
     416             : {
     417             :     ListCell   *l1;
     418             : 
     419      749472 :     foreach(l1, namespace1)
     420             :     {
     421      329480 :         ParseNamespaceItem *nsitem1 = (ParseNamespaceItem *) lfirst(l1);
     422      329480 :         RangeTblEntry *rte1 = nsitem1->p_rte;
     423      329480 :         const char *aliasname1 = rte1->eref->aliasname;
     424             :         ListCell   *l2;
     425             : 
     426      329480 :         if (!nsitem1->p_rel_visible)
     427       63834 :             continue;
     428             : 
     429      587812 :         foreach(l2, namespace2)
     430             :         {
     431      322170 :             ParseNamespaceItem *nsitem2 = (ParseNamespaceItem *) lfirst(l2);
     432      322170 :             RangeTblEntry *rte2 = nsitem2->p_rte;
     433             : 
     434      322170 :             if (!nsitem2->p_rel_visible)
     435       28262 :                 continue;
     436      293908 :             if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
     437      293904 :                 continue;       /* definitely no conflict */
     438           4 :             if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
     439           4 :                 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
     440           4 :                 rte1->relid != rte2->relid)
     441           0 :                 continue;       /* no conflict per SQL rule */
     442           4 :             ereport(ERROR,
     443             :                     (errcode(ERRCODE_DUPLICATE_ALIAS),
     444             :                      errmsg("table name \"%s\" specified more than once",
     445             :                             aliasname1)));
     446             :         }
     447             :     }
     448      419992 : }
     449             : 
     450             : /*
     451             :  * Complain if a namespace item is currently disallowed as a LATERAL reference.
     452             :  * This enforces both SQL:2008's rather odd idea of what to do with a LATERAL
     453             :  * reference to the wrong side of an outer join, and our own prohibition on
     454             :  * referencing the target table of an UPDATE or DELETE as a lateral reference
     455             :  * in a FROM/USING clause.
     456             :  *
     457             :  * Note: the pstate should be the same query level the nsitem was found in.
     458             :  *
     459             :  * Convenience subroutine to avoid multiple copies of a rather ugly ereport.
     460             :  */
     461             : static void
     462     1858316 : check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
     463             :                      int location)
     464             : {
     465     1858316 :     if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
     466             :     {
     467             :         /* SQL:2008 demands this be an error, not an invisible item */
     468          16 :         RangeTblEntry *rte = nsitem->p_rte;
     469          16 :         char       *refname = rte->eref->aliasname;
     470             : 
     471          16 :         ereport(ERROR,
     472             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
     473             :                  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
     474             :                         refname),
     475             :                  (pstate->p_target_nsitem != NULL &&
     476             :                   rte == pstate->p_target_nsitem->p_rte) ?
     477             :                  errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
     478             :                          refname) :
     479             :                  errdetail("The combining JOIN type must be INNER or LEFT for a LATERAL reference."),
     480             :                  parser_errposition(pstate, location)));
     481             :     }
     482     1858300 : }
     483             : 
     484             : /*
     485             :  * Given an RT index and nesting depth, find the corresponding
     486             :  * ParseNamespaceItem (there must be one).
     487             :  */
     488             : ParseNamespaceItem *
     489         112 : GetNSItemByRangeTablePosn(ParseState *pstate,
     490             :                           int varno,
     491             :                           int sublevels_up)
     492             : {
     493             :     ListCell   *lc;
     494             : 
     495         112 :     while (sublevels_up-- > 0)
     496             :     {
     497           0 :         pstate = pstate->parentParseState;
     498             :         Assert(pstate != NULL);
     499             :     }
     500         128 :     foreach(lc, pstate->p_namespace)
     501             :     {
     502         128 :         ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
     503             : 
     504         128 :         if (nsitem->p_rtindex == varno)
     505         112 :             return nsitem;
     506             :     }
     507           0 :     elog(ERROR, "nsitem not found (internal error)");
     508             :     return NULL;                /* keep compiler quiet */
     509             : }
     510             : 
     511             : /*
     512             :  * Given an RT index and nesting depth, find the corresponding RTE.
     513             :  * (Note that the RTE need not be in the query's namespace.)
     514             :  */
     515             : RangeTblEntry *
     516      763740 : GetRTEByRangeTablePosn(ParseState *pstate,
     517             :                        int varno,
     518             :                        int sublevels_up)
     519             : {
     520      764144 :     while (sublevels_up-- > 0)
     521             :     {
     522         404 :         pstate = pstate->parentParseState;
     523             :         Assert(pstate != NULL);
     524             :     }
     525             :     Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
     526      763740 :     return rt_fetch(varno, pstate->p_rtable);
     527             : }
     528             : 
     529             : /*
     530             :  * Fetch the CTE for a CTE-reference RTE.
     531             :  *
     532             :  * rtelevelsup is the number of query levels above the given pstate that the
     533             :  * RTE came from.
     534             :  */
     535             : CommonTableExpr *
     536        2128 : GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
     537             : {
     538             :     Index       levelsup;
     539             :     ListCell   *lc;
     540             : 
     541             :     Assert(rte->rtekind == RTE_CTE);
     542        2128 :     levelsup = rte->ctelevelsup + rtelevelsup;
     543        3658 :     while (levelsup-- > 0)
     544             :     {
     545        1530 :         pstate = pstate->parentParseState;
     546        1530 :         if (!pstate)            /* shouldn't happen */
     547           0 :             elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
     548             :     }
     549        2676 :     foreach(lc, pstate->p_ctenamespace)
     550             :     {
     551        2676 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
     552             : 
     553        2676 :         if (strcmp(cte->ctename, rte->ctename) == 0)
     554        2128 :             return cte;
     555             :     }
     556             :     /* shouldn't happen */
     557           0 :     elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
     558             :     return NULL;                /* keep compiler quiet */
     559             : }
     560             : 
     561             : /*
     562             :  * updateFuzzyAttrMatchState
     563             :  *    Using Levenshtein distance, consider if column is best fuzzy match.
     564             :  */
     565             : static void
     566        1256 : updateFuzzyAttrMatchState(int fuzzy_rte_penalty,
     567             :                           FuzzyAttrMatchState *fuzzystate, RangeTblEntry *rte,
     568             :                           const char *actual, const char *match, int attnum)
     569             : {
     570             :     int         columndistance;
     571             :     int         matchlen;
     572             : 
     573             :     /* Bail before computing the Levenshtein distance if there's no hope. */
     574        1256 :     if (fuzzy_rte_penalty > fuzzystate->distance)
     575          16 :         return;
     576             : 
     577             :     /*
     578             :      * Outright reject dropped columns, which can appear here with apparent
     579             :      * empty actual names, per remarks within scanRTEForColumn().
     580             :      */
     581        1240 :     if (actual[0] == '\0')
     582          84 :         return;
     583             : 
     584             :     /* Use Levenshtein to compute match distance. */
     585        1156 :     matchlen = strlen(match);
     586             :     columndistance =
     587        1156 :         varstr_levenshtein_less_equal(actual, strlen(actual), match, matchlen,
     588             :                                       1, 1, 1,
     589        1156 :                                       fuzzystate->distance + 1
     590        1156 :                                       - fuzzy_rte_penalty,
     591             :                                       true);
     592             : 
     593             :     /*
     594             :      * If more than half the characters are different, don't treat it as a
     595             :      * match, to avoid making ridiculous suggestions.
     596             :      */
     597        1156 :     if (columndistance > matchlen / 2)
     598         596 :         return;
     599             : 
     600             :     /*
     601             :      * From this point on, we can ignore the distinction between the RTE-name
     602             :      * distance and the column-name distance.
     603             :      */
     604         560 :     columndistance += fuzzy_rte_penalty;
     605             : 
     606             :     /*
     607             :      * If the new distance is less than or equal to that of the best match
     608             :      * found so far, update fuzzystate.
     609             :      */
     610         560 :     if (columndistance < fuzzystate->distance)
     611             :     {
     612             :         /* Store new lowest observed distance for RTE */
     613          76 :         fuzzystate->distance = columndistance;
     614          76 :         fuzzystate->rfirst = rte;
     615          76 :         fuzzystate->first = attnum;
     616          76 :         fuzzystate->rsecond = NULL;
     617          76 :         fuzzystate->second = InvalidAttrNumber;
     618             :     }
     619         484 :     else if (columndistance == fuzzystate->distance)
     620             :     {
     621             :         /*
     622             :          * This match distance may equal a prior match within this same range
     623             :          * table.  When that happens, the prior match may also be given, but
     624             :          * only if there is no more than two equally distant matches from the
     625             :          * RTE (in turn, our caller will only accept two equally distant
     626             :          * matches overall).
     627             :          */
     628           4 :         if (AttributeNumberIsValid(fuzzystate->second))
     629             :         {
     630             :             /* Too many RTE-level matches */
     631           0 :             fuzzystate->rfirst = NULL;
     632           0 :             fuzzystate->first = InvalidAttrNumber;
     633           0 :             fuzzystate->rsecond = NULL;
     634           0 :             fuzzystate->second = InvalidAttrNumber;
     635             :             /* Clearly, distance is too low a bar (for *any* RTE) */
     636           0 :             fuzzystate->distance = columndistance - 1;
     637             :         }
     638           4 :         else if (AttributeNumberIsValid(fuzzystate->first))
     639             :         {
     640             :             /* Record as provisional second match for RTE */
     641           4 :             fuzzystate->rsecond = rte;
     642           4 :             fuzzystate->second = attnum;
     643             :         }
     644           0 :         else if (fuzzystate->distance <= MAX_FUZZY_DISTANCE)
     645             :         {
     646             :             /*
     647             :              * Record as provisional first match (this can occasionally occur
     648             :              * because previous lowest distance was "too low a bar", rather
     649             :              * than being associated with a real match)
     650             :              */
     651           0 :             fuzzystate->rfirst = rte;
     652           0 :             fuzzystate->first = attnum;
     653             :         }
     654             :     }
     655             : }
     656             : 
     657             : /*
     658             :  * scanNSItemForColumn
     659             :  *    Search the column names of a single namespace item for the given name.
     660             :  *    If found, return an appropriate Var node, else return NULL.
     661             :  *    If the name proves ambiguous within this nsitem, raise error.
     662             :  *
     663             :  * Side effect: if we find a match, mark the item's RTE as requiring read
     664             :  * access for the column.
     665             :  */
     666             : Node *
     667     1937470 : scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem,
     668             :                     int sublevels_up, const char *colname, int location)
     669             : {
     670     1937470 :     RangeTblEntry *rte = nsitem->p_rte;
     671             :     int         attnum;
     672             :     Var        *var;
     673             : 
     674             :     /*
     675             :      * Scan the RTE's column names (or aliases) for a match.  Complain if
     676             :      * multiple matches.
     677             :      */
     678     1937470 :     attnum = scanRTEForColumn(pstate, rte,
     679             :                               colname, location,
     680             :                               0, NULL);
     681             : 
     682     1937462 :     if (attnum == InvalidAttrNumber)
     683      102460 :         return NULL;            /* Return NULL if no match */
     684             : 
     685             :     /* In constraint check, no system column is allowed except tableOid */
     686     1835002 :     if (pstate->p_expr_kind == EXPR_KIND_CHECK_CONSTRAINT &&
     687           8 :         attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
     688           4 :         ereport(ERROR,
     689             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
     690             :                  errmsg("system column \"%s\" reference in check constraint is invalid",
     691             :                         colname),
     692             :                  parser_errposition(pstate, location)));
     693             : 
     694             :     /* In generated column, no system column is allowed except tableOid */
     695     1834998 :     if (pstate->p_expr_kind == EXPR_KIND_GENERATED_COLUMN &&
     696          10 :         attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
     697           4 :         ereport(ERROR,
     698             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
     699             :                  errmsg("cannot use system column \"%s\" in column generation expression",
     700             :                         colname),
     701             :                  parser_errposition(pstate, location)));
     702             : 
     703             :     /* Found a valid match, so build a Var */
     704     1834994 :     if (attnum > InvalidAttrNumber)
     705             :     {
     706             :         /* Get attribute data from the ParseNamespaceColumn array */
     707     1795566 :         ParseNamespaceColumn *nscol = &nsitem->p_nscolumns[attnum - 1];
     708             : 
     709             :         /* Complain if dropped column.  See notes in scanRTEForColumn. */
     710     1795566 :         if (nscol->p_varno == 0)
     711           0 :             ereport(ERROR,
     712             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
     713             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
     714             :                             colname,
     715             :                             rte->eref->aliasname)));
     716             : 
     717     3591132 :         var = makeVar(nscol->p_varno,
     718     1795566 :                       nscol->p_varattno,
     719             :                       nscol->p_vartype,
     720             :                       nscol->p_vartypmod,
     721             :                       nscol->p_varcollid,
     722             :                       sublevels_up);
     723             :         /* makeVar doesn't offer parameters for these, so set them by hand: */
     724     1795566 :         var->varnosyn = nscol->p_varnosyn;
     725     1795566 :         var->varattnosyn = nscol->p_varattnosyn;
     726             :     }
     727             :     else
     728             :     {
     729             :         /* System column, so use predetermined type data */
     730             :         const FormData_pg_attribute *sysatt;
     731             : 
     732       39428 :         sysatt = SystemAttributeDefinition(attnum);
     733       39428 :         var = makeVar(nsitem->p_rtindex,
     734             :                       attnum,
     735             :                       sysatt->atttypid,
     736             :                       sysatt->atttypmod,
     737             :                       sysatt->attcollation,
     738             :                       sublevels_up);
     739             :     }
     740     1834994 :     var->location = location;
     741             : 
     742             :     /* Require read access to the column */
     743     1834994 :     markVarForSelectPriv(pstate, var, rte);
     744             : 
     745     1834994 :     return (Node *) var;
     746             : }
     747             : 
     748             : /*
     749             :  * scanRTEForColumn
     750             :  *    Search the column names of a single RTE for the given name.
     751             :  *    If found, return the attnum (possibly negative, for a system column);
     752             :  *    else return InvalidAttrNumber.
     753             :  *    If the name proves ambiguous within this RTE, raise error.
     754             :  *
     755             :  * pstate and location are passed only for error-reporting purposes.
     756             :  *
     757             :  * Side effect: if fuzzystate is non-NULL, check non-system columns
     758             :  * for an approximate match and update fuzzystate accordingly.
     759             :  *
     760             :  * Note: this is factored out of scanNSItemForColumn because error message
     761             :  * creation may want to check RTEs that are not in the namespace.  To support
     762             :  * that usage, minimize the number of validity checks performed here.  It's
     763             :  * okay to complain about ambiguous-name cases, though, since if we are
     764             :  * working to complain about an invalid name, we've already eliminated that.
     765             :  */
     766             : static int
     767     1937698 : scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
     768             :                  const char *colname, int location,
     769             :                  int fuzzy_rte_penalty,
     770             :                  FuzzyAttrMatchState *fuzzystate)
     771             : {
     772     1937698 :     int         result = InvalidAttrNumber;
     773     1937698 :     int         attnum = 0;
     774             :     ListCell   *c;
     775             : 
     776             :     /*
     777             :      * Scan the user column names (or aliases) for a match. Complain if
     778             :      * multiple matches.
     779             :      *
     780             :      * Note: eref->colnames may include entries for dropped columns, but those
     781             :      * will be empty strings that cannot match any legal SQL identifier, so we
     782             :      * don't bother to test for that case here.
     783             :      *
     784             :      * Should this somehow go wrong and we try to access a dropped column,
     785             :      * we'll still catch it by virtue of the check in scanNSItemForColumn().
     786             :      * Callers interested in finding match with shortest distance need to
     787             :      * defend against this directly, though.
     788             :      */
     789    39251436 :     foreach(c, rte->eref->colnames)
     790             :     {
     791    37313746 :         const char *attcolname = strVal(lfirst(c));
     792             : 
     793    37313746 :         attnum++;
     794    37313746 :         if (strcmp(attcolname, colname) == 0)
     795             :         {
     796     1795610 :             if (result)
     797           8 :                 ereport(ERROR,
     798             :                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
     799             :                          errmsg("column reference \"%s\" is ambiguous",
     800             :                                 colname),
     801             :                          parser_errposition(pstate, location)));
     802     1795602 :             result = attnum;
     803             :         }
     804             : 
     805             :         /* Update fuzzy match state, if provided. */
     806    37313738 :         if (fuzzystate != NULL)
     807        1256 :             updateFuzzyAttrMatchState(fuzzy_rte_penalty, fuzzystate,
     808             :                                       rte, attcolname, colname, attnum);
     809             :     }
     810             : 
     811             :     /*
     812             :      * If we have a unique match, return it.  Note that this allows a user
     813             :      * alias to override a system column name (such as OID) without error.
     814             :      */
     815     1937690 :     if (result)
     816     1795594 :         return result;
     817             : 
     818             :     /*
     819             :      * If the RTE represents a real relation, consider system column names.
     820             :      * Composites are only used for pseudo-relations like ON CONFLICT's
     821             :      * excluded.
     822             :      */
     823      142096 :     if (rte->rtekind == RTE_RELATION &&
     824      102236 :         rte->relkind != RELKIND_COMPOSITE_TYPE)
     825             :     {
     826             :         /* quick check to see if name could be a system column */
     827      102204 :         attnum = specialAttNum(colname);
     828      102204 :         if (attnum != InvalidAttrNumber)
     829             :         {
     830             :             /* now check to see if column actually is defined */
     831       39448 :             if (SearchSysCacheExists2(ATTNUM,
     832             :                                       ObjectIdGetDatum(rte->relid),
     833             :                                       Int16GetDatum(attnum)))
     834       39440 :                 result = attnum;
     835             :         }
     836             :     }
     837             : 
     838      142096 :     return result;
     839             : }
     840             : 
     841             : /*
     842             :  * colNameToVar
     843             :  *    Search for an unqualified column name.
     844             :  *    If found, return the appropriate Var node (or expression).
     845             :  *    If not found, return NULL.  If the name proves ambiguous, raise error.
     846             :  *    If localonly is true, only names in the innermost query are considered.
     847             :  */
     848             : Node *
     849      627916 : colNameToVar(ParseState *pstate, const char *colname, bool localonly,
     850             :              int location)
     851             : {
     852      627916 :     Node       *result = NULL;
     853      627916 :     int         sublevels_up = 0;
     854      627916 :     ParseState *orig_pstate = pstate;
     855             : 
     856      691698 :     while (pstate != NULL)
     857             :     {
     858             :         ListCell   *l;
     859             : 
     860     1971050 :         foreach(l, pstate->p_namespace)
     861             :         {
     862     1314630 :             ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
     863             :             Node       *newresult;
     864             : 
     865             :             /* Ignore table-only items */
     866     1314630 :             if (!nsitem->p_cols_visible)
     867      619716 :                 continue;
     868             :             /* If not inside LATERAL, ignore lateral-only items */
     869      694914 :             if (nsitem->p_lateral_only && !pstate->p_lateral_active)
     870          32 :                 continue;
     871             : 
     872             :             /* use orig_pstate here for consistency with other callers */
     873      694882 :             newresult = scanNSItemForColumn(orig_pstate, nsitem, sublevels_up,
     874             :                                             colname, location);
     875             : 
     876      694866 :             if (newresult)
     877             :             {
     878      592618 :                 if (result)
     879          12 :                     ereport(ERROR,
     880             :                             (errcode(ERRCODE_AMBIGUOUS_COLUMN),
     881             :                              errmsg("column reference \"%s\" is ambiguous",
     882             :                                     colname),
     883             :                              parser_errposition(pstate, location)));
     884      592606 :                 check_lateral_ref_ok(pstate, nsitem, location);
     885      592598 :                 result = newresult;
     886             :             }
     887             :         }
     888             : 
     889      656420 :         if (result != NULL || localonly)
     890             :             break;              /* found, or don't want to look at parent */
     891             : 
     892       63782 :         pstate = pstate->parentParseState;
     893       63782 :         sublevels_up++;
     894             :     }
     895             : 
     896      627880 :     return result;
     897             : }
     898             : 
     899             : /*
     900             :  * searchRangeTableForCol
     901             :  *    See if any RangeTblEntry could possibly provide the given column name (or
     902             :  *    find the best match available).  Returns state with relevant details.
     903             :  *
     904             :  * This is different from colNameToVar in that it considers every entry in
     905             :  * the ParseState's rangetable(s), not only those that are currently visible
     906             :  * in the p_namespace list(s).  This behavior is invalid per the SQL spec,
     907             :  * and it may give ambiguous results (there might be multiple equally valid
     908             :  * matches, but only one will be returned).  This must be used ONLY as a
     909             :  * heuristic in giving suitable error messages.  See errorMissingColumn.
     910             :  *
     911             :  * This function is also different in that it will consider approximate
     912             :  * matches -- if the user entered an alias/column pair that is only slightly
     913             :  * different from a valid pair, we may be able to infer what they meant to
     914             :  * type and provide a reasonable hint.
     915             :  *
     916             :  * The FuzzyAttrMatchState will have 'rfirst' pointing to the best RTE
     917             :  * containing the most promising match for the alias and column name.  If
     918             :  * the alias and column names match exactly, 'first' will be InvalidAttrNumber;
     919             :  * otherwise, it will be the attribute number for the match.  In the latter
     920             :  * case, 'rsecond' may point to a second, equally close approximate match,
     921             :  * and 'second' will contain the attribute number for the second match.
     922             :  */
     923             : static FuzzyAttrMatchState *
     924         202 : searchRangeTableForCol(ParseState *pstate, const char *alias, const char *colname,
     925             :                        int location)
     926             : {
     927         202 :     ParseState *orig_pstate = pstate;
     928         202 :     FuzzyAttrMatchState *fuzzystate = palloc(sizeof(FuzzyAttrMatchState));
     929             : 
     930         202 :     fuzzystate->distance = MAX_FUZZY_DISTANCE + 1;
     931         202 :     fuzzystate->rfirst = NULL;
     932         202 :     fuzzystate->rsecond = NULL;
     933         202 :     fuzzystate->first = InvalidAttrNumber;
     934         202 :     fuzzystate->second = InvalidAttrNumber;
     935             : 
     936         400 :     while (pstate != NULL)
     937             :     {
     938             :         ListCell   *l;
     939             : 
     940         450 :         foreach(l, pstate->p_rtable)
     941             :         {
     942         252 :             RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
     943         252 :             int         fuzzy_rte_penalty = 0;
     944             : 
     945             :             /*
     946             :              * Typically, it is not useful to look for matches within join
     947             :              * RTEs; they effectively duplicate other RTEs for our purposes,
     948             :              * and if a match is chosen from a join RTE, an unhelpful alias is
     949             :              * displayed in the final diagnostic message.
     950             :              */
     951         252 :             if (rte->rtekind == RTE_JOIN)
     952          24 :                 continue;
     953             : 
     954             :             /*
     955             :              * If the user didn't specify an alias, then matches against one
     956             :              * RTE are as good as another.  But if the user did specify an
     957             :              * alias, then we want at least a fuzzy - and preferably an exact
     958             :              * - match for the range table entry.
     959             :              */
     960         228 :             if (alias != NULL)
     961             :                 fuzzy_rte_penalty =
     962         128 :                     varstr_levenshtein_less_equal(alias, strlen(alias),
     963          64 :                                                   rte->eref->aliasname,
     964          64 :                                                   strlen(rte->eref->aliasname),
     965             :                                                   1, 1, 1,
     966             :                                                   MAX_FUZZY_DISTANCE + 1,
     967             :                                                   true);
     968             : 
     969             :             /*
     970             :              * Scan for a matching column; if we find an exact match, we're
     971             :              * done.  Otherwise, update fuzzystate.
     972             :              */
     973         228 :             if (scanRTEForColumn(orig_pstate, rte, colname, location,
     974             :                                  fuzzy_rte_penalty, fuzzystate)
     975          32 :                 && fuzzy_rte_penalty == 0)
     976             :             {
     977          24 :                 fuzzystate->rfirst = rte;
     978          24 :                 fuzzystate->first = InvalidAttrNumber;
     979          24 :                 fuzzystate->rsecond = NULL;
     980          24 :                 fuzzystate->second = InvalidAttrNumber;
     981          24 :                 return fuzzystate;
     982             :             }
     983             :         }
     984             : 
     985         198 :         pstate = pstate->parentParseState;
     986             :     }
     987             : 
     988         178 :     return fuzzystate;
     989             : }
     990             : 
     991             : /*
     992             :  * markRTEForSelectPriv
     993             :  *     Mark the specified column of an RTE as requiring SELECT privilege
     994             :  *
     995             :  * col == InvalidAttrNumber means a "whole row" reference
     996             :  *
     997             :  * External callers should always pass the Var's RTE.  Internally, we
     998             :  * allow NULL to be passed for the RTE and then look it up if needed;
     999             :  * this takes less code than requiring each internal recursion site
    1000             :  * to perform a lookup.
    1001             :  */
    1002             : static void
    1003     2014040 : markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
    1004             :                      int rtindex, AttrNumber col)
    1005             : {
    1006     2014040 :     if (rte == NULL)
    1007           8 :         rte = rt_fetch(rtindex, pstate->p_rtable);
    1008             : 
    1009     2014040 :     if (rte->rtekind == RTE_RELATION)
    1010             :     {
    1011             :         /* Make sure the rel as a whole is marked for SELECT access */
    1012     1668310 :         rte->requiredPerms |= ACL_SELECT;
    1013             :         /* Must offset the attnum to fit in a bitmapset */
    1014     1668310 :         rte->selectedCols = bms_add_member(rte->selectedCols,
    1015             :                                            col - FirstLowInvalidHeapAttributeNumber);
    1016             :     }
    1017      345730 :     else if (rte->rtekind == RTE_JOIN)
    1018             :     {
    1019       65782 :         if (col == InvalidAttrNumber)
    1020             :         {
    1021             :             /*
    1022             :              * A whole-row reference to a join has to be treated as whole-row
    1023             :              * references to the two inputs.
    1024             :              */
    1025             :             JoinExpr   *j;
    1026             : 
    1027           4 :             if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
    1028           4 :                 j = list_nth_node(JoinExpr, pstate->p_joinexprs, rtindex - 1);
    1029             :             else
    1030           0 :                 j = NULL;
    1031           4 :             if (j == NULL)
    1032           0 :                 elog(ERROR, "could not find JoinExpr for whole-row reference");
    1033             : 
    1034             :             /* Note: we can't see FromExpr here */
    1035           4 :             if (IsA(j->larg, RangeTblRef))
    1036             :             {
    1037           4 :                 int         varno = ((RangeTblRef *) j->larg)->rtindex;
    1038             : 
    1039           4 :                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
    1040             :             }
    1041           0 :             else if (IsA(j->larg, JoinExpr))
    1042             :             {
    1043           0 :                 int         varno = ((JoinExpr *) j->larg)->rtindex;
    1044             : 
    1045           0 :                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
    1046             :             }
    1047             :             else
    1048           0 :                 elog(ERROR, "unrecognized node type: %d",
    1049             :                      (int) nodeTag(j->larg));
    1050           4 :             if (IsA(j->rarg, RangeTblRef))
    1051             :             {
    1052           4 :                 int         varno = ((RangeTblRef *) j->rarg)->rtindex;
    1053             : 
    1054           4 :                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
    1055             :             }
    1056           0 :             else if (IsA(j->rarg, JoinExpr))
    1057             :             {
    1058           0 :                 int         varno = ((JoinExpr *) j->rarg)->rtindex;
    1059             : 
    1060           0 :                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
    1061             :             }
    1062             :             else
    1063           0 :                 elog(ERROR, "unrecognized node type: %d",
    1064             :                      (int) nodeTag(j->rarg));
    1065             :         }
    1066             :         else
    1067             :         {
    1068             :             /*
    1069             :              * Join alias Vars for ordinary columns must refer to merged JOIN
    1070             :              * USING columns.  We don't need to do anything here, because the
    1071             :              * join input columns will also be referenced in the join's qual
    1072             :              * clause, and will get marked for select privilege there.
    1073             :              */
    1074             :         }
    1075             :     }
    1076             :     /* other RTE types don't require privilege marking */
    1077     2014040 : }
    1078             : 
    1079             : /*
    1080             :  * markVarForSelectPriv
    1081             :  *     Mark the RTE referenced by a Var as requiring SELECT privilege
    1082             :  */
    1083             : void
    1084     2014032 : markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
    1085             : {
    1086             :     Index       lv;
    1087             : 
    1088             :     Assert(IsA(var, Var));
    1089             :     /* Find the appropriate pstate if it's an uplevel Var */
    1090     2132256 :     for (lv = 0; lv < var->varlevelsup; lv++)
    1091      118224 :         pstate = pstate->parentParseState;
    1092     2014032 :     markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
    1093     2014032 : }
    1094             : 
    1095             : /*
    1096             :  * buildRelationAliases
    1097             :  *      Construct the eref column name list for a relation RTE.
    1098             :  *      This code is also used for function RTEs.
    1099             :  *
    1100             :  * tupdesc: the physical column information
    1101             :  * alias: the user-supplied alias, or NULL if none
    1102             :  * eref: the eref Alias to store column names in
    1103             :  *
    1104             :  * eref->colnames is filled in.  Also, alias->colnames is rebuilt to insert
    1105             :  * empty strings for any dropped columns, so that it will be one-to-one with
    1106             :  * physical column numbers.
    1107             :  *
    1108             :  * It is an error for there to be more aliases present than required.
    1109             :  */
    1110             : static void
    1111      599196 : buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
    1112             : {
    1113      599196 :     int         maxattrs = tupdesc->natts;
    1114             :     List       *aliaslist;
    1115             :     ListCell   *aliaslc;
    1116             :     int         numaliases;
    1117             :     int         varattno;
    1118      599196 :     int         numdropped = 0;
    1119             : 
    1120             :     Assert(eref->colnames == NIL);
    1121             : 
    1122      599196 :     if (alias)
    1123             :     {
    1124      359048 :         aliaslist = alias->colnames;
    1125      359048 :         aliaslc = list_head(aliaslist);
    1126      359048 :         numaliases = list_length(aliaslist);
    1127             :         /* We'll rebuild the alias colname list */
    1128      359048 :         alias->colnames = NIL;
    1129             :     }
    1130             :     else
    1131             :     {
    1132      240148 :         aliaslist = NIL;
    1133      240148 :         aliaslc = NULL;
    1134      240148 :         numaliases = 0;
    1135             :     }
    1136             : 
    1137     7262708 :     for (varattno = 0; varattno < maxattrs; varattno++)
    1138             :     {
    1139     6663512 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
    1140             :         Value      *attrname;
    1141             : 
    1142     6663512 :         if (attr->attisdropped)
    1143             :         {
    1144             :             /* Always insert an empty string for a dropped column */
    1145        3514 :             attrname = makeString(pstrdup(""));
    1146        3514 :             if (aliaslc)
    1147           0 :                 alias->colnames = lappend(alias->colnames, attrname);
    1148        3514 :             numdropped++;
    1149             :         }
    1150     6659998 :         else if (aliaslc)
    1151             :         {
    1152             :             /* Use the next user-supplied alias */
    1153       21214 :             attrname = (Value *) lfirst(aliaslc);
    1154       21214 :             aliaslc = lnext(aliaslist, aliaslc);
    1155       21214 :             alias->colnames = lappend(alias->colnames, attrname);
    1156             :         }
    1157             :         else
    1158             :         {
    1159     6638784 :             attrname = makeString(pstrdup(NameStr(attr->attname)));
    1160             :             /* we're done with the alias if any */
    1161             :         }
    1162             : 
    1163     6663512 :         eref->colnames = lappend(eref->colnames, attrname);
    1164             :     }
    1165             : 
    1166             :     /* Too many user-supplied aliases? */
    1167      599196 :     if (aliaslc)
    1168           0 :         ereport(ERROR,
    1169             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1170             :                  errmsg("table \"%s\" has %d columns available but %d columns specified",
    1171             :                         eref->aliasname, maxattrs - numdropped, numaliases)));
    1172      599196 : }
    1173             : 
    1174             : /*
    1175             :  * chooseScalarFunctionAlias
    1176             :  *      Select the column alias for a function in a function RTE,
    1177             :  *      when the function returns a scalar type (not composite or RECORD).
    1178             :  *
    1179             :  * funcexpr: transformed expression tree for the function call
    1180             :  * funcname: function name (as determined by FigureColname)
    1181             :  * alias: the user-supplied alias for the RTE, or NULL if none
    1182             :  * nfuncs: the number of functions appearing in the function RTE
    1183             :  *
    1184             :  * Note that the name we choose might be overridden later, if the user-given
    1185             :  * alias includes column alias names.  That's of no concern here.
    1186             :  */
    1187             : static char *
    1188       20454 : chooseScalarFunctionAlias(Node *funcexpr, char *funcname,
    1189             :                           Alias *alias, int nfuncs)
    1190             : {
    1191             :     char       *pname;
    1192             : 
    1193             :     /*
    1194             :      * If the expression is a simple function call, and the function has a
    1195             :      * single OUT parameter that is named, use the parameter's name.
    1196             :      */
    1197       20454 :     if (funcexpr && IsA(funcexpr, FuncExpr))
    1198             :     {
    1199       20438 :         pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
    1200       20438 :         if (pname)
    1201         768 :             return pname;
    1202             :     }
    1203             : 
    1204             :     /*
    1205             :      * If there's just one function in the RTE, and the user gave an RTE alias
    1206             :      * name, use that name.  (This makes FROM func() AS foo use "foo" as the
    1207             :      * column name as well as the table alias.)
    1208             :      */
    1209       19686 :     if (nfuncs == 1 && alias)
    1210       18476 :         return alias->aliasname;
    1211             : 
    1212             :     /*
    1213             :      * Otherwise use the function name.
    1214             :      */
    1215        1210 :     return funcname;
    1216             : }
    1217             : 
    1218             : /*
    1219             :  * buildNSItemFromTupleDesc
    1220             :  *      Build a ParseNamespaceItem, given a tupdesc describing the columns.
    1221             :  *
    1222             :  * rte: the new RangeTblEntry for the rel
    1223             :  * rtindex: its index in the rangetable list
    1224             :  * tupdesc: the physical column information
    1225             :  */
    1226             : static ParseNamespaceItem *
    1227      599196 : buildNSItemFromTupleDesc(RangeTblEntry *rte, Index rtindex, TupleDesc tupdesc)
    1228             : {
    1229             :     ParseNamespaceItem *nsitem;
    1230             :     ParseNamespaceColumn *nscolumns;
    1231      599196 :     int         maxattrs = tupdesc->natts;
    1232             :     int         varattno;
    1233             : 
    1234             :     /* colnames must have the same number of entries as the nsitem */
    1235             :     Assert(maxattrs == list_length(rte->eref->colnames));
    1236             : 
    1237             :     /* extract per-column data from the tupdesc */
    1238             :     nscolumns = (ParseNamespaceColumn *)
    1239      599196 :         palloc0(maxattrs * sizeof(ParseNamespaceColumn));
    1240             : 
    1241     7262708 :     for (varattno = 0; varattno < maxattrs; varattno++)
    1242             :     {
    1243     6663512 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
    1244             : 
    1245             :         /* For a dropped column, just leave the entry as zeroes */
    1246     6663512 :         if (attr->attisdropped)
    1247        3514 :             continue;
    1248             : 
    1249     6659998 :         nscolumns[varattno].p_varno = rtindex;
    1250     6659998 :         nscolumns[varattno].p_varattno = varattno + 1;
    1251     6659998 :         nscolumns[varattno].p_vartype = attr->atttypid;
    1252     6659998 :         nscolumns[varattno].p_vartypmod = attr->atttypmod;
    1253     6659998 :         nscolumns[varattno].p_varcollid = attr->attcollation;
    1254     6659998 :         nscolumns[varattno].p_varnosyn = rtindex;
    1255     6659998 :         nscolumns[varattno].p_varattnosyn = varattno + 1;
    1256             :     }
    1257             : 
    1258             :     /* ... and build the nsitem */
    1259      599196 :     nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
    1260      599196 :     nsitem->p_rte = rte;
    1261      599196 :     nsitem->p_rtindex = rtindex;
    1262      599196 :     nsitem->p_nscolumns = nscolumns;
    1263             :     /* set default visibility flags; might get changed later */
    1264      599196 :     nsitem->p_rel_visible = true;
    1265      599196 :     nsitem->p_cols_visible = true;
    1266      599196 :     nsitem->p_lateral_only = false;
    1267      599196 :     nsitem->p_lateral_ok = true;
    1268             : 
    1269      599196 :     return nsitem;
    1270             : }
    1271             : 
    1272             : /*
    1273             :  * buildNSItemFromLists
    1274             :  *      Build a ParseNamespaceItem, given column type information in lists.
    1275             :  *
    1276             :  * rte: the new RangeTblEntry for the rel
    1277             :  * rtindex: its index in the rangetable list
    1278             :  * coltypes: per-column datatype OIDs
    1279             :  * coltypmods: per-column type modifiers
    1280             :  * colcollation: per-column collation OIDs
    1281             :  */
    1282             : static ParseNamespaceItem *
    1283       71494 : buildNSItemFromLists(RangeTblEntry *rte, Index rtindex,
    1284             :                      List *coltypes, List *coltypmods, List *colcollations)
    1285             : {
    1286             :     ParseNamespaceItem *nsitem;
    1287             :     ParseNamespaceColumn *nscolumns;
    1288       71494 :     int         maxattrs = list_length(coltypes);
    1289             :     int         varattno;
    1290             :     ListCell   *lct;
    1291             :     ListCell   *lcm;
    1292             :     ListCell   *lcc;
    1293             : 
    1294             :     /* colnames must have the same number of entries as the nsitem */
    1295             :     Assert(maxattrs == list_length(rte->eref->colnames));
    1296             : 
    1297             :     Assert(maxattrs == list_length(coltypmods));
    1298             :     Assert(maxattrs == list_length(colcollations));
    1299             : 
    1300             :     /* extract per-column data from the lists */
    1301             :     nscolumns = (ParseNamespaceColumn *)
    1302       71494 :         palloc0(maxattrs * sizeof(ParseNamespaceColumn));
    1303             : 
    1304       71494 :     varattno = 0;
    1305      359994 :     forthree(lct, coltypes,
    1306             :              lcm, coltypmods,
    1307             :              lcc, colcollations)
    1308             :     {
    1309      288500 :         nscolumns[varattno].p_varno = rtindex;
    1310      288500 :         nscolumns[varattno].p_varattno = varattno + 1;
    1311      288500 :         nscolumns[varattno].p_vartype = lfirst_oid(lct);
    1312      288500 :         nscolumns[varattno].p_vartypmod = lfirst_int(lcm);
    1313      288500 :         nscolumns[varattno].p_varcollid = lfirst_oid(lcc);
    1314      288500 :         nscolumns[varattno].p_varnosyn = rtindex;
    1315      288500 :         nscolumns[varattno].p_varattnosyn = varattno + 1;
    1316      288500 :         varattno++;
    1317             :     }
    1318             : 
    1319             :     /* ... and build the nsitem */
    1320       71494 :     nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
    1321       71494 :     nsitem->p_rte = rte;
    1322       71494 :     nsitem->p_rtindex = rtindex;
    1323       71494 :     nsitem->p_nscolumns = nscolumns;
    1324             :     /* set default visibility flags; might get changed later */
    1325       71494 :     nsitem->p_rel_visible = true;
    1326       71494 :     nsitem->p_cols_visible = true;
    1327       71494 :     nsitem->p_lateral_only = false;
    1328       71494 :     nsitem->p_lateral_ok = true;
    1329             : 
    1330       71494 :     return nsitem;
    1331             : }
    1332             : 
    1333             : /*
    1334             :  * Open a table during parse analysis
    1335             :  *
    1336             :  * This is essentially just the same as table_openrv(), except that it caters
    1337             :  * to some parser-specific error reporting needs, notably that it arranges
    1338             :  * to include the RangeVar's parse location in any resulting error.
    1339             :  *
    1340             :  * Note: properly, lockmode should be declared LOCKMODE not int, but that
    1341             :  * would require importing storage/lock.h into parse_relation.h.  Since
    1342             :  * LOCKMODE is typedef'd as int anyway, that seems like overkill.
    1343             :  */
    1344             : Relation
    1345      427394 : parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
    1346             : {
    1347             :     Relation    rel;
    1348             :     ParseCallbackState pcbstate;
    1349             : 
    1350      427394 :     setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
    1351      427394 :     rel = table_openrv_extended(relation, lockmode, true);
    1352      427394 :     if (rel == NULL)
    1353             :     {
    1354         104 :         if (relation->schemaname)
    1355           0 :             ereport(ERROR,
    1356             :                     (errcode(ERRCODE_UNDEFINED_TABLE),
    1357             :                      errmsg("relation \"%s.%s\" does not exist",
    1358             :                             relation->schemaname, relation->relname)));
    1359             :         else
    1360             :         {
    1361             :             /*
    1362             :              * An unqualified name might have been meant as a reference to
    1363             :              * some not-yet-in-scope CTE.  The bare "does not exist" message
    1364             :              * has proven remarkably unhelpful for figuring out such problems,
    1365             :              * so we take pains to offer a specific hint.
    1366             :              */
    1367         104 :             if (isFutureCTE(pstate, relation->relname))
    1368           4 :                 ereport(ERROR,
    1369             :                         (errcode(ERRCODE_UNDEFINED_TABLE),
    1370             :                          errmsg("relation \"%s\" does not exist",
    1371             :                                 relation->relname),
    1372             :                          errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
    1373             :                                    relation->relname),
    1374             :                          errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
    1375             :             else
    1376         100 :                 ereport(ERROR,
    1377             :                         (errcode(ERRCODE_UNDEFINED_TABLE),
    1378             :                          errmsg("relation \"%s\" does not exist",
    1379             :                                 relation->relname)));
    1380             :         }
    1381             :     }
    1382      427290 :     cancel_parser_errposition_callback(&pcbstate);
    1383      427290 :     return rel;
    1384             : }
    1385             : 
    1386             : /*
    1387             :  * Add an entry for a relation to the pstate's range table (p_rtable).
    1388             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    1389             :  *
    1390             :  * We do not link the ParseNamespaceItem into the pstate here; it's the
    1391             :  * caller's job to do that in the appropriate way.
    1392             :  *
    1393             :  * Note: formerly this checked for refname conflicts, but that's wrong.
    1394             :  * Caller is responsible for checking for conflicts in the appropriate scope.
    1395             :  */
    1396             : ParseNamespaceItem *
    1397      353402 : addRangeTableEntry(ParseState *pstate,
    1398             :                    RangeVar *relation,
    1399             :                    Alias *alias,
    1400             :                    bool inh,
    1401             :                    bool inFromCl)
    1402             : {
    1403      353402 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    1404      353402 :     char       *refname = alias ? alias->aliasname : relation->relname;
    1405             :     LOCKMODE    lockmode;
    1406             :     Relation    rel;
    1407             :     ParseNamespaceItem *nsitem;
    1408             : 
    1409             :     Assert(pstate != NULL);
    1410             : 
    1411      353402 :     rte->rtekind = RTE_RELATION;
    1412      353402 :     rte->alias = alias;
    1413             : 
    1414             :     /*
    1415             :      * Identify the type of lock we'll need on this relation.  It's not the
    1416             :      * query's target table (that case is handled elsewhere), so we need
    1417             :      * either RowShareLock if it's locked by FOR UPDATE/SHARE, or plain
    1418             :      * AccessShareLock otherwise.
    1419             :      */
    1420      353402 :     lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
    1421             : 
    1422             :     /*
    1423             :      * Get the rel's OID.  This access also ensures that we have an up-to-date
    1424             :      * relcache entry for the rel.  Since this is typically the first access
    1425             :      * to a rel in a statement, we must open the rel with the proper lockmode.
    1426             :      */
    1427      353402 :     rel = parserOpenTable(pstate, relation, lockmode);
    1428      353312 :     rte->relid = RelationGetRelid(rel);
    1429      353312 :     rte->relkind = rel->rd_rel->relkind;
    1430      353312 :     rte->rellockmode = lockmode;
    1431             : 
    1432             :     /*
    1433             :      * Build the list of effective column names using user-supplied aliases
    1434             :      * and/or actual column names.
    1435             :      */
    1436      353312 :     rte->eref = makeAlias(refname, NIL);
    1437      353312 :     buildRelationAliases(rel->rd_att, alias, rte->eref);
    1438             : 
    1439             :     /*
    1440             :      * Set flags and access permissions.
    1441             :      *
    1442             :      * The initial default on access checks is always check-for-READ-access,
    1443             :      * which is the right thing for all except target tables.
    1444             :      */
    1445      353312 :     rte->lateral = false;
    1446      353312 :     rte->inh = inh;
    1447      353312 :     rte->inFromCl = inFromCl;
    1448             : 
    1449      353312 :     rte->requiredPerms = ACL_SELECT;
    1450      353312 :     rte->checkAsUser = InvalidOid;   /* not set-uid by default, either */
    1451      353312 :     rte->selectedCols = NULL;
    1452      353312 :     rte->insertedCols = NULL;
    1453      353312 :     rte->updatedCols = NULL;
    1454      353312 :     rte->extraUpdatedCols = NULL;
    1455             : 
    1456             :     /*
    1457             :      * Add completed RTE to pstate's range table list, so that we know its
    1458             :      * index.  But we don't add it to the join list --- caller must do that if
    1459             :      * appropriate.
    1460             :      */
    1461      353312 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    1462             : 
    1463             :     /*
    1464             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    1465             :      * list --- caller must do that if appropriate.
    1466             :      */
    1467      353312 :     nsitem = buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
    1468             :                                       rel->rd_att);
    1469             : 
    1470             :     /*
    1471             :      * Drop the rel refcount, but keep the access lock till end of transaction
    1472             :      * so that the table can't be deleted or have its schema modified
    1473             :      * underneath us.
    1474             :      */
    1475      353312 :     table_close(rel, NoLock);
    1476             : 
    1477      353312 :     return nsitem;
    1478             : }
    1479             : 
    1480             : /*
    1481             :  * Add an entry for a relation to the pstate's range table (p_rtable).
    1482             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    1483             :  *
    1484             :  * This is just like addRangeTableEntry() except that it makes an RTE
    1485             :  * given an already-open relation instead of a RangeVar reference.
    1486             :  *
    1487             :  * lockmode is the lock type required for query execution; it must be one
    1488             :  * of AccessShareLock, RowShareLock, or RowExclusiveLock depending on the
    1489             :  * RTE's role within the query.  The caller must hold that lock mode
    1490             :  * or a stronger one.
    1491             :  *
    1492             :  * Note: properly, lockmode should be declared LOCKMODE not int, but that
    1493             :  * would require importing storage/lock.h into parse_relation.h.  Since
    1494             :  * LOCKMODE is typedef'd as int anyway, that seems like overkill.
    1495             :  */
    1496             : ParseNamespaceItem *
    1497      202894 : addRangeTableEntryForRelation(ParseState *pstate,
    1498             :                               Relation rel,
    1499             :                               int lockmode,
    1500             :                               Alias *alias,
    1501             :                               bool inh,
    1502             :                               bool inFromCl)
    1503             : {
    1504      202894 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    1505      202894 :     char       *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
    1506             : 
    1507             :     Assert(pstate != NULL);
    1508             : 
    1509             :     Assert(lockmode == AccessShareLock ||
    1510             :            lockmode == RowShareLock ||
    1511             :            lockmode == RowExclusiveLock);
    1512             :     Assert(CheckRelationLockedByMe(rel, lockmode, true));
    1513             : 
    1514      202894 :     rte->rtekind = RTE_RELATION;
    1515      202894 :     rte->alias = alias;
    1516      202894 :     rte->relid = RelationGetRelid(rel);
    1517      202894 :     rte->relkind = rel->rd_rel->relkind;
    1518      202894 :     rte->rellockmode = lockmode;
    1519             : 
    1520             :     /*
    1521             :      * Build the list of effective column names using user-supplied aliases
    1522             :      * and/or actual column names.
    1523             :      */
    1524      202894 :     rte->eref = makeAlias(refname, NIL);
    1525      202894 :     buildRelationAliases(rel->rd_att, alias, rte->eref);
    1526             : 
    1527             :     /*
    1528             :      * Set flags and access permissions.
    1529             :      *
    1530             :      * The initial default on access checks is always check-for-READ-access,
    1531             :      * which is the right thing for all except target tables.
    1532             :      */
    1533      202894 :     rte->lateral = false;
    1534      202894 :     rte->inh = inh;
    1535      202894 :     rte->inFromCl = inFromCl;
    1536             : 
    1537      202894 :     rte->requiredPerms = ACL_SELECT;
    1538      202894 :     rte->checkAsUser = InvalidOid;   /* not set-uid by default, either */
    1539      202894 :     rte->selectedCols = NULL;
    1540      202894 :     rte->insertedCols = NULL;
    1541      202894 :     rte->updatedCols = NULL;
    1542      202894 :     rte->extraUpdatedCols = NULL;
    1543             : 
    1544             :     /*
    1545             :      * Add completed RTE to pstate's range table list, so that we know its
    1546             :      * index.  But we don't add it to the join list --- caller must do that if
    1547             :      * appropriate.
    1548             :      */
    1549      202894 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    1550             : 
    1551             :     /*
    1552             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    1553             :      * list --- caller must do that if appropriate.
    1554             :      */
    1555      202894 :     return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
    1556             :                                     rel->rd_att);
    1557             : }
    1558             : 
    1559             : /*
    1560             :  * Add an entry for a subquery to the pstate's range table (p_rtable).
    1561             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    1562             :  *
    1563             :  * This is much like addRangeTableEntry() except that it makes a subquery RTE.
    1564             :  * Note that an alias clause *must* be supplied.
    1565             :  */
    1566             : ParseNamespaceItem *
    1567       64514 : addRangeTableEntryForSubquery(ParseState *pstate,
    1568             :                               Query *subquery,
    1569             :                               Alias *alias,
    1570             :                               bool lateral,
    1571             :                               bool inFromCl)
    1572             : {
    1573       64514 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    1574       64514 :     char       *refname = alias->aliasname;
    1575             :     Alias      *eref;
    1576             :     int         numaliases;
    1577             :     List       *coltypes,
    1578             :                *coltypmods,
    1579             :                *colcollations;
    1580             :     int         varattno;
    1581             :     ListCell   *tlistitem;
    1582             : 
    1583             :     Assert(pstate != NULL);
    1584             : 
    1585       64514 :     rte->rtekind = RTE_SUBQUERY;
    1586       64514 :     rte->subquery = subquery;
    1587       64514 :     rte->alias = alias;
    1588             : 
    1589       64514 :     eref = copyObject(alias);
    1590       64514 :     numaliases = list_length(eref->colnames);
    1591             : 
    1592             :     /* fill in any unspecified alias columns, and extract column type info */
    1593       64514 :     coltypes = coltypmods = colcollations = NIL;
    1594       64514 :     varattno = 0;
    1595      340206 :     foreach(tlistitem, subquery->targetList)
    1596             :     {
    1597      275692 :         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
    1598             : 
    1599      275692 :         if (te->resjunk)
    1600         112 :             continue;
    1601      275580 :         varattno++;
    1602             :         Assert(varattno == te->resno);
    1603      275580 :         if (varattno > numaliases)
    1604             :         {
    1605             :             char       *attrname;
    1606             : 
    1607      235638 :             attrname = pstrdup(te->resname);
    1608      235638 :             eref->colnames = lappend(eref->colnames, makeString(attrname));
    1609             :         }
    1610      275580 :         coltypes = lappend_oid(coltypes,
    1611      275580 :                                exprType((Node *) te->expr));
    1612      275580 :         coltypmods = lappend_int(coltypmods,
    1613      275580 :                                  exprTypmod((Node *) te->expr));
    1614      275580 :         colcollations = lappend_oid(colcollations,
    1615      275580 :                                     exprCollation((Node *) te->expr));
    1616             :     }
    1617       64514 :     if (varattno < numaliases)
    1618           0 :         ereport(ERROR,
    1619             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1620             :                  errmsg("table \"%s\" has %d columns available but %d columns specified",
    1621             :                         refname, varattno, numaliases)));
    1622             : 
    1623       64514 :     rte->eref = eref;
    1624             : 
    1625             :     /*
    1626             :      * Set flags and access permissions.
    1627             :      *
    1628             :      * Subqueries are never checked for access rights.
    1629             :      */
    1630       64514 :     rte->lateral = lateral;
    1631       64514 :     rte->inh = false;            /* never true for subqueries */
    1632       64514 :     rte->inFromCl = inFromCl;
    1633             : 
    1634       64514 :     rte->requiredPerms = 0;
    1635       64514 :     rte->checkAsUser = InvalidOid;
    1636       64514 :     rte->selectedCols = NULL;
    1637       64514 :     rte->insertedCols = NULL;
    1638       64514 :     rte->updatedCols = NULL;
    1639       64514 :     rte->extraUpdatedCols = NULL;
    1640             : 
    1641             :     /*
    1642             :      * Add completed RTE to pstate's range table list, so that we know its
    1643             :      * index.  But we don't add it to the join list --- caller must do that if
    1644             :      * appropriate.
    1645             :      */
    1646       64514 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    1647             : 
    1648             :     /*
    1649             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    1650             :      * list --- caller must do that if appropriate.
    1651             :      */
    1652       64514 :     return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
    1653             :                                 coltypes, coltypmods, colcollations);
    1654             : }
    1655             : 
    1656             : /*
    1657             :  * Add an entry for a function (or functions) to the pstate's range table
    1658             :  * (p_rtable).  Then, construct and return a ParseNamespaceItem for the new RTE.
    1659             :  *
    1660             :  * This is much like addRangeTableEntry() except that it makes a function RTE.
    1661             :  */
    1662             : ParseNamespaceItem *
    1663       42754 : addRangeTableEntryForFunction(ParseState *pstate,
    1664             :                               List *funcnames,
    1665             :                               List *funcexprs,
    1666             :                               List *coldeflists,
    1667             :                               RangeFunction *rangefunc,
    1668             :                               bool lateral,
    1669             :                               bool inFromCl)
    1670             : {
    1671       42754 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    1672       42754 :     Alias      *alias = rangefunc->alias;
    1673             :     Alias      *eref;
    1674             :     char       *aliasname;
    1675       42754 :     int         nfuncs = list_length(funcexprs);
    1676             :     TupleDesc  *functupdescs;
    1677             :     TupleDesc   tupdesc;
    1678             :     ListCell   *lc1,
    1679             :                *lc2,
    1680             :                *lc3;
    1681             :     int         i;
    1682             :     int         j;
    1683             :     int         funcno;
    1684             :     int         natts,
    1685             :                 totalatts;
    1686             : 
    1687             :     Assert(pstate != NULL);
    1688             : 
    1689       42754 :     rte->rtekind = RTE_FUNCTION;
    1690       42754 :     rte->relid = InvalidOid;
    1691       42754 :     rte->subquery = NULL;
    1692       42754 :     rte->functions = NIL;        /* we'll fill this list below */
    1693       42754 :     rte->funcordinality = rangefunc->ordinality;
    1694       42754 :     rte->alias = alias;
    1695             : 
    1696             :     /*
    1697             :      * Choose the RTE alias name.  We default to using the first function's
    1698             :      * name even when there's more than one; which is maybe arguable but beats
    1699             :      * using something constant like "table".
    1700             :      */
    1701       42754 :     if (alias)
    1702       30240 :         aliasname = alias->aliasname;
    1703             :     else
    1704       12514 :         aliasname = linitial(funcnames);
    1705             : 
    1706       42754 :     eref = makeAlias(aliasname, NIL);
    1707       42754 :     rte->eref = eref;
    1708             : 
    1709             :     /* Process each function ... */
    1710       42754 :     functupdescs = (TupleDesc *) palloc(nfuncs * sizeof(TupleDesc));
    1711             : 
    1712       42754 :     totalatts = 0;
    1713       42754 :     funcno = 0;
    1714       85660 :     forthree(lc1, funcexprs, lc2, funcnames, lc3, coldeflists)
    1715             :     {
    1716       42934 :         Node       *funcexpr = (Node *) lfirst(lc1);
    1717       42934 :         char       *funcname = (char *) lfirst(lc2);
    1718       42934 :         List       *coldeflist = (List *) lfirst(lc3);
    1719       42934 :         RangeTblFunction *rtfunc = makeNode(RangeTblFunction);
    1720             :         TypeFuncClass functypclass;
    1721             :         Oid         funcrettype;
    1722             : 
    1723             :         /* Initialize RangeTblFunction node */
    1724       42934 :         rtfunc->funcexpr = funcexpr;
    1725       42934 :         rtfunc->funccolnames = NIL;
    1726       42934 :         rtfunc->funccoltypes = NIL;
    1727       42934 :         rtfunc->funccoltypmods = NIL;
    1728       42934 :         rtfunc->funccolcollations = NIL;
    1729       42934 :         rtfunc->funcparams = NULL;   /* not set until planning */
    1730             : 
    1731             :         /*
    1732             :          * Now determine if the function returns a simple or composite type.
    1733             :          */
    1734       42934 :         functypclass = get_expr_result_type(funcexpr,
    1735             :                                             &funcrettype,
    1736             :                                             &tupdesc);
    1737             : 
    1738             :         /*
    1739             :          * A coldeflist is required if the function returns RECORD and hasn't
    1740             :          * got a predetermined record type, and is prohibited otherwise.
    1741             :          */
    1742       42934 :         if (coldeflist != NIL)
    1743             :         {
    1744         546 :             if (functypclass != TYPEFUNC_RECORD)
    1745           0 :                 ereport(ERROR,
    1746             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1747             :                          errmsg("a column definition list is only allowed for functions returning \"record\""),
    1748             :                          parser_errposition(pstate,
    1749             :                                             exprLocation((Node *) coldeflist))));
    1750             :         }
    1751             :         else
    1752             :         {
    1753       42388 :             if (functypclass == TYPEFUNC_RECORD)
    1754          24 :                 ereport(ERROR,
    1755             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    1756             :                          errmsg("a column definition list is required for functions returning \"record\""),
    1757             :                          parser_errposition(pstate, exprLocation(funcexpr))));
    1758             :         }
    1759             : 
    1760       42910 :         if (functypclass == TYPEFUNC_COMPOSITE ||
    1761             :             functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
    1762             :         {
    1763             :             /* Composite data type, e.g. a table's row type */
    1764             :             Assert(tupdesc);
    1765             :         }
    1766       21004 :         else if (functypclass == TYPEFUNC_SCALAR)
    1767             :         {
    1768             :             /* Base data type, i.e. scalar */
    1769       20454 :             tupdesc = CreateTemplateTupleDesc(1);
    1770       40908 :             TupleDescInitEntry(tupdesc,
    1771             :                                (AttrNumber) 1,
    1772       20454 :                                chooseScalarFunctionAlias(funcexpr, funcname,
    1773             :                                                          alias, nfuncs),
    1774             :                                funcrettype,
    1775             :                                exprTypmod(funcexpr),
    1776             :                                0);
    1777       20454 :             TupleDescInitEntryCollation(tupdesc,
    1778             :                                         (AttrNumber) 1,
    1779             :                                         exprCollation(funcexpr));
    1780             :         }
    1781         550 :         else if (functypclass == TYPEFUNC_RECORD)
    1782             :         {
    1783             :             ListCell   *col;
    1784             : 
    1785             :             /*
    1786             :              * Use the column definition list to construct a tupdesc and fill
    1787             :              * in the RangeTblFunction's lists.
    1788             :              */
    1789         546 :             tupdesc = CreateTemplateTupleDesc(list_length(coldeflist));
    1790         546 :             i = 1;
    1791        1870 :             foreach(col, coldeflist)
    1792             :             {
    1793        1324 :                 ColumnDef  *n = (ColumnDef *) lfirst(col);
    1794             :                 char       *attrname;
    1795             :                 Oid         attrtype;
    1796             :                 int32       attrtypmod;
    1797             :                 Oid         attrcollation;
    1798             : 
    1799        1324 :                 attrname = n->colname;
    1800        1324 :                 if (n->typeName->setof)
    1801           0 :                     ereport(ERROR,
    1802             :                             (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
    1803             :                              errmsg("column \"%s\" cannot be declared SETOF",
    1804             :                                     attrname),
    1805             :                              parser_errposition(pstate, n->location)));
    1806        1324 :                 typenameTypeIdAndMod(pstate, n->typeName,
    1807             :                                      &attrtype, &attrtypmod);
    1808        1324 :                 attrcollation = GetColumnDefCollation(pstate, n, attrtype);
    1809        2648 :                 TupleDescInitEntry(tupdesc,
    1810        1324 :                                    (AttrNumber) i,
    1811             :                                    attrname,
    1812             :                                    attrtype,
    1813             :                                    attrtypmod,
    1814             :                                    0);
    1815        1324 :                 TupleDescInitEntryCollation(tupdesc,
    1816        1324 :                                             (AttrNumber) i,
    1817             :                                             attrcollation);
    1818        1324 :                 rtfunc->funccolnames = lappend(rtfunc->funccolnames,
    1819        1324 :                                                makeString(pstrdup(attrname)));
    1820        1324 :                 rtfunc->funccoltypes = lappend_oid(rtfunc->funccoltypes,
    1821             :                                                    attrtype);
    1822        1324 :                 rtfunc->funccoltypmods = lappend_int(rtfunc->funccoltypmods,
    1823             :                                                      attrtypmod);
    1824        1324 :                 rtfunc->funccolcollations = lappend_oid(rtfunc->funccolcollations,
    1825             :                                                         attrcollation);
    1826             : 
    1827        1324 :                 i++;
    1828             :             }
    1829             : 
    1830             :             /*
    1831             :              * Ensure that the coldeflist defines a legal set of names (no
    1832             :              * duplicates, but we needn't worry about system column names) and
    1833             :              * datatypes.  Although we mostly can't allow pseudo-types, it
    1834             :              * seems safe to allow RECORD and RECORD[], since values within
    1835             :              * those type classes are self-identifying at runtime, and the
    1836             :              * coldeflist doesn't represent anything that will be visible to
    1837             :              * other sessions.
    1838             :              */
    1839         546 :             CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE,
    1840             :                                      CHKATYPE_ANYRECORD);
    1841             :         }
    1842             :         else
    1843           4 :             ereport(ERROR,
    1844             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1845             :                      errmsg("function \"%s\" in FROM has unsupported return type %s",
    1846             :                             funcname, format_type_be(funcrettype)),
    1847             :                      parser_errposition(pstate, exprLocation(funcexpr))));
    1848             : 
    1849             :         /* Finish off the RangeTblFunction and add it to the RTE's list */
    1850       42906 :         rtfunc->funccolcount = tupdesc->natts;
    1851       42906 :         rte->functions = lappend(rte->functions, rtfunc);
    1852             : 
    1853             :         /* Save the tupdesc for use below */
    1854       42906 :         functupdescs[funcno] = tupdesc;
    1855       42906 :         totalatts += tupdesc->natts;
    1856       42906 :         funcno++;
    1857             :     }
    1858             : 
    1859             :     /*
    1860             :      * If there's more than one function, or we want an ordinality column, we
    1861             :      * have to produce a merged tupdesc.
    1862             :      */
    1863       42726 :     if (nfuncs > 1 || rangefunc->ordinality)
    1864             :     {
    1865        6294 :         if (rangefunc->ordinality)
    1866        6254 :             totalatts++;
    1867             : 
    1868             :         /* Merge the tuple descs of each function into a composite one */
    1869        6294 :         tupdesc = CreateTemplateTupleDesc(totalatts);
    1870        6294 :         natts = 0;
    1871       12768 :         for (i = 0; i < nfuncs; i++)
    1872             :         {
    1873       13316 :             for (j = 1; j <= functupdescs[i]->natts; j++)
    1874        6842 :                 TupleDescCopyEntry(tupdesc, ++natts, functupdescs[i], j);
    1875             :         }
    1876             : 
    1877             :         /* Add the ordinality column if needed */
    1878        6294 :         if (rangefunc->ordinality)
    1879             :         {
    1880       12508 :             TupleDescInitEntry(tupdesc,
    1881        6254 :                                (AttrNumber) ++natts,
    1882             :                                "ordinality",
    1883             :                                INT8OID,
    1884             :                                -1,
    1885             :                                0);
    1886             :             /* no need to set collation */
    1887             :         }
    1888             : 
    1889        6294 :         Assert(natts == totalatts);
    1890             :     }
    1891             :     else
    1892             :     {
    1893             :         /* We can just use the single function's tupdesc as-is */
    1894       36432 :         tupdesc = functupdescs[0];
    1895             :     }
    1896             : 
    1897             :     /* Use the tupdesc while assigning column aliases for the RTE */
    1898       42726 :     buildRelationAliases(tupdesc, alias, eref);
    1899             : 
    1900             :     /*
    1901             :      * Set flags and access permissions.
    1902             :      *
    1903             :      * Functions are never checked for access rights (at least, not by the RTE
    1904             :      * permissions mechanism).
    1905             :      */
    1906       42726 :     rte->lateral = lateral;
    1907       42726 :     rte->inh = false;            /* never true for functions */
    1908       42726 :     rte->inFromCl = inFromCl;
    1909             : 
    1910       42726 :     rte->requiredPerms = 0;
    1911       42726 :     rte->checkAsUser = InvalidOid;
    1912       42726 :     rte->selectedCols = NULL;
    1913       42726 :     rte->insertedCols = NULL;
    1914       42726 :     rte->updatedCols = NULL;
    1915       42726 :     rte->extraUpdatedCols = NULL;
    1916             : 
    1917             :     /*
    1918             :      * Add completed RTE to pstate's range table list, so that we know its
    1919             :      * index.  But we don't add it to the join list --- caller must do that if
    1920             :      * appropriate.
    1921             :      */
    1922       42726 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    1923             : 
    1924             :     /*
    1925             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    1926             :      * list --- caller must do that if appropriate.
    1927             :      */
    1928       42726 :     return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
    1929             :                                     tupdesc);
    1930             : }
    1931             : 
    1932             : /*
    1933             :  * Add an entry for a table function to the pstate's range table (p_rtable).
    1934             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    1935             :  *
    1936             :  * This is much like addRangeTableEntry() except that it makes a tablefunc RTE.
    1937             :  */
    1938             : ParseNamespaceItem *
    1939         140 : addRangeTableEntryForTableFunc(ParseState *pstate,
    1940             :                                TableFunc *tf,
    1941             :                                Alias *alias,
    1942             :                                bool lateral,
    1943             :                                bool inFromCl)
    1944             : {
    1945         140 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    1946         140 :     char       *refname = alias ? alias->aliasname : pstrdup("xmltable");
    1947             :     Alias      *eref;
    1948             :     int         numaliases;
    1949             : 
    1950             :     Assert(pstate != NULL);
    1951             : 
    1952         140 :     rte->rtekind = RTE_TABLEFUNC;
    1953         140 :     rte->relid = InvalidOid;
    1954         140 :     rte->subquery = NULL;
    1955         140 :     rte->tablefunc = tf;
    1956         140 :     rte->coltypes = tf->coltypes;
    1957         140 :     rte->coltypmods = tf->coltypmods;
    1958         140 :     rte->colcollations = tf->colcollations;
    1959         140 :     rte->alias = alias;
    1960             : 
    1961         140 :     eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
    1962         140 :     numaliases = list_length(eref->colnames);
    1963             : 
    1964             :     /* fill in any unspecified alias columns */
    1965         140 :     if (numaliases < list_length(tf->colnames))
    1966         140 :         eref->colnames = list_concat(eref->colnames,
    1967         140 :                                      list_copy_tail(tf->colnames, numaliases));
    1968             : 
    1969         140 :     rte->eref = eref;
    1970             : 
    1971             :     /*
    1972             :      * Set flags and access permissions.
    1973             :      *
    1974             :      * Tablefuncs are never checked for access rights (at least, not by the
    1975             :      * RTE permissions mechanism).
    1976             :      */
    1977         140 :     rte->lateral = lateral;
    1978         140 :     rte->inh = false;            /* never true for tablefunc RTEs */
    1979         140 :     rte->inFromCl = inFromCl;
    1980             : 
    1981         140 :     rte->requiredPerms = 0;
    1982         140 :     rte->checkAsUser = InvalidOid;
    1983         140 :     rte->selectedCols = NULL;
    1984         140 :     rte->insertedCols = NULL;
    1985         140 :     rte->updatedCols = NULL;
    1986         140 :     rte->extraUpdatedCols = NULL;
    1987             : 
    1988             :     /*
    1989             :      * Add completed RTE to pstate's range table list, so that we know its
    1990             :      * index.  But we don't add it to the join list --- caller must do that if
    1991             :      * appropriate.
    1992             :      */
    1993         140 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    1994             : 
    1995             :     /*
    1996             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    1997             :      * list --- caller must do that if appropriate.
    1998             :      */
    1999         140 :     return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
    2000             :                                 rte->coltypes, rte->coltypmods,
    2001             :                                 rte->colcollations);
    2002             : }
    2003             : 
    2004             : /*
    2005             :  * Add an entry for a VALUES list to the pstate's range table (p_rtable).
    2006             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    2007             :  *
    2008             :  * This is much like addRangeTableEntry() except that it makes a values RTE.
    2009             :  */
    2010             : ParseNamespaceItem *
    2011        4902 : addRangeTableEntryForValues(ParseState *pstate,
    2012             :                             List *exprs,
    2013             :                             List *coltypes,
    2014             :                             List *coltypmods,
    2015             :                             List *colcollations,
    2016             :                             Alias *alias,
    2017             :                             bool lateral,
    2018             :                             bool inFromCl)
    2019             : {
    2020        4902 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    2021        4902 :     char       *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
    2022             :     Alias      *eref;
    2023             :     int         numaliases;
    2024             :     int         numcolumns;
    2025             : 
    2026             :     Assert(pstate != NULL);
    2027             : 
    2028        4902 :     rte->rtekind = RTE_VALUES;
    2029        4902 :     rte->relid = InvalidOid;
    2030        4902 :     rte->subquery = NULL;
    2031        4902 :     rte->values_lists = exprs;
    2032        4902 :     rte->coltypes = coltypes;
    2033        4902 :     rte->coltypmods = coltypmods;
    2034        4902 :     rte->colcollations = colcollations;
    2035        4902 :     rte->alias = alias;
    2036             : 
    2037        4902 :     eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
    2038             : 
    2039             :     /* fill in any unspecified alias columns */
    2040        4902 :     numcolumns = list_length((List *) linitial(exprs));
    2041        4902 :     numaliases = list_length(eref->colnames);
    2042       12882 :     while (numaliases < numcolumns)
    2043             :     {
    2044             :         char        attrname[64];
    2045             : 
    2046        7980 :         numaliases++;
    2047        7980 :         snprintf(attrname, sizeof(attrname), "column%d", numaliases);
    2048        7980 :         eref->colnames = lappend(eref->colnames,
    2049        7980 :                                  makeString(pstrdup(attrname)));
    2050             :     }
    2051        4902 :     if (numcolumns < numaliases)
    2052           0 :         ereport(ERROR,
    2053             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2054             :                  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
    2055             :                         refname, numcolumns, numaliases)));
    2056             : 
    2057        4902 :     rte->eref = eref;
    2058             : 
    2059             :     /*
    2060             :      * Set flags and access permissions.
    2061             :      *
    2062             :      * Subqueries are never checked for access rights.
    2063             :      */
    2064        4902 :     rte->lateral = lateral;
    2065        4902 :     rte->inh = false;            /* never true for values RTEs */
    2066        4902 :     rte->inFromCl = inFromCl;
    2067             : 
    2068        4902 :     rte->requiredPerms = 0;
    2069        4902 :     rte->checkAsUser = InvalidOid;
    2070        4902 :     rte->selectedCols = NULL;
    2071        4902 :     rte->insertedCols = NULL;
    2072        4902 :     rte->updatedCols = NULL;
    2073        4902 :     rte->extraUpdatedCols = NULL;
    2074             : 
    2075             :     /*
    2076             :      * Add completed RTE to pstate's range table list, so that we know its
    2077             :      * index.  But we don't add it to the join list --- caller must do that if
    2078             :      * appropriate.
    2079             :      */
    2080        4902 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    2081             : 
    2082             :     /*
    2083             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    2084             :      * list --- caller must do that if appropriate.
    2085             :      */
    2086        4902 :     return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
    2087             :                                 rte->coltypes, rte->coltypmods,
    2088             :                                 rte->colcollations);
    2089             : }
    2090             : 
    2091             : /*
    2092             :  * Add an entry for a join to the pstate's range table (p_rtable).
    2093             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    2094             :  *
    2095             :  * This is much like addRangeTableEntry() except that it makes a join RTE.
    2096             :  * Also, it's more convenient for the caller to construct the
    2097             :  * ParseNamespaceColumn array, so we pass that in.
    2098             :  */
    2099             : ParseNamespaceItem *
    2100       96826 : addRangeTableEntryForJoin(ParseState *pstate,
    2101             :                           List *colnames,
    2102             :                           ParseNamespaceColumn *nscolumns,
    2103             :                           JoinType jointype,
    2104             :                           int nummergedcols,
    2105             :                           List *aliasvars,
    2106             :                           List *leftcols,
    2107             :                           List *rightcols,
    2108             :                           Alias *alias,
    2109             :                           bool inFromCl)
    2110             : {
    2111       96826 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    2112             :     Alias      *eref;
    2113             :     int         numaliases;
    2114             :     ParseNamespaceItem *nsitem;
    2115             : 
    2116             :     Assert(pstate != NULL);
    2117             : 
    2118             :     /*
    2119             :      * Fail if join has too many columns --- we must be able to reference any
    2120             :      * of the columns with an AttrNumber.
    2121             :      */
    2122       96826 :     if (list_length(aliasvars) > MaxAttrNumber)
    2123           0 :         ereport(ERROR,
    2124             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2125             :                  errmsg("joins can have at most %d columns",
    2126             :                         MaxAttrNumber)));
    2127             : 
    2128       96826 :     rte->rtekind = RTE_JOIN;
    2129       96826 :     rte->relid = InvalidOid;
    2130       96826 :     rte->subquery = NULL;
    2131       96826 :     rte->jointype = jointype;
    2132       96826 :     rte->joinmergedcols = nummergedcols;
    2133       96826 :     rte->joinaliasvars = aliasvars;
    2134       96826 :     rte->joinleftcols = leftcols;
    2135       96826 :     rte->joinrightcols = rightcols;
    2136       96826 :     rte->alias = alias;
    2137             : 
    2138       96826 :     eref = alias ? copyObject(alias) : makeAlias("unnamed_join", NIL);
    2139       96826 :     numaliases = list_length(eref->colnames);
    2140             : 
    2141             :     /* fill in any unspecified alias columns */
    2142       96826 :     if (numaliases < list_length(colnames))
    2143       96738 :         eref->colnames = list_concat(eref->colnames,
    2144       96738 :                                      list_copy_tail(colnames, numaliases));
    2145             : 
    2146       96826 :     rte->eref = eref;
    2147             : 
    2148             :     /*
    2149             :      * Set flags and access permissions.
    2150             :      *
    2151             :      * Joins are never checked for access rights.
    2152             :      */
    2153       96826 :     rte->lateral = false;
    2154       96826 :     rte->inh = false;            /* never true for joins */
    2155       96826 :     rte->inFromCl = inFromCl;
    2156             : 
    2157       96826 :     rte->requiredPerms = 0;
    2158       96826 :     rte->checkAsUser = InvalidOid;
    2159       96826 :     rte->selectedCols = NULL;
    2160       96826 :     rte->insertedCols = NULL;
    2161       96826 :     rte->updatedCols = NULL;
    2162       96826 :     rte->extraUpdatedCols = NULL;
    2163             : 
    2164             :     /*
    2165             :      * Add completed RTE to pstate's range table list, so that we know its
    2166             :      * index.  But we don't add it to the join list --- caller must do that if
    2167             :      * appropriate.
    2168             :      */
    2169       96826 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    2170             : 
    2171             :     /*
    2172             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    2173             :      * list --- caller must do that if appropriate.
    2174             :      */
    2175       96826 :     nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
    2176       96826 :     nsitem->p_rte = rte;
    2177       96826 :     nsitem->p_rtindex = list_length(pstate->p_rtable);
    2178       96826 :     nsitem->p_nscolumns = nscolumns;
    2179             :     /* set default visibility flags; might get changed later */
    2180       96826 :     nsitem->p_rel_visible = true;
    2181       96826 :     nsitem->p_cols_visible = true;
    2182       96826 :     nsitem->p_lateral_only = false;
    2183       96826 :     nsitem->p_lateral_ok = true;
    2184             : 
    2185       96826 :     return nsitem;
    2186             : }
    2187             : 
    2188             : /*
    2189             :  * Add an entry for a CTE reference to the pstate's range table (p_rtable).
    2190             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    2191             :  *
    2192             :  * This is much like addRangeTableEntry() except that it makes a CTE RTE.
    2193             :  */
    2194             : ParseNamespaceItem *
    2195        1942 : addRangeTableEntryForCTE(ParseState *pstate,
    2196             :                          CommonTableExpr *cte,
    2197             :                          Index levelsup,
    2198             :                          RangeVar *rv,
    2199             :                          bool inFromCl)
    2200             : {
    2201        1942 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    2202        1942 :     Alias      *alias = rv->alias;
    2203        1942 :     char       *refname = alias ? alias->aliasname : cte->ctename;
    2204             :     Alias      *eref;
    2205             :     int         numaliases;
    2206             :     int         varattno;
    2207             :     ListCell   *lc;
    2208             : 
    2209             :     Assert(pstate != NULL);
    2210             : 
    2211        1942 :     rte->rtekind = RTE_CTE;
    2212        1942 :     rte->ctename = cte->ctename;
    2213        1942 :     rte->ctelevelsup = levelsup;
    2214             : 
    2215             :     /* Self-reference if and only if CTE's parse analysis isn't completed */
    2216        1942 :     rte->self_reference = !IsA(cte->ctequery, Query);
    2217             :     Assert(cte->cterecursive || !rte->self_reference);
    2218             :     /* Bump the CTE's refcount if this isn't a self-reference */
    2219        1942 :     if (!rte->self_reference)
    2220        1576 :         cte->cterefcount++;
    2221             : 
    2222             :     /*
    2223             :      * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
    2224             :      * This won't get checked in case of a self-reference, but that's OK
    2225             :      * because data-modifying CTEs aren't allowed to be recursive anyhow.
    2226             :      */
    2227        1942 :     if (IsA(cte->ctequery, Query))
    2228             :     {
    2229        1576 :         Query      *ctequery = (Query *) cte->ctequery;
    2230             : 
    2231        1576 :         if (ctequery->commandType != CMD_SELECT &&
    2232         158 :             ctequery->returningList == NIL)
    2233           4 :             ereport(ERROR,
    2234             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2235             :                      errmsg("WITH query \"%s\" does not have a RETURNING clause",
    2236             :                             cte->ctename),
    2237             :                      parser_errposition(pstate, rv->location)));
    2238             :     }
    2239             : 
    2240        1938 :     rte->coltypes = cte->ctecoltypes;
    2241        1938 :     rte->coltypmods = cte->ctecoltypmods;
    2242        1938 :     rte->colcollations = cte->ctecolcollations;
    2243             : 
    2244        1938 :     rte->alias = alias;
    2245        1938 :     if (alias)
    2246         100 :         eref = copyObject(alias);
    2247             :     else
    2248        1838 :         eref = makeAlias(refname, NIL);
    2249        1938 :     numaliases = list_length(eref->colnames);
    2250             : 
    2251             :     /* fill in any unspecified alias columns */
    2252        1938 :     varattno = 0;
    2253        6384 :     foreach(lc, cte->ctecolnames)
    2254             :     {
    2255        4446 :         varattno++;
    2256        4446 :         if (varattno > numaliases)
    2257        4446 :             eref->colnames = lappend(eref->colnames, lfirst(lc));
    2258             :     }
    2259        1938 :     if (varattno < numaliases)
    2260           0 :         ereport(ERROR,
    2261             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    2262             :                  errmsg("table \"%s\" has %d columns available but %d columns specified",
    2263             :                         refname, varattno, numaliases)));
    2264             : 
    2265        1938 :     rte->eref = eref;
    2266             : 
    2267             :     /*
    2268             :      * Set flags and access permissions.
    2269             :      *
    2270             :      * Subqueries are never checked for access rights.
    2271             :      */
    2272        1938 :     rte->lateral = false;
    2273        1938 :     rte->inh = false;            /* never true for subqueries */
    2274        1938 :     rte->inFromCl = inFromCl;
    2275             : 
    2276        1938 :     rte->requiredPerms = 0;
    2277        1938 :     rte->checkAsUser = InvalidOid;
    2278        1938 :     rte->selectedCols = NULL;
    2279        1938 :     rte->insertedCols = NULL;
    2280        1938 :     rte->updatedCols = NULL;
    2281        1938 :     rte->extraUpdatedCols = NULL;
    2282             : 
    2283             :     /*
    2284             :      * Add completed RTE to pstate's range table list, so that we know its
    2285             :      * index.  But we don't add it to the join list --- caller must do that if
    2286             :      * appropriate.
    2287             :      */
    2288        1938 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    2289             : 
    2290             :     /*
    2291             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    2292             :      * list --- caller must do that if appropriate.
    2293             :      */
    2294        1938 :     return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
    2295             :                                 rte->coltypes, rte->coltypmods,
    2296             :                                 rte->colcollations);
    2297             : }
    2298             : 
    2299             : /*
    2300             :  * Add an entry for an ephemeral named relation reference to the pstate's
    2301             :  * range table (p_rtable).
    2302             :  * Then, construct and return a ParseNamespaceItem for the new RTE.
    2303             :  *
    2304             :  * It is expected that the RangeVar, which up until now is only known to be an
    2305             :  * ephemeral named relation, will (in conjunction with the QueryEnvironment in
    2306             :  * the ParseState), create a RangeTblEntry for a specific *kind* of ephemeral
    2307             :  * named relation, based on enrtype.
    2308             :  *
    2309             :  * This is much like addRangeTableEntry() except that it makes an RTE for an
    2310             :  * ephemeral named relation.
    2311             :  */
    2312             : ParseNamespaceItem *
    2313         264 : addRangeTableEntryForENR(ParseState *pstate,
    2314             :                          RangeVar *rv,
    2315             :                          bool inFromCl)
    2316             : {
    2317         264 :     RangeTblEntry *rte = makeNode(RangeTblEntry);
    2318         264 :     Alias      *alias = rv->alias;
    2319         264 :     char       *refname = alias ? alias->aliasname : rv->relname;
    2320             :     EphemeralNamedRelationMetadata enrmd;
    2321             :     TupleDesc   tupdesc;
    2322             :     int         attno;
    2323             : 
    2324             :     Assert(pstate != NULL);
    2325         264 :     enrmd = get_visible_ENR(pstate, rv->relname);
    2326             :     Assert(enrmd != NULL);
    2327             : 
    2328         264 :     switch (enrmd->enrtype)
    2329             :     {
    2330         264 :         case ENR_NAMED_TUPLESTORE:
    2331         264 :             rte->rtekind = RTE_NAMEDTUPLESTORE;
    2332         264 :             break;
    2333             : 
    2334           0 :         default:
    2335           0 :             elog(ERROR, "unexpected enrtype: %d", enrmd->enrtype);
    2336             :             return NULL;        /* for fussy compilers */
    2337             :     }
    2338             : 
    2339             :     /*
    2340             :      * Record dependency on a relation.  This allows plans to be invalidated
    2341             :      * if they access transition tables linked to a table that is altered.
    2342             :      */
    2343         264 :     rte->relid = enrmd->reliddesc;
    2344             : 
    2345             :     /*
    2346             :      * Build the list of effective column names using user-supplied aliases
    2347             :      * and/or actual column names.
    2348             :      */
    2349         264 :     tupdesc = ENRMetadataGetTupDesc(enrmd);
    2350         264 :     rte->eref = makeAlias(refname, NIL);
    2351         264 :     buildRelationAliases(tupdesc, alias, rte->eref);
    2352             : 
    2353             :     /* Record additional data for ENR, including column type info */
    2354         264 :     rte->enrname = enrmd->name;
    2355         264 :     rte->enrtuples = enrmd->enrtuples;
    2356         264 :     rte->coltypes = NIL;
    2357         264 :     rte->coltypmods = NIL;
    2358         264 :     rte->colcollations = NIL;
    2359         876 :     for (attno = 1; attno <= tupdesc->natts; ++attno)
    2360             :     {
    2361         612 :         Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
    2362             : 
    2363         612 :         if (att->attisdropped)
    2364             :         {
    2365             :             /* Record zeroes for a dropped column */
    2366          12 :             rte->coltypes = lappend_oid(rte->coltypes, InvalidOid);
    2367          12 :             rte->coltypmods = lappend_int(rte->coltypmods, 0);
    2368          12 :             rte->colcollations = lappend_oid(rte->colcollations, InvalidOid);
    2369             :         }
    2370             :         else
    2371             :         {
    2372             :             /* Let's just make sure we can tell this isn't dropped */
    2373         600 :             if (att->atttypid == InvalidOid)
    2374           0 :                 elog(ERROR, "atttypid is invalid for non-dropped column in \"%s\"",
    2375             :                      rv->relname);
    2376         600 :             rte->coltypes = lappend_oid(rte->coltypes, att->atttypid);
    2377         600 :             rte->coltypmods = lappend_int(rte->coltypmods, att->atttypmod);
    2378         600 :             rte->colcollations = lappend_oid(rte->colcollations,
    2379             :                                              att->attcollation);
    2380             :         }
    2381             :     }
    2382             : 
    2383             :     /*
    2384             :      * Set flags and access permissions.
    2385             :      *
    2386             :      * ENRs are never checked for access rights.
    2387             :      */
    2388         264 :     rte->lateral = false;
    2389         264 :     rte->inh = false;            /* never true for ENRs */
    2390         264 :     rte->inFromCl = inFromCl;
    2391             : 
    2392         264 :     rte->requiredPerms = 0;
    2393         264 :     rte->checkAsUser = InvalidOid;
    2394         264 :     rte->selectedCols = NULL;
    2395             : 
    2396             :     /*
    2397             :      * Add completed RTE to pstate's range table list, so that we know its
    2398             :      * index.  But we don't add it to the join list --- caller must do that if
    2399             :      * appropriate.
    2400             :      */
    2401         264 :     pstate->p_rtable = lappend(pstate->p_rtable, rte);
    2402             : 
    2403             :     /*
    2404             :      * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
    2405             :      * list --- caller must do that if appropriate.
    2406             :      */
    2407         264 :     return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
    2408             :                                     tupdesc);
    2409             : }
    2410             : 
    2411             : 
    2412             : /*
    2413             :  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
    2414             :  *
    2415             :  * This is used when we have not yet done transformLockingClause, but need
    2416             :  * to know the correct lock to take during initial opening of relations.
    2417             :  *
    2418             :  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
    2419             :  * since the table-level lock is the same either way.
    2420             :  */
    2421             : bool
    2422      375138 : isLockedRefname(ParseState *pstate, const char *refname)
    2423             : {
    2424             :     ListCell   *l;
    2425             : 
    2426             :     /*
    2427             :      * If we are in a subquery specified as locked FOR UPDATE/SHARE from
    2428             :      * parent level, then act as though there's a generic FOR UPDATE here.
    2429             :      */
    2430      375138 :     if (pstate->p_locked_from_parent)
    2431           4 :         return true;
    2432             : 
    2433      375412 :     foreach(l, pstate->p_locking_clause)
    2434             :     {
    2435        4156 :         LockingClause *lc = (LockingClause *) lfirst(l);
    2436             : 
    2437        4156 :         if (lc->lockedRels == NIL)
    2438             :         {
    2439             :             /* all tables used in query */
    2440        3878 :             return true;
    2441             :         }
    2442             :         else
    2443             :         {
    2444             :             /* just the named tables */
    2445             :             ListCell   *l2;
    2446             : 
    2447        2894 :             foreach(l2, lc->lockedRels)
    2448             :             {
    2449        2616 :                 RangeVar   *thisrel = (RangeVar *) lfirst(l2);
    2450             : 
    2451        2616 :                 if (strcmp(refname, thisrel->relname) == 0)
    2452        2314 :                     return true;
    2453             :             }
    2454             :         }
    2455             :     }
    2456      371256 :     return false;
    2457             : }
    2458             : 
    2459             : /*
    2460             :  * Add the given nsitem/RTE as a top-level entry in the pstate's join list
    2461             :  * and/or namespace list.  (We assume caller has checked for any
    2462             :  * namespace conflicts.)  The nsitem is always marked as unconditionally
    2463             :  * visible, that is, not LATERAL-only.
    2464             :  */
    2465             : void
    2466       74950 : addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem,
    2467             :                  bool addToJoinList,
    2468             :                  bool addToRelNameSpace, bool addToVarNameSpace)
    2469             : {
    2470       74950 :     if (addToJoinList)
    2471             :     {
    2472       38510 :         RangeTblRef *rtr = makeNode(RangeTblRef);
    2473             : 
    2474       38510 :         rtr->rtindex = nsitem->p_rtindex;
    2475       38510 :         pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
    2476             :     }
    2477       74950 :     if (addToRelNameSpace || addToVarNameSpace)
    2478             :     {
    2479             :         /* Set the new nsitem's visibility flags correctly */
    2480       57288 :         nsitem->p_rel_visible = addToRelNameSpace;
    2481       57288 :         nsitem->p_cols_visible = addToVarNameSpace;
    2482       57288 :         nsitem->p_lateral_only = false;
    2483       57288 :         nsitem->p_lateral_ok = true;
    2484       57288 :         pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
    2485             :     }
    2486       74950 : }
    2487             : 
    2488             : /*
    2489             :  * expandRTE -- expand the columns of a rangetable entry
    2490             :  *
    2491             :  * This creates lists of an RTE's column names (aliases if provided, else
    2492             :  * real names) and Vars for each column.  Only user columns are considered.
    2493             :  * If include_dropped is false then dropped columns are omitted from the
    2494             :  * results.  If include_dropped is true then empty strings and NULL constants
    2495             :  * (not Vars!) are returned for dropped columns.
    2496             :  *
    2497             :  * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
    2498             :  * values to use in the created Vars.  Ordinarily rtindex should match the
    2499             :  * actual position of the RTE in its rangetable.
    2500             :  *
    2501             :  * The output lists go into *colnames and *colvars.
    2502             :  * If only one of the two kinds of output list is needed, pass NULL for the
    2503             :  * output pointer for the unwanted one.
    2504             :  */
    2505             : void
    2506        9104 : expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
    2507             :           int location, bool include_dropped,
    2508             :           List **colnames, List **colvars)
    2509             : {
    2510             :     int         varattno;
    2511             : 
    2512        9104 :     if (colnames)
    2513         332 :         *colnames = NIL;
    2514        9104 :     if (colvars)
    2515        9104 :         *colvars = NIL;
    2516             : 
    2517        9104 :     switch (rte->rtekind)
    2518             :     {
    2519          36 :         case RTE_RELATION:
    2520             :             /* Ordinary relation RTE */
    2521          36 :             expandRelation(rte->relid, rte->eref,
    2522             :                            rtindex, sublevels_up, location,
    2523             :                            include_dropped, colnames, colvars);
    2524          36 :             break;
    2525         296 :         case RTE_SUBQUERY:
    2526         296 :             {
    2527             :                 /* Subquery RTE */
    2528         296 :                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
    2529             :                 ListCell   *tlistitem;
    2530             : 
    2531         296 :                 varattno = 0;
    2532        1080 :                 foreach(tlistitem, rte->subquery->targetList)
    2533             :                 {
    2534         792 :                     TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
    2535             : 
    2536         792 :                     if (te->resjunk)
    2537           0 :                         continue;
    2538         792 :                     varattno++;
    2539             :                     Assert(varattno == te->resno);
    2540             : 
    2541             :                     /*
    2542             :                      * In scenarios where columns have been added to a view
    2543             :                      * since the outer query was originally parsed, there can
    2544             :                      * be more items in the subquery tlist than the outer
    2545             :                      * query expects.  We should ignore such extra column(s)
    2546             :                      * --- compare the behavior for composite-returning
    2547             :                      * functions, in the RTE_FUNCTION case below.
    2548             :                      */
    2549         792 :                     if (!aliasp_item)
    2550           8 :                         break;
    2551             : 
    2552         784 :                     if (colnames)
    2553             :                     {
    2554         784 :                         char       *label = strVal(lfirst(aliasp_item));
    2555             : 
    2556         784 :                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
    2557             :                     }
    2558             : 
    2559         784 :                     if (colvars)
    2560             :                     {
    2561             :                         Var        *varnode;
    2562             : 
    2563         784 :                         varnode = makeVar(rtindex, varattno,
    2564         784 :                                           exprType((Node *) te->expr),
    2565         784 :                                           exprTypmod((Node *) te->expr),
    2566         784 :                                           exprCollation((Node *) te->expr),
    2567             :                                           sublevels_up);
    2568         784 :                         varnode->location = location;
    2569             : 
    2570         784 :                         *colvars = lappend(*colvars, varnode);
    2571             :                     }
    2572             : 
    2573         784 :                     aliasp_item = lnext(rte->eref->colnames, aliasp_item);
    2574             :                 }
    2575             :             }
    2576         296 :             break;
    2577        7870 :         case RTE_FUNCTION:
    2578             :             {
    2579             :                 /* Function RTE */
    2580        7870 :                 int         atts_done = 0;
    2581             :                 ListCell   *lc;
    2582             : 
    2583       15760 :                 foreach(lc, rte->functions)
    2584             :                 {
    2585        7890 :                     RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
    2586             :                     TypeFuncClass functypclass;
    2587             :                     Oid         funcrettype;
    2588             :                     TupleDesc   tupdesc;
    2589             : 
    2590        7890 :                     functypclass = get_expr_result_type(rtfunc->funcexpr,
    2591             :                                                         &funcrettype,
    2592             :                                                         &tupdesc);
    2593        7890 :                     if (functypclass == TYPEFUNC_COMPOSITE ||
    2594             :                         functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
    2595             :                     {
    2596             :                         /* Composite data type, e.g. a table's row type */
    2597             :                         Assert(tupdesc);
    2598         876 :                         expandTupleDesc(tupdesc, rte->eref,
    2599             :                                         rtfunc->funccolcount, atts_done,
    2600             :                                         rtindex, sublevels_up, location,
    2601             :                                         include_dropped, colnames, colvars);
    2602             :                     }
    2603        7014 :                     else if (functypclass == TYPEFUNC_SCALAR)
    2604             :                     {
    2605             :                         /* Base data type, i.e. scalar */
    2606        7014 :                         if (colnames)
    2607           0 :                             *colnames = lappend(*colnames,
    2608           0 :                                                 list_nth(rte->eref->colnames,
    2609             :                                                          atts_done));
    2610             : 
    2611        7014 :                         if (colvars)
    2612             :                         {
    2613             :                             Var        *varnode;
    2614             : 
    2615        7014 :                             varnode = makeVar(rtindex, atts_done + 1,
    2616             :                                               funcrettype,
    2617        7014 :                                               exprTypmod(rtfunc->funcexpr),
    2618        7014 :                                               exprCollation(rtfunc->funcexpr),
    2619             :                                               sublevels_up);
    2620        7014 :                             varnode->location = location;
    2621             : 
    2622        7014 :                             *colvars = lappend(*colvars, varnode);
    2623             :                         }
    2624             :                     }
    2625           0 :                     else if (functypclass == TYPEFUNC_RECORD)
    2626             :                     {
    2627           0 :                         if (colnames)
    2628             :                         {
    2629             :                             List       *namelist;
    2630             : 
    2631             :                             /* extract appropriate subset of column list */
    2632           0 :                             namelist = list_copy_tail(rte->eref->colnames,
    2633             :                                                       atts_done);
    2634           0 :                             namelist = list_truncate(namelist,
    2635             :                                                      rtfunc->funccolcount);
    2636           0 :                             *colnames = list_concat(*colnames, namelist);
    2637             :                         }
    2638             : 
    2639           0 :                         if (colvars)
    2640             :                         {
    2641             :                             ListCell   *l1;
    2642             :                             ListCell   *l2;
    2643             :                             ListCell   *l3;
    2644           0 :                             int         attnum = atts_done;
    2645             : 
    2646           0 :                             forthree(l1, rtfunc->funccoltypes,
    2647             :                                      l2, rtfunc->funccoltypmods,
    2648             :                                      l3, rtfunc->funccolcollations)
    2649             :                             {
    2650           0 :                                 Oid         attrtype = lfirst_oid(l1);
    2651           0 :                                 int32       attrtypmod = lfirst_int(l2);
    2652           0 :                                 Oid         attrcollation = lfirst_oid(l3);
    2653             :                                 Var        *varnode;
    2654             : 
    2655           0 :                                 attnum++;
    2656           0 :                                 varnode = makeVar(rtindex,
    2657             :                                                   attnum,
    2658             :                                                   attrtype,
    2659             :                                                   attrtypmod,
    2660             :                                                   attrcollation,
    2661             :                                                   sublevels_up);
    2662           0 :                                 varnode->location = location;
    2663           0 :                                 *colvars = lappend(*colvars, varnode);
    2664             :                             }
    2665             :                         }
    2666             :                     }
    2667             :                     else
    2668             :                     {
    2669             :                         /* addRangeTableEntryForFunction should've caught this */
    2670           0 :                         elog(ERROR, "function in FROM has unsupported return type");
    2671             :                     }
    2672        7890 :                     atts_done += rtfunc->funccolcount;
    2673             :                 }
    2674             : 
    2675             :                 /* Append the ordinality column if any */
    2676        7870 :                 if (rte->funcordinality)
    2677             :                 {
    2678        6076 :                     if (colnames)
    2679           0 :                         *colnames = lappend(*colnames,
    2680           0 :                                             llast(rte->eref->colnames));
    2681             : 
    2682        6076 :                     if (colvars)
    2683             :                     {
    2684       12152 :                         Var        *varnode = makeVar(rtindex,
    2685        6076 :                                                       atts_done + 1,
    2686             :                                                       INT8OID,
    2687             :                                                       -1,
    2688             :                                                       InvalidOid,
    2689             :                                                       sublevels_up);
    2690             : 
    2691        6076 :                         *colvars = lappend(*colvars, varnode);
    2692             :                     }
    2693             :                 }
    2694             :             }
    2695        7870 :             break;
    2696           0 :         case RTE_JOIN:
    2697           0 :             {
    2698             :                 /* Join RTE */
    2699             :                 ListCell   *colname;
    2700             :                 ListCell   *aliasvar;
    2701             : 
    2702             :                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
    2703             : 
    2704           0 :                 varattno = 0;
    2705           0 :                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
    2706             :                 {
    2707           0 :                     Node       *avar = (Node *) lfirst(aliasvar);
    2708             : 
    2709           0 :                     varattno++;
    2710             : 
    2711             :                     /*
    2712             :                      * During ordinary parsing, there will never be any
    2713             :                      * deleted columns in the join.  While this function is
    2714             :                      * also used by the rewriter and planner, they do not
    2715             :                      * currently call it on any JOIN RTEs.  Therefore, this
    2716             :                      * next bit is dead code, but it seems prudent to handle
    2717             :                      * the case correctly anyway.
    2718             :                      */
    2719           0 :                     if (avar == NULL)
    2720             :                     {
    2721           0 :                         if (include_dropped)
    2722             :                         {
    2723           0 :                             if (colnames)
    2724           0 :                                 *colnames = lappend(*colnames,
    2725           0 :                                                     makeString(pstrdup("")));
    2726           0 :                             if (colvars)
    2727             :                             {
    2728             :                                 /*
    2729             :                                  * Can't use join's column type here (it might
    2730             :                                  * be dropped!); but it doesn't really matter
    2731             :                                  * what type the Const claims to be.
    2732             :                                  */
    2733           0 :                                 *colvars = lappend(*colvars,
    2734           0 :                                                    makeNullConst(INT4OID, -1,
    2735             :                                                                  InvalidOid));
    2736             :                             }
    2737             :                         }
    2738           0 :                         continue;
    2739             :                     }
    2740             : 
    2741           0 :                     if (colnames)
    2742             :                     {
    2743           0 :                         char       *label = strVal(lfirst(colname));
    2744             : 
    2745           0 :                         *colnames = lappend(*colnames,
    2746           0 :                                             makeString(pstrdup(label)));
    2747             :                     }
    2748             : 
    2749           0 :                     if (colvars)
    2750             :                     {
    2751             :                         Var        *varnode;
    2752             : 
    2753             :                         /*
    2754             :                          * If the joinaliasvars entry is a simple Var, just
    2755             :                          * copy it (with adjustment of varlevelsup and
    2756             :                          * location); otherwise it is a JOIN USING column and
    2757             :                          * we must generate a join alias Var.  This matches
    2758             :                          * the results that expansion of "join.*" by
    2759             :                          * expandNSItemVars would have produced, if we had
    2760             :                          * access to the ParseNamespaceItem for the join.
    2761             :                          */
    2762           0 :                         if (IsA(avar, Var))
    2763             :                         {
    2764           0 :                             varnode = copyObject((Var *) avar);
    2765           0 :                             varnode->varlevelsup = sublevels_up;
    2766             :                         }
    2767             :                         else
    2768           0 :                             varnode = makeVar(rtindex, varattno,
    2769             :                                               exprType(avar),
    2770             :                                               exprTypmod(avar),
    2771             :                                               exprCollation(avar),
    2772             :                                               sublevels_up);
    2773           0 :                         varnode->location = location;
    2774             : 
    2775           0 :                         *colvars = lappend(*colvars, varnode);
    2776             :                     }
    2777             :                 }
    2778             :             }
    2779           0 :             break;
    2780         902 :         case RTE_TABLEFUNC:
    2781             :         case RTE_VALUES:
    2782             :         case RTE_CTE:
    2783             :         case RTE_NAMEDTUPLESTORE:
    2784         902 :             {
    2785             :                 /* Tablefunc, Values, CTE, or ENR RTE */
    2786         902 :                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
    2787             :                 ListCell   *lct;
    2788             :                 ListCell   *lcm;
    2789             :                 ListCell   *lcc;
    2790             : 
    2791         902 :                 varattno = 0;
    2792        2640 :                 forthree(lct, rte->coltypes,
    2793             :                          lcm, rte->coltypmods,
    2794             :                          lcc, rte->colcollations)
    2795             :                 {
    2796        1738 :                     Oid         coltype = lfirst_oid(lct);
    2797        1738 :                     int32       coltypmod = lfirst_int(lcm);
    2798        1738 :                     Oid         colcoll = lfirst_oid(lcc);
    2799             : 
    2800        1738 :                     varattno++;
    2801             : 
    2802        1738 :                     if (colnames)
    2803             :                     {
    2804             :                         /* Assume there is one alias per output column */
    2805           0 :                         if (OidIsValid(coltype))
    2806             :                         {
    2807           0 :                             char       *label = strVal(lfirst(aliasp_item));
    2808             : 
    2809           0 :                             *colnames = lappend(*colnames,
    2810           0 :                                                 makeString(pstrdup(label)));
    2811             :                         }
    2812           0 :                         else if (include_dropped)
    2813           0 :                             *colnames = lappend(*colnames,
    2814           0 :                                                 makeString(pstrdup("")));
    2815             : 
    2816           0 :                         aliasp_item = lnext(rte->eref->colnames, aliasp_item);
    2817             :                     }
    2818             : 
    2819        1738 :                     if (colvars)
    2820             :                     {
    2821        1738 :                         if (OidIsValid(coltype))
    2822             :                         {
    2823             :                             Var        *varnode;
    2824             : 
    2825        1738 :                             varnode = makeVar(rtindex, varattno,
    2826             :                                               coltype, coltypmod, colcoll,
    2827             :                                               sublevels_up);
    2828        1738 :                             varnode->location = location;
    2829             : 
    2830        1738 :                             *colvars = lappend(*colvars, varnode);
    2831             :                         }
    2832           0 :                         else if (include_dropped)
    2833             :                         {
    2834             :                             /*
    2835             :                              * It doesn't really matter what type the Const
    2836             :                              * claims to be.
    2837             :                              */
    2838           0 :                             *colvars = lappend(*colvars,
    2839           0 :                                                makeNullConst(INT4OID, -1,
    2840             :                                                              InvalidOid));
    2841             :                         }
    2842             :                     }
    2843             :                 }
    2844             :             }
    2845         902 :             break;
    2846           0 :         case RTE_RESULT:
    2847             :             /* These expose no columns, so nothing to do */
    2848           0 :             break;
    2849           0 :         default:
    2850           0 :             elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
    2851             :     }
    2852        9104 : }
    2853             : 
    2854             : /*
    2855             :  * expandRelation -- expandRTE subroutine
    2856             :  */
    2857             : static void
    2858          36 : expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
    2859             :                int location, bool include_dropped,
    2860             :                List **colnames, List **colvars)
    2861             : {
    2862             :     Relation    rel;
    2863             : 
    2864             :     /* Get the tupledesc and turn it over to expandTupleDesc */
    2865          36 :     rel = relation_open(relid, AccessShareLock);
    2866          36 :     expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
    2867             :                     rtindex, sublevels_up,
    2868             :                     location, include_dropped,
    2869             :                     colnames, colvars);
    2870          36 :     relation_close(rel, AccessShareLock);
    2871          36 : }
    2872             : 
    2873             : /*
    2874             :  * expandTupleDesc -- expandRTE subroutine
    2875             :  *
    2876             :  * Generate names and/or Vars for the first "count" attributes of the tupdesc,
    2877             :  * and append them to colnames/colvars.  "offset" is added to the varattno
    2878             :  * that each Var would otherwise have, and we also skip the first "offset"
    2879             :  * entries in eref->colnames.  (These provisions allow use of this code for
    2880             :  * an individual composite-returning function in an RTE_FUNCTION RTE.)
    2881             :  */
    2882             : static void
    2883         912 : expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset,
    2884             :                 int rtindex, int sublevels_up,
    2885             :                 int location, bool include_dropped,
    2886             :                 List **colnames, List **colvars)
    2887             : {
    2888             :     ListCell   *aliascell;
    2889             :     int         varattno;
    2890             : 
    2891         912 :     aliascell = (offset < list_length(eref->colnames)) ?
    2892         912 :         list_nth_cell(eref->colnames, offset) : NULL;
    2893             : 
    2894             :     Assert(count <= tupdesc->natts);
    2895       10366 :     for (varattno = 0; varattno < count; varattno++)
    2896             :     {
    2897        9454 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
    2898             : 
    2899        9454 :         if (attr->attisdropped)
    2900             :         {
    2901           0 :             if (include_dropped)
    2902             :             {
    2903           0 :                 if (colnames)
    2904           0 :                     *colnames = lappend(*colnames, makeString(pstrdup("")));
    2905           0 :                 if (colvars)
    2906             :                 {
    2907             :                     /*
    2908             :                      * can't use atttypid here, but it doesn't really matter
    2909             :                      * what type the Const claims to be.
    2910             :                      */
    2911           0 :                     *colvars = lappend(*colvars,
    2912           0 :                                        makeNullConst(INT4OID, -1, InvalidOid));
    2913             :                 }
    2914             :             }
    2915           0 :             if (aliascell)
    2916           0 :                 aliascell = lnext(eref->colnames, aliascell);
    2917           0 :             continue;
    2918             :         }
    2919             : 
    2920        9454 :         if (colnames)
    2921             :         {
    2922             :             char       *label;
    2923             : 
    2924          92 :             if (aliascell)
    2925             :             {
    2926          92 :                 label = strVal(lfirst(aliascell));
    2927          92 :                 aliascell = lnext(eref->colnames, aliascell);
    2928             :             }
    2929             :             else
    2930             :             {
    2931             :                 /* If we run out of aliases, use the underlying name */
    2932           0 :                 label = NameStr(attr->attname);
    2933             :             }
    2934          92 :             *colnames = lappend(*colnames, makeString(pstrdup(label)));
    2935             :         }
    2936             : 
    2937        9454 :         if (colvars)
    2938             :         {
    2939             :             Var        *varnode;
    2940             : 
    2941        9454 :             varnode = makeVar(rtindex, varattno + offset + 1,
    2942             :                               attr->atttypid, attr->atttypmod,
    2943             :                               attr->attcollation,
    2944             :                               sublevels_up);
    2945        9454 :             varnode->location = location;
    2946             : 
    2947        9454 :             *colvars = lappend(*colvars, varnode);
    2948             :         }
    2949             :     }
    2950         912 : }
    2951             : 
    2952             : /*
    2953             :  * expandNSItemVars
    2954             :  *    Produce a list of Vars, and optionally a list of column names,
    2955             :  *    for the non-dropped columns of the nsitem.
    2956             :  *
    2957             :  * The emitted Vars are marked with the given sublevels_up and location.
    2958             :  *
    2959             :  * If colnames isn't NULL, a list of String items for the columns is stored
    2960             :  * there; note that it's just a subset of the RTE's eref list, and hence
    2961             :  * the list elements mustn't be modified.
    2962             :  */
    2963             : List *
    2964       39538 : expandNSItemVars(ParseNamespaceItem *nsitem,
    2965             :                  int sublevels_up, int location,
    2966             :                  List **colnames)
    2967             : {
    2968       39538 :     List       *result = NIL;
    2969             :     int         colindex;
    2970             :     ListCell   *lc;
    2971             : 
    2972       39538 :     if (colnames)
    2973       37058 :         *colnames = NIL;
    2974       39538 :     colindex = 0;
    2975      199810 :     foreach(lc, nsitem->p_rte->eref->colnames)
    2976             :     {
    2977      160272 :         Value      *colnameval = (Value *) lfirst(lc);
    2978      160272 :         const char *colname = strVal(colnameval);
    2979      160272 :         ParseNamespaceColumn *nscol = nsitem->p_nscolumns + colindex;
    2980             : 
    2981      160272 :         if (colname[0])
    2982             :         {
    2983             :             Var        *var;
    2984             : 
    2985             :             Assert(nscol->p_varno > 0);
    2986      319120 :             var = makeVar(nscol->p_varno,
    2987      159560 :                           nscol->p_varattno,
    2988             :                           nscol->p_vartype,
    2989             :                           nscol->p_vartypmod,
    2990             :                           nscol->p_varcollid,
    2991             :                           sublevels_up);
    2992             :             /* makeVar doesn't offer parameters for these, so set by hand: */
    2993      159560 :             var->varnosyn = nscol->p_varnosyn;
    2994      159560 :             var->varattnosyn = nscol->p_varattnosyn;
    2995      159560 :             var->location = location;
    2996      159560 :             result = lappend(result, var);
    2997      159560 :             if (colnames)
    2998      155302 :                 *colnames = lappend(*colnames, colnameval);
    2999             :         }
    3000             :         else
    3001             :         {
    3002             :             /* dropped column, ignore */
    3003             :             Assert(nscol->p_varno == 0);
    3004             :         }
    3005      160272 :         colindex++;
    3006             :     }
    3007       39538 :     return result;
    3008             : }
    3009             : 
    3010             : /*
    3011             :  * expandNSItemAttrs -
    3012             :  *    Workhorse for "*" expansion: produce a list of targetentries
    3013             :  *    for the attributes of the nsitem
    3014             :  *
    3015             :  * pstate->p_next_resno determines the resnos assigned to the TLEs.
    3016             :  * The referenced columns are marked as requiring SELECT access.
    3017             :  */
    3018             : List *
    3019       37058 : expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem,
    3020             :                   int sublevels_up, int location)
    3021             : {
    3022       37058 :     RangeTblEntry *rte = nsitem->p_rte;
    3023             :     List       *names,
    3024             :                *vars;
    3025             :     ListCell   *name,
    3026             :                *var;
    3027       37058 :     List       *te_list = NIL;
    3028             : 
    3029       37058 :     vars = expandNSItemVars(nsitem, sublevels_up, location, &names);
    3030             : 
    3031             :     /*
    3032             :      * Require read access to the table.  This is normally redundant with the
    3033             :      * markVarForSelectPriv calls below, but not if the table has zero
    3034             :      * columns.
    3035             :      */
    3036       37058 :     rte->requiredPerms |= ACL_SELECT;
    3037             : 
    3038      192360 :     forboth(name, names, var, vars)
    3039             :     {
    3040      155302 :         char       *label = strVal(lfirst(name));
    3041      155302 :         Var        *varnode = (Var *) lfirst(var);
    3042             :         TargetEntry *te;
    3043             : 
    3044      155302 :         te = makeTargetEntry((Expr *) varnode,
    3045      155302 :                              (AttrNumber) pstate->p_next_resno++,
    3046             :                              label,
    3047             :                              false);
    3048      155302 :         te_list = lappend(te_list, te);
    3049             : 
    3050             :         /* Require read access to each column */
    3051      155302 :         markVarForSelectPriv(pstate, varnode, rte);
    3052             :     }
    3053             : 
    3054             :     Assert(name == NULL && var == NULL);    /* lists not the same length? */
    3055             : 
    3056       37058 :     return te_list;
    3057             : }
    3058             : 
    3059             : /*
    3060             :  * get_rte_attribute_name
    3061             :  *      Get an attribute name from a RangeTblEntry
    3062             :  *
    3063             :  * This is unlike get_attname() because we use aliases if available.
    3064             :  * In particular, it will work on an RTE for a subselect or join, whereas
    3065             :  * get_attname() only works on real relations.
    3066             :  *
    3067             :  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
    3068             :  * occurs when a Var represents a whole tuple of a relation.
    3069             :  */
    3070             : char *
    3071         630 : get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
    3072             : {
    3073         630 :     if (attnum == InvalidAttrNumber)
    3074           0 :         return "*";
    3075             : 
    3076             :     /*
    3077             :      * If there is a user-written column alias, use it.
    3078             :      */
    3079         630 :     if (rte->alias &&
    3080          36 :         attnum > 0 && attnum <= list_length(rte->alias->colnames))
    3081           0 :         return strVal(list_nth(rte->alias->colnames, attnum - 1));
    3082             : 
    3083             :     /*
    3084             :      * If the RTE is a relation, go to the system catalogs not the
    3085             :      * eref->colnames list.  This is a little slower but it will give the
    3086             :      * right answer if the column has been renamed since the eref list was
    3087             :      * built (which can easily happen for rules).
    3088             :      */
    3089         630 :     if (rte->rtekind == RTE_RELATION)
    3090         610 :         return get_attname(rte->relid, attnum, false);
    3091             : 
    3092             :     /*
    3093             :      * Otherwise use the column name from eref.  There should always be one.
    3094             :      */
    3095          20 :     if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
    3096          20 :         return strVal(list_nth(rte->eref->colnames, attnum - 1));
    3097             : 
    3098             :     /* else caller gave us a bogus attnum */
    3099           0 :     elog(ERROR, "invalid attnum %d for rangetable entry %s",
    3100             :          attnum, rte->eref->aliasname);
    3101             :     return NULL;                /* keep compiler quiet */
    3102             : }
    3103             : 
    3104             : /*
    3105             :  * get_rte_attribute_is_dropped
    3106             :  *      Check whether attempted attribute ref is to a dropped column
    3107             :  */
    3108             : bool
    3109      354322 : get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
    3110             : {
    3111             :     bool        result;
    3112             : 
    3113      354322 :     switch (rte->rtekind)
    3114             :     {
    3115      320642 :         case RTE_RELATION:
    3116             :             {
    3117             :                 /*
    3118             :                  * Plain relation RTE --- get the attribute's catalog entry
    3119             :                  */
    3120             :                 HeapTuple   tp;
    3121             :                 Form_pg_attribute att_tup;
    3122             : 
    3123      641284 :                 tp = SearchSysCache2(ATTNUM,
    3124      320642 :                                      ObjectIdGetDatum(rte->relid),
    3125             :                                      Int16GetDatum(attnum));
    3126      320642 :                 if (!HeapTupleIsValid(tp))  /* shouldn't happen */
    3127           0 :                     elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    3128             :                          attnum, rte->relid);
    3129      320642 :                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
    3130      320642 :                 result = att_tup->attisdropped;
    3131      320642 :                 ReleaseSysCache(tp);
    3132             :             }
    3133      320642 :             break;
    3134          64 :         case RTE_SUBQUERY:
    3135             :         case RTE_TABLEFUNC:
    3136             :         case RTE_VALUES:
    3137             :         case RTE_CTE:
    3138             : 
    3139             :             /*
    3140             :              * Subselect, Table Functions, Values, CTE RTEs never have dropped
    3141             :              * columns
    3142             :              */
    3143          64 :             result = false;
    3144          64 :             break;
    3145           0 :         case RTE_NAMEDTUPLESTORE:
    3146             :             {
    3147             :                 /* Check dropped-ness by testing for valid coltype */
    3148           0 :                 if (attnum <= 0 ||
    3149           0 :                     attnum > list_length(rte->coltypes))
    3150           0 :                     elog(ERROR, "invalid varattno %d", attnum);
    3151           0 :                 result = !OidIsValid((list_nth_oid(rte->coltypes, attnum - 1)));
    3152             :             }
    3153           0 :             break;
    3154           0 :         case RTE_JOIN:
    3155             :             {
    3156             :                 /*
    3157             :                  * A join RTE would not have dropped columns when constructed,
    3158             :                  * but one in a stored rule might contain columns that were
    3159             :                  * dropped from the underlying tables, if said columns are
    3160             :                  * nowhere explicitly referenced in the rule.  This will be
    3161             :                  * signaled to us by a null pointer in the joinaliasvars list.
    3162             :                  */
    3163             :                 Var        *aliasvar;
    3164             : 
    3165           0 :                 if (attnum <= 0 ||
    3166           0 :                     attnum > list_length(rte->joinaliasvars))
    3167           0 :                     elog(ERROR, "invalid varattno %d", attnum);
    3168           0 :                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
    3169             : 
    3170           0 :                 result = (aliasvar == NULL);
    3171             :             }
    3172           0 :             break;
    3173       33616 :         case RTE_FUNCTION:
    3174             :             {
    3175             :                 /* Function RTE */
    3176             :                 ListCell   *lc;
    3177       33616 :                 int         atts_done = 0;
    3178             : 
    3179             :                 /*
    3180             :                  * Dropped attributes are only possible with functions that
    3181             :                  * return named composite types.  In such a case we have to
    3182             :                  * look up the result type to see if it currently has this
    3183             :                  * column dropped.  So first, loop over the funcs until we
    3184             :                  * find the one that covers the requested column.
    3185             :                  */
    3186       33656 :                 foreach(lc, rte->functions)
    3187             :                 {
    3188       33640 :                     RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
    3189             : 
    3190       33640 :                     if (attnum > atts_done &&
    3191       33640 :                         attnum <= atts_done + rtfunc->funccolcount)
    3192             :                     {
    3193             :                         TupleDesc   tupdesc;
    3194             : 
    3195       33600 :                         tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr,
    3196             :                                                           true);
    3197       33600 :                         if (tupdesc)
    3198             :                         {
    3199             :                             /* Composite data type, e.g. a table's row type */
    3200             :                             Form_pg_attribute att_tup;
    3201             : 
    3202             :                             Assert(tupdesc);
    3203             :                             Assert(attnum - atts_done <= tupdesc->natts);
    3204       33576 :                             att_tup = TupleDescAttr(tupdesc,
    3205             :                                                     attnum - atts_done - 1);
    3206       33600 :                             return att_tup->attisdropped;
    3207             :                         }
    3208             :                         /* Otherwise, it can't have any dropped columns */
    3209          24 :                         return false;
    3210             :                     }
    3211          40 :                     atts_done += rtfunc->funccolcount;
    3212             :                 }
    3213             : 
    3214             :                 /* If we get here, must be looking for the ordinality column */
    3215          16 :                 if (rte->funcordinality && attnum == atts_done + 1)
    3216          16 :                     return false;
    3217             : 
    3218             :                 /* this probably can't happen ... */
    3219           0 :                 ereport(ERROR,
    3220             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
    3221             :                          errmsg("column %d of relation \"%s\" does not exist",
    3222             :                                 attnum,
    3223             :                                 rte->eref->aliasname)));
    3224             :                 result = false; /* keep compiler quiet */
    3225             :             }
    3226             :             break;
    3227           0 :         case RTE_RESULT:
    3228             :             /* this probably can't happen ... */
    3229           0 :             ereport(ERROR,
    3230             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    3231             :                      errmsg("column %d of relation \"%s\" does not exist",
    3232             :                             attnum,
    3233             :                             rte->eref->aliasname)));
    3234             :             result = false;     /* keep compiler quiet */
    3235             :             break;
    3236           0 :         default:
    3237           0 :             elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
    3238             :             result = false;     /* keep compiler quiet */
    3239             :     }
    3240             : 
    3241      320706 :     return result;
    3242             : }
    3243             : 
    3244             : /*
    3245             :  * Given a targetlist and a resno, return the matching TargetEntry
    3246             :  *
    3247             :  * Returns NULL if resno is not present in list.
    3248             :  *
    3249             :  * Note: we need to search, rather than just indexing with list_nth(),
    3250             :  * because not all tlists are sorted by resno.
    3251             :  */
    3252             : TargetEntry *
    3253      205606 : get_tle_by_resno(List *tlist, AttrNumber resno)
    3254             : {
    3255             :     ListCell   *l;
    3256             : 
    3257      688188 :     foreach(l, tlist)
    3258             :     {
    3259      687916 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
    3260             : 
    3261      687916 :         if (tle->resno == resno)
    3262      205334 :             return tle;
    3263             :     }
    3264         272 :     return NULL;
    3265             : }
    3266             : 
    3267             : /*
    3268             :  * Given a Query and rangetable index, return relation's RowMarkClause if any
    3269             :  *
    3270             :  * Returns NULL if relation is not selected FOR UPDATE/SHARE
    3271             :  */
    3272             : RowMarkClause *
    3273       19466 : get_parse_rowmark(Query *qry, Index rtindex)
    3274             : {
    3275             :     ListCell   *l;
    3276             : 
    3277       19694 :     foreach(l, qry->rowMarks)
    3278             :     {
    3279         292 :         RowMarkClause *rc = (RowMarkClause *) lfirst(l);
    3280             : 
    3281         292 :         if (rc->rti == rtindex)
    3282          64 :             return rc;
    3283             :     }
    3284       19402 :     return NULL;
    3285             : }
    3286             : 
    3287             : /*
    3288             :  *  given relation and att name, return attnum of variable
    3289             :  *
    3290             :  *  Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
    3291             :  *
    3292             :  *  This should only be used if the relation is already
    3293             :  *  table_open()'ed.  Use the cache version get_attnum()
    3294             :  *  for access to non-opened relations.
    3295             :  */
    3296             : int
    3297       48660 : attnameAttNum(Relation rd, const char *attname, bool sysColOK)
    3298             : {
    3299             :     int         i;
    3300             : 
    3301      249544 :     for (i = 0; i < RelationGetNumberOfAttributes(rd); i++)
    3302             :     {
    3303      249478 :         Form_pg_attribute att = TupleDescAttr(rd->rd_att, i);
    3304             : 
    3305      249478 :         if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
    3306       48594 :             return i + 1;
    3307             :     }
    3308             : 
    3309          66 :     if (sysColOK)
    3310             :     {
    3311           8 :         if ((i = specialAttNum(attname)) != InvalidAttrNumber)
    3312           0 :             return i;
    3313             :     }
    3314             : 
    3315             :     /* on failure */
    3316          66 :     return InvalidAttrNumber;
    3317             : }
    3318             : 
    3319             : /* specialAttNum()
    3320             :  *
    3321             :  * Check attribute name to see if it is "special", e.g. "xmin".
    3322             :  * - thomas 2000-02-07
    3323             :  *
    3324             :  * Note: this only discovers whether the name could be a system attribute.
    3325             :  * Caller needs to ensure that it really is an attribute of the rel.
    3326             :  */
    3327             : static int
    3328      102212 : specialAttNum(const char *attname)
    3329             : {
    3330             :     const FormData_pg_attribute *sysatt;
    3331             : 
    3332      102212 :     sysatt = SystemAttributeByName(attname);
    3333      102212 :     if (sysatt != NULL)
    3334       39448 :         return sysatt->attnum;
    3335       62764 :     return InvalidAttrNumber;
    3336             : }
    3337             : 
    3338             : 
    3339             : /*
    3340             :  * given attribute id, return name of that attribute
    3341             :  *
    3342             :  *  This should only be used if the relation is already
    3343             :  *  table_open()'ed.  Use the cache version get_atttype()
    3344             :  *  for access to non-opened relations.
    3345             :  */
    3346             : const NameData *
    3347        7022 : attnumAttName(Relation rd, int attid)
    3348             : {
    3349        7022 :     if (attid <= 0)
    3350             :     {
    3351             :         const FormData_pg_attribute *sysatt;
    3352             : 
    3353           0 :         sysatt = SystemAttributeDefinition(attid);
    3354           0 :         return &sysatt->attname;
    3355             :     }
    3356        7022 :     if (attid > rd->rd_att->natts)
    3357           0 :         elog(ERROR, "invalid attribute number %d", attid);
    3358        7022 :     return &TupleDescAttr(rd->rd_att, attid - 1)->attname;
    3359             : }
    3360             : 
    3361             : /*
    3362             :  * given attribute id, return type of that attribute
    3363             :  *
    3364             :  *  This should only be used if the relation is already
    3365             :  *  table_open()'ed.  Use the cache version get_atttype()
    3366             :  *  for access to non-opened relations.
    3367             :  */
    3368             : Oid
    3369      249002 : attnumTypeId(Relation rd, int attid)
    3370             : {
    3371      249002 :     if (attid <= 0)
    3372             :     {
    3373             :         const FormData_pg_attribute *sysatt;
    3374             : 
    3375           0 :         sysatt = SystemAttributeDefinition(attid);
    3376           0 :         return sysatt->atttypid;
    3377             :     }
    3378      249002 :     if (attid > rd->rd_att->natts)
    3379           0 :         elog(ERROR, "invalid attribute number %d", attid);
    3380      249002 :     return TupleDescAttr(rd->rd_att, attid - 1)->atttypid;
    3381             : }
    3382             : 
    3383             : /*
    3384             :  * given attribute id, return collation of that attribute
    3385             :  *
    3386             :  *  This should only be used if the relation is already table_open()'ed.
    3387             :  */
    3388             : Oid
    3389        2656 : attnumCollationId(Relation rd, int attid)
    3390             : {
    3391        2656 :     if (attid <= 0)
    3392             :     {
    3393             :         /* All system attributes are of noncollatable types. */
    3394           0 :         return InvalidOid;
    3395             :     }
    3396        2656 :     if (attid > rd->rd_att->natts)
    3397           0 :         elog(ERROR, "invalid attribute number %d", attid);
    3398        2656 :     return TupleDescAttr(rd->rd_att, attid - 1)->attcollation;
    3399             : }
    3400             : 
    3401             : /*
    3402             :  * Generate a suitable error about a missing RTE.
    3403             :  *
    3404             :  * Since this is a very common type of error, we work rather hard to
    3405             :  * produce a helpful message.
    3406             :  */
    3407             : void
    3408          48 : errorMissingRTE(ParseState *pstate, RangeVar *relation)
    3409             : {
    3410             :     RangeTblEntry *rte;
    3411          48 :     const char *badAlias = NULL;
    3412             : 
    3413             :     /*
    3414             :      * Check to see if there are any potential matches in the query's
    3415             :      * rangetable.  (Note: cases involving a bad schema name in the RangeVar
    3416             :      * will throw error immediately here.  That seems OK.)
    3417             :      */
    3418          48 :     rte = searchRangeTableForRel(pstate, relation);
    3419             : 
    3420             :     /*
    3421             :      * If we found a match that has an alias and the alias is visible in the
    3422             :      * namespace, then the problem is probably use of the relation's real name
    3423             :      * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
    3424             :      * common enough to justify a specific hint.
    3425             :      *
    3426             :      * If we found a match that doesn't meet those criteria, assume the
    3427             :      * problem is illegal use of a relation outside its scope, as in the
    3428             :      * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
    3429             :      */
    3430          48 :     if (rte && rte->alias &&
    3431          32 :         strcmp(rte->eref->aliasname, relation->relname) != 0)
    3432             :     {
    3433             :         ParseNamespaceItem *nsitem;
    3434             :         int         sublevels_up;
    3435             : 
    3436          16 :         nsitem = refnameNamespaceItem(pstate, NULL, rte->eref->aliasname,
    3437             :                                       relation->location,
    3438             :                                       &sublevels_up);
    3439          16 :         if (nsitem && nsitem->p_rte == rte)
    3440          16 :             badAlias = rte->eref->aliasname;
    3441             :     }
    3442             : 
    3443          48 :     if (rte)
    3444          40 :         ereport(ERROR,
    3445             :                 (errcode(ERRCODE_UNDEFINED_TABLE),
    3446             :                  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
    3447             :                         relation->relname),
    3448             :                  (badAlias ?
    3449             :                   errhint("Perhaps you meant to reference the table alias \"%s\".",
    3450             :                           badAlias) :
    3451             :                   errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
    3452             :                           rte->eref->aliasname)),
    3453             :                  parser_errposition(pstate, relation->location)));
    3454             :     else
    3455           8 :         ereport(ERROR,
    3456             :                 (errcode(ERRCODE_UNDEFINED_TABLE),
    3457             :                  errmsg("missing FROM-clause entry for table \"%s\"",
    3458             :                         relation->relname),
    3459             :                  parser_errposition(pstate, relation->location)));
    3460             : }
    3461             : 
    3462             : /*
    3463             :  * Generate a suitable error about a missing column.
    3464             :  *
    3465             :  * Since this is a very common type of error, we work rather hard to
    3466             :  * produce a helpful message.
    3467             :  */
    3468             : void
    3469         202 : errorMissingColumn(ParseState *pstate,
    3470             :                    const char *relname, const char *colname, int location)
    3471             : {
    3472             :     FuzzyAttrMatchState *state;
    3473         202 :     char       *closestfirst = NULL;
    3474             : 
    3475             :     /*
    3476             :      * Search the entire rtable looking for possible matches.  If we find one,
    3477             :      * emit a hint about it.
    3478             :      *
    3479             :      * TODO: improve this code (and also errorMissingRTE) to mention using
    3480             :      * LATERAL if appropriate.
    3481             :      */
    3482         202 :     state = searchRangeTableForCol(pstate, relname, colname, location);
    3483             : 
    3484             :     /*
    3485             :      * Extract closest col string for best match, if any.
    3486             :      *
    3487             :      * Infer an exact match referenced despite not being visible from the fact
    3488             :      * that an attribute number was not present in state passed back -- this
    3489             :      * is what is reported when !closestfirst.  There might also be an exact
    3490             :      * match that was qualified with an incorrect alias, in which case
    3491             :      * closestfirst will be set (so hint is the same as generic fuzzy case).
    3492             :      */
    3493         202 :     if (state->rfirst && AttributeNumberIsValid(state->first))
    3494          36 :         closestfirst = strVal(list_nth(state->rfirst->eref->colnames,
    3495             :                                        state->first - 1));
    3496             : 
    3497         202 :     if (!state->rsecond)
    3498             :     {
    3499             :         /*
    3500             :          * Handle case where there is zero or one column suggestions to hint,
    3501             :          * including exact matches referenced but not visible.
    3502             :          */
    3503         198 :         ereport(ERROR,
    3504             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3505             :                  relname ?
    3506             :                  errmsg("column %s.%s does not exist", relname, colname) :
    3507             :                  errmsg("column \"%s\" does not exist", colname),
    3508             :                  state->rfirst ? closestfirst ?
    3509             :                  errhint("Perhaps you meant to reference the column \"%s.%s\".",
    3510             :                          state->rfirst->eref->aliasname, closestfirst) :
    3511             :                  errhint("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
    3512             :                          colname, state->rfirst->eref->aliasname) : 0,
    3513             :                  parser_errposition(pstate, location)));
    3514             :     }
    3515             :     else
    3516             :     {
    3517             :         /* Handle case where there are two equally useful column hints */
    3518             :         char       *closestsecond;
    3519             : 
    3520           4 :         closestsecond = strVal(list_nth(state->rsecond->eref->colnames,
    3521             :                                         state->second - 1));
    3522             : 
    3523           4 :         ereport(ERROR,
    3524             :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    3525             :                  relname ?
    3526             :                  errmsg("column %s.%s does not exist", relname, colname) :
    3527             :                  errmsg("column \"%s\" does not exist", colname),
    3528             :                  errhint("Perhaps you meant to reference the column \"%s.%s\" or the column \"%s.%s\".",
    3529             :                          state->rfirst->eref->aliasname, closestfirst,
    3530             :                          state->rsecond->eref->aliasname, closestsecond),
    3531             :                  parser_errposition(pstate, location)));
    3532             :     }
    3533             : }
    3534             : 
    3535             : 
    3536             : /*
    3537             :  * Examine a fully-parsed query, and return true iff any relation underlying
    3538             :  * the query is a temporary relation (table, view, or materialized view).
    3539             :  */
    3540             : bool
    3541       47420 : isQueryUsingTempRelation(Query *query)
    3542             : {
    3543       47420 :     return isQueryUsingTempRelation_walker((Node *) query, NULL);
    3544             : }
    3545             : 
    3546             : static bool
    3547     4834340 : isQueryUsingTempRelation_walker(Node *node, void *context)
    3548             : {
    3549     4834340 :     if (node == NULL)
    3550     1170900 :         return false;
    3551             : 
    3552     3663440 :     if (IsA(node, Query))
    3553             :     {
    3554       86514 :         Query      *query = (Query *) node;
    3555             :         ListCell   *rtable;
    3556             : 
    3557      326922 :         foreach(rtable, query->rtable)
    3558             :         {
    3559      240480 :             RangeTblEntry *rte = lfirst(rtable);
    3560             : 
    3561      240480 :             if (rte->rtekind == RTE_RELATION)
    3562             :             {
    3563      147432 :                 Relation    rel = table_open(rte->relid, AccessShareLock);
    3564      147432 :                 char        relpersistence = rel->rd_rel->relpersistence;
    3565             : 
    3566      147432 :                 table_close(rel, AccessShareLock);
    3567      147432 :                 if (relpersistence == RELPERSISTENCE_TEMP)
    3568          72 :                     return true;
    3569             :             }
    3570             :         }
    3571             : 
    3572       86442 :         return query_tree_walker(query,
    3573             :                                  isQueryUsingTempRelation_walker,
    3574             :                                  context,
    3575             :                                  QTW_IGNORE_JOINALIASES);
    3576             :     }
    3577             : 
    3578     3576926 :     return expression_tree_walker(node,
    3579             :                                   isQueryUsingTempRelation_walker,
    3580             :                                   context);
    3581             : }

Generated by: LCOV version 1.13