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

Generated by: LCOV version 1.13