Debian Codegraph @

src/backend/parser/parse_relation.c

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