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