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-2016, 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 
35 
36 #define MAX_FUZZY_DISTANCE 3
37 
39  const char *refname, int location);
40 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
41  int location);
42 static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
43  int location);
44 static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
45  int rtindex, AttrNumber col);
46 static void expandRelation(Oid relid, Alias *eref,
47  int rtindex, int sublevels_up,
48  int location, bool include_dropped,
49  List **colnames, List **colvars);
50 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
51  int count, int offset,
52  int rtindex, int sublevels_up,
53  int location, bool include_dropped,
54  List **colnames, List **colvars);
55 static int specialAttNum(const char *attname);
56 static bool isQueryUsingTempRelation_walker(Node *node, void *context);
57 
58 
59 /*
60  * refnameRangeTblEntry
61  * Given a possibly-qualified refname, look to see if it matches any RTE.
62  * If so, return a pointer to the RangeTblEntry; else return NULL.
63  *
64  * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
65  * If sublevels_up is NULL, only consider items at the current nesting
66  * level.
67  *
68  * An unqualified refname (schemaname == NULL) can match any RTE with matching
69  * alias, or matching unqualified relname in the case of alias-less relation
70  * RTEs. It is possible that such a refname matches multiple RTEs in the
71  * nearest nesting level that has a match; if so, we report an error via
72  * ereport().
73  *
74  * A qualified refname (schemaname != NULL) can only match a relation RTE
75  * that (a) has no alias and (b) is for the same relation identified by
76  * schemaname.refname. In this case we convert schemaname.refname to a
77  * relation OID and search by relid, rather than by alias name. This is
78  * peculiar, but it's what SQL says to do.
79  */
82  const char *schemaname,
83  const char *refname,
84  int location,
85  int *sublevels_up)
86 {
87  Oid relId = InvalidOid;
88 
89  if (sublevels_up)
90  *sublevels_up = 0;
91 
92  if (schemaname != NULL)
93  {
94  Oid namespaceId;
95 
96  /*
97  * We can use LookupNamespaceNoError() here because we are only
98  * interested in finding existing RTEs. Checking USAGE permission on
99  * the schema is unnecessary since it would have already been checked
100  * when the RTE was made. Furthermore, we want to report "RTE not
101  * found", not "no permissions for schema", if the name happens to
102  * match a schema name the user hasn't got access to.
103  */
104  namespaceId = LookupNamespaceNoError(schemaname);
105  if (!OidIsValid(namespaceId))
106  return NULL;
107  relId = get_relname_relid(refname, namespaceId);
108  if (!OidIsValid(relId))
109  return NULL;
110  }
111 
112  while (pstate != NULL)
113  {
114  RangeTblEntry *result;
115 
116  if (OidIsValid(relId))
117  result = scanNameSpaceForRelid(pstate, relId, location);
118  else
119  result = scanNameSpaceForRefname(pstate, refname, location);
120 
121  if (result)
122  return result;
123 
124  if (sublevels_up)
125  (*sublevels_up)++;
126  else
127  break;
128 
129  pstate = pstate->parentParseState;
130  }
131  return NULL;
132 }
133 
134 /*
135  * Search the query's table namespace for an RTE matching the
136  * given unqualified refname. Return the RTE if a unique match, or NULL
137  * if no match. Raise error if multiple matches.
138  *
139  * Note: it might seem that we shouldn't have to worry about the possibility
140  * of multiple matches; after all, the SQL standard disallows duplicate table
141  * aliases within a given SELECT level. Historically, however, Postgres has
142  * been laxer than that. For example, we allow
143  * SELECT ... FROM tab1 x CROSS JOIN (tab2 x CROSS JOIN tab3 y) z
144  * on the grounds that the aliased join (z) hides the aliases within it,
145  * therefore there is no conflict between the two RTEs named "x". However,
146  * if tab3 is a LATERAL subquery, then from within the subquery both "x"es
147  * are visible. Rather than rejecting queries that used to work, we allow
148  * this situation, and complain only if there's actually an ambiguous
149  * reference to "x".
150  */
151 static RangeTblEntry *
152 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
153 {
154  RangeTblEntry *result = NULL;
155  ListCell *l;
156 
157  foreach(l, pstate->p_namespace)
158  {
160  RangeTblEntry *rte = nsitem->p_rte;
161 
162  /* Ignore columns-only items */
163  if (!nsitem->p_rel_visible)
164  continue;
165  /* If not inside LATERAL, ignore lateral-only items */
166  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
167  continue;
168 
169  if (strcmp(rte->eref->aliasname, refname) == 0)
170  {
171  if (result)
172  ereport(ERROR,
173  (errcode(ERRCODE_AMBIGUOUS_ALIAS),
174  errmsg("table reference \"%s\" is ambiguous",
175  refname),
176  parser_errposition(pstate, location)));
177  check_lateral_ref_ok(pstate, nsitem, location);
178  result = rte;
179  }
180  }
181  return result;
182 }
183 
184 /*
185  * Search the query's table namespace for a relation RTE matching the
186  * given relation OID. Return the RTE if a unique match, or NULL
187  * if no match. Raise error if multiple matches.
188  *
189  * See the comments for refnameRangeTblEntry to understand why this
190  * acts the way it does.
191  */
192 static RangeTblEntry *
193 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
194 {
195  RangeTblEntry *result = NULL;
196  ListCell *l;
197 
198  foreach(l, pstate->p_namespace)
199  {
201  RangeTblEntry *rte = nsitem->p_rte;
202 
203  /* Ignore columns-only items */
204  if (!nsitem->p_rel_visible)
205  continue;
206  /* If not inside LATERAL, ignore lateral-only items */
207  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
208  continue;
209 
210  /* yes, the test for alias == NULL should be there... */
211  if (rte->rtekind == RTE_RELATION &&
212  rte->relid == relid &&
213  rte->alias == NULL)
214  {
215  if (result)
216  ereport(ERROR,
217  (errcode(ERRCODE_AMBIGUOUS_ALIAS),
218  errmsg("table reference %u is ambiguous",
219  relid),
220  parser_errposition(pstate, location)));
221  check_lateral_ref_ok(pstate, nsitem, location);
222  result = rte;
223  }
224  }
225  return result;
226 }
227 
228 /*
229  * Search the query's CTE namespace for a CTE matching the given unqualified
230  * refname. Return the CTE (and its levelsup count) if a match, or NULL
231  * if no match. We need not worry about multiple matches, since parse_cte.c
232  * rejects WITH lists containing duplicate CTE names.
233  */
235 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
236  Index *ctelevelsup)
237 {
238  Index levelsup;
239 
240  for (levelsup = 0;
241  pstate != NULL;
242  pstate = pstate->parentParseState, levelsup++)
243  {
244  ListCell *lc;
245 
246  foreach(lc, pstate->p_ctenamespace)
247  {
248  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
249 
250  if (strcmp(cte->ctename, refname) == 0)
251  {
252  *ctelevelsup = levelsup;
253  return cte;
254  }
255  }
256  }
257  return NULL;
258 }
259 
260 /*
261  * Search for a possible "future CTE", that is one that is not yet in scope
262  * according to the WITH scoping rules. This has nothing to do with valid
263  * SQL semantics, but it's important for error reporting purposes.
264  */
265 static bool
266 isFutureCTE(ParseState *pstate, const char *refname)
267 {
268  for (; pstate != NULL; pstate = pstate->parentParseState)
269  {
270  ListCell *lc;
271 
272  foreach(lc, pstate->p_future_ctes)
273  {
274  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
275 
276  if (strcmp(cte->ctename, refname) == 0)
277  return true;
278  }
279  }
280  return false;
281 }
282 
283 /*
284  * searchRangeTableForRel
285  * See if any RangeTblEntry could possibly match the RangeVar.
286  * If so, return a pointer to the RangeTblEntry; else return NULL.
287  *
288  * This is different from refnameRangeTblEntry in that it considers every
289  * entry in the ParseState's rangetable(s), not only those that are currently
290  * visible in the p_namespace list(s). This behavior is invalid per the SQL
291  * spec, and it may give ambiguous results (there might be multiple equally
292  * valid matches, but only one will be returned). This must be used ONLY
293  * as a heuristic in giving suitable error messages. See errorMissingRTE.
294  *
295  * Notice that we consider both matches on actual relation (or CTE) name
296  * and matches on alias.
297  */
298 static RangeTblEntry *
300 {
301  const char *refname = relation->relname;
302  Oid relId = InvalidOid;
303  CommonTableExpr *cte = NULL;
304  Index ctelevelsup = 0;
305  Index levelsup;
306 
307  /*
308  * If it's an unqualified name, check for possible CTE matches. A CTE
309  * hides any real relation matches. If no CTE, look for a matching
310  * relation.
311  *
312  * NB: It's not critical that RangeVarGetRelid return the correct answer
313  * here in the face of concurrent DDL. If it doesn't, the worst case
314  * scenario is a less-clear error message. Also, the tables involved in
315  * the query are already locked, which reduces the number of cases in
316  * which surprising behavior can occur. So we do the name lookup
317  * unlocked.
318  */
319  if (!relation->schemaname)
320  cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
321  if (!cte)
322  relId = RangeVarGetRelid(relation, NoLock, true);
323 
324  /* Now look for RTEs matching either the relation/CTE or the alias */
325  for (levelsup = 0;
326  pstate != NULL;
327  pstate = pstate->parentParseState, levelsup++)
328  {
329  ListCell *l;
330 
331  foreach(l, pstate->p_rtable)
332  {
333  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
334 
335  if (rte->rtekind == RTE_RELATION &&
336  OidIsValid(relId) &&
337  rte->relid == relId)
338  return rte;
339  if (rte->rtekind == RTE_CTE &&
340  cte != NULL &&
341  rte->ctelevelsup + levelsup == ctelevelsup &&
342  strcmp(rte->ctename, refname) == 0)
343  return rte;
344  if (strcmp(rte->eref->aliasname, refname) == 0)
345  return rte;
346  }
347  }
348  return NULL;
349 }
350 
351 /*
352  * Check for relation-name conflicts between two namespace lists.
353  * Raise an error if any is found.
354  *
355  * Note: we assume that each given argument does not contain conflicts
356  * itself; we just want to know if the two can be merged together.
357  *
358  * Per SQL, two alias-less plain relation RTEs do not conflict even if
359  * they have the same eref->aliasname (ie, same relation name), if they
360  * are for different relation OIDs (implying they are in different schemas).
361  *
362  * We ignore the lateral-only flags in the namespace items: the lists must
363  * not conflict, even when all items are considered visible. However,
364  * columns-only items should be ignored.
365  */
366 void
368  List *namespace2)
369 {
370  ListCell *l1;
371 
372  foreach(l1, namespace1)
373  {
374  ParseNamespaceItem *nsitem1 = (ParseNamespaceItem *) lfirst(l1);
375  RangeTblEntry *rte1 = nsitem1->p_rte;
376  const char *aliasname1 = rte1->eref->aliasname;
377  ListCell *l2;
378 
379  if (!nsitem1->p_rel_visible)
380  continue;
381 
382  foreach(l2, namespace2)
383  {
384  ParseNamespaceItem *nsitem2 = (ParseNamespaceItem *) lfirst(l2);
385  RangeTblEntry *rte2 = nsitem2->p_rte;
386 
387  if (!nsitem2->p_rel_visible)
388  continue;
389  if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
390  continue; /* definitely no conflict */
391  if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
392  rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
393  rte1->relid != rte2->relid)
394  continue; /* no conflict per SQL rule */
395  ereport(ERROR,
396  (errcode(ERRCODE_DUPLICATE_ALIAS),
397  errmsg("table name \"%s\" specified more than once",
398  aliasname1)));
399  }
400  }
401 }
402 
403 /*
404  * Complain if a namespace item is currently disallowed as a LATERAL reference.
405  * This enforces both SQL:2008's rather odd idea of what to do with a LATERAL
406  * reference to the wrong side of an outer join, and our own prohibition on
407  * referencing the target table of an UPDATE or DELETE as a lateral reference
408  * in a FROM/USING clause.
409  *
410  * Convenience subroutine to avoid multiple copies of a rather ugly ereport.
411  */
412 static void
414  int location)
415 {
416  if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
417  {
418  /* SQL:2008 demands this be an error, not an invisible item */
419  RangeTblEntry *rte = nsitem->p_rte;
420  char *refname = rte->eref->aliasname;
421 
422  ereport(ERROR,
423  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
424  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
425  refname),
426  (rte == pstate->p_target_rangetblentry) ?
427  errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
428  refname) :
429  errdetail("The combining JOIN type must be INNER or LEFT for a LATERAL reference."),
430  parser_errposition(pstate, location)));
431  }
432 }
433 
434 /*
435  * given an RTE, return RT index (starting with 1) of the entry,
436  * and optionally get its nesting depth (0 = current). If sublevels_up
437  * is NULL, only consider rels at the current nesting level.
438  * Raises error if RTE not found.
439  */
440 int
441 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
442 {
443  int index;
444  ListCell *l;
445 
446  if (sublevels_up)
447  *sublevels_up = 0;
448 
449  while (pstate != NULL)
450  {
451  index = 1;
452  foreach(l, pstate->p_rtable)
453  {
454  if (rte == (RangeTblEntry *) lfirst(l))
455  return index;
456  index++;
457  }
458  pstate = pstate->parentParseState;
459  if (sublevels_up)
460  (*sublevels_up)++;
461  else
462  break;
463  }
464 
465  elog(ERROR, "RTE not found (internal error)");
466  return 0; /* keep compiler quiet */
467 }
468 
469 /*
470  * Given an RT index and nesting depth, find the corresponding RTE.
471  * This is the inverse of RTERangeTablePosn.
472  */
475  int varno,
476  int sublevels_up)
477 {
478  while (sublevels_up-- > 0)
479  {
480  pstate = pstate->parentParseState;
481  Assert(pstate != NULL);
482  }
483  Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
484  return rt_fetch(varno, pstate->p_rtable);
485 }
486 
487 /*
488  * Fetch the CTE for a CTE-reference RTE.
489  *
490  * rtelevelsup is the number of query levels above the given pstate that the
491  * RTE came from. Callers that don't have this information readily available
492  * may pass -1 instead.
493  */
495 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
496 {
497  Index levelsup;
498  ListCell *lc;
499 
500  /* Determine RTE's levelsup if caller didn't know it */
501  if (rtelevelsup < 0)
502  (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
503 
504  Assert(rte->rtekind == RTE_CTE);
505  levelsup = rte->ctelevelsup + rtelevelsup;
506  while (levelsup-- > 0)
507  {
508  pstate = pstate->parentParseState;
509  if (!pstate) /* shouldn't happen */
510  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
511  }
512  foreach(lc, pstate->p_ctenamespace)
513  {
514  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
515 
516  if (strcmp(cte->ctename, rte->ctename) == 0)
517  return cte;
518  }
519  /* shouldn't happen */
520  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
521  return NULL; /* keep compiler quiet */
522 }
523 
524 /*
525  * updateFuzzyAttrMatchState
526  * Using Levenshtein distance, consider if column is best fuzzy match.
527  */
528 static void
529 updateFuzzyAttrMatchState(int fuzzy_rte_penalty,
530  FuzzyAttrMatchState *fuzzystate, RangeTblEntry *rte,
531  const char *actual, const char *match, int attnum)
532 {
533  int columndistance;
534  int matchlen;
535 
536  /* Bail before computing the Levenshtein distance if there's no hope. */
537  if (fuzzy_rte_penalty > fuzzystate->distance)
538  return;
539 
540  /*
541  * Outright reject dropped columns, which can appear here with apparent
542  * empty actual names, per remarks within scanRTEForColumn().
543  */
544  if (actual[0] == '\0')
545  return;
546 
547  /* Use Levenshtein to compute match distance. */
548  matchlen = strlen(match);
549  columndistance =
550  varstr_levenshtein_less_equal(actual, strlen(actual), match, matchlen,
551  1, 1, 1,
552  fuzzystate->distance + 1
553  - fuzzy_rte_penalty,
554  true);
555 
556  /*
557  * If more than half the characters are different, don't treat it as a
558  * match, to avoid making ridiculous suggestions.
559  */
560  if (columndistance > matchlen / 2)
561  return;
562 
563  /*
564  * From this point on, we can ignore the distinction between the RTE-name
565  * distance and the column-name distance.
566  */
567  columndistance += fuzzy_rte_penalty;
568 
569  /*
570  * If the new distance is less than or equal to that of the best match
571  * found so far, update fuzzystate.
572  */
573  if (columndistance < fuzzystate->distance)
574  {
575  /* Store new lowest observed distance for RTE */
576  fuzzystate->distance = columndistance;
577  fuzzystate->rfirst = rte;
578  fuzzystate->first = attnum;
579  fuzzystate->rsecond = NULL;
580  fuzzystate->second = InvalidAttrNumber;
581  }
582  else if (columndistance == fuzzystate->distance)
583  {
584  /*
585  * This match distance may equal a prior match within this same range
586  * table. When that happens, the prior match may also be given, but
587  * only if there is no more than two equally distant matches from the
588  * RTE (in turn, our caller will only accept two equally distant
589  * matches overall).
590  */
591  if (AttributeNumberIsValid(fuzzystate->second))
592  {
593  /* Too many RTE-level matches */
594  fuzzystate->rfirst = NULL;
595  fuzzystate->first = InvalidAttrNumber;
596  fuzzystate->rsecond = NULL;
597  fuzzystate->second = InvalidAttrNumber;
598  /* Clearly, distance is too low a bar (for *any* RTE) */
599  fuzzystate->distance = columndistance - 1;
600  }
601  else if (AttributeNumberIsValid(fuzzystate->first))
602  {
603  /* Record as provisional second match for RTE */
604  fuzzystate->rsecond = rte;
605  fuzzystate->second = attnum;
606  }
607  else if (fuzzystate->distance <= MAX_FUZZY_DISTANCE)
608  {
609  /*
610  * Record as provisional first match (this can occasionally occur
611  * because previous lowest distance was "too low a bar", rather
612  * than being associated with a real match)
613  */
614  fuzzystate->rfirst = rte;
615  fuzzystate->first = attnum;
616  }
617  }
618 }
619 
620 /*
621  * scanRTEForColumn
622  * Search the column names of a single RTE for the given name.
623  * If found, return an appropriate Var node, else return NULL.
624  * If the name proves ambiguous within this RTE, raise error.
625  *
626  * Side effect: if we find a match, mark the RTE as requiring read access
627  * for the column.
628  *
629  * Additional side effect: if fuzzystate is non-NULL, check non-system columns
630  * for an approximate match and update fuzzystate accordingly.
631  */
632 Node *
633 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
634  int location, int fuzzy_rte_penalty,
635  FuzzyAttrMatchState *fuzzystate)
636 {
637  Node *result = NULL;
638  int attnum = 0;
639  Var *var;
640  ListCell *c;
641 
642  /*
643  * Scan the user column names (or aliases) for a match. Complain if
644  * multiple matches.
645  *
646  * Note: eref->colnames may include entries for dropped columns, but those
647  * will be empty strings that cannot match any legal SQL identifier, so we
648  * don't bother to test for that case here.
649  *
650  * Should this somehow go wrong and we try to access a dropped column,
651  * we'll still catch it by virtue of the checks in
652  * get_rte_attribute_type(), which is called by make_var(). That routine
653  * has to do a cache lookup anyway, so the check there is cheap. Callers
654  * interested in finding match with shortest distance need to defend
655  * against this directly, though.
656  */
657  foreach(c, rte->eref->colnames)
658  {
659  const char *attcolname = strVal(lfirst(c));
660 
661  attnum++;
662  if (strcmp(attcolname, colname) == 0)
663  {
664  if (result)
665  ereport(ERROR,
666  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
667  errmsg("column reference \"%s\" is ambiguous",
668  colname),
669  parser_errposition(pstate, location)));
670  var = make_var(pstate, rte, attnum, location);
671  /* Require read access to the column */
672  markVarForSelectPriv(pstate, var, rte);
673  result = (Node *) var;
674  }
675 
676  /* Updating fuzzy match state, if provided. */
677  if (fuzzystate != NULL)
678  updateFuzzyAttrMatchState(fuzzy_rte_penalty, fuzzystate,
679  rte, attcolname, colname, attnum);
680  }
681 
682  /*
683  * If we have a unique match, return it. Note that this allows a user
684  * alias to override a system column name (such as OID) without error.
685  */
686  if (result)
687  return result;
688 
689  /*
690  * If the RTE represents a real relation, consider system column names.
691  * Composites are only used for pseudo-relations like ON CONFLICT's
692  * excluded.
693  */
694  if (rte->rtekind == RTE_RELATION &&
696  {
697  /* quick check to see if name could be a system column */
698  attnum = specialAttNum(colname);
699 
700  /* In constraint check, no system column is allowed except tableOid */
701  if (pstate->p_expr_kind == EXPR_KIND_CHECK_CONSTRAINT &&
702  attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
703  ereport(ERROR,
704  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
705  errmsg("system column \"%s\" reference in check constraint is invalid",
706  colname),
707  parser_errposition(pstate, location)));
708 
709  if (attnum != InvalidAttrNumber)
710  {
711  /* now check to see if column actually is defined */
713  ObjectIdGetDatum(rte->relid),
714  Int16GetDatum(attnum)))
715  {
716  var = make_var(pstate, rte, attnum, location);
717  /* Require read access to the column */
718  markVarForSelectPriv(pstate, var, rte);
719  result = (Node *) var;
720  }
721  }
722  }
723 
724  return result;
725 }
726 
727 /*
728  * colNameToVar
729  * Search for an unqualified column name.
730  * If found, return the appropriate Var node (or expression).
731  * If not found, return NULL. If the name proves ambiguous, raise error.
732  * If localonly is true, only names in the innermost query are considered.
733  */
734 Node *
735 colNameToVar(ParseState *pstate, char *colname, bool localonly,
736  int location)
737 {
738  Node *result = NULL;
739  ParseState *orig_pstate = pstate;
740 
741  while (pstate != NULL)
742  {
743  ListCell *l;
744 
745  foreach(l, pstate->p_namespace)
746  {
748  RangeTblEntry *rte = nsitem->p_rte;
749  Node *newresult;
750 
751  /* Ignore table-only items */
752  if (!nsitem->p_cols_visible)
753  continue;
754  /* If not inside LATERAL, ignore lateral-only items */
755  if (nsitem->p_lateral_only && !pstate->p_lateral_active)
756  continue;
757 
758  /* use orig_pstate here to get the right sublevels_up */
759  newresult = scanRTEForColumn(orig_pstate, rte, colname, location,
760  0, NULL);
761 
762  if (newresult)
763  {
764  if (result)
765  ereport(ERROR,
766  (errcode(ERRCODE_AMBIGUOUS_COLUMN),
767  errmsg("column reference \"%s\" is ambiguous",
768  colname),
769  parser_errposition(pstate, location)));
770  check_lateral_ref_ok(pstate, nsitem, location);
771  result = newresult;
772  }
773  }
774 
775  if (result != NULL || localonly)
776  break; /* found, or don't want to look at parent */
777 
778  pstate = pstate->parentParseState;
779  }
780 
781  return result;
782 }
783 
784 /*
785  * searchRangeTableForCol
786  * See if any RangeTblEntry could possibly provide the given column name (or
787  * find the best match available). Returns state with relevant details.
788  *
789  * This is different from colNameToVar in that it considers every entry in
790  * the ParseState's rangetable(s), not only those that are currently visible
791  * in the p_namespace list(s). This behavior is invalid per the SQL spec,
792  * and it may give ambiguous results (there might be multiple equally valid
793  * matches, but only one will be returned). This must be used ONLY as a
794  * heuristic in giving suitable error messages. See errorMissingColumn.
795  *
796  * This function is also different in that it will consider approximate
797  * matches -- if the user entered an alias/column pair that is only slightly
798  * different from a valid pair, we may be able to infer what they meant to
799  * type and provide a reasonable hint.
800  *
801  * The FuzzyAttrMatchState will have 'rfirst' pointing to the best RTE
802  * containing the most promising match for the alias and column name. If
803  * the alias and column names match exactly, 'first' will be InvalidAttrNumber;
804  * otherwise, it will be the attribute number for the match. In the latter
805  * case, 'rsecond' may point to a second, equally close approximate match,
806  * and 'second' will contain the attribute number for the second match.
807  */
808 static FuzzyAttrMatchState *
809 searchRangeTableForCol(ParseState *pstate, const char *alias, char *colname,
810  int location)
811 {
812  ParseState *orig_pstate = pstate;
813  FuzzyAttrMatchState *fuzzystate = palloc(sizeof(FuzzyAttrMatchState));
814 
815  fuzzystate->distance = MAX_FUZZY_DISTANCE + 1;
816  fuzzystate->rfirst = NULL;
817  fuzzystate->rsecond = NULL;
818  fuzzystate->first = InvalidAttrNumber;
819  fuzzystate->second = InvalidAttrNumber;
820 
821  while (pstate != NULL)
822  {
823  ListCell *l;
824 
825  foreach(l, pstate->p_rtable)
826  {
827  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
828  int fuzzy_rte_penalty = 0;
829 
830  /*
831  * Typically, it is not useful to look for matches within join
832  * RTEs; they effectively duplicate other RTEs for our purposes,
833  * and if a match is chosen from a join RTE, an unhelpful alias is
834  * displayed in the final diagnostic message.
835  */
836  if (rte->rtekind == RTE_JOIN)
837  continue;
838 
839  /*
840  * If the user didn't specify an alias, then matches against one
841  * RTE are as good as another. But if the user did specify an
842  * alias, then we want at least a fuzzy - and preferably an exact
843  * - match for the range table entry.
844  */
845  if (alias != NULL)
846  fuzzy_rte_penalty =
847  varstr_levenshtein_less_equal(alias, strlen(alias),
848  rte->eref->aliasname,
849  strlen(rte->eref->aliasname),
850  1, 1, 1,
851  MAX_FUZZY_DISTANCE + 1,
852  true);
853 
854  /*
855  * Scan for a matching column; if we find an exact match, we're
856  * done. Otherwise, update fuzzystate.
857  */
858  if (scanRTEForColumn(orig_pstate, rte, colname, location,
859  fuzzy_rte_penalty, fuzzystate)
860  && fuzzy_rte_penalty == 0)
861  {
862  fuzzystate->rfirst = rte;
863  fuzzystate->first = InvalidAttrNumber;
864  fuzzystate->rsecond = NULL;
865  fuzzystate->second = InvalidAttrNumber;
866  return fuzzystate;
867  }
868  }
869 
870  pstate = pstate->parentParseState;
871  }
872 
873  return fuzzystate;
874 }
875 
876 /*
877  * markRTEForSelectPriv
878  * Mark the specified column of an RTE as requiring SELECT privilege
879  *
880  * col == InvalidAttrNumber means a "whole row" reference
881  *
882  * The caller should pass the actual RTE if it has it handy; otherwise pass
883  * NULL, and we'll look it up here. (This uglification of the API is
884  * worthwhile because nearly all external callers have the RTE at hand.)
885  */
886 static void
888  int rtindex, AttrNumber col)
889 {
890  if (rte == NULL)
891  rte = rt_fetch(rtindex, pstate->p_rtable);
892 
893  if (rte->rtekind == RTE_RELATION)
894  {
895  /* Make sure the rel as a whole is marked for SELECT access */
896  rte->requiredPerms |= ACL_SELECT;
897  /* Must offset the attnum to fit in a bitmapset */
900  }
901  else if (rte->rtekind == RTE_JOIN)
902  {
903  if (col == InvalidAttrNumber)
904  {
905  /*
906  * A whole-row reference to a join has to be treated as whole-row
907  * references to the two inputs.
908  */
909  JoinExpr *j;
910 
911  if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
912  j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
913  else
914  j = NULL;
915  if (j == NULL)
916  elog(ERROR, "could not find JoinExpr for whole-row reference");
917  Assert(IsA(j, JoinExpr));
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 VALUES list to the pstate's range table (p_rtable).
1632  *
1633  * This is much like addRangeTableEntry() except that it makes a values RTE.
1634  */
1635 RangeTblEntry *
1637  List *exprs,
1638  List *collations,
1639  Alias *alias,
1640  bool lateral,
1641  bool inFromCl)
1642 {
1644  char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1645  Alias *eref;
1646  int numaliases;
1647  int numcolumns;
1648 
1649  Assert(pstate != NULL);
1650 
1651  rte->rtekind = RTE_VALUES;
1652  rte->relid = InvalidOid;
1653  rte->subquery = NULL;
1654  rte->values_lists = exprs;
1655  rte->values_collations = collations;
1656  rte->alias = alias;
1657 
1658  eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1659 
1660  /* fill in any unspecified alias columns */
1661  numcolumns = list_length((List *) linitial(exprs));
1662  numaliases = list_length(eref->colnames);
1663  while (numaliases < numcolumns)
1664  {
1665  char attrname[64];
1666 
1667  numaliases++;
1668  snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1669  eref->colnames = lappend(eref->colnames,
1670  makeString(pstrdup(attrname)));
1671  }
1672  if (numcolumns < numaliases)
1673  ereport(ERROR,
1674  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1675  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1676  refname, numcolumns, numaliases)));
1677 
1678  rte->eref = eref;
1679 
1680  /*
1681  * Set flags and access permissions.
1682  *
1683  * Subqueries are never checked for access rights.
1684  */
1685  rte->lateral = lateral;
1686  rte->inh = false; /* never true for values RTEs */
1687  rte->inFromCl = inFromCl;
1688 
1689  rte->requiredPerms = 0;
1690  rte->checkAsUser = InvalidOid;
1691  rte->selectedCols = NULL;
1692  rte->insertedCols = NULL;
1693  rte->updatedCols = NULL;
1694 
1695  /*
1696  * Add completed RTE to pstate's range table list, but not to join list
1697  * nor namespace --- caller must do that if appropriate.
1698  */
1699  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1700 
1701  return rte;
1702 }
1703 
1704 /*
1705  * Add an entry for a join to the pstate's range table (p_rtable).
1706  *
1707  * This is much like addRangeTableEntry() except that it makes a join RTE.
1708  */
1709 RangeTblEntry *
1711  List *colnames,
1712  JoinType jointype,
1713  List *aliasvars,
1714  Alias *alias,
1715  bool inFromCl)
1716 {
1718  Alias *eref;
1719  int numaliases;
1720 
1721  Assert(pstate != NULL);
1722 
1723  /*
1724  * Fail if join has too many columns --- we must be able to reference any
1725  * of the columns with an AttrNumber.
1726  */
1727  if (list_length(aliasvars) > MaxAttrNumber)
1728  ereport(ERROR,
1729  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1730  errmsg("joins can have at most %d columns",
1731  MaxAttrNumber)));
1732 
1733  rte->rtekind = RTE_JOIN;
1734  rte->relid = InvalidOid;
1735  rte->subquery = NULL;
1736  rte->jointype = jointype;
1737  rte->joinaliasvars = aliasvars;
1738  rte->alias = alias;
1739 
1740  eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1741  numaliases = list_length(eref->colnames);
1742 
1743  /* fill in any unspecified alias columns */
1744  if (numaliases < list_length(colnames))
1745  eref->colnames = list_concat(eref->colnames,
1746  list_copy_tail(colnames, numaliases));
1747 
1748  rte->eref = eref;
1749 
1750  /*
1751  * Set flags and access permissions.
1752  *
1753  * Joins are never checked for access rights.
1754  */
1755  rte->lateral = false;
1756  rte->inh = false; /* never true for joins */
1757  rte->inFromCl = inFromCl;
1758 
1759  rte->requiredPerms = 0;
1760  rte->checkAsUser = InvalidOid;
1761  rte->selectedCols = NULL;
1762  rte->insertedCols = NULL;
1763  rte->updatedCols = NULL;
1764 
1765  /*
1766  * Add completed RTE to pstate's range table list, but not to join list
1767  * nor namespace --- caller must do that if appropriate.
1768  */
1769  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1770 
1771  return rte;
1772 }
1773 
1774 /*
1775  * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1776  *
1777  * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1778  */
1779 RangeTblEntry *
1781  CommonTableExpr *cte,
1782  Index levelsup,
1783  RangeVar *rv,
1784  bool inFromCl)
1785 {
1787  Alias *alias = rv->alias;
1788  char *refname = alias ? alias->aliasname : cte->ctename;
1789  Alias *eref;
1790  int numaliases;
1791  int varattno;
1792  ListCell *lc;
1793 
1794  Assert(pstate != NULL);
1795 
1796  rte->rtekind = RTE_CTE;
1797  rte->ctename = cte->ctename;
1798  rte->ctelevelsup = levelsup;
1799 
1800  /* Self-reference if and only if CTE's parse analysis isn't completed */
1801  rte->self_reference = !IsA(cte->ctequery, Query);
1802  Assert(cte->cterecursive || !rte->self_reference);
1803  /* Bump the CTE's refcount if this isn't a self-reference */
1804  if (!rte->self_reference)
1805  cte->cterefcount++;
1806 
1807  /*
1808  * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
1809  * This won't get checked in case of a self-reference, but that's OK
1810  * because data-modifying CTEs aren't allowed to be recursive anyhow.
1811  */
1812  if (IsA(cte->ctequery, Query))
1813  {
1814  Query *ctequery = (Query *) cte->ctequery;
1815 
1816  if (ctequery->commandType != CMD_SELECT &&
1817  ctequery->returningList == NIL)
1818  ereport(ERROR,
1819  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1820  errmsg("WITH query \"%s\" does not have a RETURNING clause",
1821  cte->ctename),
1822  parser_errposition(pstate, rv->location)));
1823  }
1824 
1825  rte->ctecoltypes = cte->ctecoltypes;
1826  rte->ctecoltypmods = cte->ctecoltypmods;
1827  rte->ctecolcollations = cte->ctecolcollations;
1828 
1829  rte->alias = alias;
1830  if (alias)
1831  eref = copyObject(alias);
1832  else
1833  eref = makeAlias(refname, NIL);
1834  numaliases = list_length(eref->colnames);
1835 
1836  /* fill in any unspecified alias columns */
1837  varattno = 0;
1838  foreach(lc, cte->ctecolnames)
1839  {
1840  varattno++;
1841  if (varattno > numaliases)
1842  eref->colnames = lappend(eref->colnames, lfirst(lc));
1843  }
1844  if (varattno < numaliases)
1845  ereport(ERROR,
1846  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1847  errmsg("table \"%s\" has %d columns available but %d columns specified",
1848  refname, varattno, numaliases)));
1849 
1850  rte->eref = eref;
1851 
1852  /*
1853  * Set flags and access permissions.
1854  *
1855  * Subqueries are never checked for access rights.
1856  */
1857  rte->lateral = false;
1858  rte->inh = false; /* never true for subqueries */
1859  rte->inFromCl = inFromCl;
1860 
1861  rte->requiredPerms = 0;
1862  rte->checkAsUser = InvalidOid;
1863  rte->selectedCols = NULL;
1864  rte->insertedCols = NULL;
1865  rte->updatedCols = NULL;
1866 
1867  /*
1868  * Add completed RTE to pstate's range table list, but not to join list
1869  * nor namespace --- caller must do that if appropriate.
1870  */
1871  pstate->p_rtable = lappend(pstate->p_rtable, rte);
1872 
1873  return rte;
1874 }
1875 
1876 
1877 /*
1878  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1879  *
1880  * This is used when we have not yet done transformLockingClause, but need
1881  * to know the correct lock to take during initial opening of relations.
1882  *
1883  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1884  * since the table-level lock is the same either way.
1885  */
1886 bool
1887 isLockedRefname(ParseState *pstate, const char *refname)
1888 {
1889  ListCell *l;
1890 
1891  /*
1892  * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1893  * parent level, then act as though there's a generic FOR UPDATE here.
1894  */
1895  if (pstate->p_locked_from_parent)
1896  return true;
1897 
1898  foreach(l, pstate->p_locking_clause)
1899  {
1900  LockingClause *lc = (LockingClause *) lfirst(l);
1901 
1902  if (lc->lockedRels == NIL)
1903  {
1904  /* all tables used in query */
1905  return true;
1906  }
1907  else
1908  {
1909  /* just the named tables */
1910  ListCell *l2;
1911 
1912  foreach(l2, lc->lockedRels)
1913  {
1914  RangeVar *thisrel = (RangeVar *) lfirst(l2);
1915 
1916  if (strcmp(refname, thisrel->relname) == 0)
1917  return true;
1918  }
1919  }
1920  }
1921  return false;
1922 }
1923 
1924 /*
1925  * Add the given RTE as a top-level entry in the pstate's join list
1926  * and/or namespace list. (We assume caller has checked for any
1927  * namespace conflicts.) The RTE is always marked as unconditionally
1928  * visible, that is, not LATERAL-only.
1929  *
1930  * Note: some callers know that they can find the new ParseNamespaceItem
1931  * at the end of the pstate->p_namespace list. This is a bit ugly but not
1932  * worth complicating this function's signature for.
1933  */
1934 void
1936  bool addToJoinList,
1937  bool addToRelNameSpace, bool addToVarNameSpace)
1938 {
1939  if (addToJoinList)
1940  {
1941  int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1943 
1944  rtr->rtindex = rtindex;
1945  pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1946  }
1947  if (addToRelNameSpace || addToVarNameSpace)
1948  {
1949  ParseNamespaceItem *nsitem;
1950 
1951  nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1952  nsitem->p_rte = rte;
1953  nsitem->p_rel_visible = addToRelNameSpace;
1954  nsitem->p_cols_visible = addToVarNameSpace;
1955  nsitem->p_lateral_only = false;
1956  nsitem->p_lateral_ok = true;
1957  pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
1958  }
1959 }
1960 
1961 /*
1962  * expandRTE -- expand the columns of a rangetable entry
1963  *
1964  * This creates lists of an RTE's column names (aliases if provided, else
1965  * real names) and Vars for each column. Only user columns are considered.
1966  * If include_dropped is FALSE then dropped columns are omitted from the
1967  * results. If include_dropped is TRUE then empty strings and NULL constants
1968  * (not Vars!) are returned for dropped columns.
1969  *
1970  * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1971  * values to use in the created Vars. Ordinarily rtindex should match the
1972  * actual position of the RTE in its rangetable.
1973  *
1974  * The output lists go into *colnames and *colvars.
1975  * If only one of the two kinds of output list is needed, pass NULL for the
1976  * output pointer for the unwanted one.
1977  */
1978 void
1979 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1980  int location, bool include_dropped,
1981  List **colnames, List **colvars)
1982 {
1983  int varattno;
1984 
1985  if (colnames)
1986  *colnames = NIL;
1987  if (colvars)
1988  *colvars = NIL;
1989 
1990  switch (rte->rtekind)
1991  {
1992  case RTE_RELATION:
1993  /* Ordinary relation RTE */
1994  expandRelation(rte->relid, rte->eref,
1995  rtindex, sublevels_up, location,
1996  include_dropped, colnames, colvars);
1997  break;
1998  case RTE_SUBQUERY:
1999  {
2000  /* Subquery RTE */
2001  ListCell *aliasp_item = list_head(rte->eref->colnames);
2002  ListCell *tlistitem;
2003 
2004  varattno = 0;
2005  foreach(tlistitem, rte->subquery->targetList)
2006  {
2007  TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
2008 
2009  if (te->resjunk)
2010  continue;
2011  varattno++;
2012  Assert(varattno == te->resno);
2013 
2014  if (colnames)
2015  {
2016  /* Assume there is one alias per target item */
2017  char *label = strVal(lfirst(aliasp_item));
2018 
2019  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2020  aliasp_item = lnext(aliasp_item);
2021  }
2022 
2023  if (colvars)
2024  {
2025  Var *varnode;
2026 
2027  varnode = makeVar(rtindex, varattno,
2028  exprType((Node *) te->expr),
2029  exprTypmod((Node *) te->expr),
2030  exprCollation((Node *) te->expr),
2031  sublevels_up);
2032  varnode->location = location;
2033 
2034  *colvars = lappend(*colvars, varnode);
2035  }
2036  }
2037  }
2038  break;
2039  case RTE_FUNCTION:
2040  {
2041  /* Function RTE */
2042  int atts_done = 0;
2043  ListCell *lc;
2044 
2045  foreach(lc, rte->functions)
2046  {
2047  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2048  TypeFuncClass functypclass;
2049  Oid funcrettype;
2050  TupleDesc tupdesc;
2051 
2052  functypclass = get_expr_result_type(rtfunc->funcexpr,
2053  &funcrettype,
2054  &tupdesc);
2055  if (functypclass == TYPEFUNC_COMPOSITE)
2056  {
2057  /* Composite data type, e.g. a table's row type */
2058  Assert(tupdesc);
2059  expandTupleDesc(tupdesc, rte->eref,
2060  rtfunc->funccolcount, atts_done,
2061  rtindex, sublevels_up, location,
2062  include_dropped, colnames, colvars);
2063  }
2064  else if (functypclass == TYPEFUNC_SCALAR)
2065  {
2066  /* Base data type, i.e. scalar */
2067  if (colnames)
2068  *colnames = lappend(*colnames,
2069  list_nth(rte->eref->colnames,
2070  atts_done));
2071 
2072  if (colvars)
2073  {
2074  Var *varnode;
2075 
2076  varnode = makeVar(rtindex, atts_done + 1,
2077  funcrettype, -1,
2078  exprCollation(rtfunc->funcexpr),
2079  sublevels_up);
2080  varnode->location = location;
2081 
2082  *colvars = lappend(*colvars, varnode);
2083  }
2084  }
2085  else if (functypclass == TYPEFUNC_RECORD)
2086  {
2087  if (colnames)
2088  {
2089  List *namelist;
2090 
2091  /* extract appropriate subset of column list */
2092  namelist = list_copy_tail(rte->eref->colnames,
2093  atts_done);
2094  namelist = list_truncate(namelist,
2095  rtfunc->funccolcount);
2096  *colnames = list_concat(*colnames, namelist);
2097  }
2098 
2099  if (colvars)
2100  {
2101  ListCell *l1;
2102  ListCell *l2;
2103  ListCell *l3;
2104  int attnum = atts_done;
2105 
2106  forthree(l1, rtfunc->funccoltypes,
2107  l2, rtfunc->funccoltypmods,
2108  l3, rtfunc->funccolcollations)
2109  {
2110  Oid attrtype = lfirst_oid(l1);
2111  int32 attrtypmod = lfirst_int(l2);
2112  Oid attrcollation = lfirst_oid(l3);
2113  Var *varnode;
2114 
2115  attnum++;
2116  varnode = makeVar(rtindex,
2117  attnum,
2118  attrtype,
2119  attrtypmod,
2120  attrcollation,
2121  sublevels_up);
2122  varnode->location = location;
2123  *colvars = lappend(*colvars, varnode);
2124  }
2125  }
2126  }
2127  else
2128  {
2129  /* addRangeTableEntryForFunction should've caught this */
2130  elog(ERROR, "function in FROM has unsupported return type");
2131  }
2132  atts_done += rtfunc->funccolcount;
2133  }
2134 
2135  /* Append the ordinality column if any */
2136  if (rte->funcordinality)
2137  {
2138  if (colnames)
2139  *colnames = lappend(*colnames,
2140  llast(rte->eref->colnames));
2141 
2142  if (colvars)
2143  {
2144  Var *varnode = makeVar(rtindex,
2145  atts_done + 1,
2146  INT8OID,
2147  -1,
2148  InvalidOid,
2149  sublevels_up);
2150 
2151  *colvars = lappend(*colvars, varnode);
2152  }
2153  }
2154  }
2155  break;
2156  case RTE_VALUES:
2157  {
2158  /* Values RTE */
2159  ListCell *aliasp_item = list_head(rte->eref->colnames);
2160  ListCell *lcv;
2161  ListCell *lcc;
2162 
2163  varattno = 0;
2164  forboth(lcv, (List *) linitial(rte->values_lists),
2165  lcc, rte->values_collations)
2166  {
2167  Node *col = (Node *) lfirst(lcv);
2168  Oid colcollation = lfirst_oid(lcc);
2169 
2170  varattno++;
2171  if (colnames)
2172  {
2173  /* Assume there is one alias per column */
2174  char *label = strVal(lfirst(aliasp_item));
2175 
2176  *colnames = lappend(*colnames,
2177  makeString(pstrdup(label)));
2178  aliasp_item = lnext(aliasp_item);
2179  }
2180 
2181  if (colvars)
2182  {
2183  Var *varnode;
2184 
2185  varnode = makeVar(rtindex, varattno,
2186  exprType(col),
2187  exprTypmod(col),
2188  colcollation,
2189  sublevels_up);
2190  varnode->location = location;
2191  *colvars = lappend(*colvars, varnode);
2192  }
2193  }
2194  }
2195  break;
2196  case RTE_JOIN:
2197  {
2198  /* Join RTE */
2199  ListCell *colname;
2200  ListCell *aliasvar;
2201 
2203 
2204  varattno = 0;
2205  forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
2206  {
2207  Node *avar = (Node *) lfirst(aliasvar);
2208 
2209  varattno++;
2210 
2211  /*
2212  * During ordinary parsing, there will never be any
2213  * deleted columns in the join; but we have to check since
2214  * this routine is also used by the rewriter, and joins
2215  * found in stored rules might have join columns for
2216  * since-deleted columns. This will be signaled by a null
2217  * pointer in the alias-vars list.
2218  */
2219  if (avar == NULL)
2220  {
2221  if (include_dropped)
2222  {
2223  if (colnames)
2224  *colnames = lappend(*colnames,
2225  makeString(pstrdup("")));
2226  if (colvars)
2227  {
2228  /*
2229  * Can't use join's column type here (it might
2230  * be dropped!); but it doesn't really matter
2231  * what type the Const claims to be.
2232  */
2233  *colvars = lappend(*colvars,
2234  makeNullConst(INT4OID, -1,
2235  InvalidOid));
2236  }
2237  }
2238  continue;
2239  }
2240 
2241  if (colnames)
2242  {
2243  char *label = strVal(lfirst(colname));
2244 
2245  *colnames = lappend(*colnames,
2246  makeString(pstrdup(label)));
2247  }
2248 
2249  if (colvars)
2250  {
2251  Var *varnode;
2252 
2253  varnode = makeVar(rtindex, varattno,
2254  exprType(avar),
2255  exprTypmod(avar),
2256  exprCollation(avar),
2257  sublevels_up);
2258  varnode->location = location;
2259 
2260  *colvars = lappend(*colvars, varnode);
2261  }
2262  }
2263  }
2264  break;
2265  case RTE_CTE:
2266  {
2267  ListCell *aliasp_item = list_head(rte->eref->colnames);
2268  ListCell *lct;
2269  ListCell *lcm;
2270  ListCell *lcc;
2271 
2272  varattno = 0;
2273  forthree(lct, rte->ctecoltypes,
2274  lcm, rte->ctecoltypmods,
2275  lcc, rte->ctecolcollations)
2276  {
2277  Oid coltype = lfirst_oid(lct);
2278  int32 coltypmod = lfirst_int(lcm);
2279  Oid colcoll = lfirst_oid(lcc);
2280 
2281  varattno++;
2282 
2283  if (colnames)
2284  {
2285  /* Assume there is one alias per output column */
2286  char *label = strVal(lfirst(aliasp_item));
2287 
2288  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2289  aliasp_item = lnext(aliasp_item);
2290  }
2291 
2292  if (colvars)
2293  {
2294  Var *varnode;
2295 
2296  varnode = makeVar(rtindex, varattno,
2297  coltype, coltypmod, colcoll,
2298  sublevels_up);
2299  *colvars = lappend(*colvars, varnode);
2300  }
2301  }
2302  }
2303  break;
2304  default:
2305  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2306  }
2307 }
2308 
2309 /*
2310  * expandRelation -- expandRTE subroutine
2311  */
2312 static void
2313 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
2314  int location, bool include_dropped,
2315  List **colnames, List **colvars)
2316 {
2317  Relation rel;
2318 
2319  /* Get the tupledesc and turn it over to expandTupleDesc */
2320  rel = relation_open(relid, AccessShareLock);
2321  expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
2322  rtindex, sublevels_up,
2323  location, include_dropped,
2324  colnames, colvars);
2326 }
2327 
2328 /*
2329  * expandTupleDesc -- expandRTE subroutine
2330  *
2331  * Generate names and/or Vars for the first "count" attributes of the tupdesc,
2332  * and append them to colnames/colvars. "offset" is added to the varattno
2333  * that each Var would otherwise have, and we also skip the first "offset"
2334  * entries in eref->colnames. (These provisions allow use of this code for
2335  * an individual composite-returning function in an RTE_FUNCTION RTE.)
2336  */
2337 static void
2338 expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset,
2339  int rtindex, int sublevels_up,
2340  int location, bool include_dropped,
2341  List **colnames, List **colvars)
2342 {
2343  ListCell *aliascell = list_head(eref->colnames);
2344  int varattno;
2345 
2346  if (colnames)
2347  {
2348  int i;
2349 
2350  for (i = 0; i < offset; i++)
2351  {
2352  if (aliascell)
2353  aliascell = lnext(aliascell);
2354  }
2355  }
2356 
2357  Assert(count <= tupdesc->natts);
2358  for (varattno = 0; varattno < count; varattno++)
2359  {
2360  Form_pg_attribute attr = tupdesc->attrs[varattno];
2361 
2362  if (attr->attisdropped)
2363  {
2364  if (include_dropped)
2365  {
2366  if (colnames)
2367  *colnames = lappend(*colnames, makeString(pstrdup("")));
2368  if (colvars)
2369  {
2370  /*
2371  * can't use atttypid here, but it doesn't really matter
2372  * what type the Const claims to be.
2373  */
2374  *colvars = lappend(*colvars,
2376  }
2377  }
2378  if (aliascell)
2379  aliascell = lnext(aliascell);
2380  continue;
2381  }
2382 
2383  if (colnames)
2384  {
2385  char *label;
2386 
2387  if (aliascell)
2388  {
2389  label = strVal(lfirst(aliascell));
2390  aliascell = lnext(aliascell);
2391  }
2392  else
2393  {
2394  /* If we run out of aliases, use the underlying name */
2395  label = NameStr(attr->attname);
2396  }
2397  *colnames = lappend(*colnames, makeString(pstrdup(label)));
2398  }
2399 
2400  if (colvars)
2401  {
2402  Var *varnode;
2403 
2404  varnode = makeVar(rtindex, varattno + offset + 1,
2405  attr->atttypid, attr->atttypmod,
2406  attr->attcollation,
2407  sublevels_up);
2408  varnode->location = location;
2409 
2410  *colvars = lappend(*colvars, varnode);
2411  }
2412  }
2413 }
2414 
2415 /*
2416  * expandRelAttrs -
2417  * Workhorse for "*" expansion: produce a list of targetentries
2418  * for the attributes of the RTE
2419  *
2420  * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
2421  * fields of the Vars produced, and location sets their location.
2422  * pstate->p_next_resno determines the resnos assigned to the TLEs.
2423  * The referenced columns are marked as requiring SELECT access.
2424  */
2425 List *
2427  int rtindex, int sublevels_up, int location)
2428 {
2429  List *names,
2430  *vars;
2431  ListCell *name,
2432  *var;
2433  List *te_list = NIL;
2434 
2435  expandRTE(rte, rtindex, sublevels_up, location, false,
2436  &names, &vars);
2437 
2438  /*
2439  * Require read access to the table. This is normally redundant with the
2440  * markVarForSelectPriv calls below, but not if the table has zero
2441  * columns.
2442  */
2443  rte->requiredPerms |= ACL_SELECT;
2444 
2445  forboth(name, names, var, vars)
2446  {
2447  char *label = strVal(lfirst(name));
2448  Var *varnode = (Var *) lfirst(var);
2449  TargetEntry *te;
2450 
2451  te = makeTargetEntry((Expr *) varnode,
2452  (AttrNumber) pstate->p_next_resno++,
2453  label,
2454  false);
2455  te_list = lappend(te_list, te);
2456 
2457  /* Require read access to each column */
2458  markVarForSelectPriv(pstate, varnode, rte);
2459  }
2460 
2461  Assert(name == NULL && var == NULL); /* lists not the same length? */
2462 
2463  return te_list;
2464 }
2465 
2466 /*
2467  * get_rte_attribute_name
2468  * Get an attribute name from a RangeTblEntry
2469  *
2470  * This is unlike get_attname() because we use aliases if available.
2471  * In particular, it will work on an RTE for a subselect or join, whereas
2472  * get_attname() only works on real relations.
2473  *
2474  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
2475  * occurs when a Var represents a whole tuple of a relation.
2476  */
2477 char *
2479 {
2480  if (attnum == InvalidAttrNumber)
2481  return "*";
2482 
2483  /*
2484  * If there is a user-written column alias, use it.
2485  */
2486  if (rte->alias &&
2487  attnum > 0 && attnum <= list_length(rte->alias->colnames))
2488  return strVal(list_nth(rte->alias->colnames, attnum - 1));
2489 
2490  /*
2491  * If the RTE is a relation, go to the system catalogs not the
2492  * eref->colnames list. This is a little slower but it will give the
2493  * right answer if the column has been renamed since the eref list was
2494  * built (which can easily happen for rules).
2495  */
2496  if (rte->rtekind == RTE_RELATION)
2497  return get_relid_attribute_name(rte->relid, attnum);
2498 
2499  /*
2500  * Otherwise use the column name from eref. There should always be one.
2501  */
2502  if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2503  return strVal(list_nth(rte->eref->colnames, attnum - 1));
2504 
2505  /* else caller gave us a bogus attnum */
2506  elog(ERROR, "invalid attnum %d for rangetable entry %s",
2507  attnum, rte->eref->aliasname);
2508  return NULL; /* keep compiler quiet */
2509 }
2510 
2511 /*
2512  * get_rte_attribute_type
2513  * Get attribute type/typmod/collation information from a RangeTblEntry
2514  */
2515 void
2517  Oid *vartype, int32 *vartypmod, Oid *varcollid)
2518 {
2519  switch (rte->rtekind)
2520  {
2521  case RTE_RELATION:
2522  {
2523  /* Plain relation RTE --- get the attribute's type info */
2524  HeapTuple tp;
2525  Form_pg_attribute att_tup;
2526 
2527  tp = SearchSysCache2(ATTNUM,
2528  ObjectIdGetDatum(rte->relid),
2529  Int16GetDatum(attnum));
2530  if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2531  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2532  attnum, rte->relid);
2533  att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2534 
2535  /*
2536  * If dropped column, pretend it ain't there. See notes in
2537  * scanRTEForColumn.
2538  */
2539  if (att_tup->attisdropped)
2540  ereport(ERROR,
2541  (errcode(ERRCODE_UNDEFINED_COLUMN),
2542  errmsg("column \"%s\" of relation \"%s\" does not exist",
2543  NameStr(att_tup->attname),
2544  get_rel_name(rte->relid))));
2545  *vartype = att_tup->atttypid;
2546  *vartypmod = att_tup->atttypmod;
2547  *varcollid = att_tup->attcollation;
2548  ReleaseSysCache(tp);
2549  }
2550  break;
2551  case RTE_SUBQUERY:
2552  {
2553  /* Subselect RTE --- get type info from subselect's tlist */
2555  attnum);
2556 
2557  if (te == NULL || te->resjunk)
2558  elog(ERROR, "subquery %s does not have attribute %d",
2559  rte->eref->aliasname, attnum);
2560  *vartype = exprType((Node *) te->expr);
2561  *vartypmod = exprTypmod((Node *) te->expr);
2562  *varcollid = exprCollation((Node *) te->expr);
2563  }
2564  break;
2565  case RTE_FUNCTION:
2566  {
2567  /* Function RTE */
2568  ListCell *lc;
2569  int atts_done = 0;
2570 
2571  /* Identify which function covers the requested column */
2572  foreach(lc, rte->functions)
2573  {
2574  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2575 
2576  if (attnum > atts_done &&
2577  attnum <= atts_done + rtfunc->funccolcount)
2578  {
2579  TypeFuncClass functypclass;
2580  Oid funcrettype;
2581  TupleDesc tupdesc;
2582 
2583  attnum -= atts_done; /* now relative to this func */
2584  functypclass = get_expr_result_type(rtfunc->funcexpr,
2585  &funcrettype,
2586  &tupdesc);
2587 
2588  if (functypclass == TYPEFUNC_COMPOSITE)
2589  {
2590  /* Composite data type, e.g. a table's row type */
2591  Form_pg_attribute att_tup;
2592 
2593  Assert(tupdesc);
2594  Assert(attnum <= tupdesc->natts);
2595  att_tup = tupdesc->attrs[attnum - 1];
2596 
2597  /*
2598  * If dropped column, pretend it ain't there. See
2599  * notes in scanRTEForColumn.
2600  */
2601  if (att_tup->attisdropped)
2602  ereport(ERROR,
2603  (errcode(ERRCODE_UNDEFINED_COLUMN),
2604  errmsg("column \"%s\" of relation \"%s\" does not exist",
2605  NameStr(att_tup->attname),
2606  rte->eref->aliasname)));
2607  *vartype = att_tup->atttypid;
2608  *vartypmod = att_tup->atttypmod;
2609  *varcollid = att_tup->attcollation;
2610  }
2611  else if (functypclass == TYPEFUNC_SCALAR)
2612  {
2613  /* Base data type, i.e. scalar */
2614  *vartype = funcrettype;
2615  *vartypmod = -1;
2616  *varcollid = exprCollation(rtfunc->funcexpr);
2617  }
2618  else if (functypclass == TYPEFUNC_RECORD)
2619  {
2620  *vartype = list_nth_oid(rtfunc->funccoltypes,
2621  attnum - 1);
2622  *vartypmod = list_nth_int(rtfunc->funccoltypmods,
2623  attnum - 1);
2624  *varcollid = list_nth_oid(rtfunc->funccolcollations,
2625  attnum - 1);
2626  }
2627  else
2628  {
2629  /*
2630  * addRangeTableEntryForFunction should've caught
2631  * this
2632  */
2633  elog(ERROR, "function in FROM has unsupported return type");
2634  }
2635  return;
2636  }
2637  atts_done += rtfunc->funccolcount;
2638  }
2639 
2640  /* If we get here, must be looking for the ordinality column */
2641  if (rte->funcordinality && attnum == atts_done + 1)
2642  {
2643  *vartype = INT8OID;
2644  *vartypmod = -1;
2645  *varcollid = InvalidOid;
2646  return;
2647  }
2648 
2649  /* this probably can't happen ... */
2650  ereport(ERROR,
2651  (errcode(ERRCODE_UNDEFINED_COLUMN),
2652  errmsg("column %d of relation \"%s\" does not exist",
2653  attnum,
2654  rte->eref->aliasname)));
2655  }
2656  break;
2657  case RTE_VALUES:
2658  {
2659  /* Values RTE --- get type info from first sublist */
2660  /* collation is stored separately, though */
2661  List *collist = (List *) linitial(rte->values_lists);
2662  Node *col;
2663 
2664  if (attnum < 1 || attnum > list_length(collist))
2665  elog(ERROR, "values list %s does not have attribute %d",
2666  rte->eref->aliasname, attnum);
2667  col = (Node *) list_nth(collist, attnum - 1);
2668  *vartype = exprType(col);
2669  *vartypmod = exprTypmod(col);
2670  *varcollid = list_nth_oid(rte->values_collations, attnum - 1);
2671  }
2672  break;
2673  case RTE_JOIN:
2674  {
2675  /*
2676  * Join RTE --- get type info from join RTE's alias variable
2677  */
2678  Node *aliasvar;
2679 
2680  Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2681  aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2682  Assert(aliasvar != NULL);
2683  *vartype = exprType(aliasvar);
2684  *vartypmod = exprTypmod(aliasvar);
2685  *varcollid = exprCollation(aliasvar);
2686  }
2687  break;
2688  case RTE_CTE:
2689  {
2690  /* CTE RTE --- get type info from lists in the RTE */
2691  Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2692  *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2693  *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2694  *varcollid = list_nth_oid(rte->ctecolcollations, attnum - 1);
2695  }
2696  break;
2697  default:
2698  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2699  }
2700 }
2701 
2702 /*
2703  * get_rte_attribute_is_dropped
2704  * Check whether attempted attribute ref is to a dropped column
2705  */
2706 bool
2708 {
2709  bool result;
2710 
2711  switch (rte->rtekind)
2712  {
2713  case RTE_RELATION:
2714  {
2715  /*
2716  * Plain relation RTE --- get the attribute's catalog entry
2717  */
2718  HeapTuple tp;
2719  Form_pg_attribute att_tup;
2720 
2721  tp = SearchSysCache2(ATTNUM,
2722  ObjectIdGetDatum(rte->relid),
2723  Int16GetDatum(attnum));
2724  if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2725  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2726  attnum, rte->relid);
2727  att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2728  result = att_tup->attisdropped;
2729  ReleaseSysCache(tp);
2730  }
2731  break;
2732  case RTE_SUBQUERY:
2733  case RTE_VALUES:
2734  case RTE_CTE:
2735  /* Subselect, Values, CTE RTEs never have dropped columns */
2736  result = false;
2737  break;
2738  case RTE_JOIN:
2739  {
2740  /*
2741  * A join RTE would not have dropped columns when constructed,
2742  * but one in a stored rule might contain columns that were
2743  * dropped from the underlying tables, if said columns are
2744  * nowhere explicitly referenced in the rule. This will be
2745  * signaled to us by a null pointer in the joinaliasvars list.
2746  */
2747  Var *aliasvar;
2748 
2749  if (attnum <= 0 ||
2750  attnum > list_length(rte->joinaliasvars))
2751  elog(ERROR, "invalid varattno %d", attnum);
2752  aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2753 
2754  result = (aliasvar == NULL);
2755  }
2756  break;
2757  case RTE_FUNCTION:
2758  {
2759  /* Function RTE */
2760  ListCell *lc;
2761  int atts_done = 0;
2762 
2763  /*
2764  * Dropped attributes are only possible with functions that
2765  * return named composite types. In such a case we have to
2766  * look up the result type to see if it currently has this
2767  * column dropped. So first, loop over the funcs until we
2768  * find the one that covers the requested column.
2769  */
2770  foreach(lc, rte->functions)
2771  {
2772  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2773 
2774  if (attnum > atts_done &&
2775  attnum <= atts_done + rtfunc->funccolcount)
2776  {
2777  TypeFuncClass functypclass;
2778  Oid funcrettype;
2779  TupleDesc tupdesc;
2780 
2781  functypclass = get_expr_result_type(rtfunc->funcexpr,
2782  &funcrettype,
2783  &tupdesc);
2784  if (functypclass == TYPEFUNC_COMPOSITE)
2785  {
2786  /* Composite data type, e.g. a table's row type */
2787  Form_pg_attribute att_tup;
2788 
2789  Assert(tupdesc);
2790  Assert(attnum - atts_done <= tupdesc->natts);
2791  att_tup = tupdesc->attrs[attnum - atts_done - 1];
2792  return att_tup->attisdropped;
2793  }
2794  /* Otherwise, it can't have any dropped columns */
2795  return false;
2796  }
2797  atts_done += rtfunc->funccolcount;
2798  }
2799 
2800  /* If we get here, must be looking for the ordinality column */
2801  if (rte->funcordinality && attnum == atts_done + 1)
2802  return false;
2803 
2804  /* this probably can't happen ... */
2805  ereport(ERROR,
2806  (errcode(ERRCODE_UNDEFINED_COLUMN),
2807  errmsg("column %d of relation \"%s\" does not exist",
2808  attnum,
2809  rte->eref->aliasname)));
2810  result = false; /* keep compiler quiet */
2811  }
2812  break;
2813  default:
2814  elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2815  result = false; /* keep compiler quiet */
2816  }
2817 
2818  return result;
2819 }
2820 
2821 /*
2822  * Given a targetlist and a resno, return the matching TargetEntry
2823  *
2824  * Returns NULL if resno is not present in list.
2825  *
2826  * Note: we need to search, rather than just indexing with list_nth(),
2827  * because not all tlists are sorted by resno.
2828  */
2829 TargetEntry *
2831 {
2832  ListCell *l;
2833 
2834  foreach(l, tlist)
2835  {
2836  TargetEntry *tle = (TargetEntry *) lfirst(l);
2837 
2838  if (tle->resno == resno)
2839  return tle;
2840  }
2841  return NULL;
2842 }
2843 
2844 /*
2845  * Given a Query and rangetable index, return relation's RowMarkClause if any
2846  *
2847  * Returns NULL if relation is not selected FOR UPDATE/SHARE
2848  */
2849 RowMarkClause *
2851 {
2852  ListCell *l;
2853 
2854  foreach(l, qry->rowMarks)
2855  {
2856  RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2857 
2858  if (rc->rti == rtindex)
2859  return rc;
2860  }
2861  return NULL;
2862 }
2863 
2864 /*
2865  * given relation and att name, return attnum of variable
2866  *
2867  * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2868  *
2869  * This should only be used if the relation is already
2870  * heap_open()'ed. Use the cache version get_attnum()
2871  * for access to non-opened relations.
2872  */
2873 int
2874 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2875 {
2876  int i;
2877 
2878  for (i = 0; i < rd->rd_rel->relnatts; i++)
2879  {
2880  Form_pg_attribute att = rd->rd_att->attrs[i];
2881 
2882  if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2883  return i + 1;
2884  }
2885 
2886  if (sysColOK)
2887  {
2888  if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2889  {
2890  if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2891  return i;
2892  }
2893  }
2894 
2895  /* on failure */
2896  return InvalidAttrNumber;
2897 }
2898 
2899 /* specialAttNum()
2900  *
2901  * Check attribute name to see if it is "special", e.g. "oid".
2902  * - thomas 2000-02-07
2903  *
2904  * Note: this only discovers whether the name could be a system attribute.
2905  * Caller needs to verify that it really is an attribute of the rel,
2906  * at least in the case of "oid", which is now optional.
2907  */
2908 static int
2909 specialAttNum(const char *attname)
2910 {
2911  Form_pg_attribute sysatt;
2912 
2913  sysatt = SystemAttributeByName(attname,
2914  true /* "oid" will be accepted */ );
2915  if (sysatt != NULL)
2916  return sysatt->attnum;
2917  return InvalidAttrNumber;
2918 }
2919 
2920 
2921 /*
2922  * given attribute id, return name of that attribute
2923  *
2924  * This should only be used if the relation is already
2925  * heap_open()'ed. Use the cache version get_atttype()
2926  * for access to non-opened relations.
2927  */
2928 Name
2929 attnumAttName(Relation rd, int attid)
2930 {
2931  if (attid <= 0)
2932  {
2933  Form_pg_attribute sysatt;
2934 
2935  sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2936  return &sysatt->attname;
2937  }
2938  if (attid > rd->rd_att->natts)
2939  elog(ERROR, "invalid attribute number %d", attid);
2940  return &rd->rd_att->attrs[attid - 1]->attname;
2941 }
2942 
2943 /*
2944  * given attribute id, return type of that attribute
2945  *
2946  * This should only be used if the relation is already
2947  * heap_open()'ed. Use the cache version get_atttype()
2948  * for access to non-opened relations.
2949  */
2950 Oid
2951 attnumTypeId(Relation rd, int attid)
2952 {
2953  if (attid <= 0)
2954  {
2955  Form_pg_attribute sysatt;
2956 
2957  sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2958  return sysatt->atttypid;
2959  }
2960  if (attid > rd->rd_att->natts)
2961  elog(ERROR, "invalid attribute number %d", attid);
2962  return rd->rd_att->attrs[attid - 1]->atttypid;
2963 }
2964 
2965 /*
2966  * given attribute id, return collation of that attribute
2967  *
2968  * This should only be used if the relation is already heap_open()'ed.
2969  */
2970 Oid
2972 {
2973  if (attid <= 0)
2974  {
2975  /* All system attributes are of noncollatable types. */
2976  return InvalidOid;
2977  }
2978  if (attid > rd->rd_att->natts)
2979  elog(ERROR, "invalid attribute number %d", attid);
2980  return rd->rd_att->attrs[attid - 1]->attcollation;
2981 }
2982 
2983 /*
2984  * Generate a suitable error about a missing RTE.
2985  *
2986  * Since this is a very common type of error, we work rather hard to
2987  * produce a helpful message.
2988  */
2989 void
2991 {
2992  RangeTblEntry *rte;
2993  int sublevels_up;
2994  const char *badAlias = NULL;
2995 
2996  /*
2997  * Check to see if there are any potential matches in the query's
2998  * rangetable. (Note: cases involving a bad schema name in the RangeVar
2999  * will throw error immediately here. That seems OK.)
3000  */
3001  rte = searchRangeTableForRel(pstate, relation);
3002 
3003  /*
3004  * If we found a match that has an alias and the alias is visible in the
3005  * namespace, then the problem is probably use of the relation's real name
3006  * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
3007  * common enough to justify a specific hint.
3008  *
3009  * If we found a match that doesn't meet those criteria, assume the
3010  * problem is illegal use of a relation outside its scope, as in the
3011  * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
3012  */
3013  if (rte && rte->alias &&
3014  strcmp(rte->eref->aliasname, relation->relname) != 0 &&
3015  refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
3016  relation->location,
3017  &sublevels_up) == rte)
3018  badAlias = rte->eref->aliasname;
3019 
3020  if (rte)
3021  ereport(ERROR,
3023  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
3024  relation->relname),
3025  (badAlias ?
3026  errhint("Perhaps you meant to reference the table alias \"%s\".",
3027  badAlias) :
3028  errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
3029  rte->eref->aliasname)),
3030  parser_errposition(pstate, relation->location)));
3031  else
3032  ereport(ERROR,
3034  errmsg("missing FROM-clause entry for table \"%s\"",
3035  relation->relname),
3036  parser_errposition(pstate, relation->location)));
3037 }
3038 
3039 /*
3040  * Generate a suitable error about a missing column.
3041  *
3042  * Since this is a very common type of error, we work rather hard to
3043  * produce a helpful message.
3044  */
3045 void
3047  char *relname, char *colname, int location)
3048 {
3050  char *closestfirst = NULL;
3051 
3052  /*
3053  * Search the entire rtable looking for possible matches. If we find one,
3054  * emit a hint about it.
3055  *
3056  * TODO: improve this code (and also errorMissingRTE) to mention using
3057  * LATERAL if appropriate.
3058  */
3059  state = searchRangeTableForCol(pstate, relname, colname, location);
3060 
3061  /*
3062  * Extract closest col string for best match, if any.
3063  *
3064  * Infer an exact match referenced despite not being visible from the fact
3065  * that an attribute number was not present in state passed back -- this
3066  * is what is reported when !closestfirst. There might also be an exact
3067  * match that was qualified with an incorrect alias, in which case
3068  * closestfirst will be set (so hint is the same as generic fuzzy case).
3069  */
3070  if (state->rfirst && AttributeNumberIsValid(state->first))
3071  closestfirst = strVal(list_nth(state->rfirst->eref->colnames,
3072  state->first - 1));
3073 
3074  if (!state->rsecond)
3075  {
3076  /*
3077  * Handle case where there is zero or one column suggestions to hint,
3078  * including exact matches referenced but not visible.
3079  */
3080  ereport(ERROR,
3081  (errcode(ERRCODE_UNDEFINED_COLUMN),
3082  relname ?
3083  errmsg("column %s.%s does not exist", relname, colname) :
3084  errmsg("column \"%s\" does not exist", colname),
3085  state->rfirst ? closestfirst ?
3086  errhint("Perhaps you meant to reference the column \"%s.%s\".",
3087  state->rfirst->eref->aliasname, closestfirst) :
3088  errhint("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
3089  colname, state->rfirst->eref->aliasname) : 0,
3090  parser_errposition(pstate, location)));
3091  }
3092  else
3093  {
3094  /* Handle case where there are two equally useful column hints */
3095  char *closestsecond;
3096 
3097  closestsecond = strVal(list_nth(state->rsecond->eref->colnames,
3098  state->second - 1));
3099 
3100  ereport(ERROR,
3101  (errcode(ERRCODE_UNDEFINED_COLUMN),
3102  relname ?
3103  errmsg("column %s.%s does not exist", relname, colname) :
3104  errmsg("column \"%s\" does not exist", colname),
3105  errhint("Perhaps you meant to reference the column \"%s.%s\" or the column \"%s.%s\".",
3106  state->rfirst->eref->aliasname, closestfirst,
3107  state->rsecond->eref->aliasname, closestsecond),
3108  parser_errposition(pstate, location)));
3109  }
3110 }
3111 
3112 
3113 /*
3114  * Examine a fully-parsed query, and return TRUE iff any relation underlying
3115  * the query is a temporary relation (table, view, or materialized view).
3116  */
3117 bool
3119 {
3120  return isQueryUsingTempRelation_walker((Node *) query, NULL);
3121 }
3122 
3123 static bool
3125 {
3126  if (node == NULL)
3127  return false;
3128 
3129  if (IsA(node, Query))
3130  {
3131  Query *query = (Query *) node;
3132  ListCell *rtable;
3133 
3134  foreach(rtable, query->rtable)
3135  {
3136  RangeTblEntry *rte = lfirst(rtable);
3137 
3138  if (rte->rtekind == RTE_RELATION)
3139  {
3140  Relation rel = heap_open(rte->relid, AccessShareLock);
3141  char relpersistence = rel->rd_rel->relpersistence;
3142 
3144  if (relpersistence == RELPERSISTENCE_TEMP)
3145  return true;
3146  }
3147  }
3148 
3149  return query_tree_walker(query,
3151  context,
3153  }
3154 
3155  return expression_tree_walker(node,
3157  context);
3158 }
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:682
#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:2041
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:542
#define IsA(nodeptr, _type_)
Definition: nodes.h:542
List * joinaliasvars
Definition: parsenodes.h:830
Index varlevelsup
Definition: primnodes.h:158
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:631
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:60
bool isQueryUsingTempRelation(Query *query)
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1195
void CheckAttributeNamesTypes(TupleDesc tupdesc, char relkind, bool allow_system_table_mods)
Definition: heap.c:403
RangeTblEntry * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, JoinType jointype, List *aliasvars, Alias *alias, bool inFromCl)
Alias * alias
Definition: parsenodes.h:862
List * colnames
Definition: primnodes.h:42
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)
int LOCKMODE
Definition: lockdefs.h:26
void markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:270
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:1168
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:459
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:208
#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)
List * ctecoltypmods
Definition: parsenodes.h:856
Definition: nodes.h:491
#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:1274
AttrNumber varattno
Definition: primnodes.h:153
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
List * list_concat(List *list1, List *list2)
Definition: list.c:321
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:867
#define heap_close(r, l)
Definition: heapam.h:97
List * funccolnames
Definition: parsenodes.h:898
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
bool funcordinality
Definition: parsenodes.h:841
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:152
char * resname
Definition: primnodes.h:1282
Definition: primnodes.h:148
List * ctecoltypes
Definition: parsenodes.h:855
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:228
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:530
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:846
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:160
signed int int32
Definition: c.h:253
JoinType
Definition: nodes.h:627
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:156
char * schemaname
Definition: primnodes.h:73
void * copyObject(const void *from)
Definition: copyfuncs.c:4262
Node * larg
Definition: primnodes.h:1363
Definition: type.h:90
static char * relname(char const *dir, char const *base)
Definition: zic.c:755
int location
Definition: primnodes.h:79
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
char * relname
Definition: primnodes.h:74
Relation heap_openrv_extended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok)
Definition: heapam.c:1355
RangeTblEntry * p_rte
Definition: parse_node.h:200
Bitmapset * selectedCols
Definition: parsenodes.h:869
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:158
bool resjunk
Definition: primnodes.h:1287
#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:515
#define ERROR
Definition: elog.h:43
static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem, int location)
#define lfirst_int(lc)
Definition: pg_list.h:107
void TupleDescCopyEntry(TupleDesc dst, AttrNumber dstAttno, TupleDesc src, AttrNumber srcAttno)
Definition: tupdesc.c:228
bool setof
Definition: parsenodes.h:193
RangeTblEntry * rfirst
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition: tupdesc.c:563
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1651
Definition: c.h:488
int location
Definition: primnodes.h:163
List * p_namespace
Definition: parse_node.h:139
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:829
int errdetail(const char *fmt,...)
Definition: elog.c:873
AttrNumber resno
Definition: primnodes.h:1281
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:147
#define RelationGetRelationName(relation)
Definition: rel.h:361
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:149
void checkNameSpaceConflicts(ParseState *pstate, List *namespace1, List *namespace2)
int location
Definition: parsenodes.h:601
TypeFuncClass
Definition: funcapi.h:150
List * ctecoltypmods
Definition: parsenodes.h:1193
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:492
#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:142
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:151
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:522
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
struct ParseState * parentParseState
Definition: parse_node.h:133
List * ctecolnames
Definition: parsenodes.h:1191
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
List * p_future_ctes
Definition: parse_node.h:143
#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:990
#define ACL_SELECT
Definition: parsenodes.h:64
Oid attnumCollationId(Relation rd, int attid)
bool self_reference
Definition: parsenodes.h:854
static char * label
Definition: pg_basebackup.c:59
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:158
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1298
unsigned int Index
Definition: c.h:361
ParseExprKind p_expr_kind
Definition: parse_node.h:146
TupleDesc rd_att
Definition: rel.h:84
RangeTblEntry * addRangeTableEntryForValues(ParseState *pstate, List *exprs, List *collations, Alias *alias, bool lateral, bool inFromCl)
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:194
static RangeTblEntry * scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
#define InvalidOid
Definition: postgres_ext.h:36
List * funccoltypmods
Definition: parsenodes.h:900
Bitmapset * updatedCols
Definition: parsenodes.h:871
bool p_lateral_active
Definition: parse_node.h:141
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)
List * ctecolcollations
Definition: parsenodes.h:857
Var * make_var(ParseState *pstate, RangeTblEntry *rte, int attrno, int location)
Definition: parse_node.c:186
Node * colNameToVar(ParseState *pstate, char *colname, bool localonly, int location)
CommonTableExpr * scanNameSpaceForCTE(ParseState *pstate, const char *refname, Index *ctelevelsup)
List * funccolcollations
Definition: parsenodes.h:901
#define makeNode(_type_)
Definition: nodes.h:539
Node * rarg
Definition: primnodes.h:1364
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:41
Definition: regguts.h:313
List * functions
Definition: parsenodes.h:840
Definition: value.h:42
Expr * expr
Definition: primnodes.h:1280
RangeTblEntry * rsecond
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1655
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:108
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:740
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
Index ctelevelsup
Definition: parsenodes.h:853
List * values_collations
Definition: parsenodes.h:847
TypeName * typeName
Definition: parsenodes.h:589
Bitmapset * funcparams
Definition: parsenodes.h:903
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:161
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:40
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:496
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:1192
RTEKind rtekind
Definition: parsenodes.h:791
char * ctename
Definition: parsenodes.h:852
Query * subquery
Definition: parsenodes.h:809
void * palloc(Size size)
Definition: mcxt.c:894
int errmsg(const char *fmt,...)
Definition: elog.c:797
Bitmapset * insertedCols
Definition: parsenodes.h:870
int i
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
static void buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
List * funccoltypes
Definition: parsenodes.h:899
#define NameStr(name)
Definition: c.h:494
RangeTblEntry * addRangeTableEntryForCTE(ParseState *pstate, CommonTableExpr *cte, Index levelsup, RangeVar *rv, bool inFromCl)
List * p_ctenamespace
Definition: parse_node.h:142
List * p_joinlist
Definition: parse_node.h:137
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1116
Alias * alias
Definition: primnodes.h:78
bool isLockedRefname(ParseState *pstate, const char *refname)
char * colname
Definition: parsenodes.h:588
#define elog
Definition: elog.h:218
Alias * eref
Definition: parsenodes.h:863
List * ctecolcollations
Definition: parsenodes.h:1194
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:166
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:341
List * p_joinexprs
Definition: parse_node.h:136
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid LookupNamespaceNoError(const char *nspname)
Definition: namespace.c:2672
char * get_func_result_name(Oid functionId)
Definition: funcapi.c:1019
#define QTW_IGNORE_JOINALIASES
Definition: nodeFuncs.h:23
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:606
List * p_rtable
Definition: parse_node.h:135
#define SearchSysCache2(cacheId, key1, key2)
Definition: syscache.h:143