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