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. This
1741  * can be a bit confusing, so we expend some effort on delivering a
1742  * relevant error message.
1743  */
1744  if (coldeflist != NIL)
1745  {
1746  switch (functypclass)
1747  {
1748  case TYPEFUNC_RECORD:
1749  /* ok */
1750  break;
1751  case TYPEFUNC_COMPOSITE:
1753 
1754  /*
1755  * If the function's raw result type is RECORD, we must
1756  * have resolved it using its OUT parameters. Otherwise,
1757  * it must have a named composite type.
1758  */
1759  if (exprType(funcexpr) == RECORDOID)
1760  ereport(ERROR,
1761  (errcode(ERRCODE_SYNTAX_ERROR),
1762  errmsg("a column definition list is redundant for a function with OUT parameters"),
1763  parser_errposition(pstate,
1764  exprLocation((Node *) coldeflist))));
1765  else
1766  ereport(ERROR,
1767  (errcode(ERRCODE_SYNTAX_ERROR),
1768  errmsg("a column definition list is redundant for a function returning a named composite type"),
1769  parser_errposition(pstate,
1770  exprLocation((Node *) coldeflist))));
1771  break;
1772  default:
1773  ereport(ERROR,
1774  (errcode(ERRCODE_SYNTAX_ERROR),
1775  errmsg("a column definition list is only allowed for functions returning \"record\""),
1776  parser_errposition(pstate,
1777  exprLocation((Node *) coldeflist))));
1778  break;
1779  }
1780  }
1781  else
1782  {
1783  if (functypclass == TYPEFUNC_RECORD)
1784  ereport(ERROR,
1785  (errcode(ERRCODE_SYNTAX_ERROR),
1786  errmsg("a column definition list is required for functions returning \"record\""),
1787  parser_errposition(pstate, exprLocation(funcexpr))));
1788  }
1789 
1790  if (functypclass == TYPEFUNC_COMPOSITE ||
1791  functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
1792  {
1793  /* Composite data type, e.g. a table's row type */
1794  Assert(tupdesc);
1795  }
1796  else if (functypclass == TYPEFUNC_SCALAR)
1797  {
1798  /* Base data type, i.e. scalar */
1799  tupdesc = CreateTemplateTupleDesc(1);
1800  TupleDescInitEntry(tupdesc,
1801  (AttrNumber) 1,
1802  chooseScalarFunctionAlias(funcexpr, funcname,
1803  alias, nfuncs),
1804  funcrettype,
1805  exprTypmod(funcexpr),
1806  0);
1808  (AttrNumber) 1,
1809  exprCollation(funcexpr));
1810  }
1811  else if (functypclass == TYPEFUNC_RECORD)
1812  {
1813  ListCell *col;
1814 
1815  /*
1816  * Use the column definition list to construct a tupdesc and fill
1817  * in the RangeTblFunction's lists.
1818  */
1819  tupdesc = CreateTemplateTupleDesc(list_length(coldeflist));
1820  i = 1;
1821  foreach(col, coldeflist)
1822  {
1823  ColumnDef *n = (ColumnDef *) lfirst(col);
1824  char *attrname;
1825  Oid attrtype;
1826  int32 attrtypmod;
1827  Oid attrcollation;
1828 
1829  attrname = n->colname;
1830  if (n->typeName->setof)
1831  ereport(ERROR,
1832  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1833  errmsg("column \"%s\" cannot be declared SETOF",
1834  attrname),
1835  parser_errposition(pstate, n->location)));
1836  typenameTypeIdAndMod(pstate, n->typeName,
1837  &attrtype, &attrtypmod);
1838  attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1839  TupleDescInitEntry(tupdesc,
1840  (AttrNumber) i,
1841  attrname,
1842  attrtype,
1843  attrtypmod,
1844  0);
1846  (AttrNumber) i,
1847  attrcollation);
1848  rtfunc->funccolnames = lappend(rtfunc->funccolnames,
1849  makeString(pstrdup(attrname)));
1850  rtfunc->funccoltypes = lappend_oid(rtfunc->funccoltypes,
1851  attrtype);
1852  rtfunc->funccoltypmods = lappend_int(rtfunc->funccoltypmods,
1853  attrtypmod);
1855  attrcollation);
1856 
1857  i++;
1858  }
1859 
1860  /*
1861  * Ensure that the coldeflist defines a legal set of names (no
1862  * duplicates, but we needn't worry about system column names) and
1863  * datatypes. Although we mostly can't allow pseudo-types, it
1864  * seems safe to allow RECORD and RECORD[], since values within
1865  * those type classes are self-identifying at runtime, and the
1866  * coldeflist doesn't represent anything that will be visible to
1867  * other sessions.
1868  */
1869  CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE,
1871  }
1872  else
1873  ereport(ERROR,
1874  (errcode(ERRCODE_DATATYPE_MISMATCH),
1875  errmsg("function \"%s\" in FROM has unsupported return type %s",
1876  funcname, format_type_be(funcrettype)),
1877  parser_errposition(pstate, exprLocation(funcexpr))));
1878 
1879  /* Finish off the RangeTblFunction and add it to the RTE's list */
1880  rtfunc->funccolcount = tupdesc->natts;
1881  rte->functions = lappend(rte->functions, rtfunc);
1882 
1883  /* Save the tupdesc for use below */
1884  functupdescs[funcno] = tupdesc;
1885  totalatts += tupdesc->natts;
1886  funcno++;
1887  }
1888 
1889  /*
1890  * If there's more than one function, or we want an ordinality column, we
1891  * have to produce a merged tupdesc.
1892  */
1893  if (nfuncs > 1 || rangefunc->ordinality)
1894  {
1895  if (rangefunc->ordinality)
1896  totalatts++;
1897 
1898  /* Merge the tuple descs of each function into a composite one */
1899  tupdesc = CreateTemplateTupleDesc(totalatts);
1900  natts = 0;
1901  for (i = 0; i < nfuncs; i++)
1902  {
1903  for (j = 1; j <= functupdescs[i]->natts; j++)
1904  TupleDescCopyEntry(tupdesc, ++natts, functupdescs[i], j);
1905  }
1906 
1907  /* Add the ordinality column if needed */
1908  if (rangefunc->ordinality)
1909  {
1910  TupleDescInitEntry(tupdesc,
1911  (AttrNumber) ++natts,
1912  "ordinality",
1913  INT8OID,
1914  -1,
1915  0);
1916  /* no need to set collation */
1917  }
1918 
1919  Assert(natts == totalatts);
1920  }
1921  else
1922  {
1923  /* We can just use the single function's tupdesc as-is */
1924  tupdesc = functupdescs[0];
1925  }
1926 
1927  /* Use the tupdesc while assigning column aliases for the RTE */
1928  buildRelationAliases(tupdesc, alias, eref);
1929 
1930  /*
1931  * Set flags and access permissions.
1932  *
1933  * Functions are never checked for access rights (at least, not by the RTE
1934  * permissions mechanism).
1935  */
1936  rte->lateral = lateral;
1937  rte->inh = false; /* never true for functions */
1938  rte->inFromCl = inFromCl;
1939 
1940  rte->requiredPerms = 0;
1941  rte->checkAsUser = InvalidOid;
1942  rte->selectedCols = NULL;
1943  rte->insertedCols = NULL;
1944  rte->updatedCols = NULL;
1945  rte->extraUpdatedCols = NULL;
1946 
1947  /*
1948  * Add completed RTE to pstate's range table list, so that we know its
1949  * index. But we don't add it to the join list --- caller must do that if
1950  * appropriate.
1951  */
1952  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1953 
1954  /*
1955  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
1956  * list --- caller must do that if appropriate.
1957  */
1958  return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
1959  tupdesc);
1960 }
1961 
1962 /*
1963  * Add an entry for a table function to the pstate's range table (p_rtable).
1964  * Then, construct and return a ParseNamespaceItem for the new RTE.
1965  *
1966  * This is much like addRangeTableEntry() except that it makes a tablefunc RTE.
1967  */
1970  TableFunc *tf,
1971  Alias *alias,
1972  bool lateral,
1973  bool inFromCl)
1974 {
1976  char *refname = alias ? alias->aliasname : pstrdup("xmltable");
1977  Alias *eref;
1978  int numaliases;
1979 
1980  Assert(pstate != NULL);
1981 
1982  rte->rtekind = RTE_TABLEFUNC;
1983  rte->relid = InvalidOid;
1984  rte->subquery = NULL;
1985  rte->tablefunc = tf;
1986  rte->coltypes = tf->coltypes;
1987  rte->coltypmods = tf->coltypmods;
1988  rte->colcollations = tf->colcollations;
1989  rte->alias = alias;
1990 
1991  eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1992  numaliases = list_length(eref->colnames);
1993 
1994  /* fill in any unspecified alias columns */
1995  if (numaliases < list_length(tf->colnames))
1996  eref->colnames = list_concat(eref->colnames,
1997  list_copy_tail(tf->colnames, numaliases));
1998 
1999  rte->eref = eref;
2000 
2001  /*
2002  * Set flags and access permissions.
2003  *
2004  * Tablefuncs are never checked for access rights (at least, not by the
2005  * RTE permissions mechanism).
2006  */
2007  rte->lateral = lateral;
2008  rte->inh = false; /* never true for tablefunc RTEs */
2009  rte->inFromCl = inFromCl;
2010 
2011  rte->requiredPerms = 0;
2012  rte->checkAsUser = InvalidOid;
2013  rte->selectedCols = NULL;
2014  rte->insertedCols = NULL;
2015  rte->updatedCols = NULL;
2016  rte->extraUpdatedCols = NULL;
2017 
2018  /*
2019  * Add completed RTE to pstate's range table list, so that we know its
2020  * index. But we don't add it to the join list --- caller must do that if
2021  * appropriate.
2022  */
2023  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2024 
2025  /*
2026  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2027  * list --- caller must do that if appropriate.
2028  */
2029  return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2030  rte->coltypes, rte->coltypmods,
2031  rte->colcollations);
2032 }
2033 
2034 /*
2035  * Add an entry for a VALUES list to the pstate's range table (p_rtable).
2036  * Then, construct and return a ParseNamespaceItem for the new RTE.
2037  *
2038  * This is much like addRangeTableEntry() except that it makes a values RTE.
2039  */
2042  List *exprs,
2043  List *coltypes,
2044  List *coltypmods,
2045  List *colcollations,
2046  Alias *alias,
2047  bool lateral,
2048  bool inFromCl)
2049 {
2051  char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
2052  Alias *eref;
2053  int numaliases;
2054  int numcolumns;
2055 
2056  Assert(pstate != NULL);
2057 
2058  rte->rtekind = RTE_VALUES;
2059  rte->relid = InvalidOid;
2060  rte->subquery = NULL;
2061  rte->values_lists = exprs;
2062  rte->coltypes = coltypes;
2063  rte->coltypmods = coltypmods;
2064  rte->colcollations = colcollations;
2065  rte->alias = alias;
2066 
2067  eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
2068 
2069  /* fill in any unspecified alias columns */
2070  numcolumns = list_length((List *) linitial(exprs));
2071  numaliases = list_length(eref->colnames);
2072  while (numaliases < numcolumns)
2073  {
2074  char attrname[64];
2075 
2076  numaliases++;
2077  snprintf(attrname, sizeof(attrname), "column%d", numaliases);
2078  eref->colnames = lappend(eref->colnames,
2079  makeString(pstrdup(attrname)));
2080  }
2081  if (numcolumns < numaliases)
2082  ereport(ERROR,
2083  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2084  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
2085  refname, numcolumns, numaliases)));
2086 
2087  rte->eref = eref;
2088 
2089  /*
2090  * Set flags and access permissions.
2091  *
2092  * Subqueries are never checked for access rights.
2093  */
2094  rte->lateral = lateral;
2095  rte->inh = false; /* never true for values RTEs */
2096  rte->inFromCl = inFromCl;
2097 
2098  rte->requiredPerms = 0;
2099  rte->checkAsUser = InvalidOid;
2100  rte->selectedCols = NULL;
2101  rte->insertedCols = NULL;
2102  rte->updatedCols = NULL;
2103  rte->extraUpdatedCols = NULL;
2104 
2105  /*
2106  * Add completed RTE to pstate's range table list, so that we know its
2107  * index. But we don't add it to the join list --- caller must do that if
2108  * appropriate.
2109  */
2110  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2111 
2112  /*
2113  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2114  * list --- caller must do that if appropriate.
2115  */
2116  return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2117  rte->coltypes, rte->coltypmods,
2118  rte->colcollations);
2119 }
2120 
2121 /*
2122  * Add an entry for a join to the pstate's range table (p_rtable).
2123  * Then, construct and return a ParseNamespaceItem for the new RTE.
2124  *
2125  * This is much like addRangeTableEntry() except that it makes a join RTE.
2126  * Also, it's more convenient for the caller to construct the
2127  * ParseNamespaceColumn array, so we pass that in.
2128  */
2131  List *colnames,
2132  ParseNamespaceColumn *nscolumns,
2133  JoinType jointype,
2134  int nummergedcols,
2135  List *aliasvars,
2136  List *leftcols,
2137  List *rightcols,
2138  Alias *alias,
2139  bool inFromCl)
2140 {
2142  Alias *eref;
2143  int numaliases;
2144  ParseNamespaceItem *nsitem;
2145 
2146  Assert(pstate != NULL);
2147 
2148  /*
2149  * Fail if join has too many columns --- we must be able to reference any
2150  * of the columns with an AttrNumber.
2151  */
2152  if (list_length(aliasvars) > MaxAttrNumber)
2153  ereport(ERROR,
2154  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2155  errmsg("joins can have at most %d columns",
2156  MaxAttrNumber)));
2157 
2158  rte->rtekind = RTE_JOIN;
2159  rte->relid = InvalidOid;
2160  rte->subquery = NULL;
2161  rte->jointype = jointype;
2162  rte->joinmergedcols = nummergedcols;
2163  rte->joinaliasvars = aliasvars;
2164  rte->joinleftcols = leftcols;
2165  rte->joinrightcols = rightcols;
2166  rte->alias = alias;
2167 
2168  eref = alias ? copyObject(alias) : makeAlias("unnamed_join", NIL);
2169  numaliases = list_length(eref->colnames);
2170 
2171  /* fill in any unspecified alias columns */
2172  if (numaliases < list_length(colnames))
2173  eref->colnames = list_concat(eref->colnames,
2174  list_copy_tail(colnames, numaliases));
2175 
2176  rte->eref = eref;
2177 
2178  /*
2179  * Set flags and access permissions.
2180  *
2181  * Joins are never checked for access rights.
2182  */
2183  rte->lateral = false;
2184  rte->inh = false; /* never true for joins */
2185  rte->inFromCl = inFromCl;
2186 
2187  rte->requiredPerms = 0;
2188  rte->checkAsUser = InvalidOid;
2189  rte->selectedCols = NULL;
2190  rte->insertedCols = NULL;
2191  rte->updatedCols = NULL;
2192  rte->extraUpdatedCols = NULL;
2193 
2194  /*
2195  * Add completed RTE to pstate's range table list, so that we know its
2196  * index. But we don't add it to the join list --- caller must do that if
2197  * appropriate.
2198  */
2199  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2200 
2201  /*
2202  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2203  * list --- caller must do that if appropriate.
2204  */
2205  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
2206  nsitem->p_rte = rte;
2207  nsitem->p_rtindex = list_length(pstate->p_rtable);
2208  nsitem->p_nscolumns = nscolumns;
2209  /* set default visibility flags; might get changed later */
2210  nsitem->p_rel_visible = true;
2211  nsitem->p_cols_visible = true;
2212  nsitem->p_lateral_only = false;
2213  nsitem->p_lateral_ok = true;
2214 
2215  return nsitem;
2216 }
2217 
2218 /*
2219  * Add an entry for a CTE reference to the pstate's range table (p_rtable).
2220  * Then, construct and return a ParseNamespaceItem for the new RTE.
2221  *
2222  * This is much like addRangeTableEntry() except that it makes a CTE RTE.
2223  */
2226  CommonTableExpr *cte,
2227  Index levelsup,
2228  RangeVar *rv,
2229  bool inFromCl)
2230 {
2232  Alias *alias = rv->alias;
2233  char *refname = alias ? alias->aliasname : cte->ctename;
2234  Alias *eref;
2235  int numaliases;
2236  int varattno;
2237  ListCell *lc;
2238 
2239  Assert(pstate != NULL);
2240 
2241  rte->rtekind = RTE_CTE;
2242  rte->ctename = cte->ctename;
2243  rte->ctelevelsup = levelsup;
2244 
2245  /* Self-reference if and only if CTE's parse analysis isn't completed */
2246  rte->self_reference = !IsA(cte->ctequery, Query);
2247  Assert(cte->cterecursive || !rte->self_reference);
2248  /* Bump the CTE's refcount if this isn't a self-reference */
2249  if (!rte->self_reference)
2250  cte->cterefcount++;
2251 
2252  /*
2253  * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
2254  * This won't get checked in case of a self-reference, but that's OK
2255  * because data-modifying CTEs aren't allowed to be recursive anyhow.
2256  */
2257  if (IsA(cte->ctequery, Query))
2258  {
2259  Query *ctequery = (Query *) cte->ctequery;
2260 
2261  if (ctequery->commandType != CMD_SELECT &&
2262  ctequery->returningList == NIL)
2263  ereport(ERROR,
2264  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2265  errmsg("WITH query \"%s\" does not have a RETURNING clause",
2266  cte->ctename),
2267  parser_errposition(pstate, rv->location)));
2268  }
2269 
2270  rte->coltypes = cte->ctecoltypes;
2271  rte->coltypmods = cte->ctecoltypmods;
2272  rte->colcollations = cte->ctecolcollations;
2273 
2274  rte->alias = alias;
2275  if (alias)
2276  eref = copyObject(alias);
2277  else
2278  eref = makeAlias(refname, NIL);
2279  numaliases = list_length(eref->colnames);
2280 
2281  /* fill in any unspecified alias columns */
2282  varattno = 0;
2283  foreach(lc, cte->ctecolnames)
2284  {
2285  varattno++;
2286  if (varattno > numaliases)
2287  eref->colnames = lappend(eref->colnames, lfirst(lc));
2288  }
2289  if (varattno < numaliases)
2290  ereport(ERROR,
2291  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2292  errmsg("table \"%s\" has %d columns available but %d columns specified",
2293  refname, varattno, numaliases)));
2294 
2295  rte->eref = eref;
2296 
2297  /*
2298  * Set flags and access permissions.
2299  *
2300  * Subqueries are never checked for access rights.
2301  */
2302  rte->lateral = false;
2303  rte->inh = false; /* never true for subqueries */
2304  rte->inFromCl = inFromCl;
2305 
2306  rte->requiredPerms = 0;
2307  rte->checkAsUser = InvalidOid;
2308  rte->selectedCols = NULL;
2309  rte->insertedCols = NULL;
2310  rte->updatedCols = NULL;
2311  rte->extraUpdatedCols = NULL;
2312 
2313  /*
2314  * Add completed RTE to pstate's range table list, so that we know its
2315  * index. But we don't add it to the join list --- caller must do that if
2316  * appropriate.
2317  */
2318  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2319 
2320  /*
2321  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2322  * list --- caller must do that if appropriate.
2323  */
2324  return buildNSItemFromLists(rte, list_length(pstate->p_rtable),
2325  rte->coltypes, rte->coltypmods,
2326  rte->colcollations);
2327 }
2328 
2329 /*
2330  * Add an entry for an ephemeral named relation reference to the pstate's
2331  * range table (p_rtable).
2332  * Then, construct and return a ParseNamespaceItem for the new RTE.
2333  *
2334  * It is expected that the RangeVar, which up until now is only known to be an
2335  * ephemeral named relation, will (in conjunction with the QueryEnvironment in
2336  * the ParseState), create a RangeTblEntry for a specific *kind* of ephemeral
2337  * named relation, based on enrtype.
2338  *
2339  * This is much like addRangeTableEntry() except that it makes an RTE for an
2340  * ephemeral named relation.
2341  */
2344  RangeVar *rv,
2345  bool inFromCl)
2346 {
2348  Alias *alias = rv->alias;
2349  char *refname = alias ? alias->aliasname : rv->relname;
2351  TupleDesc tupdesc;
2352  int attno;
2353 
2354  Assert(pstate != NULL);
2355  enrmd = get_visible_ENR(pstate, rv->relname);
2356  Assert(enrmd != NULL);
2357 
2358  switch (enrmd->enrtype)
2359  {
2360  case ENR_NAMED_TUPLESTORE:
2362  break;
2363 
2364  default:
2365  elog(ERROR, "unexpected enrtype: %d", enrmd->enrtype);
2366  return NULL; /* for fussy compilers */
2367  }
2368 
2369  /*
2370  * Record dependency on a relation. This allows plans to be invalidated
2371  * if they access transition tables linked to a table that is altered.
2372  */
2373  rte->relid = enrmd->reliddesc;
2374 
2375  /*
2376  * Build the list of effective column names using user-supplied aliases
2377  * and/or actual column names.
2378  */
2379  tupdesc = ENRMetadataGetTupDesc(enrmd);
2380  rte->eref = makeAlias(refname, NIL);
2381  buildRelationAliases(tupdesc, alias, rte->eref);
2382 
2383  /* Record additional data for ENR, including column type info */
2384  rte->enrname = enrmd->name;
2385  rte->enrtuples = enrmd->enrtuples;
2386  rte->coltypes = NIL;
2387  rte->coltypmods = NIL;
2388  rte->colcollations = NIL;
2389  for (attno = 1; attno <= tupdesc->natts; ++attno)
2390  {
2391  Form_pg_attribute att = TupleDescAttr(tupdesc, attno - 1);
2392 
2393  if (att->attisdropped)
2394  {
2395  /* Record zeroes for a dropped column */
2396  rte->coltypes = lappend_oid(rte->coltypes, InvalidOid);
2397  rte->coltypmods = lappend_int(rte->coltypmods, 0);
2399  }
2400  else
2401  {
2402  /* Let's just make sure we can tell this isn't dropped */
2403  if (att->atttypid == InvalidOid)
2404  elog(ERROR, "atttypid is invalid for non-dropped column in \"%s\"",
2405  rv->relname);
2406  rte->coltypes = lappend_oid(rte->coltypes, att->atttypid);
2407  rte->coltypmods = lappend_int(rte->coltypmods, att->atttypmod);
2409  att->attcollation);
2410  }
2411  }
2412 
2413  /*
2414  * Set flags and access permissions.
2415  *
2416  * ENRs are never checked for access rights.
2417  */
2418  rte->lateral = false;
2419  rte->inh = false; /* never true for ENRs */
2420  rte->inFromCl = inFromCl;
2421 
2422  rte->requiredPerms = 0;
2423  rte->checkAsUser = InvalidOid;
2424  rte->selectedCols = NULL;
2425 
2426  /*
2427  * Add completed RTE to pstate's range table list, so that we know its
2428  * index. But we don't add it to the join list --- caller must do that if
2429  * appropriate.
2430  */
2431  pstate->p_rtable = lappend(pstate->p_rtable, rte);
2432 
2433  /*
2434  * Build a ParseNamespaceItem, but don't add it to the pstate's namespace
2435  * list --- caller must do that if appropriate.
2436  */
2437  return buildNSItemFromTupleDesc(rte, list_length(pstate->p_rtable),
2438  tupdesc);
2439 }
2440 
2441 
2442 /*
2443  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
2444  *
2445  * This is used when we have not yet done transformLockingClause, but need
2446  * to know the correct lock to take during initial opening of relations.
2447  *
2448  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
2449  * since the table-level lock is the same either way.
2450  */
2451 bool
2452 isLockedRefname(ParseState *pstate, const char *refname)
2453 {
2454  ListCell *l;
2455 
2456  /*
2457  * If we are in a subquery specified as locked FOR UPDATE/SHARE from
2458  * parent level, then act as though there's a generic FOR UPDATE here.
2459  */
2460  if (pstate->p_locked_from_parent)
2461  return true;
2462 
2463  foreach(l, pstate->p_locking_clause)
2464  {
2465  LockingClause *lc = (LockingClause *) lfirst(l);
2466 
2467  if (lc->lockedRels == NIL)
2468  {
2469  /* all tables used in query */
2470  return true;
2471  }
2472  else
2473  {
2474  /* just the named tables */
2475  ListCell *l2;
2476 
2477  foreach(l2, lc->lockedRels)
2478  {
2479  RangeVar *thisrel = (RangeVar *) lfirst(l2);
2480 
2481  if (strcmp(refname, thisrel->relname) == 0)
2482  return true;
2483  }
2484  }
2485  }
2486  return false;
2487 }
2488 
2489 /*
2490  * Add the given nsitem/RTE as a top-level entry in the pstate's join list
2491  * and/or namespace list. (We assume caller has checked for any
2492  * namespace conflicts.) The nsitem is always marked as unconditionally
2493  * visible, that is, not LATERAL-only.
2494  */
2495 void
2497  bool addToJoinList,
2498  bool addToRelNameSpace, bool addToVarNameSpace)
2499 {
2500  if (addToJoinList)
2501  {
2503 
2504  rtr->rtindex = nsitem->p_rtindex;
2505  pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2506  }
2507  if (addToRelNameSpace || addToVarNameSpace)
2508  {
2509  /* Set the new nsitem's visibility flags correctly */
2510  nsitem->p_rel_visible = addToRelNameSpace;
2511  nsitem->p_cols_visible = addToVarNameSpace;
2512  nsitem->p_lateral_only = false;
2513  nsitem->p_lateral_ok = true;
2514  pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
2515  }
2516 }
2517 
2518 /*
2519  * expandRTE -- expand the columns of a rangetable entry
2520  *
2521  * This creates lists of an RTE's column names (aliases if provided, else
2522  * real names) and Vars for each column. Only user columns are considered.
2523  * If include_dropped is false then dropped columns are omitted from the
2524  * results. If include_dropped is true then empty strings and NULL constants
2525  * (not Vars!) are returned for dropped columns.
2526  *
2527  * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
2528  * values to use in the created Vars. Ordinarily rtindex should match the
2529  * actual position of the RTE in its rangetable.
2530  *
2531  * The output lists go into *colnames and *colvars.
2532  * If only one of the two kinds of output list is needed, pass NULL for the
2533  * output pointer for the unwanted one.
2534  */
2535 void
2536 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
2537  int location, bool include_dropped,
2538  List **colnames, List **colvars)
2539 {
2540  int varattno;
2541 
2542  if (colnames)
2543  *colnames = NIL;
2544  if (colvars)
2545  *colvars = NIL;
2546 
2547  switch (rte->rtekind)
2548  {
2549  case RTE_RELATION:
2550  /* Ordinary relation RTE */
2551  expandRelation(rte->relid, rte->eref,
2552  rtindex, sublevels_up, location,
2553  include_dropped, colnames, colvars);
2554  break;
2555  case RTE_SUBQUERY:
2556  {
2557  /* Subquery RTE */
2558  ListCell *aliasp_item = list_head(rte->eref->colnames);
2559  ListCell *tlistitem;
2560 
2561  varattno = 0;
2562  foreach(tlistitem, rte->subquery->targetList)
2563  {
2564  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
2565 
2566  if (te->resjunk)
2567  continue;
2568  varattno++;
2569  Assert(varattno == te->resno);
2570 
2571  /*
2572  * In scenarios where columns have been added to a view
2573  * since the outer query was originally parsed, there can
2574  * be more items in the subquery tlist than the outer
2575  * query expects. We should ignore such extra column(s)
2576  * --- compare the behavior for composite-returning
2577  * functions, in the RTE_FUNCTION case below.
2578  */
2579  if (!aliasp_item)
2580  break;
2581 
2582  if (colnames)
2583  {
2584  char *label = strVal(lfirst(aliasp_item));
2585 
2586  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2587  }
2588 
2589  if (colvars)
2590  {
2591  Var *varnode;
2592 
2593  varnode = makeVar(rtindex, varattno,
2594  exprType((Node *) te->expr),
2595  exprTypmod((Node *) te->expr),
2596  exprCollation((Node *) te->expr),
2597  sublevels_up);
2598  varnode->location = location;
2599 
2600  *colvars = lappend(*colvars, varnode);
2601  }
2602 
2603  aliasp_item = lnext(rte->eref->colnames, aliasp_item);
2604  }
2605  }
2606  break;
2607  case RTE_FUNCTION:
2608  {
2609  /* Function RTE */
2610  int atts_done = 0;
2611  ListCell *lc;
2612 
2613  foreach(lc, rte->functions)
2614  {
2615  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2616  TypeFuncClass functypclass;
2617  Oid funcrettype;
2618  TupleDesc tupdesc;
2619 
2620  functypclass = get_expr_result_type(rtfunc->funcexpr,
2621  &funcrettype,
2622  &tupdesc);
2623  if (functypclass == TYPEFUNC_COMPOSITE ||
2624  functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
2625  {
2626  /* Composite data type, e.g. a table's row type */
2627  Assert(tupdesc);
2628  expandTupleDesc(tupdesc, rte->eref,
2629  rtfunc->funccolcount, atts_done,
2630  rtindex, sublevels_up, location,
2631  include_dropped, colnames, colvars);
2632  }
2633  else if (functypclass == TYPEFUNC_SCALAR)
2634  {
2635  /* Base data type, i.e. scalar */
2636  if (colnames)
2637  *colnames = lappend(*colnames,
2638  list_nth(rte->eref->colnames,
2639  atts_done));
2640 
2641  if (colvars)
2642  {
2643  Var *varnode;
2644 
2645  varnode = makeVar(rtindex, atts_done + 1,
2646  funcrettype,
2647  exprTypmod(rtfunc->funcexpr),
2648  exprCollation(rtfunc->funcexpr),
2649  sublevels_up);
2650  varnode->location = location;
2651 
2652  *colvars = lappend(*colvars, varnode);
2653  }
2654  }
2655  else if (functypclass == TYPEFUNC_RECORD)
2656  {
2657  if (colnames)
2658  {
2659  List *namelist;
2660 
2661  /* extract appropriate subset of column list */
2662  namelist = list_copy_tail(rte->eref->colnames,
2663  atts_done);
2664  namelist = list_truncate(namelist,
2665  rtfunc->funccolcount);
2666  *colnames = list_concat(*colnames, namelist);
2667  }
2668 
2669  if (colvars)
2670  {
2671  ListCell *l1;
2672  ListCell *l2;
2673  ListCell *l3;
2674  int attnum = atts_done;
2675 
2676  forthree(l1, rtfunc->funccoltypes,
2677  l2, rtfunc->funccoltypmods,
2678  l3, rtfunc->funccolcollations)
2679  {
2680  Oid attrtype = lfirst_oid(l1);
2681  int32 attrtypmod = lfirst_int(l2);
2682  Oid attrcollation = lfirst_oid(l3);
2683  Var *varnode;
2684 
2685  attnum++;
2686  varnode = makeVar(rtindex,
2687  attnum,
2688  attrtype,
2689  attrtypmod,
2690  attrcollation,
2691  sublevels_up);
2692  varnode->location = location;
2693  *colvars = lappend(*colvars, varnode);
2694  }
2695  }
2696  }
2697  else
2698  {
2699  /* addRangeTableEntryForFunction should've caught this */
2700  elog(ERROR, "function in FROM has unsupported return type");
2701  }
2702  atts_done += rtfunc->funccolcount;
2703  }
2704 
2705  /* Append the ordinality column if any */
2706  if (rte->funcordinality)
2707  {
2708  if (colnames)
2709  *colnames = lappend(*colnames,
2710  llast(rte->eref->colnames));
2711 
2712  if (colvars)
2713  {
2714  Var *varnode = makeVar(rtindex,
2715  atts_done + 1,
2716  INT8OID,
2717  -1,
2718  InvalidOid,
2719  sublevels_up);
2720 
2721  *colvars = lappend(*colvars, varnode);
2722  }
2723  }
2724  }
2725  break;
2726  case RTE_JOIN:
2727  {
2728  /* Join RTE */
2729  ListCell *colname;
2730  ListCell *aliasvar;
2731 
2733 
2734  varattno = 0;
2735  forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
2736  {
2737  Node *avar = (Node *) lfirst(aliasvar);
2738 
2739  varattno++;
2740 
2741  /*
2742  * During ordinary parsing, there will never be any
2743  * deleted columns in the join. While this function is
2744  * also used by the rewriter and planner, they do not
2745  * currently call it on any JOIN RTEs. Therefore, this
2746  * next bit is dead code, but it seems prudent to handle
2747  * the case correctly anyway.
2748  */
2749  if (avar == NULL)
2750  {
2751  if (include_dropped)
2752  {
2753  if (colnames)
2754  *colnames = lappend(*colnames,
2755  makeString(pstrdup("")));
2756  if (colvars)
2757  {
2758  /*
2759  * Can't use join's column type here (it might
2760  * be dropped!); but it doesn't really matter
2761  * what type the Const claims to be.
2762  */
2763  *colvars = lappend(*colvars,
2764  makeNullConst(INT4OID, -1,
2765  InvalidOid));
2766  }
2767  }
2768  continue;
2769  }
2770 
2771  if (colnames)
2772  {
2773  char *label = strVal(lfirst(colname));
2774 
2775  *colnames = lappend(*colnames,
2776  makeString(pstrdup(label)));
2777  }
2778 
2779  if (colvars)
2780  {
2781  Var *varnode;
2782 
2783  /*
2784  * If the joinaliasvars entry is a simple Var, just
2785  * copy it (with adjustment of varlevelsup and
2786  * location); otherwise it is a JOIN USING column and
2787  * we must generate a join alias Var. This matches
2788  * the results that expansion of "join.*" by
2789  * expandNSItemVars would have produced, if we had
2790  * access to the ParseNamespaceItem for the join.
2791  */
2792  if (IsA(avar, Var))
2793  {
2794  varnode = copyObject((Var *) avar);
2795  varnode->varlevelsup = sublevels_up;
2796  }
2797  else
2798  varnode = makeVar(rtindex, varattno,
2799  exprType(avar),
2800  exprTypmod(avar),
2801  exprCollation(avar),
2802  sublevels_up);
2803  varnode->location = location;
2804 
2805  *colvars = lappend(*colvars, varnode);
2806  }
2807  }
2808  }
2809  break;
2810  case RTE_TABLEFUNC:
2811  case RTE_VALUES:
2812  case RTE_CTE:
2813  case RTE_NAMEDTUPLESTORE:
2814  {
2815  /* Tablefunc, Values, CTE, or ENR RTE */
2816  ListCell *aliasp_item = list_head(rte->eref->colnames);
2817  ListCell *lct;
2818  ListCell *lcm;
2819  ListCell *lcc;
2820 
2821  varattno = 0;
2822  forthree(lct, rte->coltypes,
2823  lcm, rte->coltypmods,
2824  lcc, rte->colcollations)
2825  {
2826  Oid coltype = lfirst_oid(lct);
2827  int32 coltypmod = lfirst_int(lcm);
2828  Oid colcoll = lfirst_oid(lcc);
2829 
2830  varattno++;
2831 
2832  if (colnames)
2833  {
2834  /* Assume there is one alias per output column */
2835  if (OidIsValid(coltype))
2836  {
2837  char *label = strVal(lfirst(aliasp_item));
2838 
2839  *colnames = lappend(*colnames,
2840  makeString(pstrdup(label)));
2841  }
2842  else if (include_dropped)
2843  *colnames = lappend(*colnames,
2844  makeString(pstrdup("")));
2845 
2846  aliasp_item = lnext(rte->eref->colnames, aliasp_item);
2847  }
2848 
2849  if (colvars)
2850  {
2851  if (OidIsValid(coltype))
2852  {
2853  Var *varnode;
2854 
2855  varnode = makeVar(rtindex, varattno,
2856  coltype, coltypmod, colcoll,
2857  sublevels_up);
2858  varnode->location = location;
2859 
2860  *colvars = lappend(*colvars, varnode);
2861  }
2862  else if (include_dropped)
2863  {
2864  /*
2865  * It doesn't really matter what type the Const
2866  * claims to be.
2867  */
2868  *colvars = lappend(*colvars,
2869  makeNullConst(INT4OID, -1,
2870  InvalidOid));
2871  }
2872  }
2873  }
2874  }
2875  break;
2876  case RTE_RESULT:
2877  /* These expose no columns, so nothing to do */
2878  break;
2879  default:
2880  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2881  }
2882 }
2883 
2884 /*
2885  * expandRelation -- expandRTE subroutine
2886  */
2887 static void
2888 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
2889  int location, bool include_dropped,
2890  List **colnames, List **colvars)
2891 {
2892  Relation rel;
2893 
2894  /* Get the tupledesc and turn it over to expandTupleDesc */
2895  rel = relation_open(relid, AccessShareLock);
2896  expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
2897  rtindex, sublevels_up,
2898  location, include_dropped,
2899  colnames, colvars);
2901 }
2902 
2903 /*
2904  * expandTupleDesc -- expandRTE subroutine
2905  *
2906  * Generate names and/or Vars for the first "count" attributes of the tupdesc,
2907  * and append them to colnames/colvars. "offset" is added to the varattno
2908  * that each Var would otherwise have, and we also skip the first "offset"
2909  * entries in eref->colnames. (These provisions allow use of this code for
2910  * an individual composite-returning function in an RTE_FUNCTION RTE.)
2911  */
2912 static void
2913 expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset,
2914  int rtindex, int sublevels_up,
2915  int location, bool include_dropped,
2916  List **colnames, List **colvars)
2917 {
2918  ListCell *aliascell;
2919  int varattno;
2920 
2921  aliascell = (offset < list_length(eref->colnames)) ?
2922  list_nth_cell(eref->colnames, offset) : NULL;
2923 
2924  Assert(count <= tupdesc->natts);
2925  for (varattno = 0; varattno < count; varattno++)
2926  {
2927  Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
2928 
2929  if (attr->attisdropped)
2930  {
2931  if (include_dropped)
2932  {
2933  if (colnames)
2934  *colnames = lappend(*colnames, makeString(pstrdup("")));
2935  if (colvars)
2936  {
2937  /*
2938  * can't use atttypid here, but it doesn't really matter
2939  * what type the Const claims to be.
2940  */
2941  *colvars = lappend(*colvars,
2942  makeNullConst(INT4OID, -1, InvalidOid));
2943  }
2944  }
2945  if (aliascell)
2946  aliascell = lnext(eref->colnames, aliascell);
2947  continue;
2948  }
2949 
2950  if (colnames)
2951  {
2952  char *label;
2953 
2954  if (aliascell)
2955  {
2956  label = strVal(lfirst(aliascell));
2957  aliascell = lnext(eref->colnames, aliascell);
2958  }
2959  else
2960  {
2961  /* If we run out of aliases, use the underlying name */
2962  label = NameStr(attr->attname);
2963  }
2964  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2965  }
2966 
2967  if (colvars)
2968  {
2969  Var *varnode;
2970 
2971  varnode = makeVar(rtindex, varattno + offset + 1,
2972  attr->atttypid, attr->atttypmod,
2973  attr->attcollation,
2974  sublevels_up);
2975  varnode->location = location;
2976 
2977  *colvars = lappend(*colvars, varnode);
2978  }
2979  }
2980 }
2981 
2982 /*
2983  * expandNSItemVars
2984  * Produce a list of Vars, and optionally a list of column names,
2985  * for the non-dropped columns of the nsitem.
2986  *
2987  * The emitted Vars are marked with the given sublevels_up and location.
2988  *
2989  * If colnames isn't NULL, a list of String items for the columns is stored
2990  * there; note that it's just a subset of the RTE's eref list, and hence
2991  * the list elements mustn't be modified.
2992  */
2993 List *
2995  int sublevels_up, int location,
2996  List **colnames)
2997 {
2998  List *result = NIL;
2999  int colindex;
3000  ListCell *lc;
3001 
3002  if (colnames)
3003  *colnames = NIL;
3004  colindex = 0;
3005  foreach(lc, nsitem->p_rte->eref->colnames)
3006  {
3007  Value *colnameval = (Value *) lfirst(lc);
3008  const char *colname = strVal(colnameval);
3009  ParseNamespaceColumn *nscol = nsitem->p_nscolumns + colindex;
3010 
3011  if (colname[0])
3012  {
3013  Var *var;
3014 
3015  Assert(nscol->p_varno > 0);
3016  var = makeVar(nscol->p_varno,
3017  nscol->p_varattno,
3018  nscol->p_vartype,
3019  nscol->p_vartypmod,
3020  nscol->p_varcollid,
3021  sublevels_up);
3022  /* makeVar doesn't offer parameters for these, so set by hand: */
3023  var->varnosyn = nscol->p_varnosyn;
3024  var->varattnosyn = nscol->p_varattnosyn;
3025  var->location = location;
3026  result = lappend(result, var);
3027  if (colnames)
3028  *colnames = lappend(*colnames, colnameval);
3029  }
3030  else
3031  {
3032  /* dropped column, ignore */
3033  Assert(nscol->p_varno == 0);
3034  }
3035  colindex++;
3036  }
3037  return result;
3038 }
3039 
3040 /*
3041  * expandNSItemAttrs -
3042  * Workhorse for "*" expansion: produce a list of targetentries
3043  * for the attributes of the nsitem
3044  *
3045  * pstate->p_next_resno determines the resnos assigned to the TLEs.
3046  * The referenced columns are marked as requiring SELECT access.
3047  */
3048 List *
3050  int sublevels_up, int location)
3051 {
3052  RangeTblEntry *rte = nsitem->p_rte;
3053  List *names,
3054  *vars;
3055  ListCell *name,
3056  *var;
3057  List *te_list = NIL;
3058 
3059  vars = expandNSItemVars(nsitem, sublevels_up, location, &names);
3060 
3061  /*
3062  * Require read access to the table. This is normally redundant with the
3063  * markVarForSelectPriv calls below, but not if the table has zero
3064  * columns.
3065  */
3066  rte->requiredPerms |= ACL_SELECT;
3067 
3068  forboth(name, names, var, vars)
3069  {
3070  char *label = strVal(lfirst(name));
3071  Var *varnode = (Var *) lfirst(var);
3072  TargetEntry *te;
3073 
3074  te = makeTargetEntry((Expr *) varnode,
3075  (AttrNumber) pstate->p_next_resno++,
3076  label,
3077  false);
3078  te_list = lappend(te_list, te);
3079 
3080  /* Require read access to each column */
3081  markVarForSelectPriv(pstate, varnode, rte);
3082  }
3083 
3084  Assert(name == NULL && var == NULL); /* lists not the same length? */
3085 
3086  return te_list;
3087 }
3088 
3089 /*
3090  * get_rte_attribute_name
3091  * Get an attribute name from a RangeTblEntry
3092  *
3093  * This is unlike get_attname() because we use aliases if available.
3094  * In particular, it will work on an RTE for a subselect or join, whereas
3095  * get_attname() only works on real relations.
3096  *
3097  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
3098  * occurs when a Var represents a whole tuple of a relation.
3099  */
3100 char *
3102 {
3103  if (attnum == InvalidAttrNumber)
3104  return "*";
3105 
3106  /*
3107  * If there is a user-written column alias, use it.
3108  */
3109  if (rte->alias &&
3110  attnum > 0 && attnum <= list_length(rte->alias->colnames))
3111  return strVal(list_nth(rte->alias->colnames, attnum - 1));
3112 
3113  /*
3114  * If the RTE is a relation, go to the system catalogs not the
3115  * eref->colnames list. This is a little slower but it will give the
3116  * right answer if the column has been renamed since the eref list was
3117  * built (which can easily happen for rules).
3118  */
3119  if (rte->rtekind == RTE_RELATION)
3120  return get_attname(rte->relid, attnum, false);
3121 
3122  /*
3123  * Otherwise use the column name from eref. There should always be one.
3124  */
3125  if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
3126  return strVal(list_nth(rte->eref->colnames, attnum - 1));
3127 
3128  /* else caller gave us a bogus attnum */
3129  elog(ERROR, "invalid attnum %d for rangetable entry %s",
3130  attnum, rte->eref->aliasname);
3131  return NULL; /* keep compiler quiet */
3132 }
3133 
3134 /*
3135  * get_rte_attribute_is_dropped
3136  * Check whether attempted attribute ref is to a dropped column
3137  */
3138 bool
3140 {
3141  bool result;
3142 
3143  switch (rte->rtekind)
3144  {
3145  case RTE_RELATION:
3146  {
3147  /*
3148  * Plain relation RTE --- get the attribute's catalog entry
3149  */
3150  HeapTuple tp;
3151  Form_pg_attribute att_tup;
3152 
3153  tp = SearchSysCache2(ATTNUM,
3154  ObjectIdGetDatum(rte->relid),
3155  Int16GetDatum(attnum));
3156  if (!HeapTupleIsValid(tp)) /* shouldn't happen */
3157  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
3158  attnum, rte->relid);
3159  att_tup = (Form_pg_attribute) GETSTRUCT(tp);
3160  result = att_tup->attisdropped;
3161  ReleaseSysCache(tp);
3162  }
3163  break;
3164  case RTE_SUBQUERY:
3165  case RTE_TABLEFUNC:
3166  case RTE_VALUES:
3167  case RTE_CTE:
3168 
3169  /*
3170  * Subselect, Table Functions, Values, CTE RTEs never have dropped
3171  * columns
3172  */
3173  result = false;
3174  break;
3175  case RTE_NAMEDTUPLESTORE:
3176  {
3177  /* Check dropped-ness by testing for valid coltype */
3178  if (attnum <= 0 ||
3179  attnum > list_length(rte->coltypes))
3180  elog(ERROR, "invalid varattno %d", attnum);
3181  result = !OidIsValid((list_nth_oid(rte->coltypes, attnum - 1)));
3182  }
3183  break;
3184  case RTE_JOIN:
3185  {
3186  /*
3187  * A join RTE would not have dropped columns when constructed,
3188  * but one in a stored rule might contain columns that were
3189  * dropped from the underlying tables, if said columns are
3190  * nowhere explicitly referenced in the rule. This will be
3191  * signaled to us by a null pointer in the joinaliasvars list.
3192  */
3193  Var *aliasvar;
3194 
3195  if (attnum <= 0 ||
3196  attnum > list_length(rte->joinaliasvars))
3197  elog(ERROR, "invalid varattno %d", attnum);
3198  aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
3199 
3200  result = (aliasvar == NULL);
3201  }
3202  break;
3203  case RTE_FUNCTION:
3204  {
3205  /* Function RTE */
3206  ListCell *lc;
3207  int atts_done = 0;
3208 
3209  /*
3210  * Dropped attributes are only possible with functions that
3211  * return named composite types. In such a case we have to
3212  * look up the result type to see if it currently has this
3213  * column dropped. So first, loop over the funcs until we
3214  * find the one that covers the requested column.
3215  */
3216  foreach(lc, rte->functions)
3217  {
3218  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
3219 
3220  if (attnum > atts_done &&
3221  attnum <= atts_done + rtfunc->funccolcount)
3222  {
3223  TupleDesc tupdesc;
3224 
3225  tupdesc = get_expr_result_tupdesc(rtfunc->funcexpr,
3226  true);
3227  if (tupdesc)
3228  {
3229  /* Composite data type, e.g. a table's row type */
3230  Form_pg_attribute att_tup;
3231 
3232  Assert(tupdesc);
3233  Assert(attnum - atts_done <= tupdesc->natts);
3234  att_tup = TupleDescAttr(tupdesc,
3235  attnum - atts_done - 1);
3236  return att_tup->attisdropped;
3237  }
3238  /* Otherwise, it can't have any dropped columns */
3239  return false;
3240  }
3241  atts_done += rtfunc->funccolcount;
3242  }
3243 
3244  /* If we get here, must be looking for the ordinality column */
3245  if (rte->funcordinality && attnum == atts_done + 1)
3246  return false;
3247 
3248  /* this probably can't happen ... */
3249  ereport(ERROR,
3250  (errcode(ERRCODE_UNDEFINED_COLUMN),
3251  errmsg("column %d of relation \"%s\" does not exist",
3252  attnum,
3253  rte->eref->aliasname)));
3254  result = false; /* keep compiler quiet */
3255  }
3256  break;
3257  case RTE_RESULT:
3258  /* this probably can't happen ... */
3259  ereport(ERROR,
3260  (errcode(ERRCODE_UNDEFINED_COLUMN),
3261  errmsg("column %d of relation \"%s\" does not exist",
3262  attnum,
3263  rte->eref->aliasname)));
3264  result = false; /* keep compiler quiet */
3265  break;
3266  default:
3267  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
3268  result = false; /* keep compiler quiet */
3269  }
3270 
3271  return result;
3272 }
3273 
3274 /*
3275  * Given a targetlist and a resno, return the matching TargetEntry
3276  *
3277  * Returns NULL if resno is not present in list.
3278  *
3279  * Note: we need to search, rather than just indexing with list_nth(),
3280  * because not all tlists are sorted by resno.
3281  */
3282 TargetEntry *
3284 {
3285  ListCell *l;
3286 
3287  foreach(l, tlist)
3288  {
3289  TargetEntry *tle = (TargetEntry *) lfirst(l);
3290 
3291  if (tle->resno == resno)
3292  return tle;
3293  }
3294  return NULL;
3295 }
3296 
3297 /*
3298  * Given a Query and rangetable index, return relation's RowMarkClause if any
3299  *
3300  * Returns NULL if relation is not selected FOR UPDATE/SHARE
3301  */
3302 RowMarkClause *
3304 {
3305  ListCell *l;
3306 
3307  foreach(l, qry->rowMarks)
3308  {
3309  RowMarkClause *rc = (RowMarkClause *) lfirst(l);
3310 
3311  if (rc->rti == rtindex)
3312  return rc;
3313  }
3314  return NULL;
3315 }
3316 
3317 /*
3318  * given relation and att name, return attnum of variable
3319  *
3320  * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
3321  *
3322  * This should only be used if the relation is already
3323  * table_open()'ed. Use the cache version get_attnum()
3324  * for access to non-opened relations.
3325  */
3326 int
3327 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
3328 {
3329  int i;
3330 
3331  for (i = 0; i < RelationGetNumberOfAttributes(rd); i++)
3332  {
3333  Form_pg_attribute att = TupleDescAttr(rd->rd_att, i);
3334 
3335  if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
3336  return i + 1;
3337  }
3338 
3339  if (sysColOK)
3340  {
3341  if ((i = specialAttNum(attname)) != InvalidAttrNumber)
3342  return i;
3343  }
3344 
3345  /* on failure */
3346  return InvalidAttrNumber;
3347 }
3348 
3349 /* specialAttNum()
3350  *
3351  * Check attribute name to see if it is "special", e.g. "xmin".
3352  * - thomas 2000-02-07
3353  *
3354  * Note: this only discovers whether the name could be a system attribute.
3355  * Caller needs to ensure that it really is an attribute of the rel.
3356  */
3357 static int
3359 {
3360  const FormData_pg_attribute *sysatt;
3361 
3362  sysatt = SystemAttributeByName(attname);
3363  if (sysatt != NULL)
3364  return sysatt->attnum;
3365  return InvalidAttrNumber;
3366 }
3367 
3368 
3369 /*
3370  * given attribute id, return name of that attribute
3371  *
3372  * This should only be used if the relation is already
3373  * table_open()'ed. Use the cache version get_atttype()
3374  * for access to non-opened relations.
3375  */
3376 const NameData *
3377 attnumAttName(Relation rd, int attid)
3378 {
3379  if (attid <= 0)
3380  {
3381  const FormData_pg_attribute *sysatt;
3382 
3383  sysatt = SystemAttributeDefinition(attid);
3384  return &sysatt->attname;
3385  }
3386  if (attid > rd->rd_att->natts)
3387  elog(ERROR, "invalid attribute number %d", attid);
3388  return &TupleDescAttr(rd->rd_att, attid - 1)->attname;
3389 }
3390 
3391 /*
3392  * given attribute id, return type of that attribute
3393  *
3394  * This should only be used if the relation is already
3395  * table_open()'ed. Use the cache version get_atttype()
3396  * for access to non-opened relations.
3397  */
3398 Oid
3399 attnumTypeId(Relation rd, int attid)
3400 {
3401  if (attid <= 0)
3402  {
3403  const FormData_pg_attribute *sysatt;
3404 
3405  sysatt = SystemAttributeDefinition(attid);
3406  return sysatt->atttypid;
3407  }
3408  if (attid > rd->rd_att->natts)
3409  elog(ERROR, "invalid attribute number %d", attid);
3410  return TupleDescAttr(rd->rd_att, attid - 1)->atttypid;
3411 }
3412 
3413 /*
3414  * given attribute id, return collation of that attribute
3415  *
3416  * This should only be used if the relation is already table_open()'ed.
3417  */
3418 Oid
3420 {
3421  if (attid <= 0)
3422  {
3423  /* All system attributes are of noncollatable types. */
3424  return InvalidOid;
3425  }
3426  if (attid > rd->rd_att->natts)
3427  elog(ERROR, "invalid attribute number %d", attid);
3428  return TupleDescAttr(rd->rd_att, attid - 1)->attcollation;
3429 }
3430 
3431 /*
3432  * Generate a suitable error about a missing RTE.
3433  *
3434  * Since this is a very common type of error, we work rather hard to
3435  * produce a helpful message.
3436  */
3437 void
3439 {
3440  RangeTblEntry *rte;
3441  const char *badAlias = NULL;
3442 
3443  /*
3444  * Check to see if there are any potential matches in the query's
3445  * rangetable. (Note: cases involving a bad schema name in the RangeVar
3446  * will throw error immediately here. That seems OK.)
3447  */
3448  rte = searchRangeTableForRel(pstate, relation);
3449 
3450  /*
3451  * If we found a match that has an alias and the alias is visible in the
3452  * namespace, then the problem is probably use of the relation's real name
3453  * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
3454  * common enough to justify a specific hint.
3455  *
3456  * If we found a match that doesn't meet those criteria, assume the
3457  * problem is illegal use of a relation outside its scope, as in the
3458  * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
3459  */
3460  if (rte && rte->alias &&
3461  strcmp(rte->eref->aliasname, relation->relname) != 0)
3462  {
3463  ParseNamespaceItem *nsitem;
3464  int sublevels_up;
3465 
3466  nsitem = refnameNamespaceItem(pstate, NULL, rte->eref->aliasname,
3467  relation->location,
3468  &sublevels_up);
3469  if (nsitem && nsitem->p_rte == rte)
3470  badAlias = rte->eref->aliasname;
3471  }
3472 
3473  if (rte)
3474  ereport(ERROR,
3476  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3477  relation->relname),
3478  (badAlias ?
3479  errhint("Perhaps you meant to reference the table alias \"%s\".",
3480  badAlias) :
3481  errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
3482  rte->eref->aliasname)),
3483  parser_errposition(pstate, relation->location)));
3484  else
3485  ereport(ERROR,
3487  errmsg("missing FROM-clause entry for table \"%s\"",
3488  relation->relname),
3489  parser_errposition(pstate, relation->location)));
3490 }
3491 
3492 /*
3493  * Generate a suitable error about a missing column.
3494  *
3495  * Since this is a very common type of error, we work rather hard to
3496  * produce a helpful message.
3497  */
3498 void
3500  const char *relname, const char *colname, int location)
3501 {
3503  char *closestfirst = NULL;
3504 
3505  /*
3506  * Search the entire rtable looking for possible matches. If we find one,
3507  * emit a hint about it.
3508  *
3509  * TODO: improve this code (and also errorMissingRTE) to mention using
3510  * LATERAL if appropriate.
3511  */
3512  state = searchRangeTableForCol(pstate, relname, colname, location);
3513 
3514  /*
3515  * Extract closest col string for best match, if any.
3516  *
3517  * Infer an exact match referenced despite not being visible from the fact
3518  * that an attribute number was not present in state passed back -- this
3519  * is what is reported when !closestfirst. There might also be an exact
3520  * match that was qualified with an incorrect alias, in which case
3521  * closestfirst will be set (so hint is the same as generic fuzzy case).
3522  */
3523  if (state->rfirst && AttributeNumberIsValid(state->first))
3524  closestfirst = strVal(list_nth(state->rfirst->eref->colnames,
3525  state->first - 1));
3526 
3527  if (!state->rsecond)
3528  {
3529  /*
3530  * Handle case where there is zero or one column suggestions to hint,
3531  * including exact matches referenced but not visible.
3532  */
3533  ereport(ERROR,
3534  (errcode(ERRCODE_UNDEFINED_COLUMN),
3535  relname ?
3536  errmsg("column %s.%s does not exist", relname, colname) :
3537  errmsg("column \"%s\" does not exist", colname),
3538  state->rfirst ? closestfirst ?
3539  errhint("Perhaps you meant to reference the column \"%s.%s\".",
3540  state->rfirst->eref->aliasname, closestfirst) :
3541  errhint("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
3542  colname, state->rfirst->eref->aliasname) : 0,
3543  parser_errposition(pstate, location)));
3544  }
3545  else
3546  {
3547  /* Handle case where there are two equally useful column hints */
3548  char *closestsecond;
3549 
3550  closestsecond = strVal(list_nth(state->rsecond->eref->colnames,
3551  state->second - 1));
3552 
3553  ereport(ERROR,
3554  (errcode(ERRCODE_UNDEFINED_COLUMN),
3555  relname ?
3556  errmsg("column %s.%s does not exist", relname, colname) :
3557  errmsg("column \"%s\" does not exist", colname),
3558  errhint("Perhaps you meant to reference the column \"%s.%s\" or the column \"%s.%s\".",
3559  state->rfirst->eref->aliasname, closestfirst,
3560  state->rsecond->eref->aliasname, closestsecond),
3561  parser_errposition(pstate, location)));
3562  }
3563 }
3564 
3565 
3566 /*
3567  * Examine a fully-parsed query, and return true iff any relation underlying
3568  * the query is a temporary relation (table, view, or materialized view).
3569  */
3570 bool
3572 {
3573  return isQueryUsingTempRelation_walker((Node *) query, NULL);
3574 }
3575 
3576 static bool
3578 {
3579  if (node == NULL)
3580  return false;
3581 
3582  if (IsA(node, Query))
3583  {
3584  Query *query = (Query *) node;
3585  ListCell *rtable;
3586 
3587  foreach(rtable, query->rtable)
3588  {
3589  RangeTblEntry *rte = lfirst(rtable);
3590 
3591  if (rte->rtekind == RTE_RELATION)
3592  {
3594  char relpersistence = rel->rd_rel->relpersistence;
3595 
3597  if (relpersistence == RELPERSISTENCE_TEMP)
3598  return true;
3599  }
3600  }
3601 
3602  return query_tree_walker(query,
3604  context,
3606  }
3607 
3608  return expression_tree_walker(node,
3610  context);
3611 }
Value * makeString(char *str)
Definition: value.c:53
List * lockedRels
Definition: parsenodes.h:751
#define NIL
Definition: pg_list.h:65
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2322
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:569
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
List * joinaliasvars
Definition: parsenodes.h:1052
Index varlevelsup
Definition: primnodes.h:191
int errhint(const char *fmt,...)
Definition: elog.c:1068
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:434
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:74
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:1240
List * colnames
Definition: primnodes.h:89
Alias * alias
Definition: parsenodes.h:1115
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:244
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:132
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:479
char * pstrdup(const char *in)
Definition: mcxt.c:1187
List * coltypmods
Definition: parsenodes.h:1103
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:194
#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:528
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:1120
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1422
bool funcordinality
Definition: parsenodes.h:1065
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:1412
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:652
List * colcollations
Definition: parsenodes.h:1104
List * values_lists
Definition: parsenodes.h:1075
List * colcollations
Definition: primnodes.h:92
signed int int32
Definition: c.h:363
JoinType
Definition: nodes.h:695
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:288
EphemeralNamedRelationMetadata get_visible_ENR(ParseState *pstate, const char *refname)
Definition: parse_enr.c:26
Node * larg
Definition: primnodes.h:1493
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:1125
Bitmapset * selectedCols
Definition: parsenodes.h:1122
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
bool resjunk
Definition: primnodes.h:1417
#define linitial(l)
Definition: pg_list.h:174
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:1070
#define lfirst_int(lc)
Definition: pg_list.h:170
static void * list_nth(const List *list, int n)
Definition: pg_list.h:266
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:617
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:294
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:1050
int errdetail(const char *fmt,...)
Definition: elog.c:954
AttrNumber resno
Definition: primnodes.h:1411
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:665
TypeFuncClass
Definition: funcapi.h:146
List * ctecoltypmods
Definition: parsenodes.h:1463
List * joinrightcols
Definition: parsenodes.h:1054
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:1109
#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:1461
#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:981
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:1082
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:483
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:1154
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:1124
List * joinleftcols
Definition: parsenodes.h:1053
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:1155
#define makeNode(_type_)
Definition: nodes.h:576
Node * rarg
Definition: primnodes.h:1494
#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:746
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
Definition: regguts.h:298
List * functions
Definition: parsenodes.h:1064
Definition: value.h:42
List * expandNSItemVars(ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
Expr * expr
Definition: primnodes.h:1410
RangeTblEntry * rsecond
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1888
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:768
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1127
Index ctelevelsup
Definition: parsenodes.h:1081
TypeName * typeName
Definition: parsenodes.h:649
Bitmapset * funcparams
Definition: parsenodes.h:1157
#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:533
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:1462
RTEKind rtekind
Definition: parsenodes.h:977
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:1080
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
ParseNamespaceColumn * p_nscolumns
Definition: parse_node.h:260
Query * subquery
Definition: parsenodes.h:1012
double enrtuples
Definition: parsenodes.h:1110
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
Bitmapset * insertedCols
Definition: parsenodes.h:1123
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:623
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:648
Alias * eref
Definition: parsenodes.h:1116
List * ctecolcollations
Definition: parsenodes.h:1464
#define copyObject(obj)
Definition: nodes.h:644
List * coltypes
Definition: parsenodes.h:1102
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:215
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:171
Oid LookupNamespaceNoError(const char *nspname)
Definition: namespace.c:2862
Node * colNameToVar(ParseState *pstate, const char *colname, bool localonly, int location)
char * get_func_result_name(Oid functionId)
Definition: funcapi.c:1323
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
List * p_rtable
Definition: parse_node.h:180