1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_relation.c,v 1.148 2010/01/02 16:57:50 momjian Exp $
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
92 * on the schema is unnecessary since it would have already been
93 * checked when the RTE was made. Furthermore, we want to report
94 * "RTE not found", not "no permissions for schema", if the name
95 * happens to match a schema name the user hasn't got access to.
97 namespaceId = LookupNamespaceNoError(schemaname);
98 if (!OidIsValid(relId))
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 (SearchSysCacheExists(ATTNUM,
506 ObjectIdGetDatum(rte->relid),
507 Int16GetDatum(attnum),
510 var = make_var(pstate, rte, attnum, location);
511 /* Require read access to the column */
512 markVarForSelectPriv(pstate, var, rte);
513 result = (Node *) var;
523 * Search for an unqualified column name.
524 * If found, return the appropriate Var node (or expression).
525 * If not found, return NULL. If the name proves ambiguous, raise error.
526 * If localonly is true, only names in the innermost query are considered.
529 colNameToVar(ParseState *pstate, char *colname, bool localonly,
533 ParseState *orig_pstate = pstate;
535 while (pstate != NULL)
539 foreach(l, pstate->p_varnamespace)
541 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
544 /* use orig_pstate here to get the right sublevels_up */
545 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
551 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
552 errmsg("column reference \"%s\" is ambiguous",
554 parser_errposition(orig_pstate, location)));
559 if (result != NULL || localonly)
560 break; /* found, or don't want to look at parent */
562 pstate = pstate->parentParseState;
569 * markRTEForSelectPriv
570 * Mark the specified column of an RTE as requiring SELECT privilege
572 * col == InvalidAttrNumber means a "whole row" reference
574 * The caller should pass the actual RTE if it has it handy; otherwise pass
575 * NULL, and we'll look it up here. (This uglification of the API is
576 * worthwhile because nearly all external callers have the RTE at hand.)
579 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
580 int rtindex, AttrNumber col)
583 rte = rt_fetch(rtindex, pstate->p_rtable);
585 if (rte->rtekind == RTE_RELATION)
587 /* Make sure the rel as a whole is marked for SELECT access */
588 rte->requiredPerms |= ACL_SELECT;
589 /* Must offset the attnum to fit in a bitmapset */
590 rte->selectedCols = bms_add_member(rte->selectedCols,
591 col - FirstLowInvalidHeapAttributeNumber);
593 else if (rte->rtekind == RTE_JOIN)
595 if (col == InvalidAttrNumber)
598 * A whole-row reference to a join has to be treated as whole-row
599 * references to the two inputs.
603 if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
604 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
608 elog(ERROR, "could not find JoinExpr for whole-row reference");
609 Assert(IsA(j, JoinExpr));
611 /* Note: we can't see FromExpr here */
612 if (IsA(j->larg, RangeTblRef))
614 int varno = ((RangeTblRef *) j->larg)->rtindex;
616 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
618 else if (IsA(j->larg, JoinExpr))
620 int varno = ((JoinExpr *) j->larg)->rtindex;
622 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
625 elog(ERROR, "unrecognized node type: %d",
626 (int) nodeTag(j->larg));
627 if (IsA(j->rarg, RangeTblRef))
629 int varno = ((RangeTblRef *) j->rarg)->rtindex;
631 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
633 else if (IsA(j->rarg, JoinExpr))
635 int varno = ((JoinExpr *) j->rarg)->rtindex;
637 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
640 elog(ERROR, "unrecognized node type: %d",
641 (int) nodeTag(j->rarg));
646 * Regular join attribute, look at the alias-variable list.
648 * The aliasvar could be either a Var or a COALESCE expression,
649 * but in the latter case we should already have marked the two
650 * referent variables as being selected, due to their use in the
651 * JOIN clause. So we need only be concerned with the simple Var
656 Assert(col > 0 && col <= list_length(rte->joinaliasvars));
657 aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
658 if (IsA(aliasvar, Var))
659 markVarForSelectPriv(pstate, aliasvar, NULL);
662 /* other RTE types don't require privilege marking */
666 * markVarForSelectPriv
667 * Mark the RTE referenced by a Var as requiring SELECT privilege
669 * The caller should pass the Var's referenced RTE if it has it handy
670 * (nearly all do); otherwise pass NULL.
673 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
677 Assert(IsA(var, Var));
678 /* Find the appropriate pstate if it's an uplevel Var */
679 for (lv = 0; lv < var->varlevelsup; lv++)
680 pstate = pstate->parentParseState;
681 markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
685 * buildRelationAliases
686 * Construct the eref column name list for a relation RTE.
687 * This code is also used for the case of a function RTE returning
688 * a named composite type.
690 * tupdesc: the physical column information
691 * alias: the user-supplied alias, or NULL if none
692 * eref: the eref Alias to store column names in
694 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
695 * empty strings for any dropped columns, so that it will be one-to-one with
696 * physical column numbers.
699 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
701 int maxattrs = tupdesc->natts;
707 Assert(eref->colnames == NIL);
711 aliaslc = list_head(alias->colnames);
712 numaliases = list_length(alias->colnames);
713 /* We'll rebuild the alias colname list */
714 alias->colnames = NIL;
722 for (varattno = 0; varattno < maxattrs; varattno++)
724 Form_pg_attribute attr = tupdesc->attrs[varattno];
727 if (attr->attisdropped)
729 /* Always insert an empty string for a dropped column */
730 attrname = makeString(pstrdup(""));
732 alias->colnames = lappend(alias->colnames, attrname);
737 /* Use the next user-supplied alias */
738 attrname = (Value *) lfirst(aliaslc);
739 aliaslc = lnext(aliaslc);
740 alias->colnames = lappend(alias->colnames, attrname);
744 attrname = makeString(pstrdup(NameStr(attr->attname)));
745 /* we're done with the alias if any */
748 eref->colnames = lappend(eref->colnames, attrname);
751 /* Too many user-supplied aliases? */
754 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
755 errmsg("table \"%s\" has %d columns available but %d columns specified",
756 eref->aliasname, maxattrs - numdropped, numaliases)));
760 * buildScalarFunctionAlias
761 * Construct the eref column name list for a function RTE,
762 * when the function returns a scalar type (not composite or RECORD).
764 * funcexpr: transformed expression tree for the function call
765 * funcname: function name (used only for error message)
766 * alias: the user-supplied alias, or NULL if none
767 * eref: the eref Alias to store column names in
769 * eref->colnames is filled in.
772 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
773 Alias *alias, Alias *eref)
777 Assert(eref->colnames == NIL);
779 /* Use user-specified column alias if there is one. */
780 if (alias && alias->colnames != NIL)
782 if (list_length(alias->colnames) != 1)
784 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
785 errmsg("too many column aliases specified for function %s",
787 eref->colnames = copyObject(alias->colnames);
792 * If the expression is a simple function call, and the function has a
793 * single OUT parameter that is named, use the parameter's name.
795 if (funcexpr && IsA(funcexpr, FuncExpr))
797 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
800 eref->colnames = list_make1(makeString(pname));
806 * Otherwise use the previously-determined alias (not necessarily the
809 eref->colnames = list_make1(makeString(eref->aliasname));
813 * Open a table during parse analysis
815 * This is essentially just the same as heap_openrv(), except that it caters
816 * to some parser-specific error reporting needs, notably that it arranges
817 * to include the RangeVar's parse location in any resulting error.
819 * Note: properly, lockmode should be declared LOCKMODE not int, but that
820 * would require importing storage/lock.h into parse_relation.h. Since
821 * LOCKMODE is typedef'd as int anyway, that seems like overkill.
824 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
827 ParseCallbackState pcbstate;
829 setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
830 rel = try_heap_openrv(relation, lockmode);
833 if (relation->schemaname)
835 (errcode(ERRCODE_UNDEFINED_TABLE),
836 errmsg("relation \"%s.%s\" does not exist",
837 relation->schemaname, relation->relname)));
841 * An unqualified name might have been meant as a reference to
842 * some not-yet-in-scope CTE. The bare "does not exist" message
843 * has proven remarkably unhelpful for figuring out such problems,
844 * so we take pains to offer a specific hint.
846 if (isFutureCTE(pstate, relation->relname))
848 (errcode(ERRCODE_UNDEFINED_TABLE),
849 errmsg("relation \"%s\" does not exist",
851 errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
853 errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
856 (errcode(ERRCODE_UNDEFINED_TABLE),
857 errmsg("relation \"%s\" does not exist",
858 relation->relname)));
861 cancel_parser_errposition_callback(&pcbstate);
866 * Add an entry for a relation to the pstate's range table (p_rtable).
868 * If pstate is NULL, we just build an RTE and return it without adding it
871 * Note: formerly this checked for refname conflicts, but that's wrong.
872 * Caller is responsible for checking for conflicts in the appropriate scope.
875 addRangeTableEntry(ParseState *pstate,
881 RangeTblEntry *rte = makeNode(RangeTblEntry);
882 char *refname = alias ? alias->aliasname : relation->relname;
886 rte->rtekind = RTE_RELATION;
890 * Get the rel's OID. This access also ensures that we have an up-to-date
891 * relcache entry for the rel. Since this is typically the first access
892 * to a rel in a statement, be careful to get the right access level
893 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
895 lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
896 rel = parserOpenTable(pstate, relation, lockmode);
897 rte->relid = RelationGetRelid(rel);
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);
962 * Build the list of effective column names using user-supplied aliases
963 * and/or actual column names.
965 rte->eref = makeAlias(refname, NIL);
966 buildRelationAliases(rel->rd_att, alias, rte->eref);
970 * - this RTE should be expanded to include descendant tables,
971 * - this RTE is in the FROM clause,
972 * - this RTE should be checked for appropriate access rights.
974 * The initial default on access checks is always check-for-READ-access,
975 * which is the right thing for all except target tables.
979 rte->inFromCl = inFromCl;
981 rte->requiredPerms = ACL_SELECT;
982 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
983 rte->selectedCols = NULL;
984 rte->modifiedCols = NULL;
987 * Add completed RTE to pstate's range table list, but not to join list
988 * nor namespace --- caller must do that if appropriate.
991 pstate->p_rtable = lappend(pstate->p_rtable, rte);
997 * Add an entry for a subquery to the pstate's range table (p_rtable).
999 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1000 * Note that an alias clause *must* be supplied.
1003 addRangeTableEntryForSubquery(ParseState *pstate,
1008 RangeTblEntry *rte = makeNode(RangeTblEntry);
1009 char *refname = alias->aliasname;
1013 ListCell *tlistitem;
1015 rte->rtekind = RTE_SUBQUERY;
1016 rte->relid = InvalidOid;
1017 rte->subquery = subquery;
1020 eref = copyObject(alias);
1021 numaliases = list_length(eref->colnames);
1023 /* fill in any unspecified alias columns */
1025 foreach(tlistitem, subquery->targetList)
1027 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1032 Assert(varattno == te->resno);
1033 if (varattno > numaliases)
1037 attrname = pstrdup(te->resname);
1038 eref->colnames = lappend(eref->colnames, makeString(attrname));
1041 if (varattno < numaliases)
1043 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1044 errmsg("table \"%s\" has %d columns available but %d columns specified",
1045 refname, varattno, numaliases)));
1051 * - this RTE should be expanded to include descendant tables,
1052 * - this RTE is in the FROM clause,
1053 * - this RTE should be checked for appropriate access rights.
1055 * Subqueries are never checked for access rights.
1058 rte->inh = false; /* never true for subqueries */
1059 rte->inFromCl = inFromCl;
1061 rte->requiredPerms = 0;
1062 rte->checkAsUser = InvalidOid;
1063 rte->selectedCols = NULL;
1064 rte->modifiedCols = NULL;
1067 * Add completed RTE to pstate's range table list, but not to join list
1068 * nor namespace --- caller must do that if appropriate.
1071 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1077 * Add an entry for a function to the pstate's range table (p_rtable).
1079 * This is just like addRangeTableEntry() except that it makes a function RTE.
1082 addRangeTableEntryForFunction(ParseState *pstate,
1085 RangeFunction *rangefunc,
1088 RangeTblEntry *rte = makeNode(RangeTblEntry);
1089 TypeFuncClass functypclass;
1092 Alias *alias = rangefunc->alias;
1093 List *coldeflist = rangefunc->coldeflist;
1096 rte->rtekind = RTE_FUNCTION;
1097 rte->relid = InvalidOid;
1098 rte->subquery = NULL;
1099 rte->funcexpr = funcexpr;
1100 rte->funccoltypes = NIL;
1101 rte->funccoltypmods = NIL;
1104 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1108 * Now determine if the function returns a simple or composite type.
1110 functypclass = get_expr_result_type(funcexpr,
1115 * A coldeflist is required if the function returns RECORD and hasn't got
1116 * a predetermined record type, and is prohibited otherwise.
1118 if (coldeflist != NIL)
1120 if (functypclass != TYPEFUNC_RECORD)
1122 (errcode(ERRCODE_SYNTAX_ERROR),
1123 errmsg("a column definition list is only allowed for functions returning \"record\""),
1124 parser_errposition(pstate, exprLocation(funcexpr))));
1128 if (functypclass == TYPEFUNC_RECORD)
1130 (errcode(ERRCODE_SYNTAX_ERROR),
1131 errmsg("a column definition list is required for functions returning \"record\""),
1132 parser_errposition(pstate, exprLocation(funcexpr))));
1135 if (functypclass == TYPEFUNC_COMPOSITE)
1137 /* Composite data type, e.g. a table's row type */
1139 /* Build the column alias list */
1140 buildRelationAliases(tupdesc, alias, eref);
1142 else if (functypclass == TYPEFUNC_SCALAR)
1144 /* Base data type, i.e. scalar */
1145 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1147 else if (functypclass == TYPEFUNC_RECORD)
1152 * Use the column definition list to form the alias list and
1153 * funccoltypes/funccoltypmods lists.
1155 foreach(col, coldeflist)
1157 ColumnDef *n = (ColumnDef *) lfirst(col);
1162 attrname = pstrdup(n->colname);
1163 if (n->typeName->setof)
1165 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1166 errmsg("column \"%s\" cannot be declared SETOF",
1168 parser_errposition(pstate, n->typeName->location)));
1169 attrtype = typenameTypeId(pstate, n->typeName, &attrtypmod);
1170 eref->colnames = lappend(eref->colnames, makeString(attrname));
1171 rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1172 rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1177 (errcode(ERRCODE_DATATYPE_MISMATCH),
1178 errmsg("function \"%s\" in FROM has unsupported return type %s",
1179 funcname, format_type_be(funcrettype)),
1180 parser_errposition(pstate, exprLocation(funcexpr))));
1184 * - this RTE should be expanded to include descendant tables,
1185 * - this RTE is in the FROM clause,
1186 * - this RTE should be checked for appropriate access rights.
1188 * Functions are never checked for access rights (at least, not by
1189 * the RTE permissions mechanism).
1192 rte->inh = false; /* never true for functions */
1193 rte->inFromCl = inFromCl;
1195 rte->requiredPerms = 0;
1196 rte->checkAsUser = InvalidOid;
1197 rte->selectedCols = NULL;
1198 rte->modifiedCols = NULL;
1201 * Add completed RTE to pstate's range table list, but not to join list
1202 * nor namespace --- caller must do that if appropriate.
1205 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1211 * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1213 * This is much like addRangeTableEntry() except that it makes a values RTE.
1216 addRangeTableEntryForValues(ParseState *pstate,
1221 RangeTblEntry *rte = makeNode(RangeTblEntry);
1222 char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1227 rte->rtekind = RTE_VALUES;
1228 rte->relid = InvalidOid;
1229 rte->subquery = NULL;
1230 rte->values_lists = exprs;
1233 eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1235 /* fill in any unspecified alias columns */
1236 numcolumns = list_length((List *) linitial(exprs));
1237 numaliases = list_length(eref->colnames);
1238 while (numaliases < numcolumns)
1243 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1244 eref->colnames = lappend(eref->colnames,
1245 makeString(pstrdup(attrname)));
1247 if (numcolumns < numaliases)
1249 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1250 errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1251 refname, numcolumns, numaliases)));
1257 * - this RTE should be expanded to include descendant tables,
1258 * - this RTE is in the FROM clause,
1259 * - this RTE should be checked for appropriate access rights.
1261 * Subqueries are never checked for access rights.
1264 rte->inh = false; /* never true for values RTEs */
1265 rte->inFromCl = inFromCl;
1267 rte->requiredPerms = 0;
1268 rte->checkAsUser = InvalidOid;
1269 rte->selectedCols = NULL;
1270 rte->modifiedCols = NULL;
1273 * Add completed RTE to pstate's range table list, but not to join list
1274 * nor namespace --- caller must do that if appropriate.
1277 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1283 * Add an entry for a join to the pstate's range table (p_rtable).
1285 * This is much like addRangeTableEntry() except that it makes a join RTE.
1288 addRangeTableEntryForJoin(ParseState *pstate,
1295 RangeTblEntry *rte = makeNode(RangeTblEntry);
1300 * Fail if join has too many columns --- we must be able to reference any
1301 * of the columns with an AttrNumber.
1303 if (list_length(aliasvars) > MaxAttrNumber)
1305 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1306 errmsg("joins can have at most %d columns",
1309 rte->rtekind = RTE_JOIN;
1310 rte->relid = InvalidOid;
1311 rte->subquery = NULL;
1312 rte->jointype = jointype;
1313 rte->joinaliasvars = aliasvars;
1316 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1317 numaliases = list_length(eref->colnames);
1319 /* fill in any unspecified alias columns */
1320 if (numaliases < list_length(colnames))
1321 eref->colnames = list_concat(eref->colnames,
1322 list_copy_tail(colnames, numaliases));
1328 * - this RTE should be expanded to include descendant tables,
1329 * - this RTE is in the FROM clause,
1330 * - this RTE should be checked for appropriate access rights.
1332 * Joins are never checked for access rights.
1335 rte->inh = false; /* never true for joins */
1336 rte->inFromCl = inFromCl;
1338 rte->requiredPerms = 0;
1339 rte->checkAsUser = InvalidOid;
1340 rte->selectedCols = NULL;
1341 rte->modifiedCols = NULL;
1344 * Add completed RTE to pstate's range table list, but not to join list
1345 * nor namespace --- caller must do that if appropriate.
1348 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1354 * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1356 * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1359 addRangeTableEntryForCTE(ParseState *pstate,
1360 CommonTableExpr *cte,
1365 RangeTblEntry *rte = makeNode(RangeTblEntry);
1366 char *refname = alias ? alias->aliasname : cte->ctename;
1372 rte->rtekind = RTE_CTE;
1373 rte->ctename = cte->ctename;
1374 rte->ctelevelsup = levelsup;
1376 /* Self-reference if and only if CTE's parse analysis isn't completed */
1377 rte->self_reference = !IsA(cte->ctequery, Query);
1378 Assert(cte->cterecursive || !rte->self_reference);
1379 /* Bump the CTE's refcount if this isn't a self-reference */
1380 if (!rte->self_reference)
1383 rte->ctecoltypes = cte->ctecoltypes;
1384 rte->ctecoltypmods = cte->ctecoltypmods;
1388 eref = copyObject(alias);
1390 eref = makeAlias(refname, NIL);
1391 numaliases = list_length(eref->colnames);
1393 /* fill in any unspecified alias columns */
1395 foreach(lc, cte->ctecolnames)
1398 if (varattno > numaliases)
1399 eref->colnames = lappend(eref->colnames, lfirst(lc));
1401 if (varattno < numaliases)
1403 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1404 errmsg("table \"%s\" has %d columns available but %d columns specified",
1405 refname, varattno, numaliases)));
1411 * - this RTE should be expanded to include descendant tables,
1412 * - this RTE is in the FROM clause,
1413 * - this RTE should be checked for appropriate access rights.
1415 * Subqueries are never checked for access rights.
1418 rte->inh = false; /* never true for subqueries */
1419 rte->inFromCl = inFromCl;
1421 rte->requiredPerms = 0;
1422 rte->checkAsUser = InvalidOid;
1423 rte->selectedCols = NULL;
1424 rte->modifiedCols = NULL;
1427 * Add completed RTE to pstate's range table list, but not to join list
1428 * nor namespace --- caller must do that if appropriate.
1431 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1438 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1440 * This is used when we have not yet done transformLockingClause, but need
1441 * to know the correct lock to take during initial opening of relations.
1443 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1444 * since the table-level lock is the same either way.
1447 isLockedRefname(ParseState *pstate, const char *refname)
1452 * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1453 * parent level, then act as though there's a generic FOR UPDATE here.
1455 if (pstate->p_locked_from_parent)
1458 foreach(l, pstate->p_locking_clause)
1460 LockingClause *lc = (LockingClause *) lfirst(l);
1462 if (lc->lockedRels == NIL)
1464 /* all tables used in query */
1469 /* just the named tables */
1472 foreach(l2, lc->lockedRels)
1474 RangeVar *thisrel = (RangeVar *) lfirst(l2);
1476 if (strcmp(refname, thisrel->relname) == 0)
1485 * Add the given RTE as a top-level entry in the pstate's join list
1486 * and/or name space lists. (We assume caller has checked for any
1487 * namespace conflicts.)
1490 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1492 bool addToRelNameSpace, bool addToVarNameSpace)
1496 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1497 RangeTblRef *rtr = makeNode(RangeTblRef);
1499 rtr->rtindex = rtindex;
1500 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1502 if (addToRelNameSpace)
1503 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1504 if (addToVarNameSpace)
1505 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1509 * expandRTE -- expand the columns of a rangetable entry
1511 * This creates lists of an RTE's column names (aliases if provided, else
1512 * real names) and Vars for each column. Only user columns are considered.
1513 * If include_dropped is FALSE then dropped columns are omitted from the
1514 * results. If include_dropped is TRUE then empty strings and NULL constants
1515 * (not Vars!) are returned for dropped columns.
1517 * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1518 * values to use in the created Vars. Ordinarily rtindex should match the
1519 * actual position of the RTE in its rangetable.
1521 * The output lists go into *colnames and *colvars.
1522 * If only one of the two kinds of output list is needed, pass NULL for the
1523 * output pointer for the unwanted one.
1526 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1527 int location, bool include_dropped,
1528 List **colnames, List **colvars)
1537 switch (rte->rtekind)
1540 /* Ordinary relation RTE */
1541 expandRelation(rte->relid, rte->eref,
1542 rtindex, sublevels_up, location,
1543 include_dropped, colnames, colvars);
1548 ListCell *aliasp_item = list_head(rte->eref->colnames);
1549 ListCell *tlistitem;
1552 foreach(tlistitem, rte->subquery->targetList)
1554 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1559 Assert(varattno == te->resno);
1563 /* Assume there is one alias per target item */
1564 char *label = strVal(lfirst(aliasp_item));
1566 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1567 aliasp_item = lnext(aliasp_item);
1574 varnode = makeVar(rtindex, varattno,
1575 exprType((Node *) te->expr),
1576 exprTypmod((Node *) te->expr),
1578 varnode->location = location;
1580 *colvars = lappend(*colvars, varnode);
1588 TypeFuncClass functypclass;
1592 functypclass = get_expr_result_type(rte->funcexpr,
1595 if (functypclass == TYPEFUNC_COMPOSITE)
1597 /* Composite data type, e.g. a table's row type */
1599 expandTupleDesc(tupdesc, rte->eref,
1600 rtindex, sublevels_up, location,
1601 include_dropped, colnames, colvars);
1603 else if (functypclass == TYPEFUNC_SCALAR)
1605 /* Base data type, i.e. scalar */
1607 *colnames = lappend(*colnames,
1608 linitial(rte->eref->colnames));
1614 varnode = makeVar(rtindex, 1,
1617 varnode->location = location;
1619 *colvars = lappend(*colvars, varnode);
1622 else if (functypclass == TYPEFUNC_RECORD)
1625 *colnames = copyObject(rte->eref->colnames);
1632 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1634 Oid attrtype = lfirst_oid(l1);
1635 int32 attrtypmod = lfirst_int(l2);
1639 varnode = makeVar(rtindex,
1644 varnode->location = location;
1645 *colvars = lappend(*colvars, varnode);
1651 /* addRangeTableEntryForFunction should've caught this */
1652 elog(ERROR, "function in FROM has unsupported return type");
1659 ListCell *aliasp_item = list_head(rte->eref->colnames);
1663 foreach(lc, (List *) linitial(rte->values_lists))
1665 Node *col = (Node *) lfirst(lc);
1670 /* Assume there is one alias per column */
1671 char *label = strVal(lfirst(aliasp_item));
1673 *colnames = lappend(*colnames,
1674 makeString(pstrdup(label)));
1675 aliasp_item = lnext(aliasp_item);
1682 varnode = makeVar(rtindex, varattno,
1686 varnode->location = location;
1687 *colvars = lappend(*colvars, varnode);
1698 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1701 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1703 Node *avar = (Node *) lfirst(aliasvar);
1708 * During ordinary parsing, there will never be any
1709 * deleted columns in the join; but we have to check since
1710 * this routine is also used by the rewriter, and joins
1711 * found in stored rules might have join columns for
1712 * since-deleted columns. This will be signaled by a NULL
1713 * Const in the alias-vars list.
1715 if (IsA(avar, Const))
1717 if (include_dropped)
1720 *colnames = lappend(*colnames,
1721 makeString(pstrdup("")));
1723 *colvars = lappend(*colvars,
1731 char *label = strVal(lfirst(colname));
1733 *colnames = lappend(*colnames,
1734 makeString(pstrdup(label)));
1741 varnode = makeVar(rtindex, varattno,
1745 varnode->location = location;
1747 *colvars = lappend(*colvars, varnode);
1754 ListCell *aliasp_item = list_head(rte->eref->colnames);
1759 forboth(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods)
1761 Oid coltype = lfirst_oid(lct);
1762 int32 coltypmod = lfirst_int(lcm);
1768 /* Assume there is one alias per output column */
1769 char *label = strVal(lfirst(aliasp_item));
1771 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1772 aliasp_item = lnext(aliasp_item);
1779 varnode = makeVar(rtindex, varattno,
1782 *colvars = lappend(*colvars, varnode);
1788 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1793 * expandRelation -- expandRTE subroutine
1796 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1797 int location, bool include_dropped,
1798 List **colnames, List **colvars)
1802 /* Get the tupledesc and turn it over to expandTupleDesc */
1803 rel = relation_open(relid, AccessShareLock);
1804 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1805 location, include_dropped,
1807 relation_close(rel, AccessShareLock);
1811 * expandTupleDesc -- expandRTE subroutine
1814 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1815 int rtindex, int sublevels_up,
1816 int location, bool include_dropped,
1817 List **colnames, List **colvars)
1819 int maxattrs = tupdesc->natts;
1820 int numaliases = list_length(eref->colnames);
1823 for (varattno = 0; varattno < maxattrs; varattno++)
1825 Form_pg_attribute attr = tupdesc->attrs[varattno];
1827 if (attr->attisdropped)
1829 if (include_dropped)
1832 *colnames = lappend(*colnames, makeString(pstrdup("")));
1836 * can't use atttypid here, but it doesn't really matter
1837 * what type the Const claims to be.
1839 *colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1849 if (varattno < numaliases)
1850 label = strVal(list_nth(eref->colnames, varattno));
1852 label = NameStr(attr->attname);
1853 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1860 varnode = makeVar(rtindex, attr->attnum,
1861 attr->atttypid, attr->atttypmod,
1863 varnode->location = location;
1865 *colvars = lappend(*colvars, varnode);
1872 * Workhorse for "*" expansion: produce a list of targetentries
1873 * for the attributes of the RTE
1875 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1876 * fields of the Vars produced, and location sets their location.
1877 * pstate->p_next_resno determines the resnos assigned to the TLEs.
1878 * The referenced columns are marked as requiring SELECT access.
1881 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1882 int rtindex, int sublevels_up, int location)
1888 List *te_list = NIL;
1890 expandRTE(rte, rtindex, sublevels_up, location, false,
1894 * Require read access to the table. This is normally redundant with the
1895 * markVarForSelectPriv calls below, but not if the table has zero
1898 rte->requiredPerms |= ACL_SELECT;
1900 forboth(name, names, var, vars)
1902 char *label = strVal(lfirst(name));
1903 Var *varnode = (Var *) lfirst(var);
1906 te = makeTargetEntry((Expr *) varnode,
1907 (AttrNumber) pstate->p_next_resno++,
1910 te_list = lappend(te_list, te);
1912 /* Require read access to each column */
1913 markVarForSelectPriv(pstate, varnode, rte);
1916 Assert(name == NULL && var == NULL); /* lists not the same length? */
1922 * get_rte_attribute_name
1923 * Get an attribute name from a RangeTblEntry
1925 * This is unlike get_attname() because we use aliases if available.
1926 * In particular, it will work on an RTE for a subselect or join, whereas
1927 * get_attname() only works on real relations.
1929 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1930 * occurs when a Var represents a whole tuple of a relation.
1933 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1935 if (attnum == InvalidAttrNumber)
1939 * If there is a user-written column alias, use it.
1942 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1943 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1946 * If the RTE is a relation, go to the system catalogs not the
1947 * eref->colnames list. This is a little slower but it will give the
1948 * right answer if the column has been renamed since the eref list was
1949 * built (which can easily happen for rules).
1951 if (rte->rtekind == RTE_RELATION)
1952 return get_relid_attribute_name(rte->relid, attnum);
1955 * Otherwise use the column name from eref. There should always be one.
1957 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1958 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1960 /* else caller gave us a bogus attnum */
1961 elog(ERROR, "invalid attnum %d for rangetable entry %s",
1962 attnum, rte->eref->aliasname);
1963 return NULL; /* keep compiler quiet */
1967 * get_rte_attribute_type
1968 * Get attribute type information from a RangeTblEntry
1971 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1972 Oid *vartype, int32 *vartypmod)
1974 switch (rte->rtekind)
1978 /* Plain relation RTE --- get the attribute's type info */
1980 Form_pg_attribute att_tup;
1982 tp = SearchSysCache(ATTNUM,
1983 ObjectIdGetDatum(rte->relid),
1984 Int16GetDatum(attnum),
1986 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1987 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1988 attnum, rte->relid);
1989 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1992 * If dropped column, pretend it ain't there. See notes in
1995 if (att_tup->attisdropped)
1997 (errcode(ERRCODE_UNDEFINED_COLUMN),
1998 errmsg("column \"%s\" of relation \"%s\" does not exist",
1999 NameStr(att_tup->attname),
2000 get_rel_name(rte->relid))));
2001 *vartype = att_tup->atttypid;
2002 *vartypmod = att_tup->atttypmod;
2003 ReleaseSysCache(tp);
2008 /* Subselect RTE --- get type info from subselect's tlist */
2009 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2012 if (te == NULL || te->resjunk)
2013 elog(ERROR, "subquery %s does not have attribute %d",
2014 rte->eref->aliasname, attnum);
2015 *vartype = exprType((Node *) te->expr);
2016 *vartypmod = exprTypmod((Node *) te->expr);
2022 TypeFuncClass functypclass;
2026 functypclass = get_expr_result_type(rte->funcexpr,
2030 if (functypclass == TYPEFUNC_COMPOSITE)
2032 /* Composite data type, e.g. a table's row type */
2033 Form_pg_attribute att_tup;
2036 /* this is probably a can't-happen case */
2037 if (attnum < 1 || attnum > tupdesc->natts)
2039 (errcode(ERRCODE_UNDEFINED_COLUMN),
2040 errmsg("column %d of relation \"%s\" does not exist",
2042 rte->eref->aliasname)));
2044 att_tup = tupdesc->attrs[attnum - 1];
2047 * If dropped column, pretend it ain't there. See notes
2048 * in scanRTEForColumn.
2050 if (att_tup->attisdropped)
2052 (errcode(ERRCODE_UNDEFINED_COLUMN),
2053 errmsg("column \"%s\" of relation \"%s\" does not exist",
2054 NameStr(att_tup->attname),
2055 rte->eref->aliasname)));
2056 *vartype = att_tup->atttypid;
2057 *vartypmod = att_tup->atttypmod;
2059 else if (functypclass == TYPEFUNC_SCALAR)
2061 /* Base data type, i.e. scalar */
2062 *vartype = funcrettype;
2065 else if (functypclass == TYPEFUNC_RECORD)
2067 *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2068 *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2072 /* addRangeTableEntryForFunction should've caught this */
2073 elog(ERROR, "function in FROM has unsupported return type");
2079 /* Values RTE --- get type info from first sublist */
2080 List *collist = (List *) linitial(rte->values_lists);
2083 if (attnum < 1 || attnum > list_length(collist))
2084 elog(ERROR, "values list %s does not have attribute %d",
2085 rte->eref->aliasname, attnum);
2086 col = (Node *) list_nth(collist, attnum - 1);
2087 *vartype = exprType(col);
2088 *vartypmod = exprTypmod(col);
2094 * Join RTE --- get type info from join RTE's alias variable
2098 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2099 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2100 *vartype = exprType(aliasvar);
2101 *vartypmod = exprTypmod(aliasvar);
2106 /* CTE RTE --- get type info from lists in the RTE */
2107 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2108 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2109 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2113 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2118 * get_rte_attribute_is_dropped
2119 * Check whether attempted attribute ref is to a dropped column
2122 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2126 switch (rte->rtekind)
2131 * Plain relation RTE --- get the attribute's catalog entry
2134 Form_pg_attribute att_tup;
2136 tp = SearchSysCache(ATTNUM,
2137 ObjectIdGetDatum(rte->relid),
2138 Int16GetDatum(attnum),
2140 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2141 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2142 attnum, rte->relid);
2143 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2144 result = att_tup->attisdropped;
2145 ReleaseSysCache(tp);
2151 /* Subselect, Values, CTE RTEs never have dropped columns */
2157 * A join RTE would not have dropped columns when constructed,
2158 * but one in a stored rule might contain columns that were
2159 * dropped from the underlying tables, if said columns are
2160 * nowhere explicitly referenced in the rule. This will be
2161 * signaled to us by a NULL Const in the joinaliasvars list.
2166 attnum > list_length(rte->joinaliasvars))
2167 elog(ERROR, "invalid varattno %d", attnum);
2168 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2170 result = IsA(aliasvar, Const);
2176 Oid funcrettype = exprType(rte->funcexpr);
2177 Oid funcrelid = typeidTypeRelid(funcrettype);
2179 if (OidIsValid(funcrelid))
2182 * Composite data type, i.e. a table's row type
2184 * Same as ordinary relation RTE
2187 Form_pg_attribute att_tup;
2189 tp = SearchSysCache(ATTNUM,
2190 ObjectIdGetDatum(funcrelid),
2191 Int16GetDatum(attnum),
2193 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2194 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2196 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2197 result = att_tup->attisdropped;
2198 ReleaseSysCache(tp);
2203 * Must be a base data type, i.e. scalar
2210 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2211 result = false; /* keep compiler quiet */
2218 * Given a targetlist and a resno, return the matching TargetEntry
2220 * Returns NULL if resno is not present in list.
2222 * Note: we need to search, rather than just indexing with list_nth(),
2223 * because not all tlists are sorted by resno.
2226 get_tle_by_resno(List *tlist, AttrNumber resno)
2232 TargetEntry *tle = (TargetEntry *) lfirst(l);
2234 if (tle->resno == resno)
2241 * Given a Query and rangetable index, return relation's RowMarkClause if any
2243 * Returns NULL if relation is not selected FOR UPDATE/SHARE
2246 get_parse_rowmark(Query *qry, Index rtindex)
2250 foreach(l, qry->rowMarks)
2252 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2254 if (rc->rti == rtindex)
2261 * given relation and att name, return attnum of variable
2263 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2265 * This should only be used if the relation is already
2266 * heap_open()'ed. Use the cache version get_attnum()
2267 * for access to non-opened relations.
2270 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2274 for (i = 0; i < rd->rd_rel->relnatts; i++)
2276 Form_pg_attribute att = rd->rd_att->attrs[i];
2278 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2284 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2286 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2292 return InvalidAttrNumber;
2297 * Check attribute name to see if it is "special", e.g. "oid".
2298 * - thomas 2000-02-07
2300 * Note: this only discovers whether the name could be a system attribute.
2301 * Caller needs to verify that it really is an attribute of the rel,
2302 * at least in the case of "oid", which is now optional.
2305 specialAttNum(const char *attname)
2307 Form_pg_attribute sysatt;
2309 sysatt = SystemAttributeByName(attname,
2310 true /* "oid" will be accepted */ );
2312 return sysatt->attnum;
2313 return InvalidAttrNumber;
2318 * given attribute id, return name of that attribute
2320 * This should only be used if the relation is already
2321 * heap_open()'ed. Use the cache version get_atttype()
2322 * for access to non-opened relations.
2325 attnumAttName(Relation rd, int attid)
2329 Form_pg_attribute sysatt;
2331 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2332 return &sysatt->attname;
2334 if (attid > rd->rd_att->natts)
2335 elog(ERROR, "invalid attribute number %d", attid);
2336 return &rd->rd_att->attrs[attid - 1]->attname;
2340 * given attribute id, return type of that attribute
2342 * This should only be used if the relation is already
2343 * heap_open()'ed. Use the cache version get_atttype()
2344 * for access to non-opened relations.
2347 attnumTypeId(Relation rd, int attid)
2351 Form_pg_attribute sysatt;
2353 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2354 return sysatt->atttypid;
2356 if (attid > rd->rd_att->natts)
2357 elog(ERROR, "invalid attribute number %d", attid);
2358 return rd->rd_att->attrs[attid - 1]->atttypid;
2362 * Generate a suitable error about a missing RTE.
2364 * Since this is a very common type of error, we work rather hard to
2365 * produce a helpful message.
2368 errorMissingRTE(ParseState *pstate, RangeVar *relation)
2372 const char *badAlias = NULL;
2375 * Check to see if there are any potential matches in the query's
2376 * rangetable. (Note: cases involving a bad schema name in the
2377 * RangeVar will throw error immediately here. That seems OK.)
2379 rte = searchRangeTable(pstate, relation);
2382 * If we found a match that has an alias and the alias is visible in the
2383 * namespace, then the problem is probably use of the relation's real name
2384 * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2385 * common enough to justify a specific hint.
2387 * If we found a match that doesn't meet those criteria, assume the
2388 * problem is illegal use of a relation outside its scope, as in the
2389 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2391 if (rte && rte->alias &&
2392 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2393 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2395 &sublevels_up) == rte)
2396 badAlias = rte->eref->aliasname;
2400 (errcode(ERRCODE_UNDEFINED_TABLE),
2401 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2404 errhint("Perhaps you meant to reference the table alias \"%s\".",
2406 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2407 rte->eref->aliasname)),
2408 parser_errposition(pstate, relation->location)));
2411 (errcode(ERRCODE_UNDEFINED_TABLE),
2412 errmsg("missing FROM-clause entry for table \"%s\"",
2414 parser_errposition(pstate, relation->location)));