PostgreSQL Source Code  git master
parse_relation.c File Reference
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/heap.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_enr.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
#include "storage/lmgr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
Include dependency graph for parse_relation.c:

Go to the source code of this file.

Data Structures

struct  FuzzyAttrMatchState
 

Macros

#define MAX_FUZZY_DISTANCE   3
 

Functions

static ParseNamespaceItemscanNameSpaceForRefname (ParseState *pstate, const char *refname, int location)
 
static ParseNamespaceItemscanNameSpaceForRelid (ParseState *pstate, Oid relid, int location)
 
static void check_lateral_ref_ok (ParseState *pstate, ParseNamespaceItem *nsitem, int location)
 
static int scanRTEForColumn (ParseState *pstate, RangeTblEntry *rte, Alias *eref, const char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
 
static void markRTEForSelectPriv (ParseState *pstate, int rtindex, AttrNumber col)
 
static void expandRelation (Oid relid, Alias *eref, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
 
static void expandTupleDesc (TupleDesc tupdesc, Alias *eref, int count, int offset, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
 
static int specialAttNum (const char *attname)
 
static bool rte_visible_if_lateral (ParseState *pstate, RangeTblEntry *rte)
 
static bool rte_visible_if_qualified (ParseState *pstate, RangeTblEntry *rte)
 
static bool isQueryUsingTempRelation_walker (Node *node, void *context)
 
ParseNamespaceItemrefnameNamespaceItem (ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
 
CommonTableExprscanNameSpaceForCTE (ParseState *pstate, const char *refname, Index *ctelevelsup)
 
static bool isFutureCTE (ParseState *pstate, const char *refname)
 
bool scanNameSpaceForENR (ParseState *pstate, const char *refname)
 
static RangeTblEntrysearchRangeTableForRel (ParseState *pstate, RangeVar *relation)
 
void checkNameSpaceConflicts (ParseState *pstate, List *namespace1, List *namespace2)
 
ParseNamespaceItemGetNSItemByRangeTablePosn (ParseState *pstate, int varno, int sublevels_up)
 
RangeTblEntryGetRTEByRangeTablePosn (ParseState *pstate, int varno, int sublevels_up)
 
CommonTableExprGetCTEForRTE (ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
 
static void updateFuzzyAttrMatchState (int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate, RangeTblEntry *rte, const char *actual, const char *match, int attnum)
 
NodescanNSItemForColumn (ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, const char *colname, int location)
 
NodecolNameToVar (ParseState *pstate, const char *colname, bool localonly, int location)
 
static FuzzyAttrMatchStatesearchRangeTableForCol (ParseState *pstate, const char *alias, const char *colname, int location)
 
void markNullableIfNeeded (ParseState *pstate, Var *var)
 
void markVarForSelectPriv (ParseState *pstate, Var *var)
 
static void buildRelationAliases (TupleDesc tupdesc, Alias *alias, Alias *eref)
 
static char * chooseScalarFunctionAlias (Node *funcexpr, char *funcname, Alias *alias, int nfuncs)
 
static ParseNamespaceItembuildNSItemFromTupleDesc (RangeTblEntry *rte, Index rtindex, RTEPermissionInfo *perminfo, TupleDesc tupdesc)
 
static ParseNamespaceItembuildNSItemFromLists (RangeTblEntry *rte, Index rtindex, List *coltypes, List *coltypmods, List *colcollations)
 
Relation parserOpenTable (ParseState *pstate, const RangeVar *relation, int lockmode)
 
ParseNamespaceItemaddRangeTableEntry (ParseState *pstate, RangeVar *relation, Alias *alias, bool inh, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForRelation (ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForSubquery (ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForFunction (ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, RangeFunction *rangefunc, bool lateral, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForTableFunc (ParseState *pstate, TableFunc *tf, Alias *alias, bool lateral, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForValues (ParseState *pstate, List *exprs, List *coltypes, List *coltypmods, List *colcollations, Alias *alias, bool lateral, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForJoin (ParseState *pstate, List *colnames, ParseNamespaceColumn *nscolumns, JoinType jointype, int nummergedcols, List *aliasvars, List *leftcols, List *rightcols, Alias *join_using_alias, Alias *alias, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForCTE (ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
 
ParseNamespaceItemaddRangeTableEntryForENR (ParseState *pstate, RangeVar *rv, bool inFromCl)
 
bool isLockedRefname (ParseState *pstate, const char *refname)
 
void addNSItemToQuery (ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
 
void expandRTE (RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
 
ListexpandNSItemVars (ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
 
ListexpandNSItemAttrs (ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, bool require_col_privs, int location)
 
char * get_rte_attribute_name (RangeTblEntry *rte, AttrNumber attnum)
 
bool get_rte_attribute_is_dropped (RangeTblEntry *rte, AttrNumber attnum)
 
TargetEntryget_tle_by_resno (List *tlist, AttrNumber resno)
 
RowMarkClauseget_parse_rowmark (Query *qry, Index rtindex)
 
int attnameAttNum (Relation rd, const char *attname, bool sysColOK)
 
const NameDataattnumAttName (Relation rd, int attid)
 
Oid attnumTypeId (Relation rd, int attid)
 
Oid attnumCollationId (Relation rd, int attid)
 
void errorMissingRTE (ParseState *pstate, RangeVar *relation)
 
void errorMissingColumn (ParseState *pstate, const char *relname, const char *colname, int location)
 
static ParseNamespaceItemfindNSItemForRTE (ParseState *pstate, RangeTblEntry *rte)
 
bool isQueryUsingTempRelation (Query *query)
 
RTEPermissionInfoaddRTEPermissionInfo (List **rteperminfos, RangeTblEntry *rte)
 
RTEPermissionInfogetRTEPermissionInfo (List *rteperminfos, RangeTblEntry *rte)
 

Macro Definition Documentation

◆ MAX_FUZZY_DISTANCE

#define MAX_FUZZY_DISTANCE   3

Definition at line 75 of file parse_relation.c.

Function Documentation

◆ addNSItemToQuery()

void addNSItemToQuery ( ParseState pstate,
ParseNamespaceItem nsitem,
bool  addToJoinList,
bool  addToRelNameSpace,
bool  addToVarNameSpace 
)

Definition at line 2625 of file parse_relation.c.

2628 {
2629  if (addToJoinList)
2630  {
2632 
2633  rtr->rtindex = nsitem->p_rtindex;
2634  pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2635  }
2636  if (addToRelNameSpace || addToVarNameSpace)
2637  {
2638  /* Set the new nsitem's visibility flags correctly */
2639  nsitem->p_rel_visible = addToRelNameSpace;
2640  nsitem->p_cols_visible = addToVarNameSpace;
2641  nsitem->p_lateral_only = false;
2642  nsitem->p_lateral_ok = true;
2643  pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
2644  }
2645 }
List * lappend(List *list, void *datum)
Definition: list.c:338
#define makeNode(_type_)
Definition: nodes.h:176
List * p_namespace
Definition: parse_node.h:200
List * p_joinlist
Definition: parse_node.h:198

References lappend(), makeNode, ParseNamespaceItem::p_cols_visible, ParseState::p_joinlist, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseState::p_namespace, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rtindex, and RangeTblRef::rtindex.

Referenced by AddRelationNewConstraints(), AlterPolicy(), CreatePolicy(), CreateTriggerFiringOn(), DefineRelation(), DoCopy(), setTargetTable(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformAlterTableStmt(), transformIndexStmt(), transformInsertStmt(), transformMergeStmt(), transformOnConflictClause(), transformPartitionSpec(), TransformPubWhereClauses(), transformRuleStmt(), transformSetOperationStmt(), transformStatsStmt(), and transformValuesClause().

◆ addRangeTableEntry()

ParseNamespaceItem* addRangeTableEntry ( ParseState pstate,
RangeVar relation,
Alias alias,
bool  inh,
bool  inFromCl 
)

Definition at line 1470 of file parse_relation.c.

1475 {
1477  RTEPermissionInfo *perminfo;
1478  char *refname = alias ? alias->aliasname : relation->relname;
1479  LOCKMODE lockmode;
1480  Relation rel;
1481  ParseNamespaceItem *nsitem;
1482 
1483  Assert(pstate != NULL);
1484 
1485  rte->rtekind = RTE_RELATION;
1486  rte->alias = alias;
1487 
1488  /*
1489  * Identify the type of lock we'll need on this relation. It's not the
1490  * query's target table (that case is handled elsewhere), so we need
1491  * either RowShareLock if it's locked by FOR UPDATE/SHARE, or plain
1492  * AccessShareLock otherwise.
1493  */
1494  lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
1495 
1496  /*
1497  * Get the rel's OID. This access also ensures that we have an up-to-date
1498  * relcache entry for the rel. Since this is typically the first access
1499  * to a rel in a statement, we must open the rel with the proper lockmode.
1500  */
1501  rel = parserOpenTable(pstate, relation, lockmode);
1502  rte->relid = RelationGetRelid(rel);
1503  rte->relkind = rel->rd_rel->relkind;
1504  rte->rellockmode = lockmode;
1505 
1506  /*
1507  * Build the list of effective column names using user-supplied aliases
1508  * and/or actual column names.
1509  */
1510  rte->eref = makeAlias(refname, NIL);
1511  buildRelationAliases(rel->rd_att, alias, rte->eref);
1512 
1513  /*
1514  * Set flags and initialize access permissions.
1515  *
1516  * The initial default on access checks is always check-for-READ-access,
1517  * which is the right thing for all except target tables.
1518  */
1519  rte->lateral = false;
1520  rte->inh = inh;
1521  rte->inFromCl = inFromCl;
1522 
1523  perminfo = addRTEPermissionInfo(&pstate->p_rteperminfos, rte);
1524  perminfo->requiredPerms = ACL_SELECT;
1525 
1526  /*
1527  * Add completed RTE to pstate's range table list, so that we know its
1528  * index. But we don't add it to the join list --- caller must do that if
1529  * appropriate.
1530  */
1531  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1532 
1533  /*
1534  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1535  * list --- caller must do that if appropriate.
1536  */
1537  nsitem = buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
1538  perminfo, rel->rd_att);
1539 
1540  /*
1541  * Drop the rel refcount, but keep the access lock till end of transaction
1542  * so that the table can't be deleted or have its schema modified
1543  * underneath us.
1544  */
1545  table_close(rel, NoLock);
1546 
1547  return nsitem;
1548 }
Assert(fmt[strlen(fmt) - 1] !='\n')
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
#define RowShareLock
Definition: lockdefs.h:37
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:390
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
Relation parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
static ParseNamespaceItem * buildNSItemFromTupleDesc(RangeTblEntry *rte, Index rtindex, RTEPermissionInfo *perminfo, TupleDesc tupdesc)
bool isLockedRefname(ParseState *pstate, const char *refname)
static void buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
@ RTE_RELATION
Definition: parsenodes.h:1013
#define ACL_SELECT
Definition: parsenodes.h:84
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define RelationGetRelid(relation)
Definition: rel.h:504
char * aliasname
Definition: primnodes.h:42
List * p_rteperminfos
Definition: parse_node.h:194
List * p_rtable
Definition: parse_node.h:193
AclMode requiredPerms
Definition: parsenodes.h:1245
Alias * eref
Definition: parsenodes.h:1199
Alias * alias
Definition: parsenodes.h:1198
RTEKind rtekind
Definition: parsenodes.h:1032
char * relname
Definition: primnodes.h:74
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126

References AccessShareLock, ACL_SELECT, addRTEPermissionInfo(), RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromTupleDesc(), buildRelationAliases(), RangeTblEntry::eref, RangeTblEntry::inFromCl, RangeTblEntry::inh, isLockedRefname(), lappend(), RangeTblEntry::lateral, list_length(), makeAlias(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, parserOpenTable(), RelationData::rd_att, RelationData::rd_rel, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, RangeVar::relname, RTEPermissionInfo::requiredPerms, RowShareLock, RTE_RELATION, RangeTblEntry::rtekind, and table_close().

Referenced by transformTableEntry().

◆ addRangeTableEntryForCTE()

ParseNamespaceItem* addRangeTableEntryForCTE ( ParseState pstate,
CommonTableExpr cte,
Index  levelsup,
RangeVar rv,
bool  inFromCl 
)

Definition at line 2319 of file parse_relation.c.

2324 {
2326  Alias *alias = rv->alias;
2327  char *refname = alias ? alias->aliasname : cte->ctename;
2328  Alias *eref;
2329  int numaliases;
2330  int varattno;
2331  ListCell *lc;
2332  int n_dontexpand_columns = 0;
2333  ParseNamespaceItem *psi;
2334 
2335  Assert(pstate != NULL);
2336 
2337  rte->rtekind = RTE_CTE;
2338  rte->ctename = cte->ctename;
2339  rte->ctelevelsup = levelsup;
2340 
2341  /* Self-reference if and only if CTE's parse analysis isn't completed */
2342  rte->self_reference = !IsA(cte->ctequery, Query);
2343  Assert(cte->cterecursive || !rte->self_reference);
2344  /* Bump the CTE's refcount if this isn't a self-reference */
2345  if (!rte->self_reference)
2346  cte->cterefcount++;
2347 
2348  /*
2349  * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
2350  * This won't get checked in case of a self-reference, but that's OK
2351  * because data-modifying CTEs aren't allowed to be recursive anyhow.
2352  */
2353  if (IsA(cte->ctequery, Query))
2354  {
2355  Query *ctequery = (Query *) cte->ctequery;
2356 
2357  if (ctequery->commandType != CMD_SELECT &&
2358  ctequery->returningList == NIL)
2359  ereport(ERROR,
2360  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2361  errmsg("WITH query \"%s\" does not have a RETURNING clause",
2362  cte->ctename),
2363  parser_errposition(pstate, rv->location)));
2364  }
2365 
2366  rte->coltypes = list_copy(cte->ctecoltypes);
2367  rte->coltypmods = list_copy(cte->ctecoltypmods);
2368  rte->colcollations = list_copy(cte->ctecolcollations);
2369 
2370  rte->alias = alias;
2371  if (alias)
2372  eref = copyObject(alias);
2373  else
2374  eref = makeAlias(refname, NIL);
2375  numaliases = list_length(eref->colnames);
2376 
2377  /* fill in any unspecified alias columns */
2378  varattno = 0;
2379  foreach(lc, cte->ctecolnames)
2380  {
2381  varattno++;
2382  if (varattno > numaliases)
2383  eref->colnames = lappend(eref->colnames, lfirst(lc));
2384  }
2385  if (varattno < numaliases)
2386  ereport(ERROR,
2387  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2388  errmsg("table \"%s\" has %d columns available but %d columns specified",
2389  refname, varattno, numaliases)));
2390 
2391  rte->eref = eref;
2392 
2393  if (cte->search_clause)
2394  {
2395  rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->search_clause->search_seq_column));
2396  if (cte->search_clause->search_breadth_first)
2397  rte->coltypes = lappend_oid(rte->coltypes, RECORDOID);
2398  else
2399  rte->coltypes = lappend_oid(rte->coltypes, RECORDARRAYOID);
2400  rte->coltypmods = lappend_int(rte->coltypmods, -1);
2402 
2403  n_dontexpand_columns += 1;
2404  }
2405 
2406  if (cte->cycle_clause)
2407  {
2408  rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->cycle_clause->cycle_mark_column));
2409  rte->coltypes = lappend_oid(rte->coltypes, cte->cycle_clause->cycle_mark_type);
2410  rte->coltypmods = lappend_int(rte->coltypmods, cte->cycle_clause->cycle_mark_typmod);
2411  rte->colcollations = lappend_oid(rte->colcollations, cte->cycle_clause->cycle_mark_collation);
2412 
2413  rte->eref->colnames = lappend(rte->eref->colnames, makeString(cte->cycle_clause->cycle_path_column));
2414  rte->coltypes = lappend_oid(rte->coltypes, RECORDARRAYOID);
2415  rte->coltypmods = lappend_int(rte->coltypmods, -1);
2417 
2418  n_dontexpand_columns += 2;
2419  }
2420 
2421  /*
2422  * Set flags and access permissions.
2423  *
2424  * Subqueries are never checked for access rights, so no need to perform
2425  * addRTEPermissionInfo().
2426  */
2427  rte->lateral = false;
2428  rte->inh = false; /* never true for subqueries */
2429  rte->inFromCl = inFromCl;
2430 
2431  /*
2432  * Add completed RTE to pstate's range table list, so that we know its
2433  * index. But we don't add it to the join list --- caller must do that if
2434  * appropriate.
2435  */
2436  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2437 
2438  /*
2439  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2440  * list --- caller must do that if appropriate.
2441  */
2442  psi = buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2443  rte->coltypes, rte->coltypmods,
2444  rte->colcollations);
2445 
2446  /*
2447  * The columns added by search and cycle clauses are not included in star
2448  * expansion in queries contained in the CTE.
2449  */
2450  if (rte->ctelevelsup > 0)
2451  for (int i = 0; i < n_dontexpand_columns; i++)
2452  psi->p_nscolumns[list_length(psi->p_names->colnames) - 1 - i].p_dontexpand = true;
2453 
2454  return psi;
2455 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * lappend_int(List *list, int datum)
Definition: list.c:356
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
List * list_copy(const List *oldlist)
Definition: list.c:1572
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define copyObject(obj)
Definition: nodes.h:244
@ CMD_SELECT
Definition: nodes.h:276
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
static ParseNamespaceItem * buildNSItemFromLists(RangeTblEntry *rte, Index rtindex, List *coltypes, List *coltypmods, List *colcollations)
@ RTE_CTE
Definition: parsenodes.h:1019
#define lfirst(lc)
Definition: pg_list.h:172
#define InvalidOid
Definition: postgres_ext.h:36
List * colnames
Definition: primnodes.h:43
ParseNamespaceColumn * p_nscolumns
Definition: parse_node.h:290
List * returningList
Definition: parsenodes.h:195
CmdType commandType
Definition: parsenodes.h:127
List * colcollations
Definition: parsenodes.h:1187
char * ctename
Definition: parsenodes.h:1163
bool self_reference
Definition: parsenodes.h:1165
Index ctelevelsup
Definition: parsenodes.h:1164
List * coltypes
Definition: parsenodes.h:1185
List * coltypmods
Definition: parsenodes.h:1186
int location
Definition: primnodes.h:86
Alias * alias
Definition: primnodes.h:83
String * makeString(char *str)
Definition: value.c:63

References RangeTblEntry::alias, RangeVar::alias, Alias::aliasname, Assert(), buildNSItemFromLists(), CMD_SELECT, RangeTblEntry::colcollations, Alias::colnames, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, Query::commandType, copyObject, RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, CommonTableExpr::ctename, CommonTableExpr::ctequery, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, i, if(), RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, IsA, lappend(), lappend_int(), lappend_oid(), RangeTblEntry::lateral, lfirst, list_copy(), list_length(), RangeVar::location, makeAlias(), makeNode, makeString(), NIL, ParseNamespaceColumn::p_dontexpand, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseState::p_rtable, parser_errposition(), Query::returningList, RTE_CTE, RangeTblEntry::rtekind, and RangeTblEntry::self_reference.

Referenced by getNSItemForSpecialRelationTypes().

◆ addRangeTableEntryForENR()

ParseNamespaceItem* addRangeTableEntryForENR ( ParseState pstate,
RangeVar rv,
bool  inFromCl 
)

Definition at line 2471 of file parse_relation.c.

2474 {
2476  Alias *alias = rv->alias;
2477  char *refname = alias ? alias->aliasname : rv->relname;
2479  TupleDesc tupdesc;
2480  int attno;
2481 
2482  Assert(pstate != NULL);
2483  enrmd = get_visible_ENR(pstate, rv->relname);
2484  Assert(enrmd != NULL);
2485 
2486  switch (enrmd->enrtype)
2487  {
2488  case ENR_NAMED_TUPLESTORE:
2490  break;
2491 
2492  default:
2493  elog(ERROR, "unexpected enrtype: %d", enrmd->enrtype);
2494  return NULL; /* for fussy compilers */
2495  }
2496 
2497  /*
2498  * Record dependency on a relation. This allows plans to be invalidated
2499  * if they access transition tables linked to a table that is altered.
2500  */
2501  rte->relid = enrmd->reliddesc;
2502 
2503  /*
2504  * Build the list of effective column names using user-supplied aliases
2505  * and/or actual column names.
2506  */
2507  tupdesc = ENRMetadataGetTupDesc(enrmd);
2508  rte->eref = makeAlias(refname, NIL);
2509  buildRelationAliases(tupdesc, alias, rte->eref);
2510 
2511  /* Record additional data for ENR, including column type info */
2512  rte->enrname = enrmd->name;
2513  rte->enrtuples = enrmd->enrtuples;
2514  rte->coltypes = NIL;
2515  rte->coltypmods = NIL;
2516  rte->colcollations = NIL;
2517  for (attno = 1; attno <= tupdesc->natts; ++attno)
2518  {
2519  Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
2520 
2521  if (att->attisdropped)
2522  {
2523  /* Record zeroes for a dropped column */
2524  rte->coltypes = lappend_oid(rte->coltypes, InvalidOid);
2525  rte->coltypmods = lappend_int(rte->coltypmods, 0);
2527  }
2528  else
2529  {
2530  /* Let's just make sure we can tell this isn't dropped */
2531  if (att->atttypid == InvalidOid)
2532  elog(ERROR, "atttypid is invalid for non-dropped column in \"%s\"",
2533  rv->relname);
2534  rte->coltypes = lappend_oid(rte->coltypes, att->atttypid);
2535  rte->coltypmods = lappend_int(rte->coltypmods, att->atttypmod);
2537  att->attcollation);
2538  }
2539  }
2540 
2541  /*
2542  * Set flags and access permissions.
2543  *
2544  * ENRs are never checked for access rights, so no need to perform
2545  * addRTEPermissionInfo().
2546  */
2547  rte->lateral = false;
2548  rte->inh = false; /* never true for ENRs */
2549  rte->inFromCl = inFromCl;
2550 
2551  /*
2552  * Add completed RTE to pstate's range table list, so that we know its
2553  * index. But we don't add it to the join list --- caller must do that if
2554  * appropriate.
2555  */
2556  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2557 
2558  /*
2559  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2560  * list --- caller must do that if appropriate.
2561  */
2562  return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable), NULL,
2563  tupdesc);
2564 }
EphemeralNamedRelationMetadata get_visible_ENR(ParseState *pstate, const char *refname)
Definition: parse_enr.c:26
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1020
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
TupleDesc ENRMetadataGetTupDesc(EphemeralNamedRelationMetadata enrmd)
@ ENR_NAMED_TUPLESTORE
EphemeralNameRelationType enrtype
char * enrname
Definition: parsenodes.h:1192
Cardinality enrtuples
Definition: parsenodes.h:1193
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References RangeVar::alias, Alias::aliasname, Assert(), buildNSItemFromTupleDesc(), buildRelationAliases(), RangeTblEntry::colcollations, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, elog(), ENR_NAMED_TUPLESTORE, ENRMetadataGetTupDesc(), RangeTblEntry::enrname, RangeTblEntry::enrtuples, EphemeralNamedRelationMetadataData::enrtuples, EphemeralNamedRelationMetadataData::enrtype, RangeTblEntry::eref, ERROR, get_visible_ENR(), RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, lappend(), lappend_int(), lappend_oid(), RangeTblEntry::lateral, list_length(), makeAlias(), makeNode, EphemeralNamedRelationMetadataData::name, TupleDescData::natts, NIL, ParseState::p_rtable, RangeTblEntry::relid, EphemeralNamedRelationMetadataData::reliddesc, RangeVar::relname, RTE_NAMEDTUPLESTORE, RangeTblEntry::rtekind, and TupleDescAttr.

Referenced by getNSItemForSpecialRelationTypes().

◆ addRangeTableEntryForFunction()

ParseNamespaceItem* addRangeTableEntryForFunction ( ParseState pstate,
List funcnames,
List funcexprs,
List coldeflists,
RangeFunction rangefunc,
bool  lateral,
bool  inFromCl 
)

Definition at line 1735 of file parse_relation.c.

1742 {
1744  Alias *alias = rangefunc->alias;
1745  Alias *eref;
1746  char *aliasname;
1747  int nfuncs = list_length(funcexprs);
1748  TupleDesc *functupdescs;
1749  TupleDesc tupdesc;
1750  ListCell *lc1,
1751  *lc2,
1752  *lc3;
1753  int i;
1754  int j;
1755  int funcno;
1756  int natts,
1757  totalatts;
1758 
1759  Assert(pstate != NULL);
1760 
1761  rte->rtekind = RTE_FUNCTION;
1762  rte->relid = InvalidOid;
1763  rte->subquery = NULL;
1764  rte->functions = NIL; /* we'll fill this list below */
1765  rte->funcordinality = rangefunc->ordinality;
1766  rte->alias = alias;
1767 
1768  /*
1769  * Choose the RTE alias name. We default to using the first function's
1770  * name even when there's more than one; which is maybe arguable but beats
1771  * using something constant like "table".
1772  */
1773  if (alias)
1774  aliasname = alias->aliasname;
1775  else
1776  aliasname = linitial(funcnames);
1777 
1778  eref = makeAlias(aliasname, NIL);
1779  rte->eref = eref;
1780 
1781  /* Process each function ... */
1782  functupdescs = (TupleDesc *) palloc(nfuncs * sizeof(TupleDesc));
1783 
1784  totalatts = 0;
1785  funcno = 0;
1786  forthree(lc1, funcexprs, lc2, funcnames, lc3, coldeflists)
1787  {
1788  Node *funcexpr = (Node *) lfirst(lc1);
1789  char *funcname = (char *) lfirst(lc2);
1790  List *coldeflist = (List *) lfirst(lc3);
1792  TypeFuncClass functypclass;
1793  Oid funcrettype;
1794 
1795  /* Initialize RangeTblFunction node */
1796  rtfunc->funcexpr = funcexpr;
1797  rtfunc->funccolnames = NIL;
1798  rtfunc->funccoltypes = NIL;
1799  rtfunc->funccoltypmods = NIL;
1800  rtfunc->funccolcollations = NIL;
1801  rtfunc->funcparams = NULL; /* not set until planning */
1802 
1803  /*
1804  * Now determine if the function returns a simple or composite type.
1805  */
1806  functypclass = get_expr_result_type(funcexpr,
1807  &funcrettype,
1808  &tupdesc);
1809 
1810  /*
1811  * A coldeflist is required if the function returns RECORD and hasn't
1812  * got a predetermined record type, and is prohibited otherwise. This
1813  * can be a bit confusing, so we expend some effort on delivering a
1814  * relevant error message.
1815  */
1816  if (coldeflist != NIL)
1817  {
1818  switch (functypclass)
1819  {
1820  case TYPEFUNC_RECORD:
1821  /* ok */
1822  break;
1823  case TYPEFUNC_COMPOSITE:
1825 
1826  /*
1827  * If the function's raw result type is RECORD, we must
1828  * have resolved it using its OUT parameters. Otherwise,
1829  * it must have a named composite type.
1830  */
1831  if (exprType(funcexpr) == RECORDOID)
1832  ereport(ERROR,
1833  (errcode(ERRCODE_SYNTAX_ERROR),
1834  errmsg("a column definition list is redundant for a function with OUT parameters"),
1835  parser_errposition(pstate,
1836  exprLocation((Node *) coldeflist))));
1837  else
1838  ereport(ERROR,
1839  (errcode(ERRCODE_SYNTAX_ERROR),
1840  errmsg("a column definition list is redundant for a function returning a named composite type"),
1841  parser_errposition(pstate,
1842  exprLocation((Node *) coldeflist))));
1843  break;
1844  default:
1845  ereport(ERROR,
1846  (errcode(ERRCODE_SYNTAX_ERROR),
1847  errmsg("a column definition list is only allowed for functions returning \"record\""),
1848  parser_errposition(pstate,
1849  exprLocation((Node *) coldeflist))));
1850  break;
1851  }
1852  }
1853  else
1854  {
1855  if (functypclass == TYPEFUNC_RECORD)
1856  ereport(ERROR,
1857  (errcode(ERRCODE_SYNTAX_ERROR),
1858  errmsg("a column definition list is required for functions returning \"record\""),
1859  parser_errposition(pstate, exprLocation(funcexpr))));
1860  }
1861 
1862  if (functypclass == TYPEFUNC_COMPOSITE ||
1863  functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
1864  {
1865  /* Composite data type, e.g. a table's row type */
1866  Assert(tupdesc);
1867  }
1868  else if (functypclass == TYPEFUNC_SCALAR)
1869  {
1870  /* Base data type, i.e. scalar */
1871  tupdesc = CreateTemplateTupleDesc(1);
1872  TupleDescInitEntry(tupdesc,
1873  (AttrNumber) 1,
1875  alias, nfuncs),
1876  funcrettype,
1877  exprTypmod(funcexpr),
1878  0);
1880  (AttrNumber) 1,
1881  exprCollation(funcexpr));
1882  }
1883  else if (functypclass == TYPEFUNC_RECORD)
1884  {
1885  ListCell *col;
1886 
1887  /*
1888  * Use the column definition list to construct a tupdesc and fill
1889  * in the RangeTblFunction's lists. Limit number of columns to
1890  * MaxHeapAttributeNumber, because CheckAttributeNamesTypes will.
1891  */
1892  if (list_length(coldeflist) > MaxHeapAttributeNumber)
1893  ereport(ERROR,
1894  (errcode(ERRCODE_TOO_MANY_COLUMNS),
1895  errmsg("column definition lists can have at most %d entries",
1897  parser_errposition(pstate,
1898  exprLocation((Node *) coldeflist))));
1899  tupdesc = CreateTemplateTupleDesc(list_length(coldeflist));
1900  i = 1;
1901  foreach(col, coldeflist)
1902  {
1903  ColumnDef *n = (ColumnDef *) lfirst(col);
1904  char *attrname;
1905  Oid attrtype;
1906  int32 attrtypmod;
1907  Oid attrcollation;
1908 
1909  attrname = n->colname;
1910  if (n->typeName->setof)
1911  ereport(ERROR,
1912  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1913  errmsg("column \"%s\" cannot be declared SETOF",
1914  attrname),
1915  parser_errposition(pstate, n->location)));
1916  typenameTypeIdAndMod(pstate, n->typeName,
1917  &attrtype, &attrtypmod);
1918  attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1919  TupleDescInitEntry(tupdesc,
1920  (AttrNumber) i,
1921  attrname,
1922  attrtype,
1923  attrtypmod,
1924  0);
1926  (AttrNumber) i,
1927  attrcollation);
1928  rtfunc->funccolnames = lappend(rtfunc->funccolnames,
1929  makeString(pstrdup(attrname)));
1930  rtfunc->funccoltypes = lappend_oid(rtfunc->funccoltypes,
1931  attrtype);
1932  rtfunc->funccoltypmods = lappend_int(rtfunc->funccoltypmods,
1933  attrtypmod);
1934  rtfunc->funccolcollations = lappend_oid(rtfunc->funccolcollations,
1935  attrcollation);
1936 
1937  i++;
1938  }
1939 
1940  /*
1941  * Ensure that the coldeflist defines a legal set of names (no
1942  * duplicates, but we needn't worry about system column names) and
1943  * datatypes. Although we mostly can't allow pseudo-types, it
1944  * seems safe to allow RECORD and RECORD[], since values within
1945  * those type classes are self-identifying at runtime, and the
1946  * coldeflist doesn't represent anything that will be visible to
1947  * other sessions.
1948  */
1949  CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE,
1951  }
1952  else
1953  ereport(ERROR,
1954  (errcode(ERRCODE_DATATYPE_MISMATCH),
1955  errmsg("function \"%s\" in FROM has unsupported return type %s",
1956  funcname, format_type_be(funcrettype)),
1957  parser_errposition(pstate, exprLocation(funcexpr))));
1958 
1959  /* Finish off the RangeTblFunction and add it to the RTE's list */
1960  rtfunc->funccolcount = tupdesc->natts;
1961  rte->functions = lappend(rte->functions, rtfunc);
1962 
1963  /* Save the tupdesc for use below */
1964  functupdescs[funcno] = tupdesc;
1965  totalatts += tupdesc->natts;
1966  funcno++;
1967  }
1968 
1969  /*
1970  * If there's more than one function, or we want an ordinality column, we
1971  * have to produce a merged tupdesc.
1972  */
1973  if (nfuncs > 1 || rangefunc->ordinality)
1974  {
1975  if (rangefunc->ordinality)
1976  totalatts++;
1977 
1978  /* Disallow more columns than will fit in a tuple */
1979  if (totalatts > MaxTupleAttributeNumber)
1980  ereport(ERROR,
1981  (errcode(ERRCODE_TOO_MANY_COLUMNS),
1982  errmsg("functions in FROM can return at most %d columns",
1984  parser_errposition(pstate,
1985  exprLocation((Node *) funcexprs))));
1986 
1987  /* Merge the tuple descs of each function into a composite one */
1988  tupdesc = CreateTemplateTupleDesc(totalatts);
1989  natts = 0;
1990  for (i = 0; i < nfuncs; i++)
1991  {
1992  for (j = 1; j <= functupdescs[i]->natts; j++)
1993  TupleDescCopyEntry(tupdesc, ++natts, functupdescs[i], j);
1994  }
1995 
1996  /* Add the ordinality column if needed */
1997  if (rangefunc->ordinality)
1998  {
1999  TupleDescInitEntry(tupdesc,
2000  (AttrNumber) ++natts,
2001  "ordinality",
2002  INT8OID,
2003  -1,
2004  0);
2005  /* no need to set collation */
2006  }
2007 
2008  Assert(natts == totalatts);
2009  }
2010  else
2011  {
2012  /* We can just use the single function's tupdesc as-is */
2013  tupdesc = functupdescs[0];
2014  }
2015 
2016  /* Use the tupdesc while assigning column aliases for the RTE */
2017  buildRelationAliases(tupdesc, alias, eref);
2018 
2019  /*
2020  * Set flags and access permissions.
2021  *
2022  * Functions are never checked for access rights (at least, not by
2023  * ExecCheckPermissions()), so no need to perform addRTEPermissionInfo().
2024  */
2025  rte->lateral = lateral;
2026  rte->inh = false; /* never true for functions */
2027  rte->inFromCl = inFromCl;
2028 
2029  /*
2030  * Add completed RTE to pstate's range table list, so that we know its
2031  * index. But we don't add it to the join list --- caller must do that if
2032  * appropriate.
2033  */
2034  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2035 
2036  /*
2037  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2038  * list --- caller must do that if appropriate.
2039  */
2040  return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable), NULL,
2041  tupdesc);
2042 }
int16 AttrNumber
Definition: attnum.h:21
signed int int32
Definition: c.h:483
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:292
TypeFuncClass
Definition: funcapi.h:147
@ TYPEFUNC_SCALAR
Definition: funcapi.h:148
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_RECORD
Definition: funcapi.h:151
@ TYPEFUNC_COMPOSITE_DOMAIN
Definition: funcapi.h:150
void CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind, int flags)
Definition: heap.c:455
#define CHKATYPE_ANYRECORD
Definition: heap.h:24
#define MaxTupleAttributeNumber
Definition: htup_details.h:34
#define MaxHeapAttributeNumber
Definition: htup_details.h:48
#define funcname
Definition: indent_codes.h:69
int j
Definition: isn.c:74
char * pstrdup(const char *in)
Definition: mcxt.c:1644
void * palloc(Size size)
Definition: mcxt.c:1226
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:282
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:786
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1312
static char * chooseScalarFunctionAlias(Node *funcexpr, char *funcname, Alias *alias, int nfuncs)
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition: parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid)
Definition: parse_type.c:540
@ RTE_FUNCTION
Definition: parsenodes.h:1016
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:512
#define linitial(l)
Definition: pg_list.h:178
unsigned int Oid
Definition: postgres_ext.h:31
int location
Definition: parsenodes.h:739
char * colname
Definition: parsenodes.h:720
TypeName * typeName
Definition: parsenodes.h:721
Definition: pg_list.h:54
Definition: nodes.h:129
Alias * alias
Definition: parsenodes.h:641
bool funcordinality
Definition: parsenodes.h:1148
Query * subquery
Definition: parsenodes.h:1080
List * functions
Definition: parsenodes.h:1147
bool setof
Definition: parsenodes.h:267
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:767
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583
void TupleDescCopyEntry(TupleDesc dst, AttrNumber dstAttno, TupleDesc src, AttrNumber srcAttno)
Definition: tupdesc.c:267

References RangeFunction::alias, RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromTupleDesc(), buildRelationAliases(), CheckAttributeNamesTypes(), CHKATYPE_ANYRECORD, chooseScalarFunctionAlias(), ColumnDef::colname, CreateTemplateTupleDesc(), RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, exprCollation(), exprLocation(), exprType(), exprTypmod(), format_type_be(), forthree, RangeTblFunction::funcexpr, funcname, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), GetColumnDefCollation(), i, RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, j, lappend(), lappend_int(), lappend_oid(), RangeTblEntry::lateral, lfirst, linitial, list_length(), ColumnDef::location, makeAlias(), makeNode, makeString(), MaxHeapAttributeNumber, MaxTupleAttributeNumber, TupleDescData::natts, NIL, RangeFunction::ordinality, ParseState::p_rtable, palloc(), parser_errposition(), pstrdup(), RangeTblEntry::relid, RTE_FUNCTION, RangeTblEntry::rtekind, TypeName::setof, RangeTblEntry::subquery, TupleDescCopyEntry(), TupleDescInitEntry(), TupleDescInitEntryCollation(), TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, TYPEFUNC_RECORD, TYPEFUNC_SCALAR, ColumnDef::typeName, and typenameTypeIdAndMod().

Referenced by transformRangeFunction().

◆ addRangeTableEntryForJoin()

ParseNamespaceItem* addRangeTableEntryForJoin ( ParseState pstate,
List colnames,
ParseNamespaceColumn nscolumns,
JoinType  jointype,
int  nummergedcols,
List aliasvars,
List leftcols,
List rightcols,
Alias join_using_alias,
Alias alias,
bool  inFromCl 
)

Definition at line 2220 of file parse_relation.c.

2231 {
2233  Alias *eref;
2234  int numaliases;
2235  ParseNamespaceItem *nsitem;
2236 
2237  Assert(pstate != NULL);
2238 
2239  /*
2240  * Fail if join has too many columns --- we must be able to reference any
2241  * of the columns with an AttrNumber.
2242  */
2243  if (list_length(aliasvars) > MaxAttrNumber)
2244  ereport(ERROR,
2245  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2246  errmsg("joins can have at most %d columns",
2247  MaxAttrNumber)));
2248 
2249  rte->rtekind = RTE_JOIN;
2250  rte->relid = InvalidOid;
2251  rte->subquery = NULL;
2252  rte->jointype = jointype;
2253  rte->joinmergedcols = nummergedcols;
2254  rte->joinaliasvars = aliasvars;
2255  rte->joinleftcols = leftcols;
2256  rte->joinrightcols = rightcols;
2257  rte->join_using_alias = join_using_alias;
2258  rte->alias = alias;
2259 
2260  eref = alias ? copyObject(alias) : makeAlias("unnamed_join", NIL);
2261  numaliases = list_length(eref->colnames);
2262 
2263  /* fill in any unspecified alias columns */
2264  if (numaliases < list_length(colnames))
2265  eref->colnames = list_concat(eref->colnames,
2266  list_copy_tail(colnames, numaliases));
2267 
2268  if (numaliases > list_length(colnames))
2269  ereport(ERROR,
2270  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2271  errmsg("join expression \"%s\" has %d columns available but %d columns specified",
2272  eref->aliasname, list_length(colnames), numaliases)));
2273 
2274  rte->eref = eref;
2275 
2276  /*
2277  * Set flags and access permissions.
2278  *
2279  * Joins are never checked for access rights, so no need to perform
2280  * addRTEPermissionInfo().
2281  */
2282  rte->lateral = false;
2283  rte->inh = false; /* never true for joins */
2284  rte->inFromCl = inFromCl;
2285 
2286  /*
2287  * Add completed RTE to pstate's range table list, so that we know its
2288  * index. But we don't add it to the join list --- caller must do that if
2289  * appropriate.
2290  */
2291  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2292 
2293  /*
2294  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2295  * list --- caller must do that if appropriate.
2296  */
2297  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
2298  nsitem->p_names = rte->eref;
2299  nsitem->p_rte = rte;
2300  nsitem->p_perminfo = NULL;
2301  nsitem->p_rtindex = list_length(pstate->p_rtable);
2302  nsitem->p_nscolumns = nscolumns;
2303  /* set default visibility flags; might get changed later */
2304  nsitem->p_rel_visible = true;
2305  nsitem->p_cols_visible = true;
2306  nsitem->p_lateral_only = false;
2307  nsitem->p_lateral_ok = true;
2308 
2309  return nsitem;
2310 }
#define MaxAttrNumber
Definition: attnum.h:24
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1612
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
@ RTE_JOIN
Definition: parsenodes.h:1015
RangeTblEntry * p_rte
Definition: parse_node.h:286
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:288
Alias * join_using_alias
Definition: parsenodes.h:1137
List * joinrightcols
Definition: parsenodes.h:1130
List * joinaliasvars
Definition: parsenodes.h:1128
JoinType jointype
Definition: parsenodes.h:1126
List * joinleftcols
Definition: parsenodes.h:1129

References RangeTblEntry::alias, Alias::aliasname, Assert(), Alias::colnames, copyObject, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, RangeTblEntry::join_using_alias, RangeTblEntry::joinaliasvars, RangeTblEntry::joinleftcols, RangeTblEntry::joinmergedcols, RangeTblEntry::joinrightcols, RangeTblEntry::jointype, lappend(), RangeTblEntry::lateral, list_concat(), list_copy_tail(), list_length(), makeAlias(), makeNode, MaxAttrNumber, NIL, ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rel_visible, ParseState::p_rtable, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, palloc(), RangeTblEntry::relid, RTE_JOIN, RangeTblEntry::rtekind, and RangeTblEntry::subquery.

Referenced by transformFromClauseItem(), and transformSetOperationStmt().

◆ addRangeTableEntryForRelation()

ParseNamespaceItem* addRangeTableEntryForRelation ( ParseState pstate,
Relation  rel,
int  lockmode,
Alias alias,
bool  inh,
bool  inFromCl 
)

Definition at line 1567 of file parse_relation.c.

1573 {
1575  RTEPermissionInfo *perminfo;
1576  char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
1577 
1578  Assert(pstate != NULL);
1579 
1580  Assert(lockmode == AccessShareLock ||
1581  lockmode == RowShareLock ||
1582  lockmode == RowExclusiveLock);
1583  Assert(CheckRelationLockedByMe(rel, lockmode, true));
1584 
1585  rte->rtekind = RTE_RELATION;
1586  rte->alias = alias;
1587  rte->relid = RelationGetRelid(rel);
1588  rte->relkind = rel->rd_rel->relkind;
1589  rte->rellockmode = lockmode;
1590 
1591  /*
1592  * Build the list of effective column names using user-supplied aliases
1593  * and/or actual column names.
1594  */
1595  rte->eref = makeAlias(refname, NIL);
1596  buildRelationAliases(rel->rd_att, alias, rte->eref);
1597 
1598  /*
1599  * Set flags and initialize access permissions.
1600  *
1601  * The initial default on access checks is always check-for-READ-access,
1602  * which is the right thing for all except target tables.
1603  */
1604  rte->lateral = false;
1605  rte->inh = inh;
1606  rte->inFromCl = inFromCl;
1607 
1608  perminfo = addRTEPermissionInfo(&pstate->p_rteperminfos, rte);
1609  perminfo->requiredPerms = ACL_SELECT;
1610 
1611  /*
1612  * Add completed RTE to pstate's range table list, so that we know its
1613  * index. But we don't add it to the join list --- caller must do that if
1614  * appropriate.
1615  */
1616  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1617 
1618  /*
1619  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1620  * list --- caller must do that if appropriate.
1621  */
1622  return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
1623  perminfo, rel->rd_att);
1624 }
bool CheckRelationLockedByMe(Relation relation, LOCKMODE lockmode, bool orstronger)
Definition: lmgr.c:331
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:538

References AccessShareLock, ACL_SELECT, addRTEPermissionInfo(), RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromTupleDesc(), buildRelationAliases(), CheckRelationLockedByMe(), RangeTblEntry::eref, RangeTblEntry::inFromCl, RangeTblEntry::inh, lappend(), RangeTblEntry::lateral, list_length(), makeAlias(), makeNode, NIL, ParseState::p_rtable, ParseState::p_rteperminfos, RelationData::rd_att, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, RTEPermissionInfo::requiredPerms, RowExclusiveLock, RowShareLock, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by AddRelationNewConstraints(), AlterPolicy(), copy_table(), CreatePolicy(), CreateTriggerFiringOn(), DefineRelation(), DoCopy(), rewriteTargetView(), setTargetTable(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), transformAlterTableStmt(), transformIndexStmt(), transformOnConflictClause(), transformPartitionSpec(), TransformPubWhereClauses(), transformRuleStmt(), and transformStatsStmt().

◆ addRangeTableEntryForSubquery()

ParseNamespaceItem* addRangeTableEntryForSubquery ( ParseState pstate,
Query subquery,
Alias alias,
bool  lateral,
bool  inFromCl 
)

Definition at line 1638 of file parse_relation.c.

1643 {
1645  Alias *eref;
1646  int numaliases;
1647  List *coltypes,
1648  *coltypmods,
1649  *colcollations;
1650  int varattno;
1651  ListCell *tlistitem;
1652  ParseNamespaceItem *nsitem;
1653 
1654  Assert(pstate != NULL);
1655 
1656  rte->rtekind = RTE_SUBQUERY;
1657  rte->subquery = subquery;
1658  rte->alias = alias;
1659 
1660  eref = alias ? copyObject(alias) : makeAlias("unnamed_subquery", NIL);
1661  numaliases = list_length(eref->colnames);
1662 
1663  /* fill in any unspecified alias columns, and extract column type info */
1664  coltypes = coltypmods = colcollations = NIL;
1665  varattno = 0;
1666  foreach(tlistitem, subquery->targetList)
1667  {
1668  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1669 
1670  if (te->resjunk)
1671  continue;
1672  varattno++;
1673  Assert(varattno == te->resno);
1674  if (varattno > numaliases)
1675  {
1676  char *attrname;
1677 
1678  attrname = pstrdup(te->resname);
1679  eref->colnames = lappend(eref->colnames, makeString(attrname));
1680  }
1681  coltypes = lappend_oid(coltypes,
1682  exprType((Node *) te->expr));
1683  coltypmods = lappend_int(coltypmods,
1684  exprTypmod((Node *) te->expr));
1685  colcollations = lappend_oid(colcollations,
1686  exprCollation((Node *) te->expr));
1687  }
1688  if (varattno < numaliases)
1689  ereport(ERROR,
1690  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1691  errmsg("table \"%s\" has %d columns available but %d columns specified",
1692  eref->aliasname, varattno, numaliases)));
1693 
1694  rte->eref = eref;
1695 
1696  /*
1697  * Set flags.
1698  *
1699  * Subqueries are never checked for access rights, so no need to perform
1700  * addRTEPermissionInfo().
1701  */
1702  rte->lateral = lateral;
1703  rte->inh = false; /* never true for subqueries */
1704  rte->inFromCl = inFromCl;
1705 
1706  /*
1707  * Add completed RTE to pstate's range table list, so that we know its
1708  * index. But we don't add it to the join list --- caller must do that if
1709  * appropriate.
1710  */
1711  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1712 
1713  /*
1714  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1715  * list --- caller must do that if appropriate.
1716  */
1717  nsitem = buildNSItemFromLists(rte, list_length(pstate->p_rtable),
1718  coltypes, coltypmods, colcollations);
1719 
1720  /*
1721  * Mark it visible as a relation name only if it had a user-written alias.
1722  */
1723  nsitem->p_rel_visible = (alias != NULL);
1724 
1725  return nsitem;
1726 }
@ RTE_SUBQUERY
Definition: parsenodes.h:1014
List * targetList
Definition: parsenodes.h:188
Expr * expr
Definition: primnodes.h:1895
AttrNumber resno
Definition: primnodes.h:1897

References RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromLists(), Alias::colnames, copyObject, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), RangeTblEntry::inFromCl, RangeTblEntry::inh, lappend(), lappend_int(), lappend_oid(), RangeTblEntry::lateral, lfirst, list_length(), makeAlias(), makeNode, makeString(), NIL, ParseNamespaceItem::p_rel_visible, ParseState::p_rtable, pstrdup(), TargetEntry::resno, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblEntry::subquery, and Query::targetList.

Referenced by convert_ANY_sublink_to_join(), transformInsertStmt(), transformRangeSubselect(), and transformSetOperationTree().

◆ addRangeTableEntryForTableFunc()

ParseNamespaceItem* addRangeTableEntryForTableFunc ( ParseState pstate,
TableFunc tf,
Alias alias,
bool  lateral,
bool  inFromCl 
)

Definition at line 2051 of file parse_relation.c.

2056 {
2058  char *refname;
2059  Alias *eref;
2060  int numaliases;
2061 
2062  Assert(pstate != NULL);
2063 
2064  /* Disallow more columns than will fit in a tuple */
2065  if (list_length(tf->colnames) > MaxTupleAttributeNumber)
2066  ereport(ERROR,
2067  (errcode(ERRCODE_TOO_MANY_COLUMNS),
2068  errmsg("functions in FROM can return at most %d columns",
2070  parser_errposition(pstate,
2071  exprLocation((Node *) tf))));
2072  Assert(list_length(tf->coltypes) == list_length(tf->colnames));
2073  Assert(list_length(tf->coltypmods) == list_length(tf->colnames));
2074  Assert(list_length(tf->colcollations) == list_length(tf->colnames));
2075 
2076  refname = alias ? alias->aliasname : pstrdup("xmltable");
2077 
2078  rte->rtekind = RTE_TABLEFUNC;
2079  rte->relid = InvalidOid;
2080  rte->subquery = NULL;
2081  rte->tablefunc = tf;
2082  rte->coltypes = tf->coltypes;
2083  rte->coltypmods = tf->coltypmods;
2084  rte->colcollations = tf->colcollations;
2085  rte->alias = alias;
2086 
2087  eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
2088  numaliases = list_length(eref->colnames);
2089 
2090  /* fill in any unspecified alias columns */
2091  if (numaliases < list_length(tf->colnames))
2092  eref->colnames = list_concat(eref->colnames,
2093  list_copy_tail(tf->colnames, numaliases));
2094 
2095  if (numaliases > list_length(tf->colnames))
2096  ereport(ERROR,
2097  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2098  errmsg("%s function has %d columns available but %d columns specified",
2099  "XMLTABLE",
2100  list_length(tf->colnames), numaliases)));
2101 
2102  rte->eref = eref;
2103 
2104  /*
2105  * Set flags and access permissions.
2106  *
2107  * Tablefuncs are never checked for access rights (at least, not by
2108  * ExecCheckPermissions()), so no need to perform addRTEPermissionInfo().
2109  */
2110  rte->lateral = lateral;
2111  rte->inh = false; /* never true for tablefunc RTEs */
2112  rte->inFromCl = inFromCl;
2113 
2114  /*
2115  * Add completed RTE to pstate's range table list, so that we know its
2116  * index. But we don't add it to the join list --- caller must do that if
2117  * appropriate.
2118  */
2119  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2120 
2121  /*
2122  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2123  * list --- caller must do that if appropriate.
2124  */
2125  return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2126  rte->coltypes, rte->coltypmods,
2127  rte->colcollations);
2128 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1017
TableFunc * tablefunc
Definition: parsenodes.h:1153

References RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromLists(), RangeTblEntry::colcollations, Alias::colnames, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, copyObject, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, exprLocation(), RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, lappend(), RangeTblEntry::lateral, list_concat(), list_copy_tail(), list_length(), makeAlias(), makeNode, MaxTupleAttributeNumber, NIL, ParseState::p_rtable, parser_errposition(), pstrdup(), RangeTblEntry::relid, RTE_TABLEFUNC, RangeTblEntry::rtekind, RangeTblEntry::subquery, and RangeTblEntry::tablefunc.

Referenced by transformRangeTableFunc().

◆ addRangeTableEntryForValues()

ParseNamespaceItem* addRangeTableEntryForValues ( ParseState pstate,
List exprs,
List coltypes,
List coltypmods,
List colcollations,
Alias alias,
bool  lateral,
bool  inFromCl 
)

Definition at line 2137 of file parse_relation.c.

2145 {
2147  char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
2148  Alias *eref;
2149  int numaliases;
2150  int numcolumns;
2151 
2152  Assert(pstate != NULL);
2153 
2154  rte->rtekind = RTE_VALUES;
2155  rte->relid = InvalidOid;
2156  rte->subquery = NULL;
2157  rte->values_lists = exprs;
2158  rte->coltypes = coltypes;
2159  rte->coltypmods = coltypmods;
2160  rte->colcollations = colcollations;
2161  rte->alias = alias;
2162 
2163  eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
2164 
2165  /* fill in any unspecified alias columns */
2166  numcolumns = list_length((List *) linitial(exprs));
2167  numaliases = list_length(eref->colnames);
2168  while (numaliases < numcolumns)
2169  {
2170  char attrname[64];
2171 
2172  numaliases++;
2173  snprintf(attrname, sizeof(attrname), "column%d", numaliases);
2174  eref->colnames = lappend(eref->colnames,
2175  makeString(pstrdup(attrname)));
2176  }
2177  if (numcolumns < numaliases)
2178  ereport(ERROR,
2179  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2180  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
2181  refname, numcolumns, numaliases)));
2182 
2183  rte->eref = eref;
2184 
2185  /*
2186  * Set flags and access permissions.
2187  *
2188  * Subqueries are never checked for access rights, so no need to perform
2189  * addRTEPermissionInfo().
2190  */
2191  rte->lateral = lateral;
2192  rte->inh = false; /* never true for values RTEs */
2193  rte->inFromCl = inFromCl;
2194 
2195  /*
2196  * Add completed RTE to pstate's range table list, so that we know its
2197  * index. But we don't add it to the join list --- caller must do that if
2198  * appropriate.
2199  */
2200  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2201 
2202  /*
2203  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2204  * list --- caller must do that if appropriate.
2205  */
2206  return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2207  rte->coltypes, rte->coltypmods,
2208  rte->colcollations);
2209 }
@ RTE_VALUES
Definition: parsenodes.h:1018
#define snprintf
Definition: port.h:238
List * values_lists
Definition: parsenodes.h:1158

References RangeTblEntry::alias, Alias::aliasname, Assert(), buildNSItemFromLists(), RangeTblEntry::colcollations, Alias::colnames, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, copyObject, RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, lappend(), RangeTblEntry::lateral, linitial, list_length(), makeAlias(), makeNode, makeString(), NIL, ParseState::p_rtable, pstrdup(), RangeTblEntry::relid, RTE_VALUES, RangeTblEntry::rtekind, snprintf, RangeTblEntry::subquery, and RangeTblEntry::values_lists.

Referenced by transformValuesClause().

◆ addRTEPermissionInfo()

RTEPermissionInfo* addRTEPermissionInfo ( List **  rteperminfos,
RangeTblEntry rte 
)

Definition at line 3871 of file parse_relation.c.

3872 {
3873  RTEPermissionInfo *perminfo;
3874 
3875  Assert(OidIsValid(rte->relid));
3876  Assert(rte->perminfoindex == 0);
3877 
3878  /* Nope, so make one and add to the list. */
3879  perminfo = makeNode(RTEPermissionInfo);
3880  perminfo->relid = rte->relid;
3881  perminfo->inh = rte->inh;
3882  /* Other information is set by fetching the node as and where needed. */
3883 
3884  *rteperminfos = lappend(*rteperminfos, perminfo);
3885 
3886  /* Note its index (1-based!) */
3887  rte->perminfoindex = list_length(*rteperminfos);
3888 
3889  return perminfo;
3890 }
#define OidIsValid(objectId)
Definition: c.h:764
Index perminfoindex
Definition: parsenodes.h:1075

References Assert(), RangeTblEntry::inh, RTEPermissionInfo::inh, lappend(), list_length(), makeNode, OidIsValid, RangeTblEntry::perminfoindex, RangeTblEntry::relid, and RTEPermissionInfo::relid.

Referenced by add_rte_to_flat_rtable(), addRangeTableEntry(), addRangeTableEntryForRelation(), create_edata_for_relation(), create_estate_for_relation(), plan_cluster_use_sort(), plan_create_index_workers(), and rewriteTargetView().

◆ attnameAttNum()

int attnameAttNum ( Relation  rd,
const char *  attname,
bool  sysColOK 
)

Definition at line 3480 of file parse_relation.c.

3481 {
3482  int i;
3483 
3484  for (i = 0; i < RelationGetNumberOfAttributes(rd); i++)
3485  {
3487 
3488  if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
3489  return i + 1;
3490  }
3491 
3492  if (sysColOK)
3493  {
3495  return i;
3496  }
3497 
3498  /* on failure */
3499  return InvalidAttrNumber;
3500 }
#define InvalidAttrNumber
Definition: attnum.h:23
int namestrcmp(Name name, const char *str)
Definition: name.c:247
static int specialAttNum(const char *attname)
NameData attname
Definition: pg_attribute.h:41
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:510

References attname, i, InvalidAttrNumber, namestrcmp(), RelationData::rd_att, RelationGetNumberOfAttributes, specialAttNum(), and TupleDescAttr.

Referenced by checkInsertTargets(), CreateTriggerFiringOn(), do_analyze_rel(), and transformUpdateTargetList().

◆ attnumAttName()

const NameData* attnumAttName ( Relation  rd,
int  attid 
)

Definition at line 3530 of file parse_relation.c.

3531 {
3532  if (attid <= 0)
3533  {
3534  const FormData_pg_attribute *sysatt;
3535 
3536  sysatt = SystemAttributeDefinition(attid);
3537  return &sysatt->attname;
3538  }
3539  if (attid > rd->rd_att->natts)
3540  elog(ERROR, "invalid attribute number %d", attid);
3541  return &TupleDescAttr(rd->rd_att, attid - 1)->attname;
3542 }
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:239
FormData_pg_attribute
Definition: pg_attribute.h:193

References elog(), ERROR, FormData_pg_attribute, TupleDescData::natts, RelationData::rd_att, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by transformFkeyGetPrimaryKey().

◆ attnumCollationId()

Oid attnumCollationId ( Relation  rd,
int  attid 
)

Definition at line 3572 of file parse_relation.c.

3573 {
3574  if (attid <= 0)
3575  {
3576  /* All system attributes are of noncollatable types. */
3577  return InvalidOid;
3578  }
3579  if (attid > rd->rd_att->natts)
3580  elog(ERROR, "invalid attribute number %d", attid);
3581  return TupleDescAttr(rd->rd_att, attid - 1)->attcollation;
3582 }

References elog(), ERROR, InvalidOid, TupleDescData::natts, RelationData::rd_att, and TupleDescAttr.

◆ attnumTypeId()

Oid attnumTypeId ( Relation  rd,
int  attid 
)

Definition at line 3552 of file parse_relation.c.

3553 {
3554  if (attid <= 0)
3555  {
3556  const FormData_pg_attribute *sysatt;
3557 
3558  sysatt = SystemAttributeDefinition(attid);
3559  return sysatt->atttypid;
3560  }
3561  if (attid > rd->rd_att->natts)
3562  elog(ERROR, "invalid attribute number %d", attid);
3563  return TupleDescAttr(rd->rd_att, attid - 1)->atttypid;
3564 }

References elog(), ERROR, FormData_pg_attribute, TupleDescData::natts, RelationData::rd_att, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by transformAssignedExpr(), and transformFkeyGetPrimaryKey().

◆ buildNSItemFromLists()

static ParseNamespaceItem* buildNSItemFromLists ( RangeTblEntry rte,
Index  rtindex,
List coltypes,
List coltypmods,
List colcollations 
)
static

Definition at line 1354 of file parse_relation.c.

1356 {
1357  ParseNamespaceItem *nsitem;
1358  ParseNamespaceColumn *nscolumns;
1359  int maxattrs = list_length(coltypes);
1360  int varattno;
1361  ListCell *lct;
1362  ListCell *lcm;
1363  ListCell *lcc;
1364 
1365  /* colnames must have the same number of entries as the nsitem */
1366  Assert(maxattrs == list_length(rte->eref->colnames));
1367 
1368  Assert(maxattrs == list_length(coltypmods));
1369  Assert(maxattrs == list_length(colcollations));
1370 
1371  /* extract per-column data from the lists */
1372  nscolumns = (ParseNamespaceColumn *)
1373  palloc0(maxattrs * sizeof(ParseNamespaceColumn));
1374 
1375  varattno = 0;
1376  forthree(lct, coltypes,
1377  lcm, coltypmods,
1378  lcc, colcollations)
1379  {
1380  nscolumns[varattno].p_varno = rtindex;
1381  nscolumns[varattno].p_varattno = varattno + 1;
1382  nscolumns[varattno].p_vartype = lfirst_oid(lct);
1383  nscolumns[varattno].p_vartypmod = lfirst_int(lcm);
1384  nscolumns[varattno].p_varcollid = lfirst_oid(lcc);
1385  nscolumns[varattno].p_varnosyn = rtindex;
1386  nscolumns[varattno].p_varattnosyn = varattno + 1;
1387  varattno++;
1388  }
1389 
1390  /* ... and build the nsitem */
1391  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1392  nsitem->p_names = rte->eref;
1393  nsitem->p_rte = rte;
1394  nsitem->p_rtindex = rtindex;
1395  nsitem->p_perminfo = NULL;
1396  nsitem->p_nscolumns = nscolumns;
1397  /* set default visibility flags; might get changed later */
1398  nsitem->p_rel_visible = true;
1399  nsitem->p_cols_visible = true;
1400  nsitem->p_lateral_only = false;
1401  nsitem->p_lateral_ok = true;
1402 
1403  return nsitem;
1404 }
void * palloc0(Size size)
Definition: mcxt.c:1257
#define lfirst_int(lc)
Definition: pg_list.h:173
#define lfirst_oid(lc)
Definition: pg_list.h:174
AttrNumber p_varattno
Definition: parse_node.h:321
AttrNumber p_varattnosyn
Definition: parse_node.h:326

References Assert(), Alias::colnames, RangeTblEntry::eref, forthree, lfirst_int, lfirst_oid, list_length(), ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, palloc(), and palloc0().

Referenced by addRangeTableEntryForCTE(), addRangeTableEntryForSubquery(), addRangeTableEntryForTableFunc(), and addRangeTableEntryForValues().

◆ buildNSItemFromTupleDesc()

static ParseNamespaceItem* buildNSItemFromTupleDesc ( RangeTblEntry rte,
Index  rtindex,
RTEPermissionInfo perminfo,
TupleDesc  tupdesc 
)
static

Definition at line 1294 of file parse_relation.c.

1297 {
1298  ParseNamespaceItem *nsitem;
1299  ParseNamespaceColumn *nscolumns;
1300  int maxattrs = tupdesc->natts;
1301  int varattno;
1302 
1303  /* colnames must have the same number of entries as the nsitem */
1304  Assert(maxattrs == list_length(rte->eref->colnames));
1305 
1306  /* extract per-column data from the tupdesc */
1307  nscolumns = (ParseNamespaceColumn *)
1308  palloc0(maxattrs * sizeof(ParseNamespaceColumn));
1309 
1310  for (varattno = 0; varattno < maxattrs; varattno++)
1311  {
1312  Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1313 
1314  /* For a dropped column, just leave the entry as zeroes */
1315  if (attr->attisdropped)
1316  continue;
1317 
1318  nscolumns[varattno].p_varno = rtindex;
1319  nscolumns[varattno].p_varattno = varattno + 1;
1320  nscolumns[varattno].p_vartype = attr->atttypid;
1321  nscolumns[varattno].p_vartypmod = attr->atttypmod;
1322  nscolumns[varattno].p_varcollid = attr->attcollation;
1323  nscolumns[varattno].p_varnosyn = rtindex;
1324  nscolumns[varattno].p_varattnosyn = varattno + 1;
1325  }
1326 
1327  /* ... and build the nsitem */
1328  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1329  nsitem->p_names = rte->eref;
1330  nsitem->p_rte = rte;
1331  nsitem->p_rtindex = rtindex;
1332  nsitem->p_perminfo = perminfo;
1333  nsitem->p_nscolumns = nscolumns;
1334  /* set default visibility flags; might get changed later */
1335  nsitem->p_rel_visible = true;
1336  nsitem->p_cols_visible = true;
1337  nsitem->p_lateral_only = false;
1338  nsitem->p_lateral_ok = true;
1339 
1340  return nsitem;
1341 }

References Assert(), Alias::colnames, RangeTblEntry::eref, list_length(), TupleDescData::natts, ParseNamespaceItem::p_cols_visible, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, palloc(), palloc0(), and TupleDescAttr.

Referenced by addRangeTableEntry(), addRangeTableEntryForENR(), addRangeTableEntryForFunction(), and addRangeTableEntryForRelation().

◆ buildRelationAliases()

static void buildRelationAliases ( TupleDesc  tupdesc,
Alias alias,
Alias eref 
)
static

Definition at line 1177 of file parse_relation.c.

1178 {
1179  int maxattrs = tupdesc->natts;
1180  List *aliaslist;
1181  ListCell *aliaslc;
1182  int numaliases;
1183  int varattno;
1184  int numdropped = 0;
1185 
1186  Assert(eref->colnames == NIL);
1187 
1188  if (alias)
1189  {
1190  aliaslist = alias->colnames;
1191  aliaslc = list_head(aliaslist);
1192  numaliases = list_length(aliaslist);
1193  /* We'll rebuild the alias colname list */
1194  alias->colnames = NIL;
1195  }
1196  else
1197  {
1198  aliaslist = NIL;
1199  aliaslc = NULL;
1200  numaliases = 0;
1201  }
1202 
1203  for (varattno = 0; varattno < maxattrs; varattno++)
1204  {
1205  Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1206  String *attrname;
1207 
1208  if (attr->attisdropped)
1209  {
1210  /* Always insert an empty string for a dropped column */
1211  attrname = makeString(pstrdup(""));
1212  if (aliaslc)
1213  alias->colnames = lappend(alias->colnames, attrname);
1214  numdropped++;
1215  }
1216  else if (aliaslc)
1217  {
1218  /* Use the next user-supplied alias */
1219  attrname = lfirst_node(String, aliaslc);
1220  aliaslc = lnext(aliaslist, aliaslc);
1221  alias->colnames = lappend(alias->colnames, attrname);
1222  }
1223  else
1224  {
1225  attrname = makeString(pstrdup(NameStr(attr->attname)));
1226  /* we're done with the alias if any */
1227  }
1228 
1229  eref->colnames = lappend(eref->colnames, attrname);
1230  }
1231 
1232  /* Too many user-supplied aliases? */
1233  if (aliaslc)
1234  ereport(ERROR,
1235  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1236  errmsg("table \"%s\" has %d columns available but %d columns specified",
1237  eref->aliasname, maxattrs - numdropped, numaliases)));
1238 }
#define NameStr(name)
Definition: c.h:735
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
Definition: value.h:64

References Alias::aliasname, Assert(), Alias::colnames, ereport, errcode(), errmsg(), ERROR, lappend(), lfirst_node, list_head(), list_length(), lnext(), makeString(), NameStr, TupleDescData::natts, NIL, pstrdup(), and TupleDescAttr.

Referenced by addRangeTableEntry(), addRangeTableEntryForENR(), addRangeTableEntryForFunction(), and addRangeTableEntryForRelation().

◆ check_lateral_ref_ok()

static void check_lateral_ref_ok ( ParseState pstate,
ParseNamespaceItem nsitem,
int  location 
)
static

Definition at line 483 of file parse_relation.c.

485 {
486  if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
487  {
488  /* SQL:2008 demands this be an error, not an invisible item */
489  RangeTblEntry *rte = nsitem->p_rte;
490  char *refname = nsitem->p_names->aliasname;
491 
492  ereport(ERROR,
493  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
494  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
495  refname),
496  (pstate->p_target_nsitem != NULL &&
497  rte == pstate->p_target_nsitem->p_rte) ?
498  errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
499  refname) :
500  errdetail("The combining JOIN type must be INNER or LEFT for a LATERAL reference."),
501  parser_errposition(pstate, location)));
502  }
503 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:207

References Alias::aliasname, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, ParseNamespaceItem::p_lateral_ok, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseNamespaceItem::p_rte, ParseState::p_target_nsitem, and parser_errposition().

Referenced by colNameToVar(), scanNameSpaceForRefname(), and scanNameSpaceForRelid().

◆ checkNameSpaceConflicts()

void checkNameSpaceConflicts ( ParseState pstate,
List namespace1,
List namespace2 
)

Definition at line 434 of file parse_relation.c.

436 {
437  ListCell *l1;
438 
439  foreach(l1, namespace1)
440  {
441  ParseNamespaceItem *nsitem1 = (ParseNamespaceItem *) lfirst(l1);
442  RangeTblEntry *rte1 = nsitem1->p_rte;
443  const char *aliasname1 = nsitem1->p_names->aliasname;
444  ListCell *l2;
445 
446  if (!nsitem1->p_rel_visible)
447  continue;
448 
449  foreach(l2, namespace2)
450  {
451  ParseNamespaceItem *nsitem2 = (ParseNamespaceItem *) lfirst(l2);
452  RangeTblEntry *rte2 = nsitem2->p_rte;
453  const char *aliasname2 = nsitem2->p_names->aliasname;
454 
455  if (!nsitem2->p_rel_visible)
456  continue;
457  if (strcmp(aliasname2, aliasname1) != 0)
458  continue; /* definitely no conflict */
459  if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
460  rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
461  rte1->relid != rte2->relid)
462  continue; /* no conflict per SQL rule */
463  ereport(ERROR,
464  (errcode(ERRCODE_DUPLICATE_ALIAS),
465  errmsg("table name \"%s\" specified more than once",
466  aliasname1)));
467  }
468  }
469 }

References RangeTblEntry::alias, Alias::aliasname, ereport, errcode(), errmsg(), ERROR, lfirst, ParseNamespaceItem::p_names, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, RangeTblEntry::relid, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by transformFromClause(), and transformFromClauseItem().

◆ chooseScalarFunctionAlias()

static char* chooseScalarFunctionAlias ( Node funcexpr,
char *  funcname,
Alias alias,
int  nfuncs 
)
static

Definition at line 1254 of file parse_relation.c.

1256 {
1257  char *pname;
1258 
1259  /*
1260  * If the expression is a simple function call, and the function has a
1261  * single OUT parameter that is named, use the parameter's name.
1262  */
1263  if (funcexpr && IsA(funcexpr, FuncExpr))
1264  {
1265  pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
1266  if (pname)
1267  return pname;
1268  }
1269 
1270  /*
1271  * If there's just one function in the RTE, and the user gave an RTE alias
1272  * name, use that name. (This makes FROM func() AS foo use "foo" as the
1273  * column name as well as the table alias.)
1274  */
1275  if (nfuncs == 1 && alias)
1276  return alias->aliasname;
1277 
1278  /*
1279  * Otherwise use the function name.
1280  */
1281  return funcname;
1282 }
char * get_func_result_name(Oid functionId)
Definition: funcapi.c:1599

References Alias::aliasname, funcname, get_func_result_name(), and IsA.

Referenced by addRangeTableEntryForFunction().

◆ colNameToVar()

Node* colNameToVar ( ParseState pstate,
const char *  colname,
bool  localonly,
int  location 
)

Definition at line 883 of file parse_relation.c.

885 {
886  Node *result = NULL;
887  int sublevels_up = 0;
888  ParseState *orig_pstate = pstate;
889 
890  while (pstate != NULL)
891  {
892  ListCell *l;
893 
894  foreach(l, pstate->p_namespace)
895  {
897  Node *newresult;
898 
899  /* Ignore table-only items */
900  if (!nsitem->p_cols_visible)
901  continue;
902  /* If not inside LATERAL, ignore lateral-only items */
903  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
904  continue;
905 
906  /* use orig_pstate here for consistency with other callers */
907  newresult = scanNSItemForColumn(orig_pstate, nsitem, sublevels_up,
908  colname, location);
909 
910  if (newresult)
911  {
912  if (result)
913  ereport(ERROR,
914  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
915  errmsg("column reference \"%s\" is ambiguous",
916  colname),
917  parser_errposition(pstate, location)));
918  check_lateral_ref_ok(pstate, nsitem, location);
919  result = newresult;
920  }
921  }
922 
923  if (result != NULL || localonly)
924  break; /* found, or don't want to look at parent */
925 
926  pstate = pstate->parentParseState;
927  sublevels_up++;
928  }
929 
930  return result;
931 }
Node * scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, const char *colname, int location)
static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem, int location)
ParseState * parentParseState
Definition: parse_node.h:191
bool p_lateral_active
Definition: parse_node.h:202

References check_lateral_ref_ok(), ereport, errcode(), errmsg(), ERROR, lfirst, ParseNamespaceItem::p_cols_visible, ParseState::p_lateral_active, ParseNamespaceItem::p_lateral_only, ParseState::p_namespace, ParseState::parentParseState, parser_errposition(), and scanNSItemForColumn().

Referenced by findTargetlistEntrySQL92(), and transformColumnRef().

◆ errorMissingColumn()

void errorMissingColumn ( ParseState pstate,
const char *  relname,
const char *  colname,
int  location 
)

Definition at line 3662 of file parse_relation.c.

3664 {
3666 
3667  /*
3668  * Search the entire rtable looking for possible matches. If we find one,
3669  * emit a hint about it.
3670  */
3671  state = searchRangeTableForCol(pstate, relname, colname, location);
3672 
3673  /*
3674  * If there are exact match(es), they must be inaccessible for some
3675  * reason.
3676  */
3677  if (state->rexact1)
3678  {
3679  /*
3680  * We don't try too hard when there's multiple inaccessible exact
3681  * matches, but at least be sure that we don't misleadingly suggest
3682  * that there's only one.
3683  */
3684  if (state->rexact2)
3685  ereport(ERROR,
3686  (errcode(ERRCODE_UNDEFINED_COLUMN),
3687  relname ?
3688  errmsg("column %s.%s does not exist", relname, colname) :
3689  errmsg("column \"%s\" does not exist", colname),
3690  errdetail("There are columns named \"%s\", but they are in tables that cannot be referenced from this part of the query.",
3691  colname),
3692  !relname ? errhint("Try using a table-qualified name.") : 0,
3693  parser_errposition(pstate, location)));
3694  /* Single exact match, so try to determine why it's inaccessible. */
3695  ereport(ERROR,
3696  (errcode(ERRCODE_UNDEFINED_COLUMN),
3697  relname ?
3698  errmsg("column %s.%s does not exist", relname, colname) :
3699  errmsg("column \"%s\" does not exist", colname),
3700  errdetail("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
3701  colname, state->rexact1->eref->aliasname),
3702  rte_visible_if_lateral(pstate, state->rexact1) ?
3703  errhint("To reference that column, you must mark this subquery with LATERAL.") :
3704  (!relname && rte_visible_if_qualified(pstate, state->rexact1)) ?
3705  errhint("To reference that column, you must use a table-qualified name.") : 0,
3706  parser_errposition(pstate, location)));
3707  }
3708 
3709  if (!state->rsecond)
3710  {
3711  /* If we found no match at all, we have little to report */
3712  if (!state->rfirst)
3713  ereport(ERROR,
3714  (errcode(ERRCODE_UNDEFINED_COLUMN),
3715  relname ?
3716  errmsg("column %s.%s does not exist", relname, colname) :
3717  errmsg("column \"%s\" does not exist", colname),
3718  parser_errposition(pstate, location)));
3719  /* Handle case where we have a single alternative spelling to offer */
3720  ereport(ERROR,
3721  (errcode(ERRCODE_UNDEFINED_COLUMN),
3722  relname ?
3723  errmsg("column %s.%s does not exist", relname, colname) :
3724  errmsg("column \"%s\" does not exist", colname),
3725  errhint("Perhaps you meant to reference the column \"%s.%s\".",
3726  state->rfirst->eref->aliasname,
3727  strVal(list_nth(state->rfirst->eref->colnames,
3728  state->first - 1))),
3729  parser_errposition(pstate, location)));
3730  }
3731  else
3732  {
3733  /* Handle case where there are two equally useful column hints */
3734  ereport(ERROR,
3735  (errcode(ERRCODE_UNDEFINED_COLUMN),
3736  relname ?
3737  errmsg("column %s.%s does not exist", relname, colname) :
3738  errmsg("column \"%s\" does not exist", colname),
3739  errhint("Perhaps you meant to reference the column \"%s.%s\" or the column \"%s.%s\".",
3740  state->rfirst->eref->aliasname,
3741  strVal(list_nth(state->rfirst->eref->colnames,
3742  state->first - 1)),
3743  state->rsecond->eref->aliasname,
3744  strVal(list_nth(state->rsecond->eref->colnames,
3745  state->second - 1))),
3746  parser_errposition(pstate, location)));
3747  }
3748 }
static bool rte_visible_if_lateral(ParseState *pstate, RangeTblEntry *rte)
static FuzzyAttrMatchState * searchRangeTableForCol(ParseState *pstate, const char *alias, const char *colname, int location)
static bool rte_visible_if_qualified(ParseState *pstate, RangeTblEntry *rte)
NameData relname
Definition: pg_class.h:38
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
Definition: regguts.h:323
#define strVal(v)
Definition: value.h:82

References ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, list_nth(), parser_errposition(), relname, rte_visible_if_lateral(), rte_visible_if_qualified(), searchRangeTableForCol(), and strVal.

Referenced by transformColumnRef().

◆ errorMissingRTE()

void errorMissingRTE ( ParseState pstate,
RangeVar relation 
)

Definition at line 3591 of file parse_relation.c.

3592 {
3593  RangeTblEntry *rte;
3594  const char *badAlias = NULL;
3595 
3596  /*
3597  * Check to see if there are any potential matches in the query's
3598  * rangetable. (Note: cases involving a bad schema name in the RangeVar
3599  * will throw error immediately here. That seems OK.)
3600  */
3601  rte = searchRangeTableForRel(pstate, relation);
3602 
3603  /*
3604  * If we found a match that has an alias and the alias is visible in the
3605  * namespace, then the problem is probably use of the relation's real name
3606  * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
3607  * common enough to justify a specific hint.
3608  *
3609  * If we found a match that doesn't meet those criteria, assume the
3610  * problem is illegal use of a relation outside its scope, as in the
3611  * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
3612  */
3613  if (rte && rte->alias &&
3614  strcmp(rte->eref->aliasname, relation->relname) != 0)
3615  {
3616  ParseNamespaceItem *nsitem;
3617  int sublevels_up;
3618 
3619  nsitem = refnameNamespaceItem(pstate, NULL, rte->eref->aliasname,
3620  relation->location,
3621  &sublevels_up);
3622  if (nsitem && nsitem->p_rte == rte)
3623  badAlias = rte->eref->aliasname;
3624  }
3625 
3626  /* If it looks like the user forgot to use an alias, hint about that */
3627  if (badAlias)
3628  ereport(ERROR,
3630  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3631  relation->relname),
3632  errhint("Perhaps you meant to reference the table alias \"%s\".",
3633  badAlias),
3634  parser_errposition(pstate, relation->location)));
3635  /* Hint about case where we found an (inaccessible) exact match */
3636  else if (rte)
3637  ereport(ERROR,
3639  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3640  relation->relname),
3641  errdetail("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
3642  rte->eref->aliasname),
3643  rte_visible_if_lateral(pstate, rte) ?
3644  errhint("To reference that table, you must mark this subquery with LATERAL.") : 0,
3645  parser_errposition(pstate, relation->location)));
3646  /* Else, we have nothing to offer but the bald statement of error */
3647  else
3648  ereport(ERROR,
3650  errmsg("missing FROM-clause entry for table \"%s\"",
3651  relation->relname),
3652  parser_errposition(pstate, relation->location)));
3653 }
static RangeTblEntry * searchRangeTableForRel(ParseState *pstate, RangeVar *relation)
ParseNamespaceItem * refnameNamespaceItem(ParseState *pstate, const char *schemaname, const char *refname, int location, int *sublevels_up)
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78

References RangeTblEntry::alias, Alias::aliasname, RangeTblEntry::eref, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errdetail(), errhint(), errmsg(), ERROR, RangeVar::location, ParseNamespaceItem::p_rte, parser_errposition(), refnameNamespaceItem(), RangeVar::relname, rte_visible_if_lateral(), and searchRangeTableForRel().

Referenced by ExpandColumnRefStar(), and transformColumnRef().

◆ expandNSItemAttrs()

List* expandNSItemAttrs ( ParseState pstate,
ParseNamespaceItem nsitem,
int  sublevels_up,
bool  require_col_privs,
int  location 
)

Definition at line 3188 of file parse_relation.c.

3190 {
3191  RangeTblEntry *rte = nsitem->p_rte;
3192  RTEPermissionInfo *perminfo = nsitem->p_perminfo;
3193  List *names,
3194  *vars;
3195  ListCell *name,
3196  *var;
3197  List *te_list = NIL;
3198 
3199  vars = expandNSItemVars(pstate, nsitem, sublevels_up, location, &names);
3200 
3201  /*
3202  * Require read access to the table. This is normally redundant with the
3203  * markVarForSelectPriv calls below, but not if the table has zero
3204  * columns. We need not do anything if the nsitem is for a join: its
3205  * component tables will have been marked ACL_SELECT when they were added
3206  * to the rangetable. (This step changes things only for the target
3207  * relation of UPDATE/DELETE, which cannot be under a join.)
3208  */
3209  if (rte->rtekind == RTE_RELATION)
3210  {
3211  Assert(perminfo != NULL);
3212  perminfo->requiredPerms |= ACL_SELECT;
3213  }
3214 
3215  forboth(name, names, var, vars)
3216  {
3217  char *label = strVal(lfirst(name));
3218  Var *varnode = (Var *) lfirst(var);
3219  TargetEntry *te;
3220 
3221  te = makeTargetEntry((Expr *) varnode,
3222  (AttrNumber) pstate->p_next_resno++,
3223  label,
3224  false);
3225  te_list = lappend(te_list, te);
3226 
3227  if (require_col_privs)
3228  {
3229  /* Require read access to each column */
3230  markVarForSelectPriv(pstate, varnode);
3231  }
3232  }
3233 
3234  Assert(name == NULL && var == NULL); /* lists not the same length? */
3235 
3236  return te_list;
3237 }
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:241
void markVarForSelectPriv(ParseState *pstate, Var *var)
List * expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
static char * label
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
int p_next_resno
Definition: parse_node.h:211
Definition: primnodes.h:226
Definition: regcomp.c:281
const char * name

References ACL_SELECT, Assert(), expandNSItemVars(), forboth, label, lappend(), lfirst, makeTargetEntry(), markVarForSelectPriv(), name, NIL, ParseState::p_next_resno, ParseNamespaceItem::p_perminfo, ParseNamespaceItem::p_rte, RTEPermissionInfo::requiredPerms, RTE_RELATION, RangeTblEntry::rtekind, and strVal.

Referenced by ExpandAllTables(), ExpandSingleTable(), and transformValuesClause().

◆ expandNSItemVars()

List* expandNSItemVars ( ParseState pstate,
ParseNamespaceItem nsitem,
int  sublevels_up,
int  location,
List **  colnames 
)

Definition at line 3124 of file parse_relation.c.

3127 {
3128  List *result = NIL;
3129  int colindex;
3130  ListCell *lc;
3131 
3132  if (colnames)
3133  *colnames = NIL;
3134  colindex = 0;
3135  foreach(lc, nsitem->p_names->colnames)
3136  {
3137  String *colnameval = lfirst(lc);
3138  const char *colname = strVal(colnameval);
3139  ParseNamespaceColumn *nscol = nsitem->p_nscolumns + colindex;
3140 
3141  if (nscol->p_dontexpand)
3142  {
3143  /* skip */
3144  }
3145  else if (colname[0])
3146  {
3147  Var *var;
3148 
3149  Assert(nscol->p_varno > 0);
3150  var = makeVar(nscol->p_varno,
3151  nscol->p_varattno,
3152  nscol->p_vartype,
3153  nscol->p_vartypmod,
3154  nscol->p_varcollid,
3155  sublevels_up);
3156  /* makeVar doesn't offer parameters for these, so set by hand: */
3157  var->varnosyn = nscol->p_varnosyn;
3158  var->varattnosyn = nscol->p_varattnosyn;
3159  var->location = location;
3160 
3161  /* ... and update varnullingrels */
3162  markNullableIfNeeded(pstate, var);
3163 
3164  result = lappend(result, var);
3165  if (colnames)
3166  *colnames = lappend(*colnames, colnameval);
3167  }
3168  else
3169  {
3170  /* dropped column, ignore */
3171  Assert(nscol->p_varno == 0);
3172  }
3173  colindex++;
3174  }
3175  return result;
3176 }
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
void markNullableIfNeeded(ParseState *pstate, Var *var)
int location
Definition: primnodes.h:271

References Assert(), Alias::colnames, lappend(), lfirst, Var::location, makeVar(), markNullableIfNeeded(), NIL, ParseNamespaceColumn::p_dontexpand, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, and strVal.

Referenced by coerce_record_to_complex(), expandNSItemAttrs(), and ExpandSingleTable().

◆ expandRelation()

static void expandRelation ( Oid  relid,
Alias eref,
int  rtindex,
int  sublevels_up,
int  location,
bool  include_dropped,
List **  colnames,
List **  colvars 
)
static

Definition at line 3018 of file parse_relation.c.

3021 {
3022  Relation rel;
3023 
3024  /* Get the tupledesc and turn it over to expandTupleDesc */
3025  rel = relation_open(relid, AccessShareLock);
3026  expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
3027  rtindex, sublevels_up,
3028  location, include_dropped,
3029  colnames, colvars);
3031 }
static void expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48

References AccessShareLock, expandTupleDesc(), TupleDescData::natts, RelationData::rd_att, relation_close(), and relation_open().

Referenced by expandRTE().

◆ expandRTE()

void expandRTE ( RangeTblEntry rte,
int  rtindex,
int  sublevels_up,
int  location,
bool  include_dropped,
List **  colnames,
List **  colvars 
)

Definition at line 2665 of file parse_relation.c.

2668 {
2669  int varattno;
2670 
2671  if (colnames)
2672  *colnames = NIL;
2673  if (colvars)
2674  *colvars = NIL;
2675 
2676  switch (rte->rtekind)
2677  {
2678  case RTE_RELATION:
2679  /* Ordinary relation RTE */
2680  expandRelation(rte->relid, rte->eref,
2681  rtindex, sublevels_up, location,
2682  include_dropped, colnames, colvars);
2683  break;
2684  case RTE_SUBQUERY:
2685  {
2686  /* Subquery RTE */
2687  ListCell *aliasp_item = list_head(rte->eref->colnames);
2688  ListCell *tlistitem;
2689 
2690  varattno = 0;
2691  foreach(tlistitem, rte->subquery->targetList)
2692  {
2693  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
2694 
2695  if (te->resjunk)
2696  continue;
2697  varattno++;
2698  Assert(varattno == te->resno);
2699 
2700  /*
2701  * Formerly it was possible for the subquery tlist to have
2702  * more non-junk entries than the colnames list does (if
2703  * this RTE has been expanded from a view that has more
2704  * columns than it did when the current query was parsed).
2705  * Now that ApplyRetrieveRule cleans up such cases, we
2706  * shouldn't see that anymore, but let's just check.
2707  */
2708  if (!aliasp_item)
2709  elog(ERROR, "too few column names for subquery %s",
2710  rte->eref->aliasname);
2711 
2712  if (colnames)
2713  {
2714  char *label = strVal(lfirst(aliasp_item));
2715 
2716  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2717  }
2718 
2719  if (colvars)
2720  {
2721  Var *varnode;
2722 
2723  varnode = makeVar(rtindex, varattno,
2724  exprType((Node *) te->expr),
2725  exprTypmod((Node *) te->expr),
2726  exprCollation((Node *) te->expr),
2727  sublevels_up);
2728  varnode->location = location;
2729 
2730  *colvars = lappend(*colvars, varnode);
2731  }
2732 
2733  aliasp_item = lnext(rte->eref->colnames, aliasp_item);
2734  }
2735  }
2736  break;
2737  case RTE_FUNCTION:
2738  {
2739  /* Function RTE */
2740  int atts_done = 0;
2741  ListCell *lc;
2742 
2743  foreach(lc, rte->functions)
2744  {
2745  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2746  TypeFuncClass functypclass;
2747  Oid funcrettype;
2748  TupleDesc tupdesc;
2749 
2750  functypclass = get_expr_result_type(rtfunc->funcexpr,
2751  &funcrettype,
2752  &tupdesc);
2753  if (functypclass == TYPEFUNC_COMPOSITE ||
2754  functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
2755  {
2756  /* Composite data type, e.g. a table's row type */
2757  Assert(tupdesc);
2758  expandTupleDesc(tupdesc, rte->eref,
2759  rtfunc->funccolcount, atts_done,
2760  rtindex, sublevels_up, location,
2761  include_dropped, colnames, colvars);
2762  }
2763  else if (functypclass == TYPEFUNC_SCALAR)
2764  {
2765  /* Base data type, i.e. scalar */
2766  if (colnames)
2767  *colnames = lappend(*colnames,
2768  list_nth(rte->eref->colnames,
2769  atts_done));
2770 
2771  if (colvars)
2772  {
2773  Var *varnode;
2774 
2775  varnode = makeVar(rtindex, atts_done + 1,
2776  funcrettype,
2777  exprTypmod(rtfunc->funcexpr),
2778  exprCollation(rtfunc->funcexpr),
2779  sublevels_up);
2780  varnode->location = location;
2781 
2782  *colvars = lappend(*colvars, varnode);
2783  }
2784  }
2785  else if (functypclass == TYPEFUNC_RECORD)
2786  {
2787  if (colnames)
2788  {
2789  List *namelist;
2790 
2791  /* extract appropriate subset of column list */
2792  namelist = list_copy_tail(rte->eref->colnames,
2793  atts_done);
2794  namelist = list_truncate(namelist,
2795  rtfunc->funccolcount);
2796  *colnames = list_concat(*colnames, namelist);
2797  }
2798 
2799  if (colvars)
2800  {
2801  ListCell *l1;
2802  ListCell *l2;
2803  ListCell *l3;
2804  int attnum = atts_done;
2805 
2806  forthree(l1, rtfunc->funccoltypes,
2807  l2, rtfunc->funccoltypmods,
2808  l3, rtfunc->funccolcollations)
2809  {
2810  Oid attrtype = lfirst_oid(l1);
2811  int32 attrtypmod = lfirst_int(l2);
2812  Oid attrcollation = lfirst_oid(l3);
2813  Var *varnode;
2814 
2815  attnum++;
2816  varnode = makeVar(rtindex,
2817  attnum,
2818  attrtype,
2819  attrtypmod,
2820  attrcollation,
2821  sublevels_up);
2822  varnode->location = location;
2823  *colvars = lappend(*colvars, varnode);
2824  }
2825  }
2826  }
2827  else
2828  {
2829  /* addRangeTableEntryForFunction should've caught this */
2830  elog(ERROR, "function in FROM has unsupported return type");
2831  }
2832  atts_done += rtfunc->funccolcount;
2833  }
2834 
2835  /* Append the ordinality column if any */
2836  if (rte->funcordinality)
2837  {
2838  if (colnames)
2839  *colnames = lappend(*colnames,
2840  llast(rte->eref->colnames));
2841 
2842  if (colvars)
2843  {
2844  Var *varnode = makeVar(rtindex,
2845  atts_done + 1,
2846  INT8OID,
2847  -1,
2848  InvalidOid,
2849  sublevels_up);
2850 
2851  *colvars = lappend(*colvars, varnode);
2852  }
2853  }
2854  }
2855  break;
2856  case RTE_JOIN:
2857  {
2858  /* Join RTE */
2859  ListCell *colname;
2860  ListCell *aliasvar;
2861 
2863 
2864  varattno = 0;
2865  forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
2866  {
2867  Node *avar = (Node *) lfirst(aliasvar);
2868 
2869  varattno++;
2870 
2871  /*
2872  * During ordinary parsing, there will never be any
2873  * deleted columns in the join. While this function is
2874  * also used by the rewriter and planner, they do not
2875  * currently call it on any JOIN RTEs. Therefore, this
2876  * next bit is dead code, but it seems prudent to handle
2877  * the case correctly anyway.
2878  */
2879  if (avar == NULL)
2880  {
2881  if (include_dropped)
2882  {
2883  if (colnames)
2884  *colnames = lappend(*colnames,
2885  makeString(pstrdup("")));
2886  if (colvars)
2887  {
2888  /*
2889  * Can't use join's column type here (it might
2890  * be dropped!); but it doesn't really matter
2891  * what type the Const claims to be.
2892  */
2893  *colvars = lappend(*colvars,
2894  makeNullConst(INT4OID, -1,
2895  InvalidOid));
2896  }
2897  }
2898  continue;
2899  }
2900 
2901  if (colnames)
2902  {
2903  char *label = strVal(lfirst(colname));
2904 
2905  *colnames = lappend(*colnames,
2907  }
2908 
2909  if (colvars)
2910  {
2911  Var *varnode;
2912 
2913  /*
2914  * If the joinaliasvars entry is a simple Var, just
2915  * copy it (with adjustment of varlevelsup and
2916  * location); otherwise it is a JOIN USING column and
2917  * we must generate a join alias Var. This matches
2918  * the results that expansion of "join.*" by
2919  * expandNSItemVars would have produced, if we had
2920  * access to the ParseNamespaceItem for the join.
2921  */
2922  if (IsA(avar, Var))
2923  {
2924  varnode = copyObject((Var *) avar);
2925  varnode->varlevelsup = sublevels_up;
2926  }
2927  else
2928  varnode = makeVar(rtindex, varattno,
2929  exprType(avar),
2930  exprTypmod(avar),
2931  exprCollation(avar),
2932  sublevels_up);
2933  varnode->location = location;
2934 
2935  *colvars = lappend(*colvars, varnode);
2936  }
2937  }
2938  }
2939  break;
2940  case RTE_TABLEFUNC:
2941  case RTE_VALUES:
2942  case RTE_CTE:
2943  case RTE_NAMEDTUPLESTORE:
2944  {
2945  /* Tablefunc, Values, CTE, or ENR RTE */
2946  ListCell *aliasp_item = list_head(rte->eref->colnames);
2947  ListCell *lct;
2948  ListCell *lcm;
2949  ListCell *lcc;
2950 
2951  varattno = 0;
2952  forthree(lct, rte->coltypes,
2953  lcm, rte->coltypmods,
2954  lcc, rte->colcollations)
2955  {
2956  Oid coltype = lfirst_oid(lct);
2957  int32 coltypmod = lfirst_int(lcm);
2958  Oid colcoll = lfirst_oid(lcc);
2959 
2960  varattno++;
2961 
2962  if (colnames)
2963  {
2964  /* Assume there is one alias per output column */
2965  if (OidIsValid(coltype))
2966  {
2967  char *label = strVal(lfirst(aliasp_item));
2968 
2969  *colnames = lappend(*colnames,
2971  }
2972  else if (include_dropped)
2973  *colnames = lappend(*colnames,
2974  makeString(pstrdup("")));
2975 
2976  aliasp_item = lnext(rte->eref->colnames, aliasp_item);
2977  }
2978 
2979  if (colvars)
2980  {
2981  if (OidIsValid(coltype))
2982  {
2983  Var *varnode;
2984 
2985  varnode = makeVar(rtindex, varattno,
2986  coltype, coltypmod, colcoll,
2987  sublevels_up);
2988  varnode->location = location;
2989 
2990  *colvars = lappend(*colvars, varnode);
2991  }
2992  else if (include_dropped)
2993  {
2994  /*
2995  * It doesn't really matter what type the Const
2996  * claims to be.
2997  */
2998  *colvars = lappend(*colvars,
2999  makeNullConst(INT4OID, -1,
3000  InvalidOid));
3001  }
3002  }
3003  }
3004  }
3005  break;
3006  case RTE_RESULT:
3007  /* These expose no columns, so nothing to do */
3008  break;
3009  default:
3010  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
3011  }
3012 }
List * list_truncate(List *list, int new_size)
Definition: list.c:630
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:340
static void expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_RESULT
Definition: parsenodes.h:1021
int16 attnum
Definition: pg_attribute.h:74
#define llast(l)
Definition: pg_list.h:198
Index varlevelsup
Definition: primnodes.h:258

References Alias::aliasname, Assert(), attnum, RangeTblEntry::colcollations, Alias::colnames, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, copyObject, elog(), RangeTblEntry::eref, ERROR, expandRelation(), expandTupleDesc(), TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), forboth, forthree, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), InvalidOid, IsA, RangeTblEntry::joinaliasvars, label, lappend(), lfirst, lfirst_int, lfirst_oid, list_concat(), list_copy_tail(), list_head(), list_length(), list_nth(), list_truncate(), llast, lnext(), Var::location, makeNullConst(), makeString(), makeVar(), NIL, OidIsValid, pstrdup(), RangeTblEntry::relid, TargetEntry::resno, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, strVal, RangeTblEntry::subquery, Query::targetList, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, TYPEFUNC_RECORD, TYPEFUNC_SCALAR, and Var::varlevelsup.

Referenced by build_physical_tlist(), expandRecordVariable(), pullup_replace_vars_callback(), ReplaceVarsFromTargetList_callback(), set_relation_column_names(), and transformWholeRowRef().

◆ expandTupleDesc()

static void expandTupleDesc ( TupleDesc  tupdesc,
Alias eref,
int  count,
int  offset,
int  rtindex,
int  sublevels_up,
int  location,
bool  include_dropped,
List **  colnames,
List **  colvars 
)
static

Definition at line 3043 of file parse_relation.c.

3047 {
3048  ListCell *aliascell;
3049  int varattno;
3050 
3051  aliascell = (offset < list_length(eref->colnames)) ?
3052  list_nth_cell(eref->colnames, offset) : NULL;
3053 
3054  Assert(count <= tupdesc->natts);
3055  for (varattno = 0; varattno < count; varattno++)
3056  {
3057  Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
3058 
3059  if (attr->attisdropped)
3060  {
3061  if (include_dropped)
3062  {
3063  if (colnames)
3064  *colnames = lappend(*colnames, makeString(pstrdup("")));
3065  if (colvars)
3066  {
3067  /*
3068  * can't use atttypid here, but it doesn't really matter
3069  * what type the Const claims to be.
3070  */
3071  *colvars = lappend(*colvars,
3072  makeNullConst(INT4OID, -1, InvalidOid));
3073  }
3074  }
3075  if (aliascell)
3076  aliascell = lnext(eref->colnames, aliascell);
3077  continue;
3078  }
3079 
3080  if (colnames)
3081  {
3082  char *label;
3083 
3084  if (aliascell)
3085  {
3086  label = strVal(lfirst(aliascell));
3087  aliascell = lnext(eref->colnames, aliascell);
3088  }
3089  else
3090  {
3091  /* If we run out of aliases, use the underlying name */
3092  label = NameStr(attr->attname);
3093  }
3094  *colnames = lappend(*colnames, makeString(pstrdup(label)));
3095  }
3096 
3097  if (colvars)
3098  {
3099  Var *varnode;
3100 
3101  varnode = makeVar(rtindex, varattno + offset + 1,
3102  attr->atttypid, attr->atttypmod,
3103  attr->attcollation,
3104  sublevels_up);
3105  varnode->location = location;
3106 
3107  *colvars = lappend(*colvars, varnode);
3108  }
3109  }
3110 }
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:277

References Assert(), Alias::colnames, InvalidOid, label, lappend(), lfirst, list_length(), list_nth_cell(), lnext(), Var::location, makeNullConst(), makeString(), makeVar(), NameStr, pstrdup(), strVal, and TupleDescAttr.

Referenced by expandRelation(), and expandRTE().

◆ findNSItemForRTE()

static ParseNamespaceItem* findNSItemForRTE ( ParseState pstate,
RangeTblEntry rte 
)
static

Definition at line 3755 of file parse_relation.c.

3756 {
3757  while (pstate != NULL)
3758  {
3759  ListCell *l;
3760 
3761  foreach(l, pstate->p_namespace)
3762  {
3763  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
3764 
3765  if (nsitem->p_rte == rte)
3766  return nsitem;
3767  }
3768  pstate = pstate->parentParseState;
3769  }
3770  return NULL;
3771 }

References lfirst, ParseState::p_namespace, ParseNamespaceItem::p_rte, and ParseState::parentParseState.

Referenced by rte_visible_if_lateral(), and rte_visible_if_qualified().

◆ get_parse_rowmark()

RowMarkClause* get_parse_rowmark ( Query qry,
Index  rtindex 
)

Definition at line 3456 of file parse_relation.c.

3457 {
3458  ListCell *l;
3459 
3460  foreach(l, qry->rowMarks)
3461  {
3462  RowMarkClause *rc = (RowMarkClause *) lfirst(l);
3463 
3464  if (rc->rti == rtindex)
3465  return rc;
3466  }
3467  return NULL;
3468 }
List * rowMarks
Definition: parsenodes.h:214

References lfirst, Query::rowMarks, and RowMarkClause::rti.

Referenced by AcquireRewriteLocks(), applyLockingClause(), and ApplyRetrieveRule().

◆ get_rte_attribute_is_dropped()

bool get_rte_attribute_is_dropped ( RangeTblEntry rte,
AttrNumber  attnum 
)

Definition at line 3292 of file parse_relation.c.

3293 {
3294  bool result;
3295 
3296  switch (rte->rtekind)
3297  {
3298  case RTE_RELATION:
3299  {
3300  /*
3301  * Plain relation RTE --- get the attribute's catalog entry
3302  */
3303  HeapTuple tp;
3304  Form_pg_attribute att_tup;
3305 
3306  tp = SearchSysCache2(ATTNUM,
3307  ObjectIdGetDatum(rte->relid),
3309  if (!HeapTupleIsValid(tp)) /* shouldn't happen */
3310  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
3311  attnum, rte->relid);
3312  att_tup = (Form_pg_attribute) GETSTRUCT(tp);
3313  result = att_tup->attisdropped;
3314  ReleaseSysCache(tp);
3315  }
3316  break;
3317  case RTE_SUBQUERY:
3318  case RTE_TABLEFUNC:
3319  case RTE_VALUES:
3320  case RTE_CTE:
3321 
3322  /*
3323  * Subselect, Table Functions, Values, CTE RTEs never have dropped
3324  * columns
3325  */
3326  result = false;
3327  break;
3328  case RTE_NAMEDTUPLESTORE:
3329  {
3330  /* Check dropped-ness by testing for valid coltype */
3331  if (attnum <= 0 ||
3332  attnum > list_length(rte->coltypes))
3333  elog(ERROR, "invalid varattno %d", attnum);
3334  result = !OidIsValid((list_nth_oid(rte->coltypes, attnum - 1)));
3335  }
3336  break;
3337  case RTE_JOIN:
3338  {
3339  /*
3340  * A join RTE would not have dropped columns when constructed,
3341  * but one in a stored rule might contain columns that were
3342  * dropped from the underlying tables, if said columns are
3343  * nowhere explicitly referenced in the rule. This will be
3344  * signaled to us by a null pointer in the joinaliasvars list.
3345  */
3346  Var *aliasvar;
3347 
3348  if (attnum <= 0 ||
3350  elog(ERROR, "invalid varattno %d", attnum);
3351  aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
3352 
3353  result = (aliasvar == NULL);
3354  }
3355  break;
3356  case RTE_FUNCTION:
3357  {
3358  /* Function RTE */
3359  ListCell *lc;
3360  int atts_done = 0;
3361 
3362  /*
3363  * Dropped attributes are only possible with functions that
3364  * return named composite types. In such a case we have to
3365  * look up the result type to see if it currently has this
3366  * column dropped. So first, loop over the funcs until we
3367  * find the one that covers the requested column.
3368  */
3369  foreach(lc, rte->functions)
3370  {
3371  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
3372 
3373  if (attnum > atts_done &&
3374  attnum <= atts_done + rtfunc->funccolcount)
3375  {
3376  TupleDesc tupdesc;
3377 
3378  tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr,
3379  true);
3380  if (tupdesc)
3381  {
3382  /* Composite data type, e.g. a table's row type */
3383  Form_pg_attribute att_tup;
3384 
3385  Assert(tupdesc);
3386  Assert(attnum - atts_done <= tupdesc->natts);
3387  att_tup = TupleDescAttr(tupdesc,
3388  attnum - atts_done - 1);
3389  return att_tup->attisdropped;
3390  }
3391  /* Otherwise, it can't have any dropped columns */
3392  return false;
3393  }
3394  atts_done += rtfunc->funccolcount;
3395  }
3396 
3397  /* If we get here, must be looking for the ordinality column */
3398  if (rte->funcordinality && attnum == atts_done + 1)
3399  return false;
3400 
3401  /* this probably can't happen ... */
3402  ereport(ERROR,
3403  (errcode(ERRCODE_UNDEFINED_COLUMN),
3404  errmsg("column %d of relation \"%s\" does not exist",
3405  attnum,
3406  rte->eref->aliasname)));
3407  result = false; /* keep compiler quiet */
3408  }
3409  break;
3410  case RTE_RESULT:
3411  /* this probably can't happen ... */
3412  ereport(ERROR,
3413  (errcode(ERRCODE_UNDEFINED_COLUMN),
3414  errmsg("column %d of relation \"%s\" does not exist",
3415  attnum,
3416  rte->eref->aliasname)));
3417  result = false; /* keep compiler quiet */
3418  break;
3419  default:
3420  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
3421  result = false; /* keep compiler quiet */
3422  }
3423 
3424  return result;
3425 }
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:543
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
static Oid list_nth_oid(const List *list, int n)
Definition: pg_list.h:321
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:831
@ ATTNUM
Definition: syscache.h:41

References Alias::aliasname, Assert(), attnum, ATTNUM, RangeTblEntry::coltypes, elog(), RangeTblEntry::eref, ereport, errcode(), errmsg(), ERROR, RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_tupdesc(), GETSTRUCT, HeapTupleIsValid, Int16GetDatum(), RangeTblEntry::joinaliasvars, lfirst, list_length(), list_nth(), list_nth_oid(), ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), RangeTblEntry::relid, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, SearchSysCache2(), and TupleDescAttr.

Referenced by AcquireRewriteLocks().

◆ get_rte_attribute_name()

char* get_rte_attribute_name ( RangeTblEntry rte,
AttrNumber  attnum 
)

Definition at line 3254 of file parse_relation.c.

3255 {
3256  if (attnum == InvalidAttrNumber)
3257  return "*";
3258 
3259  /*
3260  * If there is a user-written column alias, use it.
3261  */
3262  if (rte->alias &&
3263  attnum > 0 && attnum <= list_length(rte->alias->colnames))
3264  return strVal(list_nth(rte->alias->colnames, attnum - 1));
3265 
3266  /*
3267  * If the RTE is a relation, go to the system catalogs not the
3268  * eref->colnames list. This is a little slower but it will give the
3269  * right answer if the column has been renamed since the eref list was
3270  * built (which can easily happen for rules).
3271  */
3272  if (rte->rtekind == RTE_RELATION)
3273  return get_attname(rte->relid, attnum, false);
3274 
3275  /*
3276  * Otherwise use the column name from eref. There should always be one.
3277  */
3278  if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
3279  return strVal(list_nth(rte->eref->colnames, attnum - 1));
3280 
3281  /* else caller gave us a bogus attnum */
3282  elog(ERROR, "invalid attnum %d for rangetable entry %s",
3283  attnum, rte->eref->aliasname);
3284  return NULL; /* keep compiler quiet */
3285 }
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:826

References RangeTblEntry::alias, Alias::aliasname, attnum, Alias::colnames, elog(), RangeTblEntry::eref, ERROR, get_attname(), InvalidAttrNumber, list_length(), list_nth(), RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, and strVal.

Referenced by check_ungrouped_columns_walker(), get_name_for_var_field(), get_variable(), and print_expr().

◆ get_tle_by_resno()

◆ GetCTEForRTE()

CommonTableExpr* GetCTEForRTE ( ParseState pstate,
RangeTblEntry rte,
int  rtelevelsup 
)

Definition at line 557 of file parse_relation.c.

558 {
559  Index levelsup;
560  ListCell *lc;
561 
562  Assert(rte->rtekind == RTE_CTE);
563  levelsup = rte->ctelevelsup + rtelevelsup;
564  while (levelsup-- > 0)
565  {
566  pstate = pstate->parentParseState;
567  if (!pstate) /* shouldn't happen */
568  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
569  }
570  foreach(lc, pstate->p_ctenamespace)
571  {
572  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
573 
574  if (strcmp(cte->ctename, rte->ctename) == 0)
575  return cte;
576  }
577  /* shouldn't happen */
578  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
579  return NULL; /* keep compiler quiet */
580 }
unsigned int Index
Definition: c.h:603
List * p_ctenamespace
Definition: parse_node.h:203

References Assert(), RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, CommonTableExpr::ctename, elog(), ERROR, lfirst, ParseState::p_ctenamespace, ParseState::parentParseState, RTE_CTE, and RangeTblEntry::rtekind.

Referenced by expandRecordVariable(), and markTargetListOrigin().

◆ GetNSItemByRangeTablePosn()

ParseNamespaceItem* GetNSItemByRangeTablePosn ( ParseState pstate,
int  varno,
int  sublevels_up 
)

Definition at line 510 of file parse_relation.c.

513 {
514  ListCell *lc;
515 
516  while (sublevels_up-- > 0)
517  {
518  pstate = pstate->parentParseState;
519  Assert(pstate != NULL);
520  }
521  foreach(lc, pstate->p_namespace)
522  {
523  ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
524 
525  if (nsitem->p_rtindex == varno)
526  return nsitem;
527  }
528  elog(ERROR, "nsitem not found (internal error)");
529  return NULL; /* keep compiler quiet */
530 }

References Assert(), elog(), ERROR, lfirst, ParseState::p_namespace, ParseNamespaceItem::p_rtindex, and ParseState::parentParseState.

Referenced by coerce_record_to_complex(), ExpandRowReference(), ParseComplexProjection(), and transformMergeStmt().

◆ GetRTEByRangeTablePosn()

RangeTblEntry* GetRTEByRangeTablePosn ( ParseState pstate,
int  varno,
int  sublevels_up 
)

Definition at line 537 of file parse_relation.c.

540 {
541  while (sublevels_up-- > 0)
542  {
543  pstate = pstate->parentParseState;
544  Assert(pstate != NULL);
545  }
546  Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
547  return rt_fetch(varno, pstate->p_rtable);
548 }
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31

References Assert(), list_length(), ParseState::p_rtable, ParseState::parentParseState, and rt_fetch.

Referenced by count_rowexpr_columns(), expandRecordVariable(), markTargetListOrigin(), and unknown_attribute().

◆ getRTEPermissionInfo()

RTEPermissionInfo* getRTEPermissionInfo ( List rteperminfos,
RangeTblEntry rte 
)

Definition at line 3900 of file parse_relation.c.

3901 {
3902  RTEPermissionInfo *perminfo;
3903 
3904  if (rte->perminfoindex == 0 ||
3905  rte->perminfoindex > list_length(rteperminfos))
3906  elog(ERROR, "invalid perminfoindex %u in RTE with relid %u",
3907  rte->perminfoindex, rte->relid);
3908  perminfo = list_nth_node(RTEPermissionInfo, rteperminfos,
3909  rte->perminfoindex - 1);
3910  if (perminfo->relid != rte->relid)
3911  elog(ERROR, "permission info at index %u (with relid=%u) does not match provided RTE (with relid=%u)",
3912  rte->perminfoindex, perminfo->relid, rte->relid);
3913 
3914  return perminfo;
3915 }
#define list_nth_node(type, list, n)
Definition: pg_list.h:327

References elog(), ERROR, list_length(), list_nth_node, RangeTblEntry::perminfoindex, RangeTblEntry::relid, and RTEPermissionInfo::relid.

Referenced by add_rte_to_flat_rtable(), build_simple_rel(), ExecCheckPermissions(), expand_inherited_rtentry(), get_rel_all_updated_cols(), get_row_security_policies(), GetResultRTEPermissionInfo(), markQueryForLocking(), markRTEForSelectPriv(), rewriteTargetView(), and transformLockingClause().

◆ isFutureCTE()

static bool isFutureCTE ( ParseState pstate,
const char *  refname 
)
static

Definition at line 313 of file parse_relation.c.

314 {
315  for (; pstate != NULL; pstate = pstate->parentParseState)
316  {
317  ListCell *lc;
318 
319  foreach(lc, pstate->p_future_ctes)
320  {
321  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
322 
323  if (strcmp(cte->ctename, refname) == 0)
324  return true;
325  }
326  }
327  return false;
328 }
List * p_future_ctes
Definition: parse_node.h:204

References CommonTableExpr::ctename, lfirst, ParseState::p_future_ctes, and ParseState::parentParseState.

Referenced by parserOpenTable().

◆ isLockedRefname()

bool isLockedRefname ( ParseState pstate,
const char *  refname 
)

Definition at line 2581 of file parse_relation.c.

2582 {
2583  ListCell *l;
2584 
2585  /*
2586  * If we are in a subquery specified as locked FOR UPDATE/SHARE from
2587  * parent level, then act as though there's a generic FOR UPDATE here.
2588  */
2589  if (pstate->p_locked_from_parent)
2590  return true;
2591 
2592  foreach(l, pstate->p_locking_clause)
2593  {
2594  LockingClause *lc = (LockingClause *) lfirst(l);
2595 
2596  if (lc->lockedRels == NIL)
2597  {
2598  /* all tables used in query */
2599  return true;
2600  }
2601  else if (refname != NULL)
2602  {
2603  /* just the named tables */
2604  ListCell *l2;
2605 
2606  foreach(l2, lc->lockedRels)
2607  {
2608  RangeVar *thisrel = (RangeVar *) lfirst(l2);
2609 
2610  if (strcmp(refname, thisrel->relname) == 0)
2611  return true;
2612  }
2613  }
2614  }
2615  return false;
2616 }
List * lockedRels
Definition: parsenodes.h:828
bool p_locked_from_parent
Definition: parse_node.h:214
List * p_locking_clause
Definition: parse_node.h:213

References lfirst, LockingClause::lockedRels, NIL, ParseState::p_locked_from_parent, ParseState::p_locking_clause, and RangeVar::relname.

Referenced by addRangeTableEntry(), and transformRangeSubselect().

◆ isQueryUsingTempRelation()

bool isQueryUsingTempRelation ( Query query)

Definition at line 3821 of file parse_relation.c.

3822 {
3823  return isQueryUsingTempRelation_walker((Node *) query, NULL);
3824 }
static bool isQueryUsingTempRelation_walker(Node *node, void *context)

References isQueryUsingTempRelation_walker().

Referenced by DefineView(), and transformCreateTableAsStmt().

◆ isQueryUsingTempRelation_walker()

static bool isQueryUsingTempRelation_walker ( Node node,
void *  context 
)
static

Definition at line 3827 of file parse_relation.c.

3828 {
3829  if (node == NULL)
3830  return false;
3831 
3832  if (IsA(node, Query))
3833  {
3834  Query *query = (Query *) node;
3835  ListCell *rtable;
3836 
3837  foreach(rtable, query->rtable)
3838  {
3839  RangeTblEntry *rte = lfirst(rtable);
3840 
3841  if (rte->rtekind == RTE_RELATION)
3842  {
3844  char relpersistence = rel->rd_rel->relpersistence;
3845 
3847  if (relpersistence == RELPERSISTENCE_TEMP)
3848  return true;
3849  }
3850  }
3851 
3852  return query_tree_walker(query,
3854  context,
3856  }
3857 
3858  return expression_tree_walker(node,
3860  context);
3861 }
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:25
List * rtable
Definition: parsenodes.h:174
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessShareLock, expression_tree_walker, IsA, lfirst, QTW_IGNORE_JOINALIASES, query_tree_walker, RelationData::rd_rel, RangeTblEntry::relid, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, table_close(), and table_open().

Referenced by isQueryUsingTempRelation().

◆ markNullableIfNeeded()

void markNullableIfNeeded ( ParseState pstate,
Var var 
)

Definition at line 1035 of file parse_relation.c.

1036 {
1037  int rtindex = var->varno;
1038  Bitmapset *relids;
1039 
1040  /* Find the appropriate pstate */
1041  for (int lv = 0; lv < var->varlevelsup; lv++)
1042  pstate = pstate->parentParseState;
1043 
1044  /* Find currently-relevant join relids for the Var's rel */
1045  if (rtindex > 0 && rtindex <= list_length(pstate->p_nullingrels))
1046  relids = (Bitmapset *) list_nth(pstate->p_nullingrels, rtindex - 1);
1047  else
1048  relids = NULL;
1049 
1050  /*
1051  * Merge with any already-declared nulling rels. (Typically there won't
1052  * be any, but let's get it right if there are.)
1053  */
1054  if (relids != NULL)
1055  var->varnullingrels = bms_union(var->varnullingrels, relids);
1056 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:211
List * p_nullingrels
Definition: parse_node.h:197
int varno
Definition: primnodes.h:233

References bms_union(), if(), list_length(), list_nth(), ParseState::p_nullingrels, ParseState::parentParseState, Var::varlevelsup, and Var::varno.

Referenced by buildVarFromNSColumn(), expandNSItemVars(), scanNSItemForColumn(), and transformWholeRowRef().

◆ markRTEForSelectPriv()

static void markRTEForSelectPriv ( ParseState pstate,
int  rtindex,
AttrNumber  col 
)
static

Definition at line 1066 of file parse_relation.c.

1067 {
1068  RangeTblEntry *rte = rt_fetch(rtindex, pstate->p_rtable);
1069 
1070  if (rte->rtekind == RTE_RELATION)
1071  {
1072  RTEPermissionInfo *perminfo;
1073 
1074  /* Make sure the rel as a whole is marked for SELECT access */
1075  perminfo = getRTEPermissionInfo(pstate->p_rteperminfos, rte);
1076  perminfo->requiredPerms |= ACL_SELECT;
1077  /* Must offset the attnum to fit in a bitmapset */
1078  perminfo->selectedCols =
1079  bms_add_member(perminfo->selectedCols,
1081  }
1082  else if (rte->rtekind == RTE_JOIN)
1083  {
1084  if (col == InvalidAttrNumber)
1085  {
1086  /*
1087  * A whole-row reference to a join has to be treated as whole-row
1088  * references to the two inputs.
1089  */
1090  JoinExpr *j;
1091 
1092  if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
1093  j = list_nth_node(JoinExpr, pstate->p_joinexprs, rtindex - 1);
1094  else
1095  j = NULL;
1096  if (j == NULL)
1097  elog(ERROR, "could not find JoinExpr for whole-row reference");
1098 
1099  /* Note: we can't see FromExpr here */
1100  if (IsA(j->larg, RangeTblRef))
1101  {
1102  int varno = ((RangeTblRef *) j->larg)->rtindex;
1103 
1104  markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1105  }
1106  else if (IsA(j->larg, JoinExpr))
1107  {
1108  int varno = ((JoinExpr *) j->larg)->rtindex;
1109 
1110  markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1111  }
1112  else
1113  elog(ERROR, "unrecognized node type: %d",
1114  (int) nodeTag(j->larg));
1115  if (IsA(j->rarg, RangeTblRef))
1116  {
1117  int varno = ((RangeTblRef *) j->rarg)->rtindex;
1118 
1119  markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1120  }
1121  else if (IsA(j->rarg, JoinExpr))
1122  {
1123  int varno = ((JoinExpr *) j->rarg)->rtindex;
1124 
1125  markRTEForSelectPriv(pstate, varno, InvalidAttrNumber);
1126  }
1127  else
1128  elog(ERROR, "unrecognized node type: %d",
1129  (int) nodeTag(j->rarg));
1130  }
1131  else
1132  {
1133  /*
1134  * Join alias Vars for ordinary columns must refer to merged JOIN
1135  * USING columns. We don't need to do anything here, because the
1136  * join input columns will also be referenced in the join's qual
1137  * clause, and will get marked for select privilege there.
1138  */
1139  }
1140  }
1141  /* other RTE types don't require privilege marking */
1142 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
#define nodeTag(nodeptr)
Definition: nodes.h:133
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
static void markRTEForSelectPriv(ParseState *pstate, int rtindex, AttrNumber col)
List * p_joinexprs
Definition: parse_node.h:196
Bitmapset * selectedCols
Definition: parsenodes.h:1247
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References ACL_SELECT, bms_add_member(), elog(), ERROR, FirstLowInvalidHeapAttributeNumber, getRTEPermissionInfo(), InvalidAttrNumber, IsA, j, list_length(), list_nth_node, nodeTag, ParseState::p_joinexprs, ParseState::p_rtable, ParseState::p_rteperminfos, RTEPermissionInfo::requiredPerms, rt_fetch, RTE_JOIN, RTE_RELATION, RangeTblEntry::rtekind, and RTEPermissionInfo::selectedCols.

Referenced by markVarForSelectPriv().

◆ markVarForSelectPriv()

void markVarForSelectPriv ( ParseState pstate,
Var var 
)

Definition at line 1150 of file parse_relation.c.

1151 {
1152  Index lv;
1153 
1154  Assert(IsA(var, Var));
1155  /* Find the appropriate pstate if it's an uplevel Var */
1156  for (lv = 0; lv < var->varlevelsup; lv++)
1157  pstate = pstate->parentParseState;
1158  markRTEForSelectPriv(pstate, var->varno, var->varattno);
1159 }
AttrNumber varattno
Definition: primnodes.h:238

References Assert(), IsA, markRTEForSelectPriv(), ParseState::parentParseState, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by expandNSItemAttrs(), ExpandSingleTable(), scanNSItemForColumn(), transformJoinUsingClause(), and transformWholeRowRef().

◆ parserOpenTable()

Relation parserOpenTable ( ParseState pstate,
const RangeVar relation,
int  lockmode 
)

Definition at line 1418 of file parse_relation.c.

1419 {
1420  Relation rel;
1421  ParseCallbackState pcbstate;
1422 
1423  setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
1424  rel = table_openrv_extended(relation, lockmode, true);
1425  if (rel == NULL)
1426  {
1427  if (relation->schemaname)
1428  ereport(ERROR,
1430  errmsg("relation \"%s.%s\" does not exist",
1431  relation->schemaname, relation->relname)));
1432  else
1433  {
1434  /*
1435  * An unqualified name might have been meant as a reference to
1436  * some not-yet-in-scope CTE. The bare "does not exist" message
1437  * has proven remarkably unhelpful for figuring out such problems,
1438  * so we take pains to offer a specific hint.
1439  */
1440  if (isFutureCTE(pstate, relation->relname))
1441  ereport(ERROR,
1443  errmsg("relation \"%s\" does not exist",
1444  relation->relname),
1445  errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
1446  relation->relname),
1447  errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
1448  else
1449  ereport(ERROR,
1451  errmsg("relation \"%s\" does not exist",
1452  relation->relname)));
1453  }
1454  }
1456  return rel;
1457 }
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
static bool isFutureCTE(ParseState *pstate, const char *refname)
char * schemaname
Definition: primnodes.h:71
Relation table_openrv_extended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok)
Definition: table.c:103

References cancel_parser_errposition_callback(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errdetail(), errhint(), errmsg(), ERROR, isFutureCTE(), RangeVar::location, RangeVar::relname, RangeVar::schemaname, setup_parser_errposition_callback(), and table_openrv_extended().

Referenced by addRangeTableEntry(), and setTargetTable().

◆ refnameNamespaceItem()

ParseNamespaceItem* refnameNamespaceItem ( ParseState pstate,
const char *  schemaname,
const char *  refname,
int  location,
int *  sublevels_up 
)

Definition at line 129 of file parse_relation.c.

134 {
135  Oid relId = InvalidOid;
136 
137  if (sublevels_up)
138  *sublevels_up = 0;
139 
140  if (schemaname != NULL)
141  {
142  Oid namespaceId;
143 
144  /*
145  * We can use LookupNamespaceNoError() here because we are only
146  * interested in finding existing RTEs. Checking USAGE permission on
147  * the schema is unnecessary since it would have already been checked
148  * when the RTE was made. Furthermore, we want to report "RTE not
149  * found", not "no permissions for schema", if the name happens to
150  * match a schema name the user hasn't got access to.
151  */
152  namespaceId = LookupNamespaceNoError(schemaname);
153  if (!OidIsValid(namespaceId))
154  return NULL;
155  relId = get_relname_relid(refname, namespaceId);
156  if (!OidIsValid(relId))
157  return NULL;
158  }
159 
160  while (pstate != NULL)
161  {
162  ParseNamespaceItem *result;
163 
164  if (OidIsValid(relId))
165  result = scanNameSpaceForRelid(pstate, relId, location);
166  else
167  result = scanNameSpaceForRefname(pstate, refname, location);
168 
169  if (result)
170  return result;
171 
172  if (sublevels_up)
173  (*sublevels_up)++;
174  else
175  break;
176 
177  pstate = pstate->parentParseState;
178  }
179  return NULL;
180 }
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1889
Oid LookupNamespaceNoError(const char *nspname)
Definition: namespace.c:2888
static ParseNamespaceItem * scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
static ParseNamespaceItem * scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)

References get_relname_relid(), InvalidOid, LookupNamespaceNoError(), OidIsValid, ParseState::parentParseState, scanNameSpaceForRefname(), and scanNameSpaceForRelid().

Referenced by errorMissingRTE(), ExpandColumnRefStar(), and transformColumnRef().

◆ rte_visible_if_lateral()

static bool rte_visible_if_lateral ( ParseState pstate,
RangeTblEntry rte 
)
static

Definition at line 3783 of file parse_relation.c.

3784 {
3785  ParseNamespaceItem *nsitem;
3786 
3787  /* If LATERAL *is* active, we're clearly barking up the wrong tree */
3788  if (pstate->p_lateral_active)
3789  return false;
3790  nsitem = findNSItemForRTE(pstate, rte);
3791  if (nsitem)
3792  {
3793  /* Found it, report whether it's LATERAL-only */
3794  return nsitem->p_lateral_only && nsitem->p_lateral_ok;
3795  }
3796  return false;
3797 }
static ParseNamespaceItem * findNSItemForRTE(ParseState *pstate, RangeTblEntry *rte)

References findNSItemForRTE(), ParseState::p_lateral_active, ParseNamespaceItem::p_lateral_ok, and ParseNamespaceItem::p_lateral_only.

Referenced by errorMissingColumn(), and errorMissingRTE().

◆ rte_visible_if_qualified()

static bool rte_visible_if_qualified ( ParseState pstate,
RangeTblEntry rte 
)
static

Definition at line 3803 of file parse_relation.c.

3804 {
3805  ParseNamespaceItem *nsitem = findNSItemForRTE(pstate, rte);
3806 
3807  if (nsitem)
3808  {
3809  /* Found it, report whether it's relation-only */
3810  return nsitem->p_rel_visible && !nsitem->p_cols_visible;
3811  }
3812  return false;
3813 }

References findNSItemForRTE(), ParseNamespaceItem::p_cols_visible, and ParseNamespaceItem::p_rel_visible.

Referenced by errorMissingColumn().

◆ scanNameSpaceForCTE()

CommonTableExpr* scanNameSpaceForCTE ( ParseState pstate,
const char *  refname,
Index ctelevelsup 
)

Definition at line 282 of file parse_relation.c.

284 {
285  Index levelsup;
286 
287  for (levelsup = 0;
288  pstate != NULL;
289  pstate = pstate->parentParseState, levelsup++)
290  {
291  ListCell *lc;
292 
293  foreach(lc, pstate->p_ctenamespace)
294  {
295  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
296 
297  if (strcmp(cte->ctename, refname) == 0)
298  {
299  *ctelevelsup = levelsup;
300  return cte;
301  }
302  }
303  }
304  return NULL;
305 }

References CommonTableExpr::ctename, lfirst, ParseState::p_ctenamespace, and ParseState::parentParseState.

Referenced by getNSItemForSpecialRelationTypes(), and searchRangeTableForRel().

◆ scanNameSpaceForENR()

bool scanNameSpaceForENR ( ParseState pstate,
const char *  refname 
)

Definition at line 335 of file parse_relation.c.

336 {
337  return name_matches_visible_ENR(pstate, refname);
338 }
bool name_matches_visible_ENR(ParseState *pstate, const char *refname)
Definition: parse_enr.c:20

References name_matches_visible_ENR().

Referenced by getNSItemForSpecialRelationTypes(), searchRangeTableForRel(), and setTargetTable().

◆ scanNameSpaceForRefname()

static ParseNamespaceItem * scanNameSpaceForRefname ( ParseState pstate,
const char *  refname,
int  location 
)
static

Definition at line 200 of file parse_relation.c.

201 {
202  ParseNamespaceItem *result = NULL;
203  ListCell *l;
204 
205  foreach(l, pstate->p_namespace)
206  {
208 
209  /* Ignore columns-only items */
210  if (!nsitem->p_rel_visible)
211  continue;
212  /* If not inside LATERAL, ignore lateral-only items */
213  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
214  continue;
215 
216  if (strcmp(nsitem->p_names->aliasname, refname) == 0)
217  {
218  if (result)
219  ereport(ERROR,
220  (errcode(ERRCODE_AMBIGUOUS_ALIAS),
221  errmsg("table reference \"%s\" is ambiguous",
222  refname),
223  parser_errposition(pstate, location)));
224  check_lateral_ref_ok(pstate, nsitem, location);
225  result = nsitem;
226  }
227  }
228  return result;
229 }

References Alias::aliasname, check_lateral_ref_ok(), ereport, errcode(), errmsg(), ERROR, lfirst, ParseState::p_lateral_active, ParseNamespaceItem::p_lateral_only, ParseNamespaceItem::p_names, ParseState::p_namespace, ParseNamespaceItem::p_rel_visible, and parser_errposition().

Referenced by refnameNamespaceItem().

◆ scanNameSpaceForRelid()

static ParseNamespaceItem * scanNameSpaceForRelid ( ParseState pstate,
Oid  relid,
int  location 
)
static

Definition at line 240 of file parse_relation.c.

241 {
242  ParseNamespaceItem *result = NULL;
243  ListCell *l;
244 
245  foreach(l, pstate->p_namespace)
246  {
248  RangeTblEntry *rte = nsitem->p_rte;
249 
250  /* Ignore columns-only items */
251  if (!nsitem->p_rel_visible)
252  continue;
253  /* If not inside LATERAL, ignore lateral-only items */
254  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
255  continue;
256 
257  /* yes, the test for alias == NULL should be there... */
258  if (rte->rtekind == RTE_RELATION &&
259  rte->relid == relid &&
260  rte->alias == NULL)
261  {
262  if (result)
263  ereport(ERROR,
264  (errcode(ERRCODE_AMBIGUOUS_ALIAS),
265  errmsg("table reference %u is ambiguous",
266  relid),
267  parser_errposition(pstate, location)));
268  check_lateral_ref_ok(pstate, nsitem, location);
269  result = nsitem;
270  }
271  }
272  return result;
273 }

References RangeTblEntry::alias, check_lateral_ref_ok(), ereport, errcode(), errmsg(), ERROR, lfirst, ParseState::p_lateral_active, ParseNamespaceItem::p_lateral_only, ParseState::p_namespace, ParseNamespaceItem::p_rel_visible, ParseNamespaceItem::p_rte, parser_errposition(), RangeTblEntry::relid, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by refnameNamespaceItem().

◆ scanNSItemForColumn()

Node* scanNSItemForColumn ( ParseState pstate,
ParseNamespaceItem nsitem,
int  sublevels_up,
const char *  colname,
int  location 
)

Definition at line 680 of file parse_relation.c.

682 {
683  RangeTblEntry *rte = nsitem->p_rte;
684  int attnum;
685  Var *var;
686 
687  /*
688  * Scan the nsitem's column names (or aliases) for a match. Complain if
689  * multiple matches.
690  */
691  attnum = scanRTEForColumn(pstate, rte, nsitem->p_names,
692  colname, location,
693  0, NULL);
694 
695  if (attnum == InvalidAttrNumber)
696  return NULL; /* Return NULL if no match */
697 
698  /* In constraint check, no system column is allowed except tableOid */
699  if (pstate->p_expr_kind == EXPR_KIND_CHECK_CONSTRAINT &&
701  ereport(ERROR,
702  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
703  errmsg("system column \"%s\" reference in check constraint is invalid",
704  colname),
705  parser_errposition(pstate, location)));
706 
707  /* In generated column, no system column is allowed except tableOid */
708  if (pstate->p_expr_kind == EXPR_KIND_GENERATED_COLUMN &&
710  ereport(ERROR,
711  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
712  errmsg("cannot use system column \"%s\" in column generation expression",
713  colname),
714  parser_errposition(pstate, location)));
715 
716  /*
717  * In a MERGE WHEN condition, no system column is allowed except tableOid
718  */
719  if (pstate->p_expr_kind == EXPR_KIND_MERGE_WHEN &&
721  ereport(ERROR,
722  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
723  errmsg("cannot use system column \"%s\" in MERGE WHEN condition",
724  colname),
725  parser_errposition(pstate, location)));
726 
727  /* Found a valid match, so build a Var */
729  {
730  /* Get attribute data from the ParseNamespaceColumn array */
731  ParseNamespaceColumn *nscol = &nsitem->p_nscolumns[attnum - 1];
732 
733  /* Complain if dropped column. See notes in scanRTEForColumn. */
734  if (nscol->p_varno == 0)
735  ereport(ERROR,
736  (errcode(ERRCODE_UNDEFINED_COLUMN),
737  errmsg("column \"%s\" of relation \"%s\" does not exist",
738  colname,
739  nsitem->p_names->aliasname)));
740 
741  var = makeVar(nscol->p_varno,
742  nscol->p_varattno,
743  nscol->p_vartype,
744  nscol->p_vartypmod,
745  nscol->p_varcollid,
746  sublevels_up);
747  /* makeVar doesn't offer parameters for these, so set them by hand: */
748  var->varnosyn = nscol->p_varnosyn;
749  var->varattnosyn = nscol->p_varattnosyn;
750  }
751  else
752  {
753  /* System column, so use predetermined type data */
754  const FormData_pg_attribute *sysatt;
755 
757  var = makeVar(nsitem->p_rtindex,
758  attnum,
759  sysatt->atttypid,
760  sysatt->atttypmod,
761  sysatt->attcollation,
762  sublevels_up);
763  }
764  var->location = location;
765 
766  /* Mark Var if it's nulled by any outer joins */
767  markNullableIfNeeded(pstate, var);
768 
769  /* Require read access to the column */
770  markVarForSelectPriv(pstate, var);
771 
772  return (Node *) var;
773 }
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:82
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:67
static int scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, Alias *eref, const char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
ParseExprKind p_expr_kind
Definition: parse_node.h:210
#define TableOidAttributeNumber
Definition: sysattr.h:26

References Alias::aliasname, attnum, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_GENERATED_COLUMN, EXPR_KIND_MERGE_WHEN, FormData_pg_attribute, InvalidAttrNumber, Var::location, makeVar(), markNullableIfNeeded(), markVarForSelectPriv(), ParseState::p_expr_kind, ParseNamespaceItem::p_names, ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_rte, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, ParseNamespaceColumn::p_vartypmod, parser_errposition(), scanRTEForColumn(), SystemAttributeDefinition(), and TableOidAttributeNumber.

Referenced by colNameToVar(), ParseComplexProjection(), and transformColumnRef().

◆ scanRTEForColumn()

static int scanRTEForColumn ( ParseState pstate,
RangeTblEntry rte,
Alias eref,
const char *  colname,
int  location,
int  fuzzy_rte_penalty,
FuzzyAttrMatchState fuzzystate 
)
static

Definition at line 800 of file parse_relation.c.

805 {
806  int result = InvalidAttrNumber;
807  int attnum = 0;
808  ListCell *c;
809 
810  /*
811  * Scan the user column names (or aliases) for a match. Complain if
812  * multiple matches.
813  *
814  * Note: eref->colnames may include entries for dropped columns, but those
815  * will be empty strings that cannot match any legal SQL identifier, so we
816  * don't bother to test for that case here.
817  *
818  * Should this somehow go wrong and we try to access a dropped column,
819  * we'll still catch it by virtue of the check in scanNSItemForColumn().
820  * Callers interested in finding match with shortest distance need to
821  * defend against this directly, though.
822  */
823  foreach(c, eref->colnames)
824  {
825  const char *attcolname = strVal(lfirst(c));
826 
827  attnum++;
828  if (strcmp(attcolname, colname) == 0)
829  {
830  if (result)
831  ereport(ERROR,
832  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
833  errmsg("column reference \"%s\" is ambiguous",
834  colname),
835  parser_errposition(pstate, location)));
836  result = attnum;
837  }
838 
839  /* Update fuzzy match state, if provided. */
840  if (fuzzystate != NULL)
841  updateFuzzyAttrMatchState(fuzzy_rte_penalty, fuzzystate,
842  rte, attcolname, colname, attnum);
843  }
844 
845  /*
846  * If we have a unique match, return it. Note that this allows a user
847  * alias to override a system column name (such as OID) without error.
848  */
849  if (result)
850  return result;
851 
852  /*
853  * If the RTE represents a real relation, consider system column names.
854  * Composites are only used for pseudo-relations like ON CONFLICT's
855  * excluded.
856  */
857  if (rte->rtekind == RTE_RELATION &&
858  rte->relkind != RELKIND_COMPOSITE_TYPE)
859  {
860  /* quick check to see if name could be a system column */
861  attnum = specialAttNum(colname);
862  if (attnum != InvalidAttrNumber)
863  {
864  /* now check to see if column actually is defined */
866  ObjectIdGetDatum(rte->relid),
868  result = attnum;
869  }
870  }
871 
872  return result;
873 }
static void updateFuzzyAttrMatchState(int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate, RangeTblEntry *rte, const char *actual, const char *match, int attnum)
char * c
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:193

References attnum, ATTNUM, Alias::colnames, ereport, errcode(), errmsg(), ERROR, Int16GetDatum(), InvalidAttrNumber, lfirst, ObjectIdGetDatum(), parser_errposition(), RangeTblEntry::relid, RangeTblEntry::relkind, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCacheExists2, specialAttNum(), strVal, and updateFuzzyAttrMatchState().

Referenced by scanNSItemForColumn(), and searchRangeTableForCol().

◆ searchRangeTableForCol()

static FuzzyAttrMatchState* searchRangeTableForCol ( ParseState pstate,
const char *  alias,
const char *  colname,
int  location 
)
static

Definition at line 952 of file parse_relation.c.

954 {
955  ParseState *orig_pstate = pstate;
956  FuzzyAttrMatchState *fuzzystate = palloc(sizeof(FuzzyAttrMatchState));
957 
958  fuzzystate->distance = MAX_FUZZY_DISTANCE + 1;
959  fuzzystate->rfirst = NULL;
960  fuzzystate->rsecond = NULL;
961  fuzzystate->rexact1 = NULL;
962  fuzzystate->rexact2 = NULL;
963 
964  while (pstate != NULL)
965  {
966  ListCell *l;
967 
968  foreach(l, pstate->p_rtable)
969  {
970  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
971  int fuzzy_rte_penalty = 0;
972  int attnum;
973 
974  /*
975  * Typically, it is not useful to look for matches within join
976  * RTEs; they effectively duplicate other RTEs for our purposes,
977  * and if a match is chosen from a join RTE, an unhelpful alias is
978  * displayed in the final diagnostic message.
979  */
980  if (rte->rtekind == RTE_JOIN)
981  continue;
982 
983  /*
984  * If the user didn't specify an alias, then matches against one
985  * RTE are as good as another. But if the user did specify an
986  * alias, then we want at least a fuzzy - and preferably an exact
987  * - match for the range table entry.
988  */
989  if (alias != NULL)
990  fuzzy_rte_penalty =
991  varstr_levenshtein_less_equal(alias, strlen(alias),
992  rte->eref->aliasname,
993  strlen(rte->eref->aliasname),
994  1, 1, 1,
995  MAX_FUZZY_DISTANCE + 1,
996  true);
997 
998  /*
999  * Scan for a matching column, and update fuzzystate. Non-exact
1000  * matches are dealt with inside scanRTEForColumn, but exact
1001  * matches are handled here. (There won't be more than one exact
1002  * match in the same RTE, else we'd have thrown error earlier.)
1003  */
1004  attnum = scanRTEForColumn(orig_pstate, rte, rte->eref,
1005  colname, location,
1006  fuzzy_rte_penalty, fuzzystate);
1007  if (attnum != InvalidAttrNumber && fuzzy_rte_penalty == 0)
1008  {
1009  if (fuzzystate->rexact1 == NULL)
1010  {
1011  fuzzystate->rexact1 = rte;
1012  fuzzystate->exact1 = attnum;
1013  }
1014  else
1015  {
1016  /* Needn't worry about overwriting previous rexact2 */
1017  fuzzystate->rexact2 = rte;
1018  fuzzystate->exact2 = attnum;
1019  }
1020  }
1021  }
1022 
1023  pstate = pstate->parentParseState;
1024  }
1025 
1026  return fuzzystate;
1027 }
#define MAX_FUZZY_DISTANCE
RangeTblEntry * rfirst
RangeTblEntry * rexact1
RangeTblEntry * rexact2
RangeTblEntry * rsecond
int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)

References Alias::aliasname, attnum, FuzzyAttrMatchState::distance, RangeTblEntry::eref, FuzzyAttrMatchState::exact1, FuzzyAttrMatchState::exact2, InvalidAttrNumber, lfirst, MAX_FUZZY_DISTANCE, ParseState::p_rtable, palloc(), ParseState::parentParseState, FuzzyAttrMatchState::rexact1, FuzzyAttrMatchState::rexact2, FuzzyAttrMatchState::rfirst, FuzzyAttrMatchState::rsecond, RTE_JOIN, RangeTblEntry::rtekind, scanRTEForColumn(), and varstr_levenshtein_less_equal().

Referenced by errorMissingColumn().

◆ searchRangeTableForRel()

static RangeTblEntry* searchRangeTableForRel ( ParseState pstate,
RangeVar relation 
)
static

Definition at line 356 of file parse_relation.c.

357 {
358  const char *refname = relation->relname;
359  Oid relId = InvalidOid;
360  CommonTableExpr *cte = NULL;
361  bool isenr = false;
362  Index ctelevelsup = 0;
363  Index levelsup;
364 
365  /*
366  * If it's an unqualified name, check for possible CTE matches. A CTE
367  * hides any real relation matches. If no CTE, look for a matching
368  * relation.
369  *
370  * NB: It's not critical that RangeVarGetRelid return the correct answer
371  * here in the face of concurrent DDL. If it doesn't, the worst case
372  * scenario is a less-clear error message. Also, the tables involved in
373  * the query are already locked, which reduces the number of cases in
374  * which surprising behavior can occur. So we do the name lookup
375  * unlocked.
376  */
377  if (!relation->schemaname)
378  {
379  cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
380  if (!cte)
381  isenr = scanNameSpaceForENR(pstate, refname);
382  }
383 
384  if (!cte && !isenr)
385  relId = RangeVarGetRelid(relation, NoLock, true);
386 
387  /* Now look for RTEs matching either the relation/CTE/ENR or the alias */
388  for (levelsup = 0;
389  pstate != NULL;
390  pstate = pstate->parentParseState, levelsup++)
391  {
392  ListCell *l;
393 
394  foreach(l, pstate->p_rtable)
395  {
396  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
397 
398  if (rte->rtekind == RTE_RELATION &&
399  OidIsValid(relId) &&
400  rte->relid == relId)
401  return rte;
402  if (rte->rtekind == RTE_CTE &&
403  cte != NULL &&
404  rte->ctelevelsup + levelsup == ctelevelsup &&
405  strcmp(rte->ctename, refname) == 0)
406  return rte;
407  if (rte->rtekind == RTE_NAMEDTUPLESTORE &&
408  isenr &&
409  strcmp(rte->enrname, refname) == 0)
410  return rte;
411  if (strcmp(rte->eref->aliasname, refname) == 0)
412  return rte;
413  }
414  }
415  return NULL;
416 }
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
bool scanNameSpaceForENR(ParseState *pstate, const char *refname)

References Alias::aliasname, RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, RangeTblEntry::enrname, RangeTblEntry::eref, InvalidOid, lfirst, NoLock, OidIsValid, ParseState::p_rtable, ParseState::parentParseState, RangeVarGetRelid, RangeTblEntry::relid, RangeVar::relname, RTE_CTE, RTE_NAMEDTUPLESTORE, RTE_RELATION, RangeTblEntry::rtekind, scanNameSpaceForCTE(), scanNameSpaceForENR(), and RangeVar::schemaname.

Referenced by errorMissingRTE().

◆ specialAttNum()

static int specialAttNum ( const char *  attname)
static

Definition at line 3511 of file parse_relation.c.

3512 {
3513  const FormData_pg_attribute *sysatt;
3514 
3515  sysatt = SystemAttributeByName(attname);
3516  if (sysatt != NULL)
3517  return sysatt->attnum;
3518  return InvalidAttrNumber;
3519 }
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:251

References attname, FormData_pg_attribute, InvalidAttrNumber, and SystemAttributeByName().

Referenced by attnameAttNum(), and scanRTEForColumn().

◆ updateFuzzyAttrMatchState()

static void updateFuzzyAttrMatchState ( int  fuzzy_rte_penalty,
FuzzyAttrMatchState fuzzystate,
RangeTblEntry rte,
const char *  actual,
const char *  match,
int  attnum 
)
static

Definition at line 587 of file parse_relation.c.

590 {
591  int columndistance;
592  int matchlen;
593 
594  /* Bail before computing the Levenshtein distance if there's no hope. */
595  if (fuzzy_rte_penalty > fuzzystate->distance)
596  return;
597 
598  /*
599  * Outright reject dropped columns, which can appear here with apparent
600  * empty actual names, per remarks within scanRTEForColumn().
601  */
602  if (actual[0] == '\0')
603  return;
604 
605  /* Use Levenshtein to compute match distance. */
606  matchlen = strlen(match);
607  columndistance =
608  varstr_levenshtein_less_equal(actual, strlen(actual), match, matchlen,
609  1, 1, 1,
610  fuzzystate->distance + 1
611  - fuzzy_rte_penalty,
612  true);
613 
614  /*
615  * If more than half the characters are different, don't treat it as a
616  * match, to avoid making ridiculous suggestions.
617  */
618  if (columndistance > matchlen / 2)
619  return;
620 
621  /*
622  * From this point on, we can ignore the distinction between the RTE-name
623  * distance and the column-name distance.
624  */
625  columndistance += fuzzy_rte_penalty;
626 
627  /*
628  * If the new distance is less than or equal to that of the best match
629  * found so far, update fuzzystate.
630  */
631  if (columndistance < fuzzystate->distance)
632  {
633  /* Store new lowest observed distance as first/only match */
634  fuzzystate->distance = columndistance;
635  fuzzystate->rfirst = rte;
636  fuzzystate->first = attnum;
637  fuzzystate->rsecond = NULL;
638  }
639  else if (columndistance == fuzzystate->distance)
640  {
641  /* If we already have a match of this distance, update state */
642  if (fuzzystate->rsecond != NULL)
643  {
644  /*
645  * Too many matches at same distance. Clearly, this value of
646  * distance is too low a bar, so drop these entries while keeping
647  * the current distance value, so that only smaller distances will
648  * be considered interesting. Only if we find something of lower
649  * distance will we re-populate rfirst (via the stanza above).
650  */
651  fuzzystate->rfirst = NULL;
652  fuzzystate->rsecond = NULL;
653  }
654  else if (fuzzystate->rfirst != NULL)
655  {
656  /* Record as provisional second match */
657  fuzzystate->rsecond = rte;
658  fuzzystate->second = attnum;
659  }
660  else
661  {
662  /*
663  * Do nothing. When rfirst is NULL, distance is more than what we
664  * want to consider acceptable, so we should ignore this match.
665  */
666  }
667  }
668 }

References attnum, FuzzyAttrMatchState::distance, FuzzyAttrMatchState::first, FuzzyAttrMatchState::rfirst, FuzzyAttrMatchState::rsecond, FuzzyAttrMatchState::second, and varstr_levenshtein_less_equal().

Referenced by scanRTEForColumn().