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