1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2012, 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/sysattr.h"
20 #include "catalog/heap.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_type.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/parsetree.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/rel.h"
32 #include "utils/syscache.h"
35 static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
36 const char *refname, int location);
37 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
39 static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
40 int rtindex, AttrNumber col);
41 static void expandRelation(Oid relid, Alias *eref,
42 int rtindex, int sublevels_up,
43 int location, bool include_dropped,
44 List **colnames, List **colvars);
45 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
46 int rtindex, int sublevels_up,
47 int location, bool include_dropped,
48 List **colnames, List **colvars);
49 static int specialAttNum(const char *attname);
53 * refnameRangeTblEntry
54 * Given a possibly-qualified refname, look to see if it matches any RTE.
55 * If so, return a pointer to the RangeTblEntry; else return NULL.
57 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
58 * If sublevels_up is NULL, only consider items at the current nesting
61 * An unqualified refname (schemaname == NULL) can match any RTE with matching
62 * alias, or matching unqualified relname in the case of alias-less relation
63 * RTEs. It is possible that such a refname matches multiple RTEs in the
64 * nearest nesting level that has a match; if so, we report an error via
67 * A qualified refname (schemaname != NULL) can only match a relation RTE
68 * that (a) has no alias and (b) is for the same relation identified by
69 * schemaname.refname. In this case we convert schemaname.refname to a
70 * relation OID and search by relid, rather than by alias name. This is
71 * peculiar, but it's what SQL92 says to do.
74 refnameRangeTblEntry(ParseState *pstate,
75 const char *schemaname,
80 Oid relId = InvalidOid;
85 if (schemaname != NULL)
90 * We can use LookupNamespaceNoError() here because we are only
91 * interested in finding existing RTEs. Checking USAGE permission on
92 * the schema is unnecessary since it would have already been checked
93 * when the RTE was made. Furthermore, we want to report "RTE not
94 * found", not "no permissions for schema", if the name happens to
95 * match a schema name the user hasn't got access to.
97 namespaceId = LookupNamespaceNoError(schemaname);
98 if (!OidIsValid(namespaceId))
100 relId = get_relname_relid(refname, namespaceId);
101 if (!OidIsValid(relId))
105 while (pstate != NULL)
107 RangeTblEntry *result;
109 if (OidIsValid(relId))
110 result = scanNameSpaceForRelid(pstate, relId, location);
112 result = scanNameSpaceForRefname(pstate, refname, location);
122 pstate = pstate->parentParseState;
128 * Search the query's table namespace for an RTE matching the
129 * given unqualified refname. Return the RTE if a unique match, or NULL
130 * if no match. Raise error if multiple matches.
132 static RangeTblEntry *
133 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
135 RangeTblEntry *result = NULL;
138 foreach(l, pstate->p_relnamespace)
140 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
142 if (strcmp(rte->eref->aliasname, refname) == 0)
146 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
147 errmsg("table reference \"%s\" is ambiguous",
149 parser_errposition(pstate, location)));
157 * Search the query's table namespace for a relation RTE matching the
158 * given relation OID. Return the RTE if a unique match, or NULL
159 * if no match. Raise error if multiple matches (which shouldn't
160 * happen if the namespace was checked correctly when it was created).
162 * See the comments for refnameRangeTblEntry to understand why this
163 * acts the way it does.
165 static RangeTblEntry *
166 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
168 RangeTblEntry *result = NULL;
171 foreach(l, pstate->p_relnamespace)
173 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
175 /* yes, the test for alias == NULL should be there... */
176 if (rte->rtekind == RTE_RELATION &&
177 rte->relid == relid &&
182 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
183 errmsg("table reference %u is ambiguous",
185 parser_errposition(pstate, location)));
193 * Search the query's CTE namespace for a CTE matching the given unqualified
194 * refname. Return the CTE (and its levelsup count) if a match, or NULL
195 * if no match. We need not worry about multiple matches, since parse_cte.c
196 * rejects WITH lists containing duplicate CTE names.
199 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
206 pstate = pstate->parentParseState, levelsup++)
210 foreach(lc, pstate->p_ctenamespace)
212 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
214 if (strcmp(cte->ctename, refname) == 0)
216 *ctelevelsup = levelsup;
225 * Search for a possible "future CTE", that is one that is not yet in scope
226 * according to the WITH scoping rules. This has nothing to do with valid
227 * SQL semantics, but it's important for error reporting purposes.
230 isFutureCTE(ParseState *pstate, const char *refname)
232 for (; pstate != NULL; pstate = pstate->parentParseState)
236 foreach(lc, pstate->p_future_ctes)
238 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
240 if (strcmp(cte->ctename, refname) == 0)
249 * See if any RangeTblEntry could possibly match the RangeVar.
250 * If so, return a pointer to the RangeTblEntry; else return NULL.
252 * This is different from refnameRangeTblEntry in that it considers every
253 * entry in the ParseState's rangetable(s), not only those that are currently
254 * visible in the p_relnamespace lists. This behavior is invalid per the SQL
255 * spec, and it may give ambiguous results (there might be multiple equally
256 * valid matches, but only one will be returned). This must be used ONLY
257 * as a heuristic in giving suitable error messages. See errorMissingRTE.
259 * Notice that we consider both matches on actual relation (or CTE) name
260 * and matches on alias.
262 static RangeTblEntry *
263 searchRangeTable(ParseState *pstate, RangeVar *relation)
265 const char *refname = relation->relname;
266 Oid relId = InvalidOid;
267 CommonTableExpr *cte = NULL;
268 Index ctelevelsup = 0;
272 * If it's an unqualified name, check for possible CTE matches. A CTE
273 * hides any real relation matches. If no CTE, look for a matching
276 * NB: It's not critical that RangeVarGetRelid return the correct answer
277 * here in the face of concurrent DDL. If it doesn't, the worst case
278 * scenario is a less-clear error message. Also, the tables involved in
279 * the query are already locked, which reduces the number of cases in
280 * which surprising behavior can occur. So we do the name lookup
283 if (!relation->schemaname)
284 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
286 relId = RangeVarGetRelid(relation, NoLock, true);
288 /* Now look for RTEs matching either the relation/CTE or the alias */
291 pstate = pstate->parentParseState, levelsup++)
295 foreach(l, pstate->p_rtable)
297 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
299 if (rte->rtekind == RTE_RELATION &&
303 if (rte->rtekind == RTE_CTE &&
305 rte->ctelevelsup + levelsup == ctelevelsup &&
306 strcmp(rte->ctename, refname) == 0)
308 if (strcmp(rte->eref->aliasname, refname) == 0)
316 * Check for relation-name conflicts between two relnamespace lists.
317 * Raise an error if any is found.
319 * Note: we assume that each given argument does not contain conflicts
320 * itself; we just want to know if the two can be merged together.
322 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
323 * they have the same eref->aliasname (ie, same relation name), if they
324 * are for different relation OIDs (implying they are in different schemas).
327 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
332 foreach(l1, namespace1)
334 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
335 const char *aliasname1 = rte1->eref->aliasname;
338 foreach(l2, namespace2)
340 RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
342 if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
343 continue; /* definitely no conflict */
344 if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
345 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
346 rte1->relid != rte2->relid)
347 continue; /* no conflict per SQL92 rule */
349 (errcode(ERRCODE_DUPLICATE_ALIAS),
350 errmsg("table name \"%s\" specified more than once",
357 * given an RTE, return RT index (starting with 1) of the entry,
358 * and optionally get its nesting depth (0 = current). If sublevels_up
359 * is NULL, only consider rels at the current nesting level.
360 * Raises error if RTE not found.
363 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
371 while (pstate != NULL)
374 foreach(l, pstate->p_rtable)
376 if (rte == (RangeTblEntry *) lfirst(l))
380 pstate = pstate->parentParseState;
387 elog(ERROR, "RTE not found (internal error)");
388 return 0; /* keep compiler quiet */
392 * Given an RT index and nesting depth, find the corresponding RTE.
393 * This is the inverse of RTERangeTablePosn.
396 GetRTEByRangeTablePosn(ParseState *pstate,
400 while (sublevels_up-- > 0)
402 pstate = pstate->parentParseState;
403 Assert(pstate != NULL);
405 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
406 return rt_fetch(varno, pstate->p_rtable);
410 * Fetch the CTE for a CTE-reference RTE.
412 * rtelevelsup is the number of query levels above the given pstate that the
413 * RTE came from. Callers that don't have this information readily available
414 * may pass -1 instead.
417 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
422 /* Determine RTE's levelsup if caller didn't know it */
424 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
426 Assert(rte->rtekind == RTE_CTE);
427 levelsup = rte->ctelevelsup + rtelevelsup;
428 while (levelsup-- > 0)
430 pstate = pstate->parentParseState;
431 if (!pstate) /* shouldn't happen */
432 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
434 foreach(lc, pstate->p_ctenamespace)
436 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
438 if (strcmp(cte->ctename, rte->ctename) == 0)
441 /* shouldn't happen */
442 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
443 return NULL; /* keep compiler quiet */
448 * Search the column names of a single RTE for the given name.
449 * If found, return an appropriate Var node, else return NULL.
450 * If the name proves ambiguous within this RTE, raise error.
452 * Side effect: if we find a match, mark the RTE as requiring read access
456 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
465 * Scan the user column names (or aliases) for a match. Complain if
468 * Note: eref->colnames may include entries for dropped columns, but those
469 * will be empty strings that cannot match any legal SQL identifier, so we
470 * don't bother to test for that case here.
472 * Should this somehow go wrong and we try to access a dropped column,
473 * we'll still catch it by virtue of the checks in
474 * get_rte_attribute_type(), which is called by make_var(). That routine
475 * has to do a cache lookup anyway, so the check there is cheap.
477 foreach(c, rte->eref->colnames)
480 if (strcmp(strVal(lfirst(c)), colname) == 0)
484 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
485 errmsg("column reference \"%s\" is ambiguous",
487 parser_errposition(pstate, location)));
488 var = make_var(pstate, rte, attnum, location);
489 /* Require read access to the column */
490 markVarForSelectPriv(pstate, var, rte);
491 result = (Node *) var;
496 * If we have a unique match, return it. Note that this allows a user
497 * alias to override a system column name (such as OID) without error.
503 * If the RTE represents a real table, consider system column names.
505 if (rte->rtekind == RTE_RELATION)
507 /* quick check to see if name could be a system column */
508 attnum = specialAttNum(colname);
509 if (attnum != InvalidAttrNumber)
511 /* now check to see if column actually is defined */
512 if (SearchSysCacheExists2(ATTNUM,
513 ObjectIdGetDatum(rte->relid),
514 Int16GetDatum(attnum)))
516 var = make_var(pstate, rte, attnum, location);
517 /* Require read access to the column */
518 markVarForSelectPriv(pstate, var, rte);
519 result = (Node *) var;
529 * Search for an unqualified column name.
530 * If found, return the appropriate Var node (or expression).
531 * If not found, return NULL. If the name proves ambiguous, raise error.
532 * If localonly is true, only names in the innermost query are considered.
535 colNameToVar(ParseState *pstate, char *colname, bool localonly,
539 ParseState *orig_pstate = pstate;
541 while (pstate != NULL)
545 foreach(l, pstate->p_varnamespace)
547 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
550 /* use orig_pstate here to get the right sublevels_up */
551 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
557 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
558 errmsg("column reference \"%s\" is ambiguous",
560 parser_errposition(orig_pstate, location)));
565 if (result != NULL || localonly)
566 break; /* found, or don't want to look at parent */
568 pstate = pstate->parentParseState;
575 * markRTEForSelectPriv
576 * Mark the specified column of an RTE as requiring SELECT privilege
578 * col == InvalidAttrNumber means a "whole row" reference
580 * The caller should pass the actual RTE if it has it handy; otherwise pass
581 * NULL, and we'll look it up here. (This uglification of the API is
582 * worthwhile because nearly all external callers have the RTE at hand.)
585 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
586 int rtindex, AttrNumber col)
589 rte = rt_fetch(rtindex, pstate->p_rtable);
591 if (rte->rtekind == RTE_RELATION)
593 /* Make sure the rel as a whole is marked for SELECT access */
594 rte->requiredPerms |= ACL_SELECT;
595 /* Must offset the attnum to fit in a bitmapset */
596 rte->selectedCols = bms_add_member(rte->selectedCols,
597 col - FirstLowInvalidHeapAttributeNumber);
599 else if (rte->rtekind == RTE_JOIN)
601 if (col == InvalidAttrNumber)
604 * A whole-row reference to a join has to be treated as whole-row
605 * references to the two inputs.
609 if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
610 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
614 elog(ERROR, "could not find JoinExpr for whole-row reference");
615 Assert(IsA(j, JoinExpr));
617 /* Note: we can't see FromExpr here */
618 if (IsA(j->larg, RangeTblRef))
620 int varno = ((RangeTblRef *) j->larg)->rtindex;
622 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
624 else if (IsA(j->larg, JoinExpr))
626 int varno = ((JoinExpr *) j->larg)->rtindex;
628 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
631 elog(ERROR, "unrecognized node type: %d",
632 (int) nodeTag(j->larg));
633 if (IsA(j->rarg, RangeTblRef))
635 int varno = ((RangeTblRef *) j->rarg)->rtindex;
637 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
639 else if (IsA(j->rarg, JoinExpr))
641 int varno = ((JoinExpr *) j->rarg)->rtindex;
643 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
646 elog(ERROR, "unrecognized node type: %d",
647 (int) nodeTag(j->rarg));
652 * Regular join attribute, look at the alias-variable list.
654 * The aliasvar could be either a Var or a COALESCE expression,
655 * but in the latter case we should already have marked the two
656 * referent variables as being selected, due to their use in the
657 * JOIN clause. So we need only be concerned with the simple Var
662 Assert(col > 0 && col <= list_length(rte->joinaliasvars));
663 aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
664 if (IsA(aliasvar, Var))
665 markVarForSelectPriv(pstate, aliasvar, NULL);
668 /* other RTE types don't require privilege marking */
672 * markVarForSelectPriv
673 * Mark the RTE referenced by a Var as requiring SELECT privilege
675 * The caller should pass the Var's referenced RTE if it has it handy
676 * (nearly all do); otherwise pass NULL.
679 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
683 Assert(IsA(var, Var));
684 /* Find the appropriate pstate if it's an uplevel Var */
685 for (lv = 0; lv < var->varlevelsup; lv++)
686 pstate = pstate->parentParseState;
687 markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
691 * buildRelationAliases
692 * Construct the eref column name list for a relation RTE.
693 * This code is also used for the case of a function RTE returning
694 * a named composite type.
696 * tupdesc: the physical column information
697 * alias: the user-supplied alias, or NULL if none
698 * eref: the eref Alias to store column names in
700 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
701 * empty strings for any dropped columns, so that it will be one-to-one with
702 * physical column numbers.
705 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
707 int maxattrs = tupdesc->natts;
713 Assert(eref->colnames == NIL);
717 aliaslc = list_head(alias->colnames);
718 numaliases = list_length(alias->colnames);
719 /* We'll rebuild the alias colname list */
720 alias->colnames = NIL;
728 for (varattno = 0; varattno < maxattrs; varattno++)
730 Form_pg_attribute attr = tupdesc->attrs[varattno];
733 if (attr->attisdropped)
735 /* Always insert an empty string for a dropped column */
736 attrname = makeString(pstrdup(""));
738 alias->colnames = lappend(alias->colnames, attrname);
743 /* Use the next user-supplied alias */
744 attrname = (Value *) lfirst(aliaslc);
745 aliaslc = lnext(aliaslc);
746 alias->colnames = lappend(alias->colnames, attrname);
750 attrname = makeString(pstrdup(NameStr(attr->attname)));
751 /* we're done with the alias if any */
754 eref->colnames = lappend(eref->colnames, attrname);
757 /* Too many user-supplied aliases? */
760 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
761 errmsg("table \"%s\" has %d columns available but %d columns specified",
762 eref->aliasname, maxattrs - numdropped, numaliases)));
766 * buildScalarFunctionAlias
767 * Construct the eref column name list for a function RTE,
768 * when the function returns a scalar type (not composite or RECORD).
770 * funcexpr: transformed expression tree for the function call
771 * funcname: function name (used only for error message)
772 * alias: the user-supplied alias, or NULL if none
773 * eref: the eref Alias to store column names in
775 * eref->colnames is filled in.
778 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
779 Alias *alias, Alias *eref)
783 Assert(eref->colnames == NIL);
785 /* Use user-specified column alias if there is one. */
786 if (alias && alias->colnames != NIL)
788 if (list_length(alias->colnames) != 1)
790 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
791 errmsg("too many column aliases specified for function %s",
793 eref->colnames = copyObject(alias->colnames);
798 * If the expression is a simple function call, and the function has a
799 * single OUT parameter that is named, use the parameter's name.
801 if (funcexpr && IsA(funcexpr, FuncExpr))
803 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
806 eref->colnames = list_make1(makeString(pname));
812 * Otherwise use the previously-determined alias (not necessarily the
815 eref->colnames = list_make1(makeString(eref->aliasname));
819 * Open a table during parse analysis
821 * This is essentially just the same as heap_openrv(), except that it caters
822 * to some parser-specific error reporting needs, notably that it arranges
823 * to include the RangeVar's parse location in any resulting error.
825 * Note: properly, lockmode should be declared LOCKMODE not int, but that
826 * would require importing storage/lock.h into parse_relation.h. Since
827 * LOCKMODE is typedef'd as int anyway, that seems like overkill.
830 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
833 ParseCallbackState pcbstate;
835 setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
836 rel = heap_openrv_extended(relation, lockmode, true);
839 if (relation->schemaname)
841 (errcode(ERRCODE_UNDEFINED_TABLE),
842 errmsg("relation \"%s.%s\" does not exist",
843 relation->schemaname, relation->relname)));
847 * An unqualified name might have been meant as a reference to
848 * some not-yet-in-scope CTE. The bare "does not exist" message
849 * has proven remarkably unhelpful for figuring out such problems,
850 * so we take pains to offer a specific hint.
852 if (isFutureCTE(pstate, relation->relname))
854 (errcode(ERRCODE_UNDEFINED_TABLE),
855 errmsg("relation \"%s\" does not exist",
857 errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
859 errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
862 (errcode(ERRCODE_UNDEFINED_TABLE),
863 errmsg("relation \"%s\" does not exist",
864 relation->relname)));
867 cancel_parser_errposition_callback(&pcbstate);
872 * Add an entry for a relation to the pstate's range table (p_rtable).
874 * If pstate is NULL, we just build an RTE and return it without adding it
877 * Note: formerly this checked for refname conflicts, but that's wrong.
878 * Caller is responsible for checking for conflicts in the appropriate scope.
881 addRangeTableEntry(ParseState *pstate,
887 RangeTblEntry *rte = makeNode(RangeTblEntry);
888 char *refname = alias ? alias->aliasname : relation->relname;
892 rte->rtekind = RTE_RELATION;
896 * Get the rel's OID. This access also ensures that we have an up-to-date
897 * relcache entry for the rel. Since this is typically the first access
898 * to a rel in a statement, be careful to get the right access level
899 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
901 lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
902 rel = parserOpenTable(pstate, relation, lockmode);
903 rte->relid = RelationGetRelid(rel);
904 rte->relkind = rel->rd_rel->relkind;
907 * Build the list of effective column names using user-supplied aliases
908 * and/or actual column names.
910 rte->eref = makeAlias(refname, NIL);
911 buildRelationAliases(rel->rd_att, alias, rte->eref);
914 * Drop the rel refcount, but keep the access lock till end of transaction
915 * so that the table can't be deleted or have its schema modified
918 heap_close(rel, NoLock);
922 * - this RTE should be expanded to include descendant tables,
923 * - this RTE is in the FROM clause,
924 * - this RTE should be checked for appropriate access rights.
926 * The initial default on access checks is always check-for-READ-access,
927 * which is the right thing for all except target tables.
931 rte->inFromCl = inFromCl;
933 rte->requiredPerms = ACL_SELECT;
934 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
935 rte->selectedCols = NULL;
936 rte->modifiedCols = NULL;
939 * Add completed RTE to pstate's range table list, but not to join list
940 * nor namespace --- caller must do that if appropriate.
943 pstate->p_rtable = lappend(pstate->p_rtable, rte);
949 * Add an entry for a relation to the pstate's range table (p_rtable).
951 * This is just like addRangeTableEntry() except that it makes an RTE
952 * given an already-open relation instead of a RangeVar reference.
955 addRangeTableEntryForRelation(ParseState *pstate,
961 RangeTblEntry *rte = makeNode(RangeTblEntry);
962 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
964 rte->rtekind = RTE_RELATION;
966 rte->relid = RelationGetRelid(rel);
967 rte->relkind = rel->rd_rel->relkind;
970 * Build the list of effective column names using user-supplied aliases
971 * and/or actual column names.
973 rte->eref = makeAlias(refname, NIL);
974 buildRelationAliases(rel->rd_att, alias, rte->eref);
978 * - this RTE should be expanded to include descendant tables,
979 * - this RTE is in the FROM clause,
980 * - this RTE should be checked for appropriate access rights.
982 * The initial default on access checks is always check-for-READ-access,
983 * which is the right thing for all except target tables.
987 rte->inFromCl = inFromCl;
989 rte->requiredPerms = ACL_SELECT;
990 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
991 rte->selectedCols = NULL;
992 rte->modifiedCols = NULL;
995 * Add completed RTE to pstate's range table list, but not to join list
996 * nor namespace --- caller must do that if appropriate.
999 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1005 * Add an entry for a subquery to the pstate's range table (p_rtable).
1007 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1008 * Note that an alias clause *must* be supplied.
1011 addRangeTableEntryForSubquery(ParseState *pstate,
1016 RangeTblEntry *rte = makeNode(RangeTblEntry);
1017 char *refname = alias->aliasname;
1021 ListCell *tlistitem;
1023 rte->rtekind = RTE_SUBQUERY;
1024 rte->relid = InvalidOid;
1025 rte->subquery = subquery;
1028 eref = copyObject(alias);
1029 numaliases = list_length(eref->colnames);
1031 /* fill in any unspecified alias columns */
1033 foreach(tlistitem, subquery->targetList)
1035 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1040 Assert(varattno == te->resno);
1041 if (varattno > numaliases)
1045 attrname = pstrdup(te->resname);
1046 eref->colnames = lappend(eref->colnames, makeString(attrname));
1049 if (varattno < numaliases)
1051 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1052 errmsg("table \"%s\" has %d columns available but %d columns specified",
1053 refname, varattno, numaliases)));
1059 * - this RTE should be expanded to include descendant tables,
1060 * - this RTE is in the FROM clause,
1061 * - this RTE should be checked for appropriate access rights.
1063 * Subqueries are never checked for access rights.
1066 rte->inh = false; /* never true for subqueries */
1067 rte->inFromCl = inFromCl;
1069 rte->requiredPerms = 0;
1070 rte->checkAsUser = InvalidOid;
1071 rte->selectedCols = NULL;
1072 rte->modifiedCols = NULL;
1075 * Add completed RTE to pstate's range table list, but not to join list
1076 * nor namespace --- caller must do that if appropriate.
1079 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1085 * Add an entry for a function to the pstate's range table (p_rtable).
1087 * This is just like addRangeTableEntry() except that it makes a function RTE.
1090 addRangeTableEntryForFunction(ParseState *pstate,
1093 RangeFunction *rangefunc,
1096 RangeTblEntry *rte = makeNode(RangeTblEntry);
1097 TypeFuncClass functypclass;
1100 Alias *alias = rangefunc->alias;
1101 List *coldeflist = rangefunc->coldeflist;
1104 rte->rtekind = RTE_FUNCTION;
1105 rte->relid = InvalidOid;
1106 rte->subquery = NULL;
1107 rte->funcexpr = funcexpr;
1108 rte->funccoltypes = NIL;
1109 rte->funccoltypmods = NIL;
1110 rte->funccolcollations = NIL;
1113 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1117 * Now determine if the function returns a simple or composite type.
1119 functypclass = get_expr_result_type(funcexpr,
1124 * A coldeflist is required if the function returns RECORD and hasn't got
1125 * a predetermined record type, and is prohibited otherwise.
1127 if (coldeflist != NIL)
1129 if (functypclass != TYPEFUNC_RECORD)
1131 (errcode(ERRCODE_SYNTAX_ERROR),
1132 errmsg("a column definition list is only allowed for functions returning \"record\""),
1133 parser_errposition(pstate, exprLocation(funcexpr))));
1137 if (functypclass == TYPEFUNC_RECORD)
1139 (errcode(ERRCODE_SYNTAX_ERROR),
1140 errmsg("a column definition list is required for functions returning \"record\""),
1141 parser_errposition(pstate, exprLocation(funcexpr))));
1144 if (functypclass == TYPEFUNC_COMPOSITE)
1146 /* Composite data type, e.g. a table's row type */
1148 /* Build the column alias list */
1149 buildRelationAliases(tupdesc, alias, eref);
1151 else if (functypclass == TYPEFUNC_SCALAR)
1153 /* Base data type, i.e. scalar */
1154 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1156 else if (functypclass == TYPEFUNC_RECORD)
1161 * Use the column definition list to form the alias list and
1162 * funccoltypes/funccoltypmods/funccolcollations lists.
1164 foreach(col, coldeflist)
1166 ColumnDef *n = (ColumnDef *) lfirst(col);
1172 attrname = pstrdup(n->colname);
1173 if (n->typeName->setof)
1175 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1176 errmsg("column \"%s\" cannot be declared SETOF",
1178 parser_errposition(pstate, n->typeName->location)));
1179 typenameTypeIdAndMod(pstate, n->typeName, &attrtype, &attrtypmod);
1180 attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1181 eref->colnames = lappend(eref->colnames, makeString(attrname));
1182 rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1183 rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1184 rte->funccolcollations = lappend_oid(rte->funccolcollations,
1190 (errcode(ERRCODE_DATATYPE_MISMATCH),
1191 errmsg("function \"%s\" in FROM has unsupported return type %s",
1192 funcname, format_type_be(funcrettype)),
1193 parser_errposition(pstate, exprLocation(funcexpr))));
1197 * - this RTE should be expanded to include descendant tables,
1198 * - this RTE is in the FROM clause,
1199 * - this RTE should be checked for appropriate access rights.
1201 * Functions are never checked for access rights (at least, not by
1202 * the RTE permissions mechanism).
1205 rte->inh = false; /* never true for functions */
1206 rte->inFromCl = inFromCl;
1208 rte->requiredPerms = 0;
1209 rte->checkAsUser = InvalidOid;
1210 rte->selectedCols = NULL;
1211 rte->modifiedCols = NULL;
1214 * Add completed RTE to pstate's range table list, but not to join list
1215 * nor namespace --- caller must do that if appropriate.
1218 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1224 * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1226 * This is much like addRangeTableEntry() except that it makes a values RTE.
1229 addRangeTableEntryForValues(ParseState *pstate,
1235 RangeTblEntry *rte = makeNode(RangeTblEntry);
1236 char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1241 rte->rtekind = RTE_VALUES;
1242 rte->relid = InvalidOid;
1243 rte->subquery = NULL;
1244 rte->values_lists = exprs;
1245 rte->values_collations = collations;
1248 eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1250 /* fill in any unspecified alias columns */
1251 numcolumns = list_length((List *) linitial(exprs));
1252 numaliases = list_length(eref->colnames);
1253 while (numaliases < numcolumns)
1258 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1259 eref->colnames = lappend(eref->colnames,
1260 makeString(pstrdup(attrname)));
1262 if (numcolumns < numaliases)
1264 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1265 errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1266 refname, numcolumns, numaliases)));
1272 * - this RTE should be expanded to include descendant tables,
1273 * - this RTE is in the FROM clause,
1274 * - this RTE should be checked for appropriate access rights.
1276 * Subqueries are never checked for access rights.
1279 rte->inh = false; /* never true for values RTEs */
1280 rte->inFromCl = inFromCl;
1282 rte->requiredPerms = 0;
1283 rte->checkAsUser = InvalidOid;
1284 rte->selectedCols = NULL;
1285 rte->modifiedCols = NULL;
1288 * Add completed RTE to pstate's range table list, but not to join list
1289 * nor namespace --- caller must do that if appropriate.
1292 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1298 * Add an entry for a join to the pstate's range table (p_rtable).
1300 * This is much like addRangeTableEntry() except that it makes a join RTE.
1303 addRangeTableEntryForJoin(ParseState *pstate,
1310 RangeTblEntry *rte = makeNode(RangeTblEntry);
1315 * Fail if join has too many columns --- we must be able to reference any
1316 * of the columns with an AttrNumber.
1318 if (list_length(aliasvars) > MaxAttrNumber)
1320 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1321 errmsg("joins can have at most %d columns",
1324 rte->rtekind = RTE_JOIN;
1325 rte->relid = InvalidOid;
1326 rte->subquery = NULL;
1327 rte->jointype = jointype;
1328 rte->joinaliasvars = aliasvars;
1331 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1332 numaliases = list_length(eref->colnames);
1334 /* fill in any unspecified alias columns */
1335 if (numaliases < list_length(colnames))
1336 eref->colnames = list_concat(eref->colnames,
1337 list_copy_tail(colnames, numaliases));
1343 * - this RTE should be expanded to include descendant tables,
1344 * - this RTE is in the FROM clause,
1345 * - this RTE should be checked for appropriate access rights.
1347 * Joins are never checked for access rights.
1350 rte->inh = false; /* never true for joins */
1351 rte->inFromCl = inFromCl;
1353 rte->requiredPerms = 0;
1354 rte->checkAsUser = InvalidOid;
1355 rte->selectedCols = NULL;
1356 rte->modifiedCols = NULL;
1359 * Add completed RTE to pstate's range table list, but not to join list
1360 * nor namespace --- caller must do that if appropriate.
1363 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1369 * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1371 * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1374 addRangeTableEntryForCTE(ParseState *pstate,
1375 CommonTableExpr *cte,
1380 RangeTblEntry *rte = makeNode(RangeTblEntry);
1381 Alias *alias = rv->alias;
1382 char *refname = alias ? alias->aliasname : cte->ctename;
1388 rte->rtekind = RTE_CTE;
1389 rte->ctename = cte->ctename;
1390 rte->ctelevelsup = levelsup;
1392 /* Self-reference if and only if CTE's parse analysis isn't completed */
1393 rte->self_reference = !IsA(cte->ctequery, Query);
1394 Assert(cte->cterecursive || !rte->self_reference);
1395 /* Bump the CTE's refcount if this isn't a self-reference */
1396 if (!rte->self_reference)
1400 * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
1401 * This won't get checked in case of a self-reference, but that's OK
1402 * because data-modifying CTEs aren't allowed to be recursive anyhow.
1404 if (IsA(cte->ctequery, Query))
1406 Query *ctequery = (Query *) cte->ctequery;
1408 if (ctequery->commandType != CMD_SELECT &&
1409 ctequery->returningList == NIL)
1411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1412 errmsg("WITH query \"%s\" does not have a RETURNING clause",
1414 parser_errposition(pstate, rv->location)));
1417 rte->ctecoltypes = cte->ctecoltypes;
1418 rte->ctecoltypmods = cte->ctecoltypmods;
1419 rte->ctecolcollations = cte->ctecolcollations;
1423 eref = copyObject(alias);
1425 eref = makeAlias(refname, NIL);
1426 numaliases = list_length(eref->colnames);
1428 /* fill in any unspecified alias columns */
1430 foreach(lc, cte->ctecolnames)
1433 if (varattno > numaliases)
1434 eref->colnames = lappend(eref->colnames, lfirst(lc));
1436 if (varattno < numaliases)
1438 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1439 errmsg("table \"%s\" has %d columns available but %d columns specified",
1440 refname, varattno, numaliases)));
1446 * - this RTE should be expanded to include descendant tables,
1447 * - this RTE is in the FROM clause,
1448 * - this RTE should be checked for appropriate access rights.
1450 * Subqueries are never checked for access rights.
1453 rte->inh = false; /* never true for subqueries */
1454 rte->inFromCl = inFromCl;
1456 rte->requiredPerms = 0;
1457 rte->checkAsUser = InvalidOid;
1458 rte->selectedCols = NULL;
1459 rte->modifiedCols = NULL;
1462 * Add completed RTE to pstate's range table list, but not to join list
1463 * nor namespace --- caller must do that if appropriate.
1466 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1473 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1475 * This is used when we have not yet done transformLockingClause, but need
1476 * to know the correct lock to take during initial opening of relations.
1478 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1479 * since the table-level lock is the same either way.
1482 isLockedRefname(ParseState *pstate, const char *refname)
1487 * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1488 * parent level, then act as though there's a generic FOR UPDATE here.
1490 if (pstate->p_locked_from_parent)
1493 foreach(l, pstate->p_locking_clause)
1495 LockingClause *lc = (LockingClause *) lfirst(l);
1497 if (lc->lockedRels == NIL)
1499 /* all tables used in query */
1504 /* just the named tables */
1507 foreach(l2, lc->lockedRels)
1509 RangeVar *thisrel = (RangeVar *) lfirst(l2);
1511 if (strcmp(refname, thisrel->relname) == 0)
1520 * Add the given RTE as a top-level entry in the pstate's join list
1521 * and/or name space lists. (We assume caller has checked for any
1522 * namespace conflicts.)
1525 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1527 bool addToRelNameSpace, bool addToVarNameSpace)
1531 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1532 RangeTblRef *rtr = makeNode(RangeTblRef);
1534 rtr->rtindex = rtindex;
1535 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1537 if (addToRelNameSpace)
1538 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1539 if (addToVarNameSpace)
1540 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1544 * expandRTE -- expand the columns of a rangetable entry
1546 * This creates lists of an RTE's column names (aliases if provided, else
1547 * real names) and Vars for each column. Only user columns are considered.
1548 * If include_dropped is FALSE then dropped columns are omitted from the
1549 * results. If include_dropped is TRUE then empty strings and NULL constants
1550 * (not Vars!) are returned for dropped columns.
1552 * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1553 * values to use in the created Vars. Ordinarily rtindex should match the
1554 * actual position of the RTE in its rangetable.
1556 * The output lists go into *colnames and *colvars.
1557 * If only one of the two kinds of output list is needed, pass NULL for the
1558 * output pointer for the unwanted one.
1561 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1562 int location, bool include_dropped,
1563 List **colnames, List **colvars)
1572 switch (rte->rtekind)
1575 /* Ordinary relation RTE */
1576 expandRelation(rte->relid, rte->eref,
1577 rtindex, sublevels_up, location,
1578 include_dropped, colnames, colvars);
1583 ListCell *aliasp_item = list_head(rte->eref->colnames);
1584 ListCell *tlistitem;
1587 foreach(tlistitem, rte->subquery->targetList)
1589 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1594 Assert(varattno == te->resno);
1598 /* Assume there is one alias per target item */
1599 char *label = strVal(lfirst(aliasp_item));
1601 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1602 aliasp_item = lnext(aliasp_item);
1609 varnode = makeVar(rtindex, varattno,
1610 exprType((Node *) te->expr),
1611 exprTypmod((Node *) te->expr),
1612 exprCollation((Node *) te->expr),
1614 varnode->location = location;
1616 *colvars = lappend(*colvars, varnode);
1624 TypeFuncClass functypclass;
1628 functypclass = get_expr_result_type(rte->funcexpr,
1631 if (functypclass == TYPEFUNC_COMPOSITE)
1633 /* Composite data type, e.g. a table's row type */
1635 expandTupleDesc(tupdesc, rte->eref,
1636 rtindex, sublevels_up, location,
1637 include_dropped, colnames, colvars);
1639 else if (functypclass == TYPEFUNC_SCALAR)
1641 /* Base data type, i.e. scalar */
1643 *colnames = lappend(*colnames,
1644 linitial(rte->eref->colnames));
1650 varnode = makeVar(rtindex, 1,
1652 exprCollation(rte->funcexpr),
1654 varnode->location = location;
1656 *colvars = lappend(*colvars, varnode);
1659 else if (functypclass == TYPEFUNC_RECORD)
1662 *colnames = copyObject(rte->eref->colnames);
1670 forthree(l1, rte->funccoltypes,
1671 l2, rte->funccoltypmods,
1672 l3, rte->funccolcollations)
1674 Oid attrtype = lfirst_oid(l1);
1675 int32 attrtypmod = lfirst_int(l2);
1676 Oid attrcollation = lfirst_oid(l3);
1680 varnode = makeVar(rtindex,
1686 varnode->location = location;
1687 *colvars = lappend(*colvars, varnode);
1693 /* addRangeTableEntryForFunction should've caught this */
1694 elog(ERROR, "function in FROM has unsupported return type");
1701 ListCell *aliasp_item = list_head(rte->eref->colnames);
1706 forboth(lcv, (List *) linitial(rte->values_lists),
1707 lcc, rte->values_collations)
1709 Node *col = (Node *) lfirst(lcv);
1710 Oid colcollation = lfirst_oid(lcc);
1715 /* Assume there is one alias per column */
1716 char *label = strVal(lfirst(aliasp_item));
1718 *colnames = lappend(*colnames,
1719 makeString(pstrdup(label)));
1720 aliasp_item = lnext(aliasp_item);
1727 varnode = makeVar(rtindex, varattno,
1732 varnode->location = location;
1733 *colvars = lappend(*colvars, varnode);
1744 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1747 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1749 Node *avar = (Node *) lfirst(aliasvar);
1754 * During ordinary parsing, there will never be any
1755 * deleted columns in the join; but we have to check since
1756 * this routine is also used by the rewriter, and joins
1757 * found in stored rules might have join columns for
1758 * since-deleted columns. This will be signaled by a NULL
1759 * Const in the alias-vars list.
1761 if (IsA(avar, Const))
1763 if (include_dropped)
1766 *colnames = lappend(*colnames,
1767 makeString(pstrdup("")));
1769 *colvars = lappend(*colvars,
1777 char *label = strVal(lfirst(colname));
1779 *colnames = lappend(*colnames,
1780 makeString(pstrdup(label)));
1787 varnode = makeVar(rtindex, varattno,
1790 exprCollation(avar),
1792 varnode->location = location;
1794 *colvars = lappend(*colvars, varnode);
1801 ListCell *aliasp_item = list_head(rte->eref->colnames);
1807 forthree(lct, rte->ctecoltypes,
1808 lcm, rte->ctecoltypmods,
1809 lcc, rte->ctecolcollations)
1811 Oid coltype = lfirst_oid(lct);
1812 int32 coltypmod = lfirst_int(lcm);
1813 Oid colcoll = lfirst_oid(lcc);
1819 /* Assume there is one alias per output column */
1820 char *label = strVal(lfirst(aliasp_item));
1822 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1823 aliasp_item = lnext(aliasp_item);
1830 varnode = makeVar(rtindex, varattno,
1831 coltype, coltypmod, colcoll,
1833 *colvars = lappend(*colvars, varnode);
1839 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1844 * expandRelation -- expandRTE subroutine
1847 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1848 int location, bool include_dropped,
1849 List **colnames, List **colvars)
1853 /* Get the tupledesc and turn it over to expandTupleDesc */
1854 rel = relation_open(relid, AccessShareLock);
1855 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1856 location, include_dropped,
1858 relation_close(rel, AccessShareLock);
1862 * expandTupleDesc -- expandRTE subroutine
1865 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1866 int rtindex, int sublevels_up,
1867 int location, bool include_dropped,
1868 List **colnames, List **colvars)
1870 int maxattrs = tupdesc->natts;
1871 int numaliases = list_length(eref->colnames);
1874 for (varattno = 0; varattno < maxattrs; varattno++)
1876 Form_pg_attribute attr = tupdesc->attrs[varattno];
1878 if (attr->attisdropped)
1880 if (include_dropped)
1883 *colnames = lappend(*colnames, makeString(pstrdup("")));
1887 * can't use atttypid here, but it doesn't really matter
1888 * what type the Const claims to be.
1890 *colvars = lappend(*colvars,
1891 makeNullConst(INT4OID, -1, InvalidOid));
1901 if (varattno < numaliases)
1902 label = strVal(list_nth(eref->colnames, varattno));
1904 label = NameStr(attr->attname);
1905 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1912 varnode = makeVar(rtindex, attr->attnum,
1913 attr->atttypid, attr->atttypmod,
1916 varnode->location = location;
1918 *colvars = lappend(*colvars, varnode);
1925 * Workhorse for "*" expansion: produce a list of targetentries
1926 * for the attributes of the RTE
1928 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1929 * fields of the Vars produced, and location sets their location.
1930 * pstate->p_next_resno determines the resnos assigned to the TLEs.
1931 * The referenced columns are marked as requiring SELECT access.
1934 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1935 int rtindex, int sublevels_up, int location)
1941 List *te_list = NIL;
1943 expandRTE(rte, rtindex, sublevels_up, location, false,
1947 * Require read access to the table. This is normally redundant with the
1948 * markVarForSelectPriv calls below, but not if the table has zero
1951 rte->requiredPerms |= ACL_SELECT;
1953 forboth(name, names, var, vars)
1955 char *label = strVal(lfirst(name));
1956 Var *varnode = (Var *) lfirst(var);
1959 te = makeTargetEntry((Expr *) varnode,
1960 (AttrNumber) pstate->p_next_resno++,
1963 te_list = lappend(te_list, te);
1965 /* Require read access to each column */
1966 markVarForSelectPriv(pstate, varnode, rte);
1969 Assert(name == NULL && var == NULL); /* lists not the same length? */
1975 * get_rte_attribute_name
1976 * Get an attribute name from a RangeTblEntry
1978 * This is unlike get_attname() because we use aliases if available.
1979 * In particular, it will work on an RTE for a subselect or join, whereas
1980 * get_attname() only works on real relations.
1982 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1983 * occurs when a Var represents a whole tuple of a relation.
1986 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1988 if (attnum == InvalidAttrNumber)
1992 * If there is a user-written column alias, use it.
1995 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1996 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1999 * If the RTE is a relation, go to the system catalogs not the
2000 * eref->colnames list. This is a little slower but it will give the
2001 * right answer if the column has been renamed since the eref list was
2002 * built (which can easily happen for rules).
2004 if (rte->rtekind == RTE_RELATION)
2005 return get_relid_attribute_name(rte->relid, attnum);
2008 * Otherwise use the column name from eref. There should always be one.
2010 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2011 return strVal(list_nth(rte->eref->colnames, attnum - 1));
2013 /* else caller gave us a bogus attnum */
2014 elog(ERROR, "invalid attnum %d for rangetable entry %s",
2015 attnum, rte->eref->aliasname);
2016 return NULL; /* keep compiler quiet */
2020 * get_rte_attribute_type
2021 * Get attribute type/typmod/collation information from a RangeTblEntry
2024 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2025 Oid *vartype, int32 *vartypmod, Oid *varcollid)
2027 switch (rte->rtekind)
2031 /* Plain relation RTE --- get the attribute's type info */
2033 Form_pg_attribute att_tup;
2035 tp = SearchSysCache2(ATTNUM,
2036 ObjectIdGetDatum(rte->relid),
2037 Int16GetDatum(attnum));
2038 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2039 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2040 attnum, rte->relid);
2041 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2044 * If dropped column, pretend it ain't there. See notes in
2047 if (att_tup->attisdropped)
2049 (errcode(ERRCODE_UNDEFINED_COLUMN),
2050 errmsg("column \"%s\" of relation \"%s\" does not exist",
2051 NameStr(att_tup->attname),
2052 get_rel_name(rte->relid))));
2053 *vartype = att_tup->atttypid;
2054 *vartypmod = att_tup->atttypmod;
2055 *varcollid = att_tup->attcollation;
2056 ReleaseSysCache(tp);
2061 /* Subselect RTE --- get type info from subselect's tlist */
2062 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2065 if (te == NULL || te->resjunk)
2066 elog(ERROR, "subquery %s does not have attribute %d",
2067 rte->eref->aliasname, attnum);
2068 *vartype = exprType((Node *) te->expr);
2069 *vartypmod = exprTypmod((Node *) te->expr);
2070 *varcollid = exprCollation((Node *) te->expr);
2076 TypeFuncClass functypclass;
2080 functypclass = get_expr_result_type(rte->funcexpr,
2084 if (functypclass == TYPEFUNC_COMPOSITE)
2086 /* Composite data type, e.g. a table's row type */
2087 Form_pg_attribute att_tup;
2090 /* this is probably a can't-happen case */
2091 if (attnum < 1 || attnum > tupdesc->natts)
2093 (errcode(ERRCODE_UNDEFINED_COLUMN),
2094 errmsg("column %d of relation \"%s\" does not exist",
2096 rte->eref->aliasname)));
2098 att_tup = tupdesc->attrs[attnum - 1];
2101 * If dropped column, pretend it ain't there. See notes
2102 * in scanRTEForColumn.
2104 if (att_tup->attisdropped)
2106 (errcode(ERRCODE_UNDEFINED_COLUMN),
2107 errmsg("column \"%s\" of relation \"%s\" does not exist",
2108 NameStr(att_tup->attname),
2109 rte->eref->aliasname)));
2110 *vartype = att_tup->atttypid;
2111 *vartypmod = att_tup->atttypmod;
2112 *varcollid = att_tup->attcollation;
2114 else if (functypclass == TYPEFUNC_SCALAR)
2116 /* Base data type, i.e. scalar */
2117 *vartype = funcrettype;
2119 *varcollid = exprCollation(rte->funcexpr);
2121 else if (functypclass == TYPEFUNC_RECORD)
2123 *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2124 *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2125 *varcollid = list_nth_oid(rte->funccolcollations, attnum - 1);
2129 /* addRangeTableEntryForFunction should've caught this */
2130 elog(ERROR, "function in FROM has unsupported return type");
2136 /* Values RTE --- get type info from first sublist */
2137 /* collation is stored separately, though */
2138 List *collist = (List *) linitial(rte->values_lists);
2141 if (attnum < 1 || attnum > list_length(collist))
2142 elog(ERROR, "values list %s does not have attribute %d",
2143 rte->eref->aliasname, attnum);
2144 col = (Node *) list_nth(collist, attnum - 1);
2145 *vartype = exprType(col);
2146 *vartypmod = exprTypmod(col);
2147 *varcollid = list_nth_oid(rte->values_collations, attnum - 1);
2153 * Join RTE --- get type info from join RTE's alias variable
2157 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2158 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2159 *vartype = exprType(aliasvar);
2160 *vartypmod = exprTypmod(aliasvar);
2161 *varcollid = exprCollation(aliasvar);
2166 /* CTE RTE --- get type info from lists in the RTE */
2167 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2168 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2169 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2170 *varcollid = list_nth_oid(rte->ctecolcollations, attnum - 1);
2174 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2179 * get_rte_attribute_is_dropped
2180 * Check whether attempted attribute ref is to a dropped column
2183 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2187 switch (rte->rtekind)
2192 * Plain relation RTE --- get the attribute's catalog entry
2195 Form_pg_attribute att_tup;
2197 tp = SearchSysCache2(ATTNUM,
2198 ObjectIdGetDatum(rte->relid),
2199 Int16GetDatum(attnum));
2200 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2201 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2202 attnum, rte->relid);
2203 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2204 result = att_tup->attisdropped;
2205 ReleaseSysCache(tp);
2211 /* Subselect, Values, CTE RTEs never have dropped columns */
2217 * A join RTE would not have dropped columns when constructed,
2218 * but one in a stored rule might contain columns that were
2219 * dropped from the underlying tables, if said columns are
2220 * nowhere explicitly referenced in the rule. This will be
2221 * signaled to us by a NULL Const in the joinaliasvars list.
2226 attnum > list_length(rte->joinaliasvars))
2227 elog(ERROR, "invalid varattno %d", attnum);
2228 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2230 result = IsA(aliasvar, Const);
2236 Oid funcrettype = exprType(rte->funcexpr);
2237 Oid funcrelid = typeidTypeRelid(funcrettype);
2239 if (OidIsValid(funcrelid))
2242 * Composite data type, i.e. a table's row type
2244 * Same as ordinary relation RTE
2247 Form_pg_attribute att_tup;
2249 tp = SearchSysCache2(ATTNUM,
2250 ObjectIdGetDatum(funcrelid),
2251 Int16GetDatum(attnum));
2252 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2253 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2255 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2256 result = att_tup->attisdropped;
2257 ReleaseSysCache(tp);
2262 * Must be a base data type, i.e. scalar
2269 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2270 result = false; /* keep compiler quiet */
2277 * Given a targetlist and a resno, return the matching TargetEntry
2279 * Returns NULL if resno is not present in list.
2281 * Note: we need to search, rather than just indexing with list_nth(),
2282 * because not all tlists are sorted by resno.
2285 get_tle_by_resno(List *tlist, AttrNumber resno)
2291 TargetEntry *tle = (TargetEntry *) lfirst(l);
2293 if (tle->resno == resno)
2300 * Given a Query and rangetable index, return relation's RowMarkClause if any
2302 * Returns NULL if relation is not selected FOR UPDATE/SHARE
2305 get_parse_rowmark(Query *qry, Index rtindex)
2309 foreach(l, qry->rowMarks)
2311 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2313 if (rc->rti == rtindex)
2320 * given relation and att name, return attnum of variable
2322 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2324 * This should only be used if the relation is already
2325 * heap_open()'ed. Use the cache version get_attnum()
2326 * for access to non-opened relations.
2329 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2333 for (i = 0; i < rd->rd_rel->relnatts; i++)
2335 Form_pg_attribute att = rd->rd_att->attrs[i];
2337 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2343 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2345 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2351 return InvalidAttrNumber;
2356 * Check attribute name to see if it is "special", e.g. "oid".
2357 * - thomas 2000-02-07
2359 * Note: this only discovers whether the name could be a system attribute.
2360 * Caller needs to verify that it really is an attribute of the rel,
2361 * at least in the case of "oid", which is now optional.
2364 specialAttNum(const char *attname)
2366 Form_pg_attribute sysatt;
2368 sysatt = SystemAttributeByName(attname,
2369 true /* "oid" will be accepted */ );
2371 return sysatt->attnum;
2372 return InvalidAttrNumber;
2377 * given attribute id, return name of that attribute
2379 * This should only be used if the relation is already
2380 * heap_open()'ed. Use the cache version get_atttype()
2381 * for access to non-opened relations.
2384 attnumAttName(Relation rd, int attid)
2388 Form_pg_attribute sysatt;
2390 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2391 return &sysatt->attname;
2393 if (attid > rd->rd_att->natts)
2394 elog(ERROR, "invalid attribute number %d", attid);
2395 return &rd->rd_att->attrs[attid - 1]->attname;
2399 * given attribute id, return type of that attribute
2401 * This should only be used if the relation is already
2402 * heap_open()'ed. Use the cache version get_atttype()
2403 * for access to non-opened relations.
2406 attnumTypeId(Relation rd, int attid)
2410 Form_pg_attribute sysatt;
2412 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2413 return sysatt->atttypid;
2415 if (attid > rd->rd_att->natts)
2416 elog(ERROR, "invalid attribute number %d", attid);
2417 return rd->rd_att->attrs[attid - 1]->atttypid;
2421 * given attribute id, return collation of that attribute
2423 * This should only be used if the relation is already heap_open()'ed.
2426 attnumCollationId(Relation rd, int attid)
2430 /* All system attributes are of noncollatable types. */
2433 if (attid > rd->rd_att->natts)
2434 elog(ERROR, "invalid attribute number %d", attid);
2435 return rd->rd_att->attrs[attid - 1]->attcollation;
2439 * Generate a suitable error about a missing RTE.
2441 * Since this is a very common type of error, we work rather hard to
2442 * produce a helpful message.
2445 errorMissingRTE(ParseState *pstate, RangeVar *relation)
2449 const char *badAlias = NULL;
2452 * Check to see if there are any potential matches in the query's
2453 * rangetable. (Note: cases involving a bad schema name in the RangeVar
2454 * will throw error immediately here. That seems OK.)
2456 rte = searchRangeTable(pstate, relation);
2459 * If we found a match that has an alias and the alias is visible in the
2460 * namespace, then the problem is probably use of the relation's real name
2461 * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2462 * common enough to justify a specific hint.
2464 * If we found a match that doesn't meet those criteria, assume the
2465 * problem is illegal use of a relation outside its scope, as in the
2466 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2468 if (rte && rte->alias &&
2469 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2470 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2472 &sublevels_up) == rte)
2473 badAlias = rte->eref->aliasname;
2477 (errcode(ERRCODE_UNDEFINED_TABLE),
2478 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2481 errhint("Perhaps you meant to reference the table alias \"%s\".",
2483 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2484 rte->eref->aliasname)),
2485 parser_errposition(pstate, relation->location)));
2488 (errcode(ERRCODE_UNDEFINED_TABLE),
2489 errmsg("missing FROM-clause entry for table \"%s\"",
2491 parser_errposition(pstate, relation->location)));