1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2011, 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/heapam.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/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 if (!relation->schemaname)
277 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
279 relId = RangeVarGetRelid(relation, true);
281 /* Now look for RTEs matching either the relation/CTE or the alias */
284 pstate = pstate->parentParseState, levelsup++)
288 foreach(l, pstate->p_rtable)
290 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
292 if (rte->rtekind == RTE_RELATION &&
296 if (rte->rtekind == RTE_CTE &&
298 rte->ctelevelsup + levelsup == ctelevelsup &&
299 strcmp(rte->ctename, refname) == 0)
301 if (strcmp(rte->eref->aliasname, refname) == 0)
309 * Check for relation-name conflicts between two relnamespace lists.
310 * Raise an error if any is found.
312 * Note: we assume that each given argument does not contain conflicts
313 * itself; we just want to know if the two can be merged together.
315 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
316 * they have the same eref->aliasname (ie, same relation name), if they
317 * are for different relation OIDs (implying they are in different schemas).
320 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
325 foreach(l1, namespace1)
327 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
328 const char *aliasname1 = rte1->eref->aliasname;
331 foreach(l2, namespace2)
333 RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
335 if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
336 continue; /* definitely no conflict */
337 if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
338 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
339 rte1->relid != rte2->relid)
340 continue; /* no conflict per SQL92 rule */
342 (errcode(ERRCODE_DUPLICATE_ALIAS),
343 errmsg("table name \"%s\" specified more than once",
350 * given an RTE, return RT index (starting with 1) of the entry,
351 * and optionally get its nesting depth (0 = current). If sublevels_up
352 * is NULL, only consider rels at the current nesting level.
353 * Raises error if RTE not found.
356 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
364 while (pstate != NULL)
367 foreach(l, pstate->p_rtable)
369 if (rte == (RangeTblEntry *) lfirst(l))
373 pstate = pstate->parentParseState;
380 elog(ERROR, "RTE not found (internal error)");
381 return 0; /* keep compiler quiet */
385 * Given an RT index and nesting depth, find the corresponding RTE.
386 * This is the inverse of RTERangeTablePosn.
389 GetRTEByRangeTablePosn(ParseState *pstate,
393 while (sublevels_up-- > 0)
395 pstate = pstate->parentParseState;
396 Assert(pstate != NULL);
398 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
399 return rt_fetch(varno, pstate->p_rtable);
403 * Fetch the CTE for a CTE-reference RTE.
405 * rtelevelsup is the number of query levels above the given pstate that the
406 * RTE came from. Callers that don't have this information readily available
407 * may pass -1 instead.
410 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
415 /* Determine RTE's levelsup if caller didn't know it */
417 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
419 Assert(rte->rtekind == RTE_CTE);
420 levelsup = rte->ctelevelsup + rtelevelsup;
421 while (levelsup-- > 0)
423 pstate = pstate->parentParseState;
424 if (!pstate) /* shouldn't happen */
425 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
427 foreach(lc, pstate->p_ctenamespace)
429 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
431 if (strcmp(cte->ctename, rte->ctename) == 0)
434 /* shouldn't happen */
435 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
436 return NULL; /* keep compiler quiet */
441 * Search the column names of a single RTE for the given name.
442 * If found, return an appropriate Var node, else return NULL.
443 * If the name proves ambiguous within this RTE, raise error.
445 * Side effect: if we find a match, mark the RTE as requiring read access
449 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
458 * Scan the user column names (or aliases) for a match. Complain if
461 * Note: eref->colnames may include entries for dropped columns, but those
462 * will be empty strings that cannot match any legal SQL identifier, so we
463 * don't bother to test for that case here.
465 * Should this somehow go wrong and we try to access a dropped column,
466 * we'll still catch it by virtue of the checks in
467 * get_rte_attribute_type(), which is called by make_var(). That routine
468 * has to do a cache lookup anyway, so the check there is cheap.
470 foreach(c, rte->eref->colnames)
473 if (strcmp(strVal(lfirst(c)), colname) == 0)
477 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
478 errmsg("column reference \"%s\" is ambiguous",
480 parser_errposition(pstate, location)));
481 var = make_var(pstate, rte, attnum, location);
482 /* Require read access to the column */
483 markVarForSelectPriv(pstate, var, rte);
484 result = (Node *) var;
489 * If we have a unique match, return it. Note that this allows a user
490 * alias to override a system column name (such as OID) without error.
496 * If the RTE represents a real table, consider system column names.
498 if (rte->rtekind == RTE_RELATION)
500 /* quick check to see if name could be a system column */
501 attnum = specialAttNum(colname);
502 if (attnum != InvalidAttrNumber)
504 /* now check to see if column actually is defined */
505 if (SearchSysCacheExists2(ATTNUM,
506 ObjectIdGetDatum(rte->relid),
507 Int16GetDatum(attnum)))
509 var = make_var(pstate, rte, attnum, location);
510 /* Require read access to the column */
511 markVarForSelectPriv(pstate, var, rte);
512 result = (Node *) var;
522 * Search for an unqualified column name.
523 * If found, return the appropriate Var node (or expression).
524 * If not found, return NULL. If the name proves ambiguous, raise error.
525 * If localonly is true, only names in the innermost query are considered.
528 colNameToVar(ParseState *pstate, char *colname, bool localonly,
532 ParseState *orig_pstate = pstate;
534 while (pstate != NULL)
538 foreach(l, pstate->p_varnamespace)
540 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
543 /* use orig_pstate here to get the right sublevels_up */
544 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
550 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
551 errmsg("column reference \"%s\" is ambiguous",
553 parser_errposition(orig_pstate, location)));
558 if (result != NULL || localonly)
559 break; /* found, or don't want to look at parent */
561 pstate = pstate->parentParseState;
568 * markRTEForSelectPriv
569 * Mark the specified column of an RTE as requiring SELECT privilege
571 * col == InvalidAttrNumber means a "whole row" reference
573 * The caller should pass the actual RTE if it has it handy; otherwise pass
574 * NULL, and we'll look it up here. (This uglification of the API is
575 * worthwhile because nearly all external callers have the RTE at hand.)
578 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
579 int rtindex, AttrNumber col)
582 rte = rt_fetch(rtindex, pstate->p_rtable);
584 if (rte->rtekind == RTE_RELATION)
586 /* Make sure the rel as a whole is marked for SELECT access */
587 rte->requiredPerms |= ACL_SELECT;
588 /* Must offset the attnum to fit in a bitmapset */
589 rte->selectedCols = bms_add_member(rte->selectedCols,
590 col - FirstLowInvalidHeapAttributeNumber);
592 else if (rte->rtekind == RTE_JOIN)
594 if (col == InvalidAttrNumber)
597 * A whole-row reference to a join has to be treated as whole-row
598 * references to the two inputs.
602 if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
603 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
607 elog(ERROR, "could not find JoinExpr for whole-row reference");
608 Assert(IsA(j, JoinExpr));
610 /* Note: we can't see FromExpr here */
611 if (IsA(j->larg, RangeTblRef))
613 int varno = ((RangeTblRef *) j->larg)->rtindex;
615 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
617 else if (IsA(j->larg, JoinExpr))
619 int varno = ((JoinExpr *) j->larg)->rtindex;
621 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
624 elog(ERROR, "unrecognized node type: %d",
625 (int) nodeTag(j->larg));
626 if (IsA(j->rarg, RangeTblRef))
628 int varno = ((RangeTblRef *) j->rarg)->rtindex;
630 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
632 else if (IsA(j->rarg, JoinExpr))
634 int varno = ((JoinExpr *) j->rarg)->rtindex;
636 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
639 elog(ERROR, "unrecognized node type: %d",
640 (int) nodeTag(j->rarg));
645 * Regular join attribute, look at the alias-variable list.
647 * The aliasvar could be either a Var or a COALESCE expression,
648 * but in the latter case we should already have marked the two
649 * referent variables as being selected, due to their use in the
650 * JOIN clause. So we need only be concerned with the simple Var
655 Assert(col > 0 && col <= list_length(rte->joinaliasvars));
656 aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
657 if (IsA(aliasvar, Var))
658 markVarForSelectPriv(pstate, aliasvar, NULL);
661 /* other RTE types don't require privilege marking */
665 * markVarForSelectPriv
666 * Mark the RTE referenced by a Var as requiring SELECT privilege
668 * The caller should pass the Var's referenced RTE if it has it handy
669 * (nearly all do); otherwise pass NULL.
672 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
676 Assert(IsA(var, Var));
677 /* Find the appropriate pstate if it's an uplevel Var */
678 for (lv = 0; lv < var->varlevelsup; lv++)
679 pstate = pstate->parentParseState;
680 markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
684 * buildRelationAliases
685 * Construct the eref column name list for a relation RTE.
686 * This code is also used for the case of a function RTE returning
687 * a named composite type.
689 * tupdesc: the physical column information
690 * alias: the user-supplied alias, or NULL if none
691 * eref: the eref Alias to store column names in
693 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
694 * empty strings for any dropped columns, so that it will be one-to-one with
695 * physical column numbers.
698 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
700 int maxattrs = tupdesc->natts;
706 Assert(eref->colnames == NIL);
710 aliaslc = list_head(alias->colnames);
711 numaliases = list_length(alias->colnames);
712 /* We'll rebuild the alias colname list */
713 alias->colnames = NIL;
721 for (varattno = 0; varattno < maxattrs; varattno++)
723 Form_pg_attribute attr = tupdesc->attrs[varattno];
726 if (attr->attisdropped)
728 /* Always insert an empty string for a dropped column */
729 attrname = makeString(pstrdup(""));
731 alias->colnames = lappend(alias->colnames, attrname);
736 /* Use the next user-supplied alias */
737 attrname = (Value *) lfirst(aliaslc);
738 aliaslc = lnext(aliaslc);
739 alias->colnames = lappend(alias->colnames, attrname);
743 attrname = makeString(pstrdup(NameStr(attr->attname)));
744 /* we're done with the alias if any */
747 eref->colnames = lappend(eref->colnames, attrname);
750 /* Too many user-supplied aliases? */
753 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
754 errmsg("table \"%s\" has %d columns available but %d columns specified",
755 eref->aliasname, maxattrs - numdropped, numaliases)));
759 * buildScalarFunctionAlias
760 * Construct the eref column name list for a function RTE,
761 * when the function returns a scalar type (not composite or RECORD).
763 * funcexpr: transformed expression tree for the function call
764 * funcname: function name (used only for error message)
765 * alias: the user-supplied alias, or NULL if none
766 * eref: the eref Alias to store column names in
768 * eref->colnames is filled in.
771 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
772 Alias *alias, Alias *eref)
776 Assert(eref->colnames == NIL);
778 /* Use user-specified column alias if there is one. */
779 if (alias && alias->colnames != NIL)
781 if (list_length(alias->colnames) != 1)
783 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
784 errmsg("too many column aliases specified for function %s",
786 eref->colnames = copyObject(alias->colnames);
791 * If the expression is a simple function call, and the function has a
792 * single OUT parameter that is named, use the parameter's name.
794 if (funcexpr && IsA(funcexpr, FuncExpr))
796 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
799 eref->colnames = list_make1(makeString(pname));
805 * Otherwise use the previously-determined alias (not necessarily the
808 eref->colnames = list_make1(makeString(eref->aliasname));
812 * Open a table during parse analysis
814 * This is essentially just the same as heap_openrv(), except that it caters
815 * to some parser-specific error reporting needs, notably that it arranges
816 * to include the RangeVar's parse location in any resulting error.
818 * Note: properly, lockmode should be declared LOCKMODE not int, but that
819 * would require importing storage/lock.h into parse_relation.h. Since
820 * LOCKMODE is typedef'd as int anyway, that seems like overkill.
823 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
826 ParseCallbackState pcbstate;
828 setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
829 rel = try_heap_openrv(relation, lockmode);
832 if (relation->schemaname)
834 (errcode(ERRCODE_UNDEFINED_TABLE),
835 errmsg("relation \"%s.%s\" does not exist",
836 relation->schemaname, relation->relname)));
840 * An unqualified name might have been meant as a reference to
841 * some not-yet-in-scope CTE. The bare "does not exist" message
842 * has proven remarkably unhelpful for figuring out such problems,
843 * so we take pains to offer a specific hint.
845 if (isFutureCTE(pstate, relation->relname))
847 (errcode(ERRCODE_UNDEFINED_TABLE),
848 errmsg("relation \"%s\" does not exist",
850 errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
852 errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
855 (errcode(ERRCODE_UNDEFINED_TABLE),
856 errmsg("relation \"%s\" does not exist",
857 relation->relname)));
860 cancel_parser_errposition_callback(&pcbstate);
865 * Add an entry for a relation to the pstate's range table (p_rtable).
867 * If pstate is NULL, we just build an RTE and return it without adding it
870 * Note: formerly this checked for refname conflicts, but that's wrong.
871 * Caller is responsible for checking for conflicts in the appropriate scope.
874 addRangeTableEntry(ParseState *pstate,
880 RangeTblEntry *rte = makeNode(RangeTblEntry);
881 char *refname = alias ? alias->aliasname : relation->relname;
885 rte->rtekind = RTE_RELATION;
889 * Get the rel's OID. This access also ensures that we have an up-to-date
890 * relcache entry for the rel. Since this is typically the first access
891 * to a rel in a statement, be careful to get the right access level
892 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
894 lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
895 rel = parserOpenTable(pstate, relation, lockmode);
896 rte->relid = RelationGetRelid(rel);
897 rte->relkind = rel->rd_rel->relkind;
900 * Build the list of effective column names using user-supplied aliases
901 * and/or actual column names.
903 rte->eref = makeAlias(refname, NIL);
904 buildRelationAliases(rel->rd_att, alias, rte->eref);
907 * Drop the rel refcount, but keep the access lock till end of transaction
908 * so that the table can't be deleted or have its schema modified
911 heap_close(rel, NoLock);
915 * - this RTE should be expanded to include descendant tables,
916 * - this RTE is in the FROM clause,
917 * - this RTE should be checked for appropriate access rights.
919 * The initial default on access checks is always check-for-READ-access,
920 * which is the right thing for all except target tables.
924 rte->inFromCl = inFromCl;
926 rte->requiredPerms = ACL_SELECT;
927 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
928 rte->selectedCols = NULL;
929 rte->modifiedCols = NULL;
932 * Add completed RTE to pstate's range table list, but not to join list
933 * nor namespace --- caller must do that if appropriate.
936 pstate->p_rtable = lappend(pstate->p_rtable, rte);
942 * Add an entry for a relation to the pstate's range table (p_rtable).
944 * This is just like addRangeTableEntry() except that it makes an RTE
945 * given an already-open relation instead of a RangeVar reference.
948 addRangeTableEntryForRelation(ParseState *pstate,
954 RangeTblEntry *rte = makeNode(RangeTblEntry);
955 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
957 rte->rtekind = RTE_RELATION;
959 rte->relid = RelationGetRelid(rel);
960 rte->relkind = rel->rd_rel->relkind;
963 * Build the list of effective column names using user-supplied aliases
964 * and/or actual column names.
966 rte->eref = makeAlias(refname, NIL);
967 buildRelationAliases(rel->rd_att, alias, rte->eref);
971 * - this RTE should be expanded to include descendant tables,
972 * - this RTE is in the FROM clause,
973 * - this RTE should be checked for appropriate access rights.
975 * The initial default on access checks is always check-for-READ-access,
976 * which is the right thing for all except target tables.
980 rte->inFromCl = inFromCl;
982 rte->requiredPerms = ACL_SELECT;
983 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
984 rte->selectedCols = NULL;
985 rte->modifiedCols = NULL;
988 * Add completed RTE to pstate's range table list, but not to join list
989 * nor namespace --- caller must do that if appropriate.
992 pstate->p_rtable = lappend(pstate->p_rtable, rte);
998 * Add an entry for a subquery to the pstate's range table (p_rtable).
1000 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1001 * Note that an alias clause *must* be supplied.
1004 addRangeTableEntryForSubquery(ParseState *pstate,
1009 RangeTblEntry *rte = makeNode(RangeTblEntry);
1010 char *refname = alias->aliasname;
1014 ListCell *tlistitem;
1016 rte->rtekind = RTE_SUBQUERY;
1017 rte->relid = InvalidOid;
1018 rte->subquery = subquery;
1021 eref = copyObject(alias);
1022 numaliases = list_length(eref->colnames);
1024 /* fill in any unspecified alias columns */
1026 foreach(tlistitem, subquery->targetList)
1028 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1033 Assert(varattno == te->resno);
1034 if (varattno > numaliases)
1038 attrname = pstrdup(te->resname);
1039 eref->colnames = lappend(eref->colnames, makeString(attrname));
1042 if (varattno < numaliases)
1044 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1045 errmsg("table \"%s\" has %d columns available but %d columns specified",
1046 refname, varattno, numaliases)));
1052 * - this RTE should be expanded to include descendant tables,
1053 * - this RTE is in the FROM clause,
1054 * - this RTE should be checked for appropriate access rights.
1056 * Subqueries are never checked for access rights.
1059 rte->inh = false; /* never true for subqueries */
1060 rte->inFromCl = inFromCl;
1062 rte->requiredPerms = 0;
1063 rte->checkAsUser = InvalidOid;
1064 rte->selectedCols = NULL;
1065 rte->modifiedCols = NULL;
1068 * Add completed RTE to pstate's range table list, but not to join list
1069 * nor namespace --- caller must do that if appropriate.
1072 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1078 * Add an entry for a function to the pstate's range table (p_rtable).
1080 * This is just like addRangeTableEntry() except that it makes a function RTE.
1083 addRangeTableEntryForFunction(ParseState *pstate,
1086 RangeFunction *rangefunc,
1089 RangeTblEntry *rte = makeNode(RangeTblEntry);
1090 TypeFuncClass functypclass;
1093 Alias *alias = rangefunc->alias;
1094 List *coldeflist = rangefunc->coldeflist;
1097 rte->rtekind = RTE_FUNCTION;
1098 rte->relid = InvalidOid;
1099 rte->subquery = NULL;
1100 rte->funcexpr = funcexpr;
1101 rte->funccoltypes = NIL;
1102 rte->funccoltypmods = NIL;
1103 rte->funccolcollations = NIL;
1106 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1110 * Now determine if the function returns a simple or composite type.
1112 functypclass = get_expr_result_type(funcexpr,
1117 * A coldeflist is required if the function returns RECORD and hasn't got
1118 * a predetermined record type, and is prohibited otherwise.
1120 if (coldeflist != NIL)
1122 if (functypclass != TYPEFUNC_RECORD)
1124 (errcode(ERRCODE_SYNTAX_ERROR),
1125 errmsg("a column definition list is only allowed for functions returning \"record\""),
1126 parser_errposition(pstate, exprLocation(funcexpr))));
1130 if (functypclass == TYPEFUNC_RECORD)
1132 (errcode(ERRCODE_SYNTAX_ERROR),
1133 errmsg("a column definition list is required for functions returning \"record\""),
1134 parser_errposition(pstate, exprLocation(funcexpr))));
1137 if (functypclass == TYPEFUNC_COMPOSITE)
1139 /* Composite data type, e.g. a table's row type */
1141 /* Build the column alias list */
1142 buildRelationAliases(tupdesc, alias, eref);
1144 else if (functypclass == TYPEFUNC_SCALAR)
1146 /* Base data type, i.e. scalar */
1147 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1149 else if (functypclass == TYPEFUNC_RECORD)
1154 * Use the column definition list to form the alias list and
1155 * funccoltypes/funccoltypmods lists.
1157 foreach(col, coldeflist)
1159 ColumnDef *n = (ColumnDef *) lfirst(col);
1165 attrname = pstrdup(n->colname);
1166 if (n->typeName->setof)
1168 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1169 errmsg("column \"%s\" cannot be declared SETOF",
1171 parser_errposition(pstate, n->typeName->location)));
1172 typenameTypeIdAndMod(pstate, n->typeName, &attrtype, &attrtypmod);
1173 attrcollation = GetColumnDefCollation(pstate, n, attrtype);
1174 eref->colnames = lappend(eref->colnames, makeString(attrname));
1175 rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1176 rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1177 rte->funccolcollations = lappend_oid(rte->funccolcollations, attrcollation);
1182 (errcode(ERRCODE_DATATYPE_MISMATCH),
1183 errmsg("function \"%s\" in FROM has unsupported return type %s",
1184 funcname, format_type_be(funcrettype)),
1185 parser_errposition(pstate, exprLocation(funcexpr))));
1189 * - this RTE should be expanded to include descendant tables,
1190 * - this RTE is in the FROM clause,
1191 * - this RTE should be checked for appropriate access rights.
1193 * Functions are never checked for access rights (at least, not by
1194 * the RTE permissions mechanism).
1197 rte->inh = false; /* never true for functions */
1198 rte->inFromCl = inFromCl;
1200 rte->requiredPerms = 0;
1201 rte->checkAsUser = InvalidOid;
1202 rte->selectedCols = NULL;
1203 rte->modifiedCols = NULL;
1206 * Add completed RTE to pstate's range table list, but not to join list
1207 * nor namespace --- caller must do that if appropriate.
1210 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1216 * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1218 * This is much like addRangeTableEntry() except that it makes a values RTE.
1221 addRangeTableEntryForValues(ParseState *pstate,
1226 RangeTblEntry *rte = makeNode(RangeTblEntry);
1227 char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1232 rte->rtekind = RTE_VALUES;
1233 rte->relid = InvalidOid;
1234 rte->subquery = NULL;
1235 rte->values_lists = exprs;
1238 eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1240 /* fill in any unspecified alias columns */
1241 numcolumns = list_length((List *) linitial(exprs));
1242 numaliases = list_length(eref->colnames);
1243 while (numaliases < numcolumns)
1248 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1249 eref->colnames = lappend(eref->colnames,
1250 makeString(pstrdup(attrname)));
1252 if (numcolumns < numaliases)
1254 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1255 errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1256 refname, numcolumns, numaliases)));
1262 * - this RTE should be expanded to include descendant tables,
1263 * - this RTE is in the FROM clause,
1264 * - this RTE should be checked for appropriate access rights.
1266 * Subqueries are never checked for access rights.
1269 rte->inh = false; /* never true for values RTEs */
1270 rte->inFromCl = inFromCl;
1272 rte->requiredPerms = 0;
1273 rte->checkAsUser = InvalidOid;
1274 rte->selectedCols = NULL;
1275 rte->modifiedCols = NULL;
1278 * Add completed RTE to pstate's range table list, but not to join list
1279 * nor namespace --- caller must do that if appropriate.
1282 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1288 * Add an entry for a join to the pstate's range table (p_rtable).
1290 * This is much like addRangeTableEntry() except that it makes a join RTE.
1293 addRangeTableEntryForJoin(ParseState *pstate,
1300 RangeTblEntry *rte = makeNode(RangeTblEntry);
1305 * Fail if join has too many columns --- we must be able to reference any
1306 * of the columns with an AttrNumber.
1308 if (list_length(aliasvars) > MaxAttrNumber)
1310 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1311 errmsg("joins can have at most %d columns",
1314 rte->rtekind = RTE_JOIN;
1315 rte->relid = InvalidOid;
1316 rte->subquery = NULL;
1317 rte->jointype = jointype;
1318 rte->joinaliasvars = aliasvars;
1321 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1322 numaliases = list_length(eref->colnames);
1324 /* fill in any unspecified alias columns */
1325 if (numaliases < list_length(colnames))
1326 eref->colnames = list_concat(eref->colnames,
1327 list_copy_tail(colnames, numaliases));
1333 * - this RTE should be expanded to include descendant tables,
1334 * - this RTE is in the FROM clause,
1335 * - this RTE should be checked for appropriate access rights.
1337 * Joins are never checked for access rights.
1340 rte->inh = false; /* never true for joins */
1341 rte->inFromCl = inFromCl;
1343 rte->requiredPerms = 0;
1344 rte->checkAsUser = InvalidOid;
1345 rte->selectedCols = NULL;
1346 rte->modifiedCols = NULL;
1349 * Add completed RTE to pstate's range table list, but not to join list
1350 * nor namespace --- caller must do that if appropriate.
1353 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1359 * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1361 * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1364 addRangeTableEntryForCTE(ParseState *pstate,
1365 CommonTableExpr *cte,
1370 RangeTblEntry *rte = makeNode(RangeTblEntry);
1371 Alias *alias = rv->alias;
1372 char *refname = alias ? alias->aliasname : cte->ctename;
1378 rte->rtekind = RTE_CTE;
1379 rte->ctename = cte->ctename;
1380 rte->ctelevelsup = levelsup;
1382 /* Self-reference if and only if CTE's parse analysis isn't completed */
1383 rte->self_reference = !IsA(cte->ctequery, Query);
1384 Assert(cte->cterecursive || !rte->self_reference);
1385 /* Bump the CTE's refcount if this isn't a self-reference */
1386 if (!rte->self_reference)
1390 * We throw error if the CTE is INSERT/UPDATE/DELETE without RETURNING.
1391 * This won't get checked in case of a self-reference, but that's OK
1392 * because data-modifying CTEs aren't allowed to be recursive anyhow.
1394 if (IsA(cte->ctequery, Query))
1396 Query *ctequery = (Query *) cte->ctequery;
1398 if (ctequery->commandType != CMD_SELECT &&
1399 ctequery->returningList == NIL)
1401 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1402 errmsg("WITH query \"%s\" does not have a RETURNING clause",
1404 parser_errposition(pstate, rv->location)));
1407 rte->ctecoltypes = cte->ctecoltypes;
1408 rte->ctecoltypmods = cte->ctecoltypmods;
1409 rte->ctecolcollations = cte->ctecolcollations;
1413 eref = copyObject(alias);
1415 eref = makeAlias(refname, NIL);
1416 numaliases = list_length(eref->colnames);
1418 /* fill in any unspecified alias columns */
1420 foreach(lc, cte->ctecolnames)
1423 if (varattno > numaliases)
1424 eref->colnames = lappend(eref->colnames, lfirst(lc));
1426 if (varattno < numaliases)
1428 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1429 errmsg("table \"%s\" has %d columns available but %d columns specified",
1430 refname, varattno, numaliases)));
1436 * - this RTE should be expanded to include descendant tables,
1437 * - this RTE is in the FROM clause,
1438 * - this RTE should be checked for appropriate access rights.
1440 * Subqueries are never checked for access rights.
1443 rte->inh = false; /* never true for subqueries */
1444 rte->inFromCl = inFromCl;
1446 rte->requiredPerms = 0;
1447 rte->checkAsUser = InvalidOid;
1448 rte->selectedCols = NULL;
1449 rte->modifiedCols = NULL;
1452 * Add completed RTE to pstate's range table list, but not to join list
1453 * nor namespace --- caller must do that if appropriate.
1456 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1463 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1465 * This is used when we have not yet done transformLockingClause, but need
1466 * to know the correct lock to take during initial opening of relations.
1468 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1469 * since the table-level lock is the same either way.
1472 isLockedRefname(ParseState *pstate, const char *refname)
1477 * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1478 * parent level, then act as though there's a generic FOR UPDATE here.
1480 if (pstate->p_locked_from_parent)
1483 foreach(l, pstate->p_locking_clause)
1485 LockingClause *lc = (LockingClause *) lfirst(l);
1487 if (lc->lockedRels == NIL)
1489 /* all tables used in query */
1494 /* just the named tables */
1497 foreach(l2, lc->lockedRels)
1499 RangeVar *thisrel = (RangeVar *) lfirst(l2);
1501 if (strcmp(refname, thisrel->relname) == 0)
1510 * Add the given RTE as a top-level entry in the pstate's join list
1511 * and/or name space lists. (We assume caller has checked for any
1512 * namespace conflicts.)
1515 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1517 bool addToRelNameSpace, bool addToVarNameSpace)
1521 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1522 RangeTblRef *rtr = makeNode(RangeTblRef);
1524 rtr->rtindex = rtindex;
1525 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1527 if (addToRelNameSpace)
1528 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1529 if (addToVarNameSpace)
1530 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1534 * expandRTE -- expand the columns of a rangetable entry
1536 * This creates lists of an RTE's column names (aliases if provided, else
1537 * real names) and Vars for each column. Only user columns are considered.
1538 * If include_dropped is FALSE then dropped columns are omitted from the
1539 * results. If include_dropped is TRUE then empty strings and NULL constants
1540 * (not Vars!) are returned for dropped columns.
1542 * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1543 * values to use in the created Vars. Ordinarily rtindex should match the
1544 * actual position of the RTE in its rangetable.
1546 * The output lists go into *colnames and *colvars.
1547 * If only one of the two kinds of output list is needed, pass NULL for the
1548 * output pointer for the unwanted one.
1551 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1552 int location, bool include_dropped,
1553 List **colnames, List **colvars)
1562 switch (rte->rtekind)
1565 /* Ordinary relation RTE */
1566 expandRelation(rte->relid, rte->eref,
1567 rtindex, sublevels_up, location,
1568 include_dropped, colnames, colvars);
1573 ListCell *aliasp_item = list_head(rte->eref->colnames);
1574 ListCell *tlistitem;
1577 foreach(tlistitem, rte->subquery->targetList)
1579 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1584 Assert(varattno == te->resno);
1588 /* Assume there is one alias per target item */
1589 char *label = strVal(lfirst(aliasp_item));
1591 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1592 aliasp_item = lnext(aliasp_item);
1599 varnode = makeVar(rtindex, varattno,
1600 exprType((Node *) te->expr),
1601 exprTypmod((Node *) te->expr),
1602 exprCollation((Node *) te->expr),
1604 varnode->location = location;
1606 *colvars = lappend(*colvars, varnode);
1614 TypeFuncClass functypclass;
1618 functypclass = get_expr_result_type(rte->funcexpr,
1621 if (functypclass == TYPEFUNC_COMPOSITE)
1623 /* Composite data type, e.g. a table's row type */
1625 expandTupleDesc(tupdesc, rte->eref,
1626 rtindex, sublevels_up, location,
1627 include_dropped, colnames, colvars);
1629 else if (functypclass == TYPEFUNC_SCALAR)
1631 /* Base data type, i.e. scalar */
1633 *colnames = lappend(*colnames,
1634 linitial(rte->eref->colnames));
1640 varnode = makeVar(rtindex, 1,
1642 exprCollation(rte->funcexpr),
1644 varnode->location = location;
1646 *colvars = lappend(*colvars, varnode);
1649 else if (functypclass == TYPEFUNC_RECORD)
1652 *colnames = copyObject(rte->eref->colnames);
1660 forthree(l1, rte->funccoltypes, l2, rte->funccoltypmods, l3, rte->funccolcollations)
1662 Oid attrtype = lfirst_oid(l1);
1663 int32 attrtypmod = lfirst_int(l2);
1664 Oid attrcollation = lfirst_oid(l3);
1668 varnode = makeVar(rtindex,
1674 varnode->location = location;
1675 *colvars = lappend(*colvars, varnode);
1681 /* addRangeTableEntryForFunction should've caught this */
1682 elog(ERROR, "function in FROM has unsupported return type");
1689 ListCell *aliasp_item = list_head(rte->eref->colnames);
1693 foreach(lc, (List *) linitial(rte->values_lists))
1695 Node *col = (Node *) lfirst(lc);
1700 /* Assume there is one alias per column */
1701 char *label = strVal(lfirst(aliasp_item));
1703 *colnames = lappend(*colnames,
1704 makeString(pstrdup(label)));
1705 aliasp_item = lnext(aliasp_item);
1712 varnode = makeVar(rtindex, varattno,
1717 varnode->location = location;
1718 *colvars = lappend(*colvars, varnode);
1729 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1732 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1734 Node *avar = (Node *) lfirst(aliasvar);
1739 * During ordinary parsing, there will never be any
1740 * deleted columns in the join; but we have to check since
1741 * this routine is also used by the rewriter, and joins
1742 * found in stored rules might have join columns for
1743 * since-deleted columns. This will be signaled by a NULL
1744 * Const in the alias-vars list.
1746 if (IsA(avar, Const))
1748 if (include_dropped)
1751 *colnames = lappend(*colnames,
1752 makeString(pstrdup("")));
1754 *colvars = lappend(*colvars,
1762 char *label = strVal(lfirst(colname));
1764 *colnames = lappend(*colnames,
1765 makeString(pstrdup(label)));
1772 varnode = makeVar(rtindex, varattno,
1775 exprCollation(avar),
1777 varnode->location = location;
1779 *colvars = lappend(*colvars, varnode);
1786 ListCell *aliasp_item = list_head(rte->eref->colnames);
1792 forthree(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods, lcc, rte->ctecolcollations)
1794 Oid coltype = lfirst_oid(lct);
1795 int32 coltypmod = lfirst_int(lcm);
1796 Oid colcoll = lfirst_oid(lcc);
1802 /* Assume there is one alias per output column */
1803 char *label = strVal(lfirst(aliasp_item));
1805 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1806 aliasp_item = lnext(aliasp_item);
1813 varnode = makeVar(rtindex, varattno,
1814 coltype, coltypmod, colcoll,
1816 *colvars = lappend(*colvars, varnode);
1822 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1827 * expandRelation -- expandRTE subroutine
1830 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1831 int location, bool include_dropped,
1832 List **colnames, List **colvars)
1836 /* Get the tupledesc and turn it over to expandTupleDesc */
1837 rel = relation_open(relid, AccessShareLock);
1838 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1839 location, include_dropped,
1841 relation_close(rel, AccessShareLock);
1845 * expandTupleDesc -- expandRTE subroutine
1848 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1849 int rtindex, int sublevels_up,
1850 int location, bool include_dropped,
1851 List **colnames, List **colvars)
1853 int maxattrs = tupdesc->natts;
1854 int numaliases = list_length(eref->colnames);
1857 for (varattno = 0; varattno < maxattrs; varattno++)
1859 Form_pg_attribute attr = tupdesc->attrs[varattno];
1861 if (attr->attisdropped)
1863 if (include_dropped)
1866 *colnames = lappend(*colnames, makeString(pstrdup("")));
1870 * can't use atttypid here, but it doesn't really matter
1871 * what type the Const claims to be.
1873 *colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1883 if (varattno < numaliases)
1884 label = strVal(list_nth(eref->colnames, varattno));
1886 label = NameStr(attr->attname);
1887 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1894 varnode = makeVar(rtindex, attr->attnum,
1895 attr->atttypid, attr->atttypmod, attr->attcollation,
1897 varnode->location = location;
1899 *colvars = lappend(*colvars, varnode);
1906 * Workhorse for "*" expansion: produce a list of targetentries
1907 * for the attributes of the RTE
1909 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1910 * fields of the Vars produced, and location sets their location.
1911 * pstate->p_next_resno determines the resnos assigned to the TLEs.
1912 * The referenced columns are marked as requiring SELECT access.
1915 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1916 int rtindex, int sublevels_up, int location)
1922 List *te_list = NIL;
1924 expandRTE(rte, rtindex, sublevels_up, location, false,
1928 * Require read access to the table. This is normally redundant with the
1929 * markVarForSelectPriv calls below, but not if the table has zero
1932 rte->requiredPerms |= ACL_SELECT;
1934 forboth(name, names, var, vars)
1936 char *label = strVal(lfirst(name));
1937 Var *varnode = (Var *) lfirst(var);
1940 te = makeTargetEntry((Expr *) varnode,
1941 (AttrNumber) pstate->p_next_resno++,
1944 te_list = lappend(te_list, te);
1946 /* Require read access to each column */
1947 markVarForSelectPriv(pstate, varnode, rte);
1950 Assert(name == NULL && var == NULL); /* lists not the same length? */
1956 * get_rte_attribute_name
1957 * Get an attribute name from a RangeTblEntry
1959 * This is unlike get_attname() because we use aliases if available.
1960 * In particular, it will work on an RTE for a subselect or join, whereas
1961 * get_attname() only works on real relations.
1963 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1964 * occurs when a Var represents a whole tuple of a relation.
1967 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1969 if (attnum == InvalidAttrNumber)
1973 * If there is a user-written column alias, use it.
1976 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1977 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1980 * If the RTE is a relation, go to the system catalogs not the
1981 * eref->colnames list. This is a little slower but it will give the
1982 * right answer if the column has been renamed since the eref list was
1983 * built (which can easily happen for rules).
1985 if (rte->rtekind == RTE_RELATION)
1986 return get_relid_attribute_name(rte->relid, attnum);
1989 * Otherwise use the column name from eref. There should always be one.
1991 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1992 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1994 /* else caller gave us a bogus attnum */
1995 elog(ERROR, "invalid attnum %d for rangetable entry %s",
1996 attnum, rte->eref->aliasname);
1997 return NULL; /* keep compiler quiet */
2001 * get_rte_attribute_type
2002 * Get attribute type information from a RangeTblEntry
2005 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2006 Oid *vartype, int32 *vartypmod, Oid *varcollid)
2008 switch (rte->rtekind)
2012 /* Plain relation RTE --- get the attribute's type info */
2014 Form_pg_attribute att_tup;
2016 tp = SearchSysCache2(ATTNUM,
2017 ObjectIdGetDatum(rte->relid),
2018 Int16GetDatum(attnum));
2019 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2020 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2021 attnum, rte->relid);
2022 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2025 * If dropped column, pretend it ain't there. See notes in
2028 if (att_tup->attisdropped)
2030 (errcode(ERRCODE_UNDEFINED_COLUMN),
2031 errmsg("column \"%s\" of relation \"%s\" does not exist",
2032 NameStr(att_tup->attname),
2033 get_rel_name(rte->relid))));
2034 *vartype = att_tup->atttypid;
2035 *vartypmod = att_tup->atttypmod;
2036 *varcollid = att_tup->attcollation;
2037 ReleaseSysCache(tp);
2042 /* Subselect RTE --- get type info from subselect's tlist */
2043 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2046 if (te == NULL || te->resjunk)
2047 elog(ERROR, "subquery %s does not have attribute %d",
2048 rte->eref->aliasname, attnum);
2049 *vartype = exprType((Node *) te->expr);
2050 *vartypmod = exprTypmod((Node *) te->expr);
2051 *varcollid = exprCollation((Node *) te->expr);
2057 TypeFuncClass functypclass;
2061 functypclass = get_expr_result_type(rte->funcexpr,
2065 if (functypclass == TYPEFUNC_COMPOSITE)
2067 /* Composite data type, e.g. a table's row type */
2068 Form_pg_attribute att_tup;
2071 /* this is probably a can't-happen case */
2072 if (attnum < 1 || attnum > tupdesc->natts)
2074 (errcode(ERRCODE_UNDEFINED_COLUMN),
2075 errmsg("column %d of relation \"%s\" does not exist",
2077 rte->eref->aliasname)));
2079 att_tup = tupdesc->attrs[attnum - 1];
2082 * If dropped column, pretend it ain't there. See notes
2083 * in scanRTEForColumn.
2085 if (att_tup->attisdropped)
2087 (errcode(ERRCODE_UNDEFINED_COLUMN),
2088 errmsg("column \"%s\" of relation \"%s\" does not exist",
2089 NameStr(att_tup->attname),
2090 rte->eref->aliasname)));
2091 *vartype = att_tup->atttypid;
2092 *vartypmod = att_tup->atttypmod;
2093 *varcollid = att_tup->attcollation;
2095 else if (functypclass == TYPEFUNC_SCALAR)
2097 /* Base data type, i.e. scalar */
2098 *vartype = funcrettype;
2100 *varcollid = exprCollation(rte->funcexpr);
2102 else if (functypclass == TYPEFUNC_RECORD)
2104 *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2105 *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2106 *varcollid = list_nth_oid(rte->funccolcollations, attnum - 1);
2110 /* addRangeTableEntryForFunction should've caught this */
2111 elog(ERROR, "function in FROM has unsupported return type");
2117 /* Values RTE --- get type info from first sublist */
2118 List *collist = (List *) linitial(rte->values_lists);
2121 if (attnum < 1 || attnum > list_length(collist))
2122 elog(ERROR, "values list %s does not have attribute %d",
2123 rte->eref->aliasname, attnum);
2124 col = (Node *) list_nth(collist, attnum - 1);
2125 *vartype = exprType(col);
2126 *vartypmod = exprTypmod(col);
2127 *varcollid = exprCollation(col);
2133 * Join RTE --- get type info from join RTE's alias variable
2137 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2138 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2139 *vartype = exprType(aliasvar);
2140 *vartypmod = exprTypmod(aliasvar);
2141 *varcollid = exprCollation(aliasvar);
2146 /* CTE RTE --- get type info from lists in the RTE */
2147 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2148 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2149 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2150 *varcollid = list_nth_oid(rte->ctecolcollations, attnum - 1);
2154 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2159 * get_rte_attribute_is_dropped
2160 * Check whether attempted attribute ref is to a dropped column
2163 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2167 switch (rte->rtekind)
2172 * Plain relation RTE --- get the attribute's catalog entry
2175 Form_pg_attribute att_tup;
2177 tp = SearchSysCache2(ATTNUM,
2178 ObjectIdGetDatum(rte->relid),
2179 Int16GetDatum(attnum));
2180 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2181 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2182 attnum, rte->relid);
2183 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2184 result = att_tup->attisdropped;
2185 ReleaseSysCache(tp);
2191 /* Subselect, Values, CTE RTEs never have dropped columns */
2197 * A join RTE would not have dropped columns when constructed,
2198 * but one in a stored rule might contain columns that were
2199 * dropped from the underlying tables, if said columns are
2200 * nowhere explicitly referenced in the rule. This will be
2201 * signaled to us by a NULL Const in the joinaliasvars list.
2206 attnum > list_length(rte->joinaliasvars))
2207 elog(ERROR, "invalid varattno %d", attnum);
2208 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2210 result = IsA(aliasvar, Const);
2216 Oid funcrettype = exprType(rte->funcexpr);
2217 Oid funcrelid = typeidTypeRelid(funcrettype);
2219 if (OidIsValid(funcrelid))
2222 * Composite data type, i.e. a table's row type
2224 * Same as ordinary relation RTE
2227 Form_pg_attribute att_tup;
2229 tp = SearchSysCache2(ATTNUM,
2230 ObjectIdGetDatum(funcrelid),
2231 Int16GetDatum(attnum));
2232 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2233 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2235 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2236 result = att_tup->attisdropped;
2237 ReleaseSysCache(tp);
2242 * Must be a base data type, i.e. scalar
2249 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2250 result = false; /* keep compiler quiet */
2257 * Given a targetlist and a resno, return the matching TargetEntry
2259 * Returns NULL if resno is not present in list.
2261 * Note: we need to search, rather than just indexing with list_nth(),
2262 * because not all tlists are sorted by resno.
2265 get_tle_by_resno(List *tlist, AttrNumber resno)
2271 TargetEntry *tle = (TargetEntry *) lfirst(l);
2273 if (tle->resno == resno)
2280 * Given a Query and rangetable index, return relation's RowMarkClause if any
2282 * Returns NULL if relation is not selected FOR UPDATE/SHARE
2285 get_parse_rowmark(Query *qry, Index rtindex)
2289 foreach(l, qry->rowMarks)
2291 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2293 if (rc->rti == rtindex)
2300 * given relation and att name, return attnum of variable
2302 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2304 * This should only be used if the relation is already
2305 * heap_open()'ed. Use the cache version get_attnum()
2306 * for access to non-opened relations.
2309 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2313 for (i = 0; i < rd->rd_rel->relnatts; i++)
2315 Form_pg_attribute att = rd->rd_att->attrs[i];
2317 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2323 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2325 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2331 return InvalidAttrNumber;
2336 * Check attribute name to see if it is "special", e.g. "oid".
2337 * - thomas 2000-02-07
2339 * Note: this only discovers whether the name could be a system attribute.
2340 * Caller needs to verify that it really is an attribute of the rel,
2341 * at least in the case of "oid", which is now optional.
2344 specialAttNum(const char *attname)
2346 Form_pg_attribute sysatt;
2348 sysatt = SystemAttributeByName(attname,
2349 true /* "oid" will be accepted */ );
2351 return sysatt->attnum;
2352 return InvalidAttrNumber;
2357 * given attribute id, return name of that attribute
2359 * This should only be used if the relation is already
2360 * heap_open()'ed. Use the cache version get_atttype()
2361 * for access to non-opened relations.
2364 attnumAttName(Relation rd, int attid)
2368 Form_pg_attribute sysatt;
2370 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2371 return &sysatt->attname;
2373 if (attid > rd->rd_att->natts)
2374 elog(ERROR, "invalid attribute number %d", attid);
2375 return &rd->rd_att->attrs[attid - 1]->attname;
2379 * given attribute id, return type of that attribute
2381 * This should only be used if the relation is already
2382 * heap_open()'ed. Use the cache version get_atttype()
2383 * for access to non-opened relations.
2386 attnumTypeId(Relation rd, int attid)
2390 Form_pg_attribute sysatt;
2392 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2393 return sysatt->atttypid;
2395 if (attid > rd->rd_att->natts)
2396 elog(ERROR, "invalid attribute number %d", attid);
2397 return rd->rd_att->attrs[attid - 1]->atttypid;
2401 * Generate a suitable error about a missing RTE.
2403 * Since this is a very common type of error, we work rather hard to
2404 * produce a helpful message.
2407 errorMissingRTE(ParseState *pstate, RangeVar *relation)
2411 const char *badAlias = NULL;
2414 * Check to see if there are any potential matches in the query's
2415 * rangetable. (Note: cases involving a bad schema name in the RangeVar
2416 * will throw error immediately here. That seems OK.)
2418 rte = searchRangeTable(pstate, relation);
2421 * If we found a match that has an alias and the alias is visible in the
2422 * namespace, then the problem is probably use of the relation's real name
2423 * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2424 * common enough to justify a specific hint.
2426 * If we found a match that doesn't meet those criteria, assume the
2427 * problem is illegal use of a relation outside its scope, as in the
2428 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2430 if (rte && rte->alias &&
2431 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2432 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2434 &sublevels_up) == rte)
2435 badAlias = rte->eref->aliasname;
2439 (errcode(ERRCODE_UNDEFINED_TABLE),
2440 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2443 errhint("Perhaps you meant to reference the table alias \"%s\".",
2445 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2446 rte->eref->aliasname)),
2447 parser_errposition(pstate, relation->location)));
2450 (errcode(ERRCODE_UNDEFINED_TABLE),
2451 errmsg("missing FROM-clause entry for table \"%s\"",
2453 parser_errposition(pstate, relation->location)));