1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_relation.c
13 *-------------------------------------------------------------------------
19 #include "access/htup_details.h"
20 #include "access/sysattr.h"
21 #include "catalog/heap.h"
22 #include "catalog/namespace.h"
23 #include "catalog/pg_type.h"
25 #include "nodes/makefuncs.h"
26 #include "nodes/nodeFuncs.h"
27 #include "parser/parsetree.h"
28 #include "parser/parse_relation.h"
29 #include "parser/parse_type.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/rel.h"
33 #include "utils/syscache.h"
36 static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
37 const char *refname, int location);
38 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
40 static void check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
42 static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
43 int rtindex, AttrNumber col);
44 static void expandRelation(Oid relid, Alias *eref,
45 int rtindex, int sublevels_up,
46 int location, bool include_dropped,
47 List **colnames, List **colvars);
48 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
49 int count, int offset,
50 int rtindex, int sublevels_up,
51 int location, bool include_dropped,
52 List **colnames, List **colvars);
53 static int specialAttNum(const char *attname);
54 static bool isQueryUsingTempRelation_walker(Node *node, void *context);
58 * refnameRangeTblEntry
59 * Given a possibly-qualified refname, look to see if it matches any RTE.
60 * If so, return a pointer to the RangeTblEntry; else return NULL.
62 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
63 * If sublevels_up is NULL, only consider items at the current nesting
66 * An unqualified refname (schemaname == NULL) can match any RTE with matching
67 * alias, or matching unqualified relname in the case of alias-less relation
68 * RTEs. It is possible that such a refname matches multiple RTEs in the
69 * nearest nesting level that has a match; if so, we report an error via
72 * A qualified refname (schemaname != NULL) can only match a relation RTE
73 * that (a) has no alias and (b) is for the same relation identified by
74 * schemaname.refname. In this case we convert schemaname.refname to a
75 * relation OID and search by relid, rather than by alias name. This is
76 * peculiar, but it's what SQL says to do.
79 refnameRangeTblEntry(ParseState *pstate,
80 const char *schemaname,
85 Oid relId = InvalidOid;
90 if (schemaname != NULL)
95 * We can use LookupNamespaceNoError() here because we are only
96 * interested in finding existing RTEs. Checking USAGE permission on
97 * the schema is unnecessary since it would have already been checked
98 * when the RTE was made. Furthermore, we want to report "RTE not
99 * found", not "no permissions for schema", if the name happens to
100 * match a schema name the user hasn't got access to.
102 namespaceId = LookupNamespaceNoError(schemaname);
103 if (!OidIsValid(namespaceId))
105 relId = get_relname_relid(refname, namespaceId);
106 if (!OidIsValid(relId))
110 while (pstate != NULL)
112 RangeTblEntry *result;
114 if (OidIsValid(relId))
115 result = scanNameSpaceForRelid(pstate, relId, location);
117 result = scanNameSpaceForRefname(pstate, refname, location);
127 pstate = pstate->parentParseState;
133 * Search the query's table namespace for an RTE matching the
134 * given unqualified refname. Return the RTE if a unique match, or NULL
135 * if no match. Raise error if multiple matches.
137 * Note: it might seem that we shouldn't have to worry about the possibility
138 * of multiple matches; after all, the SQL standard disallows duplicate table
139 * aliases within a given SELECT level. Historically, however, Postgres has
140 * been laxer than that. For example, we allow
141 * SELECT ... FROM tab1 x CROSS JOIN (tab2 x CROSS JOIN tab3 y) z
142 * on the grounds that the aliased join (z) hides the aliases within it,
143 * therefore there is no conflict between the two RTEs named "x". However,
144 * if tab3 is a LATERAL subquery, then from within the subquery both "x"es
145 * are visible. Rather than rejecting queries that used to work, we allow
146 * this situation, and complain only if there's actually an ambiguous
149 static RangeTblEntry *
150 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
152 RangeTblEntry *result = NULL;
155 foreach(l, pstate->p_namespace)
157 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
158 RangeTblEntry *rte = nsitem->p_rte;
160 /* Ignore columns-only items */
161 if (!nsitem->p_rel_visible)
163 /* If not inside LATERAL, ignore lateral-only items */
164 if (nsitem->p_lateral_only && !pstate->p_lateral_active)
167 if (strcmp(rte->eref->aliasname, refname) == 0)
171 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
172 errmsg("table reference \"%s\" is ambiguous",
174 parser_errposition(pstate, location)));
175 check_lateral_ref_ok(pstate, nsitem, location);
183 * Search the query's table namespace for a relation RTE matching the
184 * given relation OID. Return the RTE if a unique match, or NULL
185 * if no match. Raise error if multiple matches.
187 * See the comments for refnameRangeTblEntry to understand why this
188 * acts the way it does.
190 static RangeTblEntry *
191 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
193 RangeTblEntry *result = NULL;
196 foreach(l, pstate->p_namespace)
198 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
199 RangeTblEntry *rte = nsitem->p_rte;
201 /* Ignore columns-only items */
202 if (!nsitem->p_rel_visible)
204 /* If not inside LATERAL, ignore lateral-only items */
205 if (nsitem->p_lateral_only && !pstate->p_lateral_active)
208 /* yes, the test for alias == NULL should be there... */
209 if (rte->rtekind == RTE_RELATION &&
210 rte->relid == relid &&
215 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
216 errmsg("table reference %u is ambiguous",
218 parser_errposition(pstate, location)));
219 check_lateral_ref_ok(pstate, nsitem, location);
227 * Search the query's CTE namespace for a CTE matching the given unqualified
228 * refname. Return the CTE (and its levelsup count) if a match, or NULL
229 * if no match. We need not worry about multiple matches, since parse_cte.c
230 * rejects WITH lists containing duplicate CTE names.
233 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
240 pstate = pstate->parentParseState, levelsup++)
244 foreach(lc, pstate->p_ctenamespace)
246 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
248 if (strcmp(cte->ctename, refname) == 0)
250 *ctelevelsup = levelsup;
259 * Search for a possible "future CTE", that is one that is not yet in scope
260 * according to the WITH scoping rules. This has nothing to do with valid
261 * SQL semantics, but it's important for error reporting purposes.
264 isFutureCTE(ParseState *pstate, const char *refname)
266 for (; pstate != NULL; pstate = pstate->parentParseState)
270 foreach(lc, pstate->p_future_ctes)
272 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
274 if (strcmp(cte->ctename, refname) == 0)
282 * searchRangeTableForRel
283 * See if any RangeTblEntry could possibly match the RangeVar.
284 * If so, return a pointer to the RangeTblEntry; else return NULL.
286 * This is different from refnameRangeTblEntry in that it considers every
287 * entry in the ParseState's rangetable(s), not only those that are currently
288 * visible in the p_namespace list(s). This behavior is invalid per the SQL
289 * spec, and it may give ambiguous results (there might be multiple equally
290 * valid matches, but only one will be returned). This must be used ONLY
291 * as a heuristic in giving suitable error messages. See errorMissingRTE.
293 * Notice that we consider both matches on actual relation (or CTE) name
294 * and matches on alias.
296 static RangeTblEntry *
297 searchRangeTableForRel(ParseState *pstate, RangeVar *relation)
299 const char *refname = relation->relname;
300 Oid relId = InvalidOid;
301 CommonTableExpr *cte = NULL;
302 Index ctelevelsup = 0;
306 * If it's an unqualified name, check for possible CTE matches. A CTE
307 * hides any real relation matches. If no CTE, look for a matching
310 * NB: It's not critical that RangeVarGetRelid return the correct answer
311 * here in the face of concurrent DDL. If it doesn't, the worst case
312 * scenario is a less-clear error message. Also, the tables involved in
313 * the query are already locked, which reduces the number of cases in
314 * which surprising behavior can occur. So we do the name lookup
317 if (!relation->schemaname)
318 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
320 relId = RangeVarGetRelid(relation, NoLock, true);
322 /* Now look for RTEs matching either the relation/CTE or the alias */
325 pstate = pstate->parentParseState, levelsup++)
329 foreach(l, pstate->p_rtable)
331 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
333 if (rte->rtekind == RTE_RELATION &&
337 if (rte->rtekind == RTE_CTE &&
339 rte->ctelevelsup + levelsup == ctelevelsup &&
340 strcmp(rte->ctename, refname) == 0)
342 if (strcmp(rte->eref->aliasname, refname) == 0)
350 * Check for relation-name conflicts between two namespace lists.
351 * Raise an error if any is found.
353 * Note: we assume that each given argument does not contain conflicts
354 * itself; we just want to know if the two can be merged together.
356 * Per SQL, two alias-less plain relation RTEs do not conflict even if
357 * they have the same eref->aliasname (ie, same relation name), if they
358 * are for different relation OIDs (implying they are in different schemas).
360 * We ignore the lateral-only flags in the namespace items: the lists must
361 * not conflict, even when all items are considered visible. However,
362 * columns-only items should be ignored.
365 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
370 foreach(l1, namespace1)
372 ParseNamespaceItem *nsitem1 = (ParseNamespaceItem *) lfirst(l1);
373 RangeTblEntry *rte1 = nsitem1->p_rte;
374 const char *aliasname1 = rte1->eref->aliasname;
377 if (!nsitem1->p_rel_visible)
380 foreach(l2, namespace2)
382 ParseNamespaceItem *nsitem2 = (ParseNamespaceItem *) lfirst(l2);
383 RangeTblEntry *rte2 = nsitem2->p_rte;
385 if (!nsitem2->p_rel_visible)
387 if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
388 continue; /* definitely no conflict */
389 if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
390 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
391 rte1->relid != rte2->relid)
392 continue; /* no conflict per SQL rule */
394 (errcode(ERRCODE_DUPLICATE_ALIAS),
395 errmsg("table name \"%s\" specified more than once",
402 * Complain if a namespace item is currently disallowed as a LATERAL reference.
403 * This enforces both SQL:2008's rather odd idea of what to do with a LATERAL
404 * reference to the wrong side of an outer join, and our own prohibition on
405 * referencing the target table of an UPDATE or DELETE as a lateral reference
406 * in a FROM/USING clause.
408 * Convenience subroutine to avoid multiple copies of a rather ugly ereport.
411 check_lateral_ref_ok(ParseState *pstate, ParseNamespaceItem *nsitem,
414 if (nsitem->p_lateral_only && !nsitem->p_lateral_ok)
416 /* SQL:2008 demands this be an error, not an invisible item */
417 RangeTblEntry *rte = nsitem->p_rte;
418 char *refname = rte->eref->aliasname;
421 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
422 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
424 (rte == pstate->p_target_rangetblentry) ?
425 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
427 errdetail("The combining JOIN type must be INNER or LEFT for a LATERAL reference."),
428 parser_errposition(pstate, location)));
433 * given an RTE, return RT index (starting with 1) of the entry,
434 * and optionally get its nesting depth (0 = current). If sublevels_up
435 * is NULL, only consider rels at the current nesting level.
436 * Raises error if RTE not found.
439 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
447 while (pstate != NULL)
450 foreach(l, pstate->p_rtable)
452 if (rte == (RangeTblEntry *) lfirst(l))
456 pstate = pstate->parentParseState;
463 elog(ERROR, "RTE not found (internal error)");
464 return 0; /* keep compiler quiet */
468 * Given an RT index and nesting depth, find the corresponding RTE.
469 * This is the inverse of RTERangeTablePosn.
472 GetRTEByRangeTablePosn(ParseState *pstate,
476 while (sublevels_up-- > 0)
478 pstate = pstate->parentParseState;
479 Assert(pstate != NULL);
481 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
482 return rt_fetch(varno, pstate->p_rtable);
486 * Fetch the CTE for a CTE-reference RTE.
488 * rtelevelsup is the number of query levels above the given pstate that the
489 * RTE came from. Callers that don't have this information readily available
490 * may pass -1 instead.
493 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
498 /* Determine RTE's levelsup if caller didn't know it */
500 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
502 Assert(rte->rtekind == RTE_CTE);
503 levelsup = rte->ctelevelsup + rtelevelsup;
504 while (levelsup-- > 0)
506 pstate = pstate->parentParseState;
507 if (!pstate) /* shouldn't happen */
508 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
510 foreach(lc, pstate->p_ctenamespace)
512 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
514 if (strcmp(cte->ctename, rte->ctename) == 0)
517 /* shouldn't happen */
518 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
519 return NULL; /* keep compiler quiet */
524 * Search the column names of a single RTE for the given name.
525 * If found, return an appropriate Var node, else return NULL.
526 * If the name proves ambiguous within this RTE, raise error.
528 * Side effect: if we find a match, mark the RTE as requiring read access
532 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
541 * Scan the user column names (or aliases) for a match. Complain if
544 * Note: eref->colnames may include entries for dropped columns, but those
545 * will be empty strings that cannot match any legal SQL identifier, so we
546 * don't bother to test for that case here.
548 * Should this somehow go wrong and we try to access a dropped column,
549 * we'll still catch it by virtue of the checks in
550 * get_rte_attribute_type(), which is called by make_var(). That routine
551 * has to do a cache lookup anyway, so the check there is cheap.
553 foreach(c, rte->eref->colnames)
556 if (strcmp(strVal(lfirst(c)), colname) == 0)
560 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
561 errmsg("column reference \"%s\" is ambiguous",
563 parser_errposition(pstate, location)));
564 var = make_var(pstate, rte, attnum, location);
565 /* Require read access to the column */
566 markVarForSelectPriv(pstate, var, rte);
567 result = (Node *) var;
572 * If we have a unique match, return it. Note that this allows a user
573 * alias to override a system column name (such as OID) without error.
579 * If the RTE represents a real table, consider system column names.
581 if (rte->rtekind == RTE_RELATION)
583 /* quick check to see if name could be a system column */
584 attnum = specialAttNum(colname);
586 /* In constraint check, no system column is allowed except tableOid */
587 if (pstate->p_expr_kind == EXPR_KIND_CHECK_CONSTRAINT &&
588 attnum < InvalidAttrNumber && attnum != TableOidAttributeNumber)
590 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
591 errmsg("system column \"%s\" reference in check constraint is invalid",
593 parser_errposition(pstate, location)));
595 if (attnum != InvalidAttrNumber)
597 /* now check to see if column actually is defined */
598 if (SearchSysCacheExists2(ATTNUM,
599 ObjectIdGetDatum(rte->relid),
600 Int16GetDatum(attnum)))
602 var = make_var(pstate, rte, attnum, location);
603 /* Require read access to the column */
604 markVarForSelectPriv(pstate, var, rte);
605 result = (Node *) var;
615 * Search for an unqualified column name.
616 * If found, return the appropriate Var node (or expression).
617 * If not found, return NULL. If the name proves ambiguous, raise error.
618 * If localonly is true, only names in the innermost query are considered.
621 colNameToVar(ParseState *pstate, char *colname, bool localonly,
625 ParseState *orig_pstate = pstate;
627 while (pstate != NULL)
631 foreach(l, pstate->p_namespace)
633 ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(l);
634 RangeTblEntry *rte = nsitem->p_rte;
637 /* Ignore table-only items */
638 if (!nsitem->p_cols_visible)
640 /* If not inside LATERAL, ignore lateral-only items */
641 if (nsitem->p_lateral_only && !pstate->p_lateral_active)
644 /* use orig_pstate here to get the right sublevels_up */
645 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
651 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
652 errmsg("column reference \"%s\" is ambiguous",
654 parser_errposition(pstate, location)));
655 check_lateral_ref_ok(pstate, nsitem, location);
660 if (result != NULL || localonly)
661 break; /* found, or don't want to look at parent */
663 pstate = pstate->parentParseState;
670 * searchRangeTableForCol
671 * See if any RangeTblEntry could possibly provide the given column name.
672 * If so, return a pointer to the RangeTblEntry; else return NULL.
674 * This is different from colNameToVar in that it considers every entry in
675 * the ParseState's rangetable(s), not only those that are currently visible
676 * in the p_namespace list(s). This behavior is invalid per the SQL spec,
677 * and it may give ambiguous results (there might be multiple equally valid
678 * matches, but only one will be returned). This must be used ONLY as a
679 * heuristic in giving suitable error messages. See errorMissingColumn.
681 static RangeTblEntry *
682 searchRangeTableForCol(ParseState *pstate, char *colname, int location)
684 ParseState *orig_pstate = pstate;
686 while (pstate != NULL)
690 foreach(l, pstate->p_rtable)
692 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
694 if (scanRTEForColumn(orig_pstate, rte, colname, location))
698 pstate = pstate->parentParseState;
704 * markRTEForSelectPriv
705 * Mark the specified column of an RTE as requiring SELECT privilege
707 * col == InvalidAttrNumber means a "whole row" reference
709 * The caller should pass the actual RTE if it has it handy; otherwise pass
710 * NULL, and we'll look it up here. (This uglification of the API is
711 * worthwhile because nearly all external callers have the RTE at hand.)
714 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
715 int rtindex, AttrNumber col)
718 rte = rt_fetch(rtindex, pstate->p_rtable);
720 if (rte->rtekind == RTE_RELATION)
722 /* Make sure the rel as a whole is marked for SELECT access */
723 rte->requiredPerms |= ACL_SELECT;
724 /* Must offset the attnum to fit in a bitmapset */
725 rte->selectedCols = bms_add_member(rte->selectedCols,
726 col - FirstLowInvalidHeapAttributeNumber);
728 else if (rte->rtekind == RTE_JOIN)
730 if (col == InvalidAttrNumber)
733 * A whole-row reference to a join has to be treated as whole-row
734 * references to the two inputs.
738 if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
739 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
743 elog(ERROR, "could not find JoinExpr for whole-row reference");
744 Assert(IsA(j, JoinExpr));
746 /* Note: we can't see FromExpr here */
747 if (IsA(j->larg, RangeTblRef))
749 int varno = ((RangeTblRef *) j->larg)->rtindex;
751 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
753 else if (IsA(j->larg, JoinExpr))
755 int varno = ((JoinExpr *) j->larg)->rtindex;
757 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
760 elog(ERROR, "unrecognized node type: %d",
761 (int) nodeTag(j->larg));
762 if (IsA(j->rarg, RangeTblRef))
764 int varno = ((RangeTblRef *) j->rarg)->rtindex;
766 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
768 else if (IsA(j->rarg, JoinExpr))
770 int varno = ((JoinExpr *) j->rarg)->rtindex;
772 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
775 elog(ERROR, "unrecognized node type: %d",
776 (int) nodeTag(j->rarg));
781 * Regular join attribute, look at the alias-variable list.
783 * The aliasvar could be either a Var or a COALESCE expression,
784 * but in the latter case we should already have marked the two
785 * referent variables as being selected, due to their use in the
786 * JOIN clause. So we need only be concerned with the Var case.
787 * But we do need to drill down through implicit coercions.
791 Assert(col > 0 && col <= list_length(rte->joinaliasvars));
792 aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
793 aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
794 if (aliasvar && IsA(aliasvar, Var))
795 markVarForSelectPriv(pstate, aliasvar, NULL);
798 /* other RTE types don't require privilege marking */
802 * markVarForSelectPriv
803 * Mark the RTE referenced by a Var as requiring SELECT privilege
805 * The caller should pass the Var's referenced RTE if it has it handy
806 * (nearly all do); otherwise pass NULL.
809 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
813 Assert(IsA(var, Var));
814 /* Find the appropriate pstate if it's an uplevel Var */
815 for (lv = 0; lv < var->varlevelsup; lv++)
816 pstate = pstate->parentParseState;
817 markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
821 * buildRelationAliases
822 * Construct the eref column name list for a relation RTE.
823 * This code is also used for function RTEs.
825 * tupdesc: the physical column information
826 * alias: the user-supplied alias, or NULL if none
827 * eref: the eref Alias to store column names in
829 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
830 * empty strings for any dropped columns, so that it will be one-to-one with
831 * physical column numbers.
833 * It is an error for there to be more aliases present than required.
836 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
838 int maxattrs = tupdesc->natts;
844 Assert(eref->colnames == NIL);
848 aliaslc = list_head(alias->colnames);
849 numaliases = list_length(alias->colnames);
850 /* We'll rebuild the alias colname list */
851 alias->colnames = NIL;
859 for (varattno = 0; varattno < maxattrs; varattno++)
861 Form_pg_attribute attr = tupdesc->attrs[varattno];
864 if (attr->attisdropped)
866 /* Always insert an empty string for a dropped column */
867 attrname = makeString(pstrdup(""));
869 alias->colnames = lappend(alias->colnames, attrname);
874 /* Use the next user-supplied alias */
875 attrname = (Value *) lfirst(aliaslc);
876 aliaslc = lnext(aliaslc);
877 alias->colnames = lappend(alias->colnames, attrname);
881 attrname = makeString(pstrdup(NameStr(attr->attname)));
882 /* we're done with the alias if any */
885 eref->colnames = lappend(eref->colnames, attrname);
888 /* Too many user-supplied aliases? */
891 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
892 errmsg("table \"%s\" has %d columns available but %d columns specified",
893 eref->aliasname, maxattrs - numdropped, numaliases)));
897 * chooseScalarFunctionAlias
898 * Select the column alias for a function in a function RTE,
899 * when the function returns a scalar type (not composite or RECORD).
901 * funcexpr: transformed expression tree for the function call
902 * funcname: function name (as determined by FigureColname)
903 * alias: the user-supplied alias for the RTE, or NULL if none
904 * nfuncs: the number of functions appearing in the function RTE
906 * Note that the name we choose might be overridden later, if the user-given
907 * alias includes column alias names. That's of no concern here.
910 chooseScalarFunctionAlias(Node *funcexpr, char *funcname,
911 Alias *alias, int nfuncs)
916 * If the expression is a simple function call, and the function has a
917 * single OUT parameter that is named, use the parameter's name.
919 if (funcexpr && IsA(funcexpr, FuncExpr))
921 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
927 * If there's just one function in the RTE, and the user gave an RTE alias
928 * name, use that name. (This makes FROM func() AS foo use "foo" as the
929 * column name as well as the table alias.)
931 if (nfuncs == 1 && alias)
932 return alias->aliasname;
935 * Otherwise use the function name.
941 * Open a table during parse analysis
943 * This is essentially just the same as heap_openrv(), except that it caters
944 * to some parser-specific error reporting needs, notably that it arranges
945 * to include the RangeVar's parse location in any resulting error.
947 * Note: properly, lockmode should be declared LOCKMODE not int, but that
948 * would require importing storage/lock.h into parse_relation.h. Since
949 * LOCKMODE is typedef'd as int anyway, that seems like overkill.
952 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
955 ParseCallbackState pcbstate;
957 setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
958 rel = heap_openrv_extended(relation, lockmode, true);
961 if (relation->schemaname)
963 (errcode(ERRCODE_UNDEFINED_TABLE),
964 errmsg("relation \"%s.%s\" does not exist",
965 relation->schemaname, relation->relname)));
969 * An unqualified name might have been meant as a reference to
970 * some not-yet-in-scope CTE. The bare "does not exist" message
971 * has proven remarkably unhelpful for figuring out such problems,
972 * so we take pains to offer a specific hint.
974 if (isFutureCTE(pstate, relation->relname))
976 (errcode(ERRCODE_UNDEFINED_TABLE),
977 errmsg("relation \"%s\" does not exist",
979 errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
981 errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
984 (errcode(ERRCODE_UNDEFINED_TABLE),
985 errmsg("relation \"%s\" does not exist",
986 relation->relname)));
989 cancel_parser_errposition_callback(&pcbstate);
994 * Add an entry for a relation to the pstate's range table (p_rtable).
996 * If pstate is NULL, we just build an RTE and return it without adding it
999 * Note: formerly this checked for refname conflicts, but that's wrong.
1000 * Caller is responsible for checking for conflicts in the appropriate scope.
1003 addRangeTableEntry(ParseState *pstate,
1009 RangeTblEntry *rte = makeNode(RangeTblEntry);
1010 char *refname = alias ? alias->aliasname : relation->relname;
1014 rte->rtekind = RTE_RELATION;
1018 * Get the rel's OID. This access also ensures that we have an up-to-date
1019 * relcache entry for the rel. Since this is typically the first access
1020 * to a rel in a statement, be careful to get the right access level
1021 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
1023 lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
1024 rel = parserOpenTable(pstate, relation, lockmode);
1025 rte->relid = RelationGetRelid(rel);
1026 rte->relkind = rel->rd_rel->relkind;
1029 * Build the list of effective column names using user-supplied aliases
1030 * and/or actual column names.
1032 rte->eref = makeAlias(refname, NIL);
1033 buildRelationAliases(rel->rd_att, alias, rte->eref);
1036 * Drop the rel refcount, but keep the access lock till end of transaction
1037 * so that the table can't be deleted or have its schema modified
1040 heap_close(rel, NoLock);
1043 * Set flags and access permissions.
1045 * The initial default on access checks is always check-for-READ-access,
1046 * which is the right thing for all except target tables.
1048 rte->lateral = false;
1050 rte->inFromCl = inFromCl;
1052 rte->requiredPerms = ACL_SELECT;
1053 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
1054 rte->selectedCols = NULL;
1055 rte->modifiedCols = NULL;
1058 * Add completed RTE to pstate's range table list, but not to join list
1059 * nor namespace --- caller must do that if appropriate.
1062 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1068 * Add an entry for a relation to the pstate's range table (p_rtable).
1070 * This is just like addRangeTableEntry() except that it makes an RTE
1071 * given an already-open relation instead of a RangeVar reference.
1074 addRangeTableEntryForRelation(ParseState *pstate,
1080 RangeTblEntry *rte = makeNode(RangeTblEntry);
1081 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
1083 rte->rtekind = RTE_RELATION;
1085 rte->relid = RelationGetRelid(rel);
1086 rte->relkind = rel->rd_rel->relkind;
1089 * Build the list of effective column names using user-supplied aliases
1090 * and/or actual column names.
1092 rte->eref = makeAlias(refname, NIL);
1093 buildRelationAliases(rel->rd_att, alias, rte->eref);
1096 * Set flags and access permissions.
1098 * The initial default on access checks is always check-for-READ-access,
1099 * which is the right thing for all except target tables.
1101 rte->lateral = false;
1103 rte->inFromCl = inFromCl;
1105 rte->requiredPerms = ACL_SELECT;
1106 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
1107 rte->selectedCols = NULL;
1108 rte->modifiedCols = NULL;
1111 * Add completed RTE to pstate's range table list, but not to join list
1112 * nor namespace --- caller must do that if appropriate.
1115 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1121 * Add an entry for a subquery to the pstate's range table (p_rtable).
1123 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1124 * Note that an alias clause *must* be supplied.
1127 addRangeTableEntryForSubquery(ParseState *pstate,
1133 RangeTblEntry *rte = makeNode(RangeTblEntry);
1134 char *refname = alias->aliasname;
1138 ListCell *tlistitem;
1140 rte->rtekind = RTE_SUBQUERY;
1141 rte->relid = InvalidOid;
1142 rte->subquery = subquery;
1145 eref = copyObject(alias);
1146 numaliases = list_length(eref->colnames);
1148 /* fill in any unspecified alias columns */
1150 foreach(tlistitem, subquery->targetList)
1152 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1157 Assert(varattno == te->resno);
1158 if (varattno > numaliases)
1162 attrname = pstrdup(te->resname);
1163 eref->colnames = lappend(eref->colnames, makeString(attrname));
1166 if (varattno < numaliases)
1168 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1169 errmsg("table \"%s\" has %d columns available but %d columns specified",
1170 refname, varattno, numaliases)));
1175 * Set flags and access permissions.
1177 * Subqueries are never checked for access rights.
1179 rte->lateral = lateral;
1180 rte->inh = false; /* never true for subqueries */
1181 rte->inFromCl = inFromCl;
1183 rte->requiredPerms = 0;
1184 rte->checkAsUser = InvalidOid;
1185 rte->selectedCols = NULL;
1186 rte->modifiedCols = NULL;
1189 * Add completed RTE to pstate's range table list, but not to join list
1190 * nor namespace --- caller must do that if appropriate.
1193 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1199 * Add an entry for a function (or functions) to the pstate's range table
1202 * This is just like addRangeTableEntry() except that it makes a function RTE.
1205 addRangeTableEntryForFunction(ParseState *pstate,
1209 RangeFunction *rangefunc,
1213 RangeTblEntry *rte = makeNode(RangeTblEntry);
1214 Alias *alias = rangefunc->alias;
1217 int nfuncs = list_length(funcexprs);
1218 TupleDesc *functupdescs;
1229 rte->rtekind = RTE_FUNCTION;
1230 rte->relid = InvalidOid;
1231 rte->subquery = NULL;
1232 rte->functions = NIL; /* we'll fill this list below */
1233 rte->funcordinality = rangefunc->ordinality;
1237 * Choose the RTE alias name. We default to using the first function's
1238 * name even when there's more than one; which is maybe arguable but beats
1239 * using something constant like "table".
1242 aliasname = alias->aliasname;
1244 aliasname = linitial(funcnames);
1246 eref = makeAlias(aliasname, NIL);
1249 /* Process each function ... */
1250 functupdescs = (TupleDesc *) palloc(nfuncs * sizeof(TupleDesc));
1254 forthree(lc1, funcexprs, lc2, funcnames, lc3, coldeflists)
1256 Node *funcexpr = (Node *) lfirst(lc1);
1257 char *funcname = (char *) lfirst(lc2);
1258 List *coldeflist = (List *) lfirst(lc3);
1259 RangeTblFunction *rtfunc = makeNode(RangeTblFunction);
1260 TypeFuncClass functypclass;
1263 /* Initialize RangeTblFunction node */
1264 rtfunc->funcexpr = funcexpr;
1265 rtfunc->funccolnames = NIL;
1266 rtfunc->funccoltypes = NIL;
1267 rtfunc->funccoltypmods = NIL;
1268 rtfunc->funccolcollations = NIL;
1269 rtfunc->funcparams = NULL; /* not set until planning */
1272 * Now determine if the function returns a simple or composite type.
1274 functypclass = get_expr_result_type(funcexpr,
1279 * A coldeflist is required if the function returns RECORD and hasn't
1280 * got a predetermined record type, and is prohibited otherwise.
1282 if (coldeflist != NIL)
1284 if (functypclass != TYPEFUNC_RECORD)
1286 (errcode(ERRCODE_SYNTAX_ERROR),
1287 errmsg("a column definition list is only allowed for functions returning \"record\""),
1288 parser_errposition(pstate,
1289 exprLocation((Node *) coldeflist))));
1293 if (functypclass == TYPEFUNC_RECORD)
1295 (errcode(ERRCODE_SYNTAX_ERROR),
1296 errmsg("a column definition list is required for functions returning \"record\""),
1297 parser_errposition(pstate, exprLocation(funcexpr))));
1300 if (functypclass == TYPEFUNC_COMPOSITE)
1302 /* Composite data type, e.g. a table's row type */
1305 else if (functypclass == TYPEFUNC_SCALAR)
1307 /* Base data type, i.e. scalar */
1308 tupdesc = CreateTemplateTupleDesc(1, false);
1309 TupleDescInitEntry(tupdesc,
1311 chooseScalarFunctionAlias(funcexpr, funcname,
1317 else if (functypclass == TYPEFUNC_RECORD)
1322 * Use the column definition list to construct a tupdesc and fill
1323 * in the RangeTblFunction's lists.
1325 tupdesc = CreateTemplateTupleDesc(list_length(coldeflist), false);
1327 foreach(col, coldeflist)
1329 ColumnDef *n = (ColumnDef *) lfirst(col);
1335 attrname = n->colname;
1336 if (n->typeName->setof)
1338 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1339 errmsg("column \"%s\" cannot be declared SETOF",
1341 parser_errposition(pstate, n->location)));
1342 typenameTypeIdAndMod(pstate, n->typeName,
1343 &attrtype, &attrtypmod);
1344 attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1345 TupleDescInitEntry(tupdesc,
1351 TupleDescInitEntryCollation(tupdesc,
1354 rtfunc->funccolnames = lappend(rtfunc->funccolnames,
1355 makeString(pstrdup(attrname)));
1356 rtfunc->funccoltypes = lappend_oid(rtfunc->funccoltypes,
1358 rtfunc->funccoltypmods = lappend_int(rtfunc->funccoltypmods,
1360 rtfunc->funccolcollations = lappend_oid(rtfunc->funccolcollations,
1367 * Ensure that the coldeflist defines a legal set of names (no
1368 * duplicates) and datatypes (no pseudo-types, for instance).
1370 CheckAttributeNamesTypes(tupdesc, RELKIND_COMPOSITE_TYPE, false);
1374 (errcode(ERRCODE_DATATYPE_MISMATCH),
1375 errmsg("function \"%s\" in FROM has unsupported return type %s",
1376 funcname, format_type_be(funcrettype)),
1377 parser_errposition(pstate, exprLocation(funcexpr))));
1379 /* Finish off the RangeTblFunction and add it to the RTE's list */
1380 rtfunc->funccolcount = tupdesc->natts;
1381 rte->functions = lappend(rte->functions, rtfunc);
1383 /* Save the tupdesc for use below */
1384 functupdescs[funcno] = tupdesc;
1385 totalatts += tupdesc->natts;
1390 * If there's more than one function, or we want an ordinality column, we
1391 * have to produce a merged tupdesc.
1393 if (nfuncs > 1 || rangefunc->ordinality)
1395 if (rangefunc->ordinality)
1398 /* Merge the tuple descs of each function into a composite one */
1399 tupdesc = CreateTemplateTupleDesc(totalatts, false);
1401 for (i = 0; i < nfuncs; i++)
1403 for (j = 1; j <= functupdescs[i]->natts; j++)
1404 TupleDescCopyEntry(tupdesc, ++natts, functupdescs[i], j);
1407 /* Add the ordinality column if needed */
1408 if (rangefunc->ordinality)
1409 TupleDescInitEntry(tupdesc,
1410 (AttrNumber) ++natts,
1416 Assert(natts == totalatts);
1420 /* We can just use the single function's tupdesc as-is */
1421 tupdesc = functupdescs[0];
1424 /* Use the tupdesc while assigning column aliases for the RTE */
1425 buildRelationAliases(tupdesc, alias, eref);
1428 * Set flags and access permissions.
1430 * Functions are never checked for access rights (at least, not by the RTE
1431 * permissions mechanism).
1433 rte->lateral = lateral;
1434 rte->inh = false; /* never true for functions */
1435 rte->inFromCl = inFromCl;
1437 rte->requiredPerms = 0;
1438 rte->checkAsUser = InvalidOid;
1439 rte->selectedCols = NULL;
1440 rte->modifiedCols = NULL;
1443 * Add completed RTE to pstate's range table list, but not to join list
1444 * nor namespace --- caller must do that if appropriate.
1447 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1453 * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1455 * This is much like addRangeTableEntry() except that it makes a values RTE.
1458 addRangeTableEntryForValues(ParseState *pstate,
1465 RangeTblEntry *rte = makeNode(RangeTblEntry);
1466 char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1471 rte->rtekind = RTE_VALUES;
1472 rte->relid = InvalidOid;
1473 rte->subquery = NULL;
1474 rte->values_lists = exprs;
1475 rte->values_collations = collations;
1478 eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1480 /* fill in any unspecified alias columns */
1481 numcolumns = list_length((List *) linitial(exprs));
1482 numaliases = list_length(eref->colnames);
1483 while (numaliases < numcolumns)
1488 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1489 eref->colnames = lappend(eref->colnames,
1490 makeString(pstrdup(attrname)));
1492 if (numcolumns < numaliases)
1494 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1495 errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1496 refname, numcolumns, numaliases)));
1501 * Set flags and access permissions.
1503 * Subqueries are never checked for access rights.
1505 rte->lateral = lateral;
1506 rte->inh = false; /* never true for values RTEs */
1507 rte->inFromCl = inFromCl;
1509 rte->requiredPerms = 0;
1510 rte->checkAsUser = InvalidOid;
1511 rte->selectedCols = NULL;
1512 rte->modifiedCols = NULL;
1515 * Add completed RTE to pstate's range table list, but not to join list
1516 * nor namespace --- caller must do that if appropriate.
1519 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1525 * Add an entry for a join to the pstate's range table (p_rtable).
1527 * This is much like addRangeTableEntry() except that it makes a join RTE.
1530 addRangeTableEntryForJoin(ParseState *pstate,
1537 RangeTblEntry *rte = makeNode(RangeTblEntry);
1542 * Fail if join has too many columns --- we must be able to reference any
1543 * of the columns with an AttrNumber.
1545 if (list_length(aliasvars) > MaxAttrNumber)
1547 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1548 errmsg("joins can have at most %d columns",
1551 rte->rtekind = RTE_JOIN;
1552 rte->relid = InvalidOid;
1553 rte->subquery = NULL;
1554 rte->jointype = jointype;
1555 rte->joinaliasvars = aliasvars;
1558 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1559 numaliases = list_length(eref->colnames);
1561 /* fill in any unspecified alias columns */
1562 if (numaliases < list_length(colnames))
1563 eref->colnames = list_concat(eref->colnames,
1564 list_copy_tail(colnames, numaliases));
1569 * Set flags and access permissions.
1571 * Joins are never checked for access rights.
1573 rte->lateral = false;
1574 rte->inh = false; /* never true for joins */
1575 rte->inFromCl = inFromCl;
1577 rte->requiredPerms = 0;
1578 rte->checkAsUser = InvalidOid;
1579 rte->selectedCols = NULL;
1580 rte->modifiedCols = NULL;
1583 * Add completed RTE to pstate's range table list, but not to join list
1584 * nor namespace --- caller must do that if appropriate.
1587 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1593 * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1595 * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1598 addRangeTableEntryForCTE(ParseState *pstate,
1599 CommonTableExpr *cte,
1604 RangeTblEntry *rte = makeNode(RangeTblEntry);
1605 Alias *alias = rv->alias;
1606 char *refname = alias ? alias->aliasname : cte->ctename;
1612 rte->rtekind = RTE_CTE;
1613 rte->ctename = cte->ctename;
1614 rte->ctelevelsup = levelsup;
1616 /* Self-reference if and only if CTE's parse analysis isn't completed */
1617 rte->self_reference = !IsA(cte->ctequery, Query);
1618 Assert(cte->cterecursive || !rte->self_reference);
1619 /* Bump the CTE's refcount if this isn't a self-reference */
1620 if (!rte->self_reference)
1624 * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
1625 * This won't get checked in case of a self-reference, but that's OK
1626 * because data-modifying CTEs aren't allowed to be recursive anyhow.
1628 if (IsA(cte->ctequery, Query))
1630 Query *ctequery = (Query *) cte->ctequery;
1632 if (ctequery->commandType != CMD_SELECT &&
1633 ctequery->returningList == NIL)
1635 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1636 errmsg("WITH query \"%s\" does not have a RETURNING clause",
1638 parser_errposition(pstate, rv->location)));
1641 rte->ctecoltypes = cte->ctecoltypes;
1642 rte->ctecoltypmods = cte->ctecoltypmods;
1643 rte->ctecolcollations = cte->ctecolcollations;
1647 eref = copyObject(alias);
1649 eref = makeAlias(refname, NIL);
1650 numaliases = list_length(eref->colnames);
1652 /* fill in any unspecified alias columns */
1654 foreach(lc, cte->ctecolnames)
1657 if (varattno > numaliases)
1658 eref->colnames = lappend(eref->colnames, lfirst(lc));
1660 if (varattno < numaliases)
1662 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1663 errmsg("table \"%s\" has %d columns available but %d columns specified",
1664 refname, varattno, numaliases)));
1669 * Set flags and access permissions.
1671 * Subqueries are never checked for access rights.
1673 rte->lateral = false;
1674 rte->inh = false; /* never true for subqueries */
1675 rte->inFromCl = inFromCl;
1677 rte->requiredPerms = 0;
1678 rte->checkAsUser = InvalidOid;
1679 rte->selectedCols = NULL;
1680 rte->modifiedCols = NULL;
1683 * Add completed RTE to pstate's range table list, but not to join list
1684 * nor namespace --- caller must do that if appropriate.
1687 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1694 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1696 * This is used when we have not yet done transformLockingClause, but need
1697 * to know the correct lock to take during initial opening of relations.
1699 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1700 * since the table-level lock is the same either way.
1703 isLockedRefname(ParseState *pstate, const char *refname)
1708 * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1709 * parent level, then act as though there's a generic FOR UPDATE here.
1711 if (pstate->p_locked_from_parent)
1714 foreach(l, pstate->p_locking_clause)
1716 LockingClause *lc = (LockingClause *) lfirst(l);
1718 if (lc->lockedRels == NIL)
1720 /* all tables used in query */
1725 /* just the named tables */
1728 foreach(l2, lc->lockedRels)
1730 RangeVar *thisrel = (RangeVar *) lfirst(l2);
1732 if (strcmp(refname, thisrel->relname) == 0)
1741 * Add the given RTE as a top-level entry in the pstate's join list
1742 * and/or namespace list. (We assume caller has checked for any
1743 * namespace conflicts.) The RTE is always marked as unconditionally
1744 * visible, that is, not LATERAL-only.
1746 * Note: some callers know that they can find the new ParseNamespaceItem
1747 * at the end of the pstate->p_namespace list. This is a bit ugly but not
1748 * worth complicating this function's signature for.
1751 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1753 bool addToRelNameSpace, bool addToVarNameSpace)
1757 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1758 RangeTblRef *rtr = makeNode(RangeTblRef);
1760 rtr->rtindex = rtindex;
1761 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1763 if (addToRelNameSpace || addToVarNameSpace)
1765 ParseNamespaceItem *nsitem;
1767 nsitem = (ParseNamespaceItem *) palloc(sizeof(ParseNamespaceItem));
1768 nsitem->p_rte = rte;
1769 nsitem->p_rel_visible = addToRelNameSpace;
1770 nsitem->p_cols_visible = addToVarNameSpace;
1771 nsitem->p_lateral_only = false;
1772 nsitem->p_lateral_ok = true;
1773 pstate->p_namespace = lappend(pstate->p_namespace, nsitem);
1778 * expandRTE -- expand the columns of a rangetable entry
1780 * This creates lists of an RTE's column names (aliases if provided, else
1781 * real names) and Vars for each column. Only user columns are considered.
1782 * If include_dropped is FALSE then dropped columns are omitted from the
1783 * results. If include_dropped is TRUE then empty strings and NULL constants
1784 * (not Vars!) are returned for dropped columns.
1786 * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1787 * values to use in the created Vars. Ordinarily rtindex should match the
1788 * actual position of the RTE in its rangetable.
1790 * The output lists go into *colnames and *colvars.
1791 * If only one of the two kinds of output list is needed, pass NULL for the
1792 * output pointer for the unwanted one.
1795 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1796 int location, bool include_dropped,
1797 List **colnames, List **colvars)
1806 switch (rte->rtekind)
1809 /* Ordinary relation RTE */
1810 expandRelation(rte->relid, rte->eref,
1811 rtindex, sublevels_up, location,
1812 include_dropped, colnames, colvars);
1817 ListCell *aliasp_item = list_head(rte->eref->colnames);
1818 ListCell *tlistitem;
1821 foreach(tlistitem, rte->subquery->targetList)
1823 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1828 Assert(varattno == te->resno);
1832 /* Assume there is one alias per target item */
1833 char *label = strVal(lfirst(aliasp_item));
1835 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1836 aliasp_item = lnext(aliasp_item);
1843 varnode = makeVar(rtindex, varattno,
1844 exprType((Node *) te->expr),
1845 exprTypmod((Node *) te->expr),
1846 exprCollation((Node *) te->expr),
1848 varnode->location = location;
1850 *colvars = lappend(*colvars, varnode);
1861 foreach(lc, rte->functions)
1863 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
1864 TypeFuncClass functypclass;
1868 functypclass = get_expr_result_type(rtfunc->funcexpr,
1871 if (functypclass == TYPEFUNC_COMPOSITE)
1873 /* Composite data type, e.g. a table's row type */
1875 expandTupleDesc(tupdesc, rte->eref,
1876 rtfunc->funccolcount, atts_done,
1877 rtindex, sublevels_up, location,
1878 include_dropped, colnames, colvars);
1880 else if (functypclass == TYPEFUNC_SCALAR)
1882 /* Base data type, i.e. scalar */
1884 *colnames = lappend(*colnames,
1885 list_nth(rte->eref->colnames,
1892 varnode = makeVar(rtindex, atts_done + 1,
1894 exprCollation(rtfunc->funcexpr),
1896 varnode->location = location;
1898 *colvars = lappend(*colvars, varnode);
1901 else if (functypclass == TYPEFUNC_RECORD)
1907 /* extract appropriate subset of column list */
1908 namelist = list_copy_tail(rte->eref->colnames,
1910 namelist = list_truncate(namelist,
1911 rtfunc->funccolcount);
1912 *colnames = list_concat(*colnames, namelist);
1920 int attnum = atts_done;
1922 forthree(l1, rtfunc->funccoltypes,
1923 l2, rtfunc->funccoltypmods,
1924 l3, rtfunc->funccolcollations)
1926 Oid attrtype = lfirst_oid(l1);
1927 int32 attrtypmod = lfirst_int(l2);
1928 Oid attrcollation = lfirst_oid(l3);
1932 varnode = makeVar(rtindex,
1938 varnode->location = location;
1939 *colvars = lappend(*colvars, varnode);
1945 /* addRangeTableEntryForFunction should've caught this */
1946 elog(ERROR, "function in FROM has unsupported return type");
1948 atts_done += rtfunc->funccolcount;
1951 /* Append the ordinality column if any */
1952 if (rte->funcordinality)
1955 *colnames = lappend(*colnames,
1956 llast(rte->eref->colnames));
1960 Var *varnode = makeVar(rtindex,
1967 *colvars = lappend(*colvars, varnode);
1975 ListCell *aliasp_item = list_head(rte->eref->colnames);
1980 forboth(lcv, (List *) linitial(rte->values_lists),
1981 lcc, rte->values_collations)
1983 Node *col = (Node *) lfirst(lcv);
1984 Oid colcollation = lfirst_oid(lcc);
1989 /* Assume there is one alias per column */
1990 char *label = strVal(lfirst(aliasp_item));
1992 *colnames = lappend(*colnames,
1993 makeString(pstrdup(label)));
1994 aliasp_item = lnext(aliasp_item);
2001 varnode = makeVar(rtindex, varattno,
2006 varnode->location = location;
2007 *colvars = lappend(*colvars, varnode);
2018 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
2021 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
2023 Node *avar = (Node *) lfirst(aliasvar);
2028 * During ordinary parsing, there will never be any
2029 * deleted columns in the join; but we have to check since
2030 * this routine is also used by the rewriter, and joins
2031 * found in stored rules might have join columns for
2032 * since-deleted columns. This will be signaled by a null
2033 * pointer in the alias-vars list.
2037 if (include_dropped)
2040 *colnames = lappend(*colnames,
2041 makeString(pstrdup("")));
2045 * Can't use join's column type here (it might
2046 * be dropped!); but it doesn't really matter
2047 * what type the Const claims to be.
2049 *colvars = lappend(*colvars,
2050 makeNullConst(INT4OID, -1,
2059 char *label = strVal(lfirst(colname));
2061 *colnames = lappend(*colnames,
2062 makeString(pstrdup(label)));
2069 varnode = makeVar(rtindex, varattno,
2072 exprCollation(avar),
2074 varnode->location = location;
2076 *colvars = lappend(*colvars, varnode);
2083 ListCell *aliasp_item = list_head(rte->eref->colnames);
2089 forthree(lct, rte->ctecoltypes,
2090 lcm, rte->ctecoltypmods,
2091 lcc, rte->ctecolcollations)
2093 Oid coltype = lfirst_oid(lct);
2094 int32 coltypmod = lfirst_int(lcm);
2095 Oid colcoll = lfirst_oid(lcc);
2101 /* Assume there is one alias per output column */
2102 char *label = strVal(lfirst(aliasp_item));
2104 *colnames = lappend(*colnames, makeString(pstrdup(label)));
2105 aliasp_item = lnext(aliasp_item);
2112 varnode = makeVar(rtindex, varattno,
2113 coltype, coltypmod, colcoll,
2115 *colvars = lappend(*colvars, varnode);
2121 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2126 * expandRelation -- expandRTE subroutine
2129 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
2130 int location, bool include_dropped,
2131 List **colnames, List **colvars)
2135 /* Get the tupledesc and turn it over to expandTupleDesc */
2136 rel = relation_open(relid, AccessShareLock);
2137 expandTupleDesc(rel->rd_att, eref, rel->rd_att->natts, 0,
2138 rtindex, sublevels_up,
2139 location, include_dropped,
2141 relation_close(rel, AccessShareLock);
2145 * expandTupleDesc -- expandRTE subroutine
2147 * Generate names and/or Vars for the first "count" attributes of the tupdesc,
2148 * and append them to colnames/colvars. "offset" is added to the varattno
2149 * that each Var would otherwise have, and we also skip the first "offset"
2150 * entries in eref->colnames. (These provisions allow use of this code for
2151 * an individual composite-returning function in an RTE_FUNCTION RTE.)
2154 expandTupleDesc(TupleDesc tupdesc, Alias *eref, int count, int offset,
2155 int rtindex, int sublevels_up,
2156 int location, bool include_dropped,
2157 List **colnames, List **colvars)
2159 ListCell *aliascell = list_head(eref->colnames);
2166 for (i = 0; i < offset; i++)
2169 aliascell = lnext(aliascell);
2173 Assert(count <= tupdesc->natts);
2174 for (varattno = 0; varattno < count; varattno++)
2176 Form_pg_attribute attr = tupdesc->attrs[varattno];
2178 if (attr->attisdropped)
2180 if (include_dropped)
2183 *colnames = lappend(*colnames, makeString(pstrdup("")));
2187 * can't use atttypid here, but it doesn't really matter
2188 * what type the Const claims to be.
2190 *colvars = lappend(*colvars,
2191 makeNullConst(INT4OID, -1, InvalidOid));
2195 aliascell = lnext(aliascell);
2205 label = strVal(lfirst(aliascell));
2206 aliascell = lnext(aliascell);
2210 /* If we run out of aliases, use the underlying name */
2211 label = NameStr(attr->attname);
2213 *colnames = lappend(*colnames, makeString(pstrdup(label)));
2220 varnode = makeVar(rtindex, varattno + offset + 1,
2221 attr->atttypid, attr->atttypmod,
2224 varnode->location = location;
2226 *colvars = lappend(*colvars, varnode);
2233 * Workhorse for "*" expansion: produce a list of targetentries
2234 * for the attributes of the RTE
2236 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
2237 * fields of the Vars produced, and location sets their location.
2238 * pstate->p_next_resno determines the resnos assigned to the TLEs.
2239 * The referenced columns are marked as requiring SELECT access.
2242 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
2243 int rtindex, int sublevels_up, int location)
2249 List *te_list = NIL;
2251 expandRTE(rte, rtindex, sublevels_up, location, false,
2255 * Require read access to the table. This is normally redundant with the
2256 * markVarForSelectPriv calls below, but not if the table has zero
2259 rte->requiredPerms |= ACL_SELECT;
2261 forboth(name, names, var, vars)
2263 char *label = strVal(lfirst(name));
2264 Var *varnode = (Var *) lfirst(var);
2267 te = makeTargetEntry((Expr *) varnode,
2268 (AttrNumber) pstate->p_next_resno++,
2271 te_list = lappend(te_list, te);
2273 /* Require read access to each column */
2274 markVarForSelectPriv(pstate, varnode, rte);
2277 Assert(name == NULL && var == NULL); /* lists not the same length? */
2283 * get_rte_attribute_name
2284 * Get an attribute name from a RangeTblEntry
2286 * This is unlike get_attname() because we use aliases if available.
2287 * In particular, it will work on an RTE for a subselect or join, whereas
2288 * get_attname() only works on real relations.
2290 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
2291 * occurs when a Var represents a whole tuple of a relation.
2294 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
2296 if (attnum == InvalidAttrNumber)
2300 * If there is a user-written column alias, use it.
2303 attnum > 0 && attnum <= list_length(rte->alias->colnames))
2304 return strVal(list_nth(rte->alias->colnames, attnum - 1));
2307 * If the RTE is a relation, go to the system catalogs not the
2308 * eref->colnames list. This is a little slower but it will give the
2309 * right answer if the column has been renamed since the eref list was
2310 * built (which can easily happen for rules).
2312 if (rte->rtekind == RTE_RELATION)
2313 return get_relid_attribute_name(rte->relid, attnum);
2316 * Otherwise use the column name from eref. There should always be one.
2318 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2319 return strVal(list_nth(rte->eref->colnames, attnum - 1));
2321 /* else caller gave us a bogus attnum */
2322 elog(ERROR, "invalid attnum %d for rangetable entry %s",
2323 attnum, rte->eref->aliasname);
2324 return NULL; /* keep compiler quiet */
2328 * get_rte_attribute_type
2329 * Get attribute type/typmod/collation information from a RangeTblEntry
2332 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2333 Oid *vartype, int32 *vartypmod, Oid *varcollid)
2335 switch (rte->rtekind)
2339 /* Plain relation RTE --- get the attribute's type info */
2341 Form_pg_attribute att_tup;
2343 tp = SearchSysCache2(ATTNUM,
2344 ObjectIdGetDatum(rte->relid),
2345 Int16GetDatum(attnum));
2346 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2347 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2348 attnum, rte->relid);
2349 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2352 * If dropped column, pretend it ain't there. See notes in
2355 if (att_tup->attisdropped)
2357 (errcode(ERRCODE_UNDEFINED_COLUMN),
2358 errmsg("column \"%s\" of relation \"%s\" does not exist",
2359 NameStr(att_tup->attname),
2360 get_rel_name(rte->relid))));
2361 *vartype = att_tup->atttypid;
2362 *vartypmod = att_tup->atttypmod;
2363 *varcollid = att_tup->attcollation;
2364 ReleaseSysCache(tp);
2369 /* Subselect RTE --- get type info from subselect's tlist */
2370 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2373 if (te == NULL || te->resjunk)
2374 elog(ERROR, "subquery %s does not have attribute %d",
2375 rte->eref->aliasname, attnum);
2376 *vartype = exprType((Node *) te->expr);
2377 *vartypmod = exprTypmod((Node *) te->expr);
2378 *varcollid = exprCollation((Node *) te->expr);
2387 /* Identify which function covers the requested column */
2388 foreach(lc, rte->functions)
2390 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2392 if (attnum > atts_done &&
2393 attnum <= atts_done + rtfunc->funccolcount)
2395 TypeFuncClass functypclass;
2399 attnum -= atts_done; /* now relative to this func */
2400 functypclass = get_expr_result_type(rtfunc->funcexpr,
2404 if (functypclass == TYPEFUNC_COMPOSITE)
2406 /* Composite data type, e.g. a table's row type */
2407 Form_pg_attribute att_tup;
2410 Assert(attnum <= tupdesc->natts);
2411 att_tup = tupdesc->attrs[attnum - 1];
2414 * If dropped column, pretend it ain't there. See
2415 * notes in scanRTEForColumn.
2417 if (att_tup->attisdropped)
2419 (errcode(ERRCODE_UNDEFINED_COLUMN),
2420 errmsg("column \"%s\" of relation \"%s\" does not exist",
2421 NameStr(att_tup->attname),
2422 rte->eref->aliasname)));
2423 *vartype = att_tup->atttypid;
2424 *vartypmod = att_tup->atttypmod;
2425 *varcollid = att_tup->attcollation;
2427 else if (functypclass == TYPEFUNC_SCALAR)
2429 /* Base data type, i.e. scalar */
2430 *vartype = funcrettype;
2432 *varcollid = exprCollation(rtfunc->funcexpr);
2434 else if (functypclass == TYPEFUNC_RECORD)
2436 *vartype = list_nth_oid(rtfunc->funccoltypes,
2438 *vartypmod = list_nth_int(rtfunc->funccoltypmods,
2440 *varcollid = list_nth_oid(rtfunc->funccolcollations,
2446 * addRangeTableEntryForFunction should've caught
2449 elog(ERROR, "function in FROM has unsupported return type");
2453 atts_done += rtfunc->funccolcount;
2456 /* If we get here, must be looking for the ordinality column */
2457 if (rte->funcordinality && attnum == atts_done + 1)
2461 *varcollid = InvalidOid;
2465 /* this probably can't happen ... */
2467 (errcode(ERRCODE_UNDEFINED_COLUMN),
2468 errmsg("column %d of relation \"%s\" does not exist",
2470 rte->eref->aliasname)));
2475 /* Values RTE --- get type info from first sublist */
2476 /* collation is stored separately, though */
2477 List *collist = (List *) linitial(rte->values_lists);
2480 if (attnum < 1 || attnum > list_length(collist))
2481 elog(ERROR, "values list %s does not have attribute %d",
2482 rte->eref->aliasname, attnum);
2483 col = (Node *) list_nth(collist, attnum - 1);
2484 *vartype = exprType(col);
2485 *vartypmod = exprTypmod(col);
2486 *varcollid = list_nth_oid(rte->values_collations, attnum - 1);
2492 * Join RTE --- get type info from join RTE's alias variable
2496 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2497 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2498 Assert(aliasvar != NULL);
2499 *vartype = exprType(aliasvar);
2500 *vartypmod = exprTypmod(aliasvar);
2501 *varcollid = exprCollation(aliasvar);
2506 /* CTE RTE --- get type info from lists in the RTE */
2507 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2508 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2509 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2510 *varcollid = list_nth_oid(rte->ctecolcollations, attnum - 1);
2514 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2519 * get_rte_attribute_is_dropped
2520 * Check whether attempted attribute ref is to a dropped column
2523 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2527 switch (rte->rtekind)
2532 * Plain relation RTE --- get the attribute's catalog entry
2535 Form_pg_attribute att_tup;
2537 tp = SearchSysCache2(ATTNUM,
2538 ObjectIdGetDatum(rte->relid),
2539 Int16GetDatum(attnum));
2540 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2541 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2542 attnum, rte->relid);
2543 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2544 result = att_tup->attisdropped;
2545 ReleaseSysCache(tp);
2551 /* Subselect, Values, CTE RTEs never have dropped columns */
2557 * A join RTE would not have dropped columns when constructed,
2558 * but one in a stored rule might contain columns that were
2559 * dropped from the underlying tables, if said columns are
2560 * nowhere explicitly referenced in the rule. This will be
2561 * signaled to us by a null pointer in the joinaliasvars list.
2566 attnum > list_length(rte->joinaliasvars))
2567 elog(ERROR, "invalid varattno %d", attnum);
2568 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2570 result = (aliasvar == NULL);
2580 * Dropped attributes are only possible with functions that
2581 * return named composite types. In such a case we have to
2582 * look up the result type to see if it currently has this
2583 * column dropped. So first, loop over the funcs until we
2584 * find the one that covers the requested column.
2586 foreach(lc, rte->functions)
2588 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2590 if (attnum > atts_done &&
2591 attnum <= atts_done + rtfunc->funccolcount)
2593 TypeFuncClass functypclass;
2597 functypclass = get_expr_result_type(rtfunc->funcexpr,
2600 if (functypclass == TYPEFUNC_COMPOSITE)
2602 /* Composite data type, e.g. a table's row type */
2603 Form_pg_attribute att_tup;
2606 Assert(attnum - atts_done <= tupdesc->natts);
2607 att_tup = tupdesc->attrs[attnum - atts_done - 1];
2608 return att_tup->attisdropped;
2610 /* Otherwise, it can't have any dropped columns */
2613 atts_done += rtfunc->funccolcount;
2616 /* If we get here, must be looking for the ordinality column */
2617 if (rte->funcordinality && attnum == atts_done + 1)
2620 /* this probably can't happen ... */
2622 (errcode(ERRCODE_UNDEFINED_COLUMN),
2623 errmsg("column %d of relation \"%s\" does not exist",
2625 rte->eref->aliasname)));
2626 result = false; /* keep compiler quiet */
2630 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2631 result = false; /* keep compiler quiet */
2638 * Given a targetlist and a resno, return the matching TargetEntry
2640 * Returns NULL if resno is not present in list.
2642 * Note: we need to search, rather than just indexing with list_nth(),
2643 * because not all tlists are sorted by resno.
2646 get_tle_by_resno(List *tlist, AttrNumber resno)
2652 TargetEntry *tle = (TargetEntry *) lfirst(l);
2654 if (tle->resno == resno)
2661 * Given a Query and rangetable index, return relation's RowMarkClause if any
2663 * Returns NULL if relation is not selected FOR UPDATE/SHARE
2666 get_parse_rowmark(Query *qry, Index rtindex)
2670 foreach(l, qry->rowMarks)
2672 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2674 if (rc->rti == rtindex)
2681 * given relation and att name, return attnum of variable
2683 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2685 * This should only be used if the relation is already
2686 * heap_open()'ed. Use the cache version get_attnum()
2687 * for access to non-opened relations.
2690 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2694 for (i = 0; i < rd->rd_rel->relnatts; i++)
2696 Form_pg_attribute att = rd->rd_att->attrs[i];
2698 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2704 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2706 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2712 return InvalidAttrNumber;
2717 * Check attribute name to see if it is "special", e.g. "oid".
2718 * - thomas 2000-02-07
2720 * Note: this only discovers whether the name could be a system attribute.
2721 * Caller needs to verify that it really is an attribute of the rel,
2722 * at least in the case of "oid", which is now optional.
2725 specialAttNum(const char *attname)
2727 Form_pg_attribute sysatt;
2729 sysatt = SystemAttributeByName(attname,
2730 true /* "oid" will be accepted */ );
2732 return sysatt->attnum;
2733 return InvalidAttrNumber;
2738 * given attribute id, return name of that attribute
2740 * This should only be used if the relation is already
2741 * heap_open()'ed. Use the cache version get_atttype()
2742 * for access to non-opened relations.
2745 attnumAttName(Relation rd, int attid)
2749 Form_pg_attribute sysatt;
2751 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2752 return &sysatt->attname;
2754 if (attid > rd->rd_att->natts)
2755 elog(ERROR, "invalid attribute number %d", attid);
2756 return &rd->rd_att->attrs[attid - 1]->attname;
2760 * given attribute id, return type of that attribute
2762 * This should only be used if the relation is already
2763 * heap_open()'ed. Use the cache version get_atttype()
2764 * for access to non-opened relations.
2767 attnumTypeId(Relation rd, int attid)
2771 Form_pg_attribute sysatt;
2773 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2774 return sysatt->atttypid;
2776 if (attid > rd->rd_att->natts)
2777 elog(ERROR, "invalid attribute number %d", attid);
2778 return rd->rd_att->attrs[attid - 1]->atttypid;
2782 * given attribute id, return collation of that attribute
2784 * This should only be used if the relation is already heap_open()'ed.
2787 attnumCollationId(Relation rd, int attid)
2791 /* All system attributes are of noncollatable types. */
2794 if (attid > rd->rd_att->natts)
2795 elog(ERROR, "invalid attribute number %d", attid);
2796 return rd->rd_att->attrs[attid - 1]->attcollation;
2800 * Generate a suitable error about a missing RTE.
2802 * Since this is a very common type of error, we work rather hard to
2803 * produce a helpful message.
2806 errorMissingRTE(ParseState *pstate, RangeVar *relation)
2810 const char *badAlias = NULL;
2813 * Check to see if there are any potential matches in the query's
2814 * rangetable. (Note: cases involving a bad schema name in the RangeVar
2815 * will throw error immediately here. That seems OK.)
2817 rte = searchRangeTableForRel(pstate, relation);
2820 * If we found a match that has an alias and the alias is visible in the
2821 * namespace, then the problem is probably use of the relation's real name
2822 * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2823 * common enough to justify a specific hint.
2825 * If we found a match that doesn't meet those criteria, assume the
2826 * problem is illegal use of a relation outside its scope, as in the
2827 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2829 if (rte && rte->alias &&
2830 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2831 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2833 &sublevels_up) == rte)
2834 badAlias = rte->eref->aliasname;
2838 (errcode(ERRCODE_UNDEFINED_TABLE),
2839 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2842 errhint("Perhaps you meant to reference the table alias \"%s\".",
2844 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2845 rte->eref->aliasname)),
2846 parser_errposition(pstate, relation->location)));
2849 (errcode(ERRCODE_UNDEFINED_TABLE),
2850 errmsg("missing FROM-clause entry for table \"%s\"",
2852 parser_errposition(pstate, relation->location)));
2856 * Generate a suitable error about a missing column.
2858 * Since this is a very common type of error, we work rather hard to
2859 * produce a helpful message.
2862 errorMissingColumn(ParseState *pstate,
2863 char *relname, char *colname, int location)
2868 * If relname was given, just play dumb and report it. (In practice, a
2869 * bad qualification name should end up at errorMissingRTE, not here, so
2870 * no need to work hard on this case.)
2874 (errcode(ERRCODE_UNDEFINED_COLUMN),
2875 errmsg("column %s.%s does not exist", relname, colname),
2876 parser_errposition(pstate, location)));
2879 * Otherwise, search the entire rtable looking for possible matches. If
2880 * we find one, emit a hint about it.
2882 * TODO: improve this code (and also errorMissingRTE) to mention using
2883 * LATERAL if appropriate.
2885 rte = searchRangeTableForCol(pstate, colname, location);
2888 (errcode(ERRCODE_UNDEFINED_COLUMN),
2889 errmsg("column \"%s\" does not exist", colname),
2890 rte ? errhint("There is a column named \"%s\" in table \"%s\", but it cannot be referenced from this part of the query.",
2891 colname, rte->eref->aliasname) : 0,
2892 parser_errposition(pstate, location)));
2897 * Examine a fully-parsed query, and return TRUE iff any relation underlying
2898 * the query is a temporary relation (table, view, or materialized view).
2901 isQueryUsingTempRelation(Query *query)
2903 return isQueryUsingTempRelation_walker((Node *) query, NULL);
2907 isQueryUsingTempRelation_walker(Node *node, void *context)
2912 if (IsA(node, Query))
2914 Query *query = (Query *) node;
2917 foreach(rtable, query->rtable)
2919 RangeTblEntry *rte = lfirst(rtable);
2921 if (rte->rtekind == RTE_RELATION)
2923 Relation rel = heap_open(rte->relid, AccessShareLock);
2924 char relpersistence = rel->rd_rel->relpersistence;
2926 heap_close(rel, AccessShareLock);
2927 if (relpersistence == RELPERSISTENCE_TEMP)
2932 return query_tree_walker(query,
2933 isQueryUsingTempRelation_walker,
2935 QTW_IGNORE_JOINALIASES);
2938 return expression_tree_walker(node,
2939 isQueryUsingTempRelation_walker,