1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.81 2003/04/29 22:13:10 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "access/htup.h"
21 #include "catalog/heap.h"
22 #include "catalog/namespace.h"
23 #include "catalog/pg_type.h"
24 #include "nodes/makefuncs.h"
25 #include "parser/parsetree.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_expr.h"
28 #include "parser/parse_relation.h"
29 #include "parser/parse_type.h"
30 #include "rewrite/rewriteManip.h"
31 #include "utils/builtins.h"
32 #include "utils/lsyscache.h"
33 #include "utils/syscache.h"
36 static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
38 static Node *scanNameSpaceForRelid(ParseState *pstate, Node *nsnode,
40 static void scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
41 RangeTblEntry *rte1, const char *aliasname1);
42 static Node *scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
44 static bool isForUpdate(ParseState *pstate, char *refname);
45 static bool get_rte_attribute_is_dropped(RangeTblEntry *rte,
47 static int specialAttNum(const char *attname);
48 static void warnAutoRange(ParseState *pstate, RangeVar *relation);
52 * refnameRangeTblEntry
53 * Given a possibly-qualified refname, look to see if it matches any RTE.
54 * If so, return a pointer to the RangeTblEntry; else return NULL.
56 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
57 * If sublevels_up is NULL, only consider items at the current nesting
60 * An unqualified refname (schemaname == NULL) can match any RTE with matching
61 * alias, or matching unqualified relname in the case of alias-less relation
62 * RTEs. It is possible that such a refname matches multiple RTEs in the
63 * nearest nesting level that has a match; if so, we report an error via elog.
65 * A qualified refname (schemaname != NULL) can only match a relation RTE
66 * that (a) has no alias and (b) is for the same relation identified by
67 * schemaname.refname. In this case we convert schemaname.refname to a
68 * relation OID and search by relid, rather than by alias name. This is
69 * peculiar, but it's what SQL92 says to do.
72 refnameRangeTblEntry(ParseState *pstate,
73 const char *schemaname,
77 Oid relId = InvalidOid;
82 if (schemaname != NULL)
86 namespaceId = LookupExplicitNamespace(schemaname);
87 relId = get_relname_relid(refname, namespaceId);
88 if (!OidIsValid(relId))
92 while (pstate != NULL)
96 if (OidIsValid(relId))
97 nsnode = scanNameSpaceForRelid(pstate,
98 (Node *) pstate->p_namespace,
101 nsnode = scanNameSpaceForRefname(pstate,
102 (Node *) pstate->p_namespace,
107 /* should get an RTE or JoinExpr */
108 if (IsA(nsnode, RangeTblEntry))
109 return (RangeTblEntry *) nsnode;
110 Assert(IsA(nsnode, JoinExpr));
111 return rt_fetch(((JoinExpr *) nsnode)->rtindex, pstate->p_rtable);
114 pstate = pstate->parentParseState;
124 * Recursively search a namespace for an RTE or joinexpr matching the
125 * given unqualified refname. Return the node if a unique match, or NULL
126 * if no match. Raise error if multiple matches.
128 * The top level of p_namespace is a list, and we recurse into any joins
129 * that are not subqueries.
132 scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
140 if (IsA(nsnode, RangeTblRef))
142 int varno = ((RangeTblRef *) nsnode)->rtindex;
143 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
145 if (strcmp(rte->eref->aliasname, refname) == 0)
146 result = (Node *) rte;
148 else if (IsA(nsnode, JoinExpr))
150 JoinExpr *j = (JoinExpr *) nsnode;
154 if (strcmp(j->alias->aliasname, refname) == 0)
155 return (Node *) j; /* matched a join alias */
158 * Tables within an aliased join are invisible from outside
159 * the join, according to the scope rules of SQL92 (the join
160 * is considered a subquery). So, stop here.
164 result = scanNameSpaceForRefname(pstate, j->larg, refname);
165 newresult = scanNameSpaceForRefname(pstate, j->rarg, refname);
169 elog(ERROR, "Table reference \"%s\" is ambiguous", refname);
171 else if (IsA(nsnode, List))
175 foreach(l, (List *) nsnode)
177 newresult = scanNameSpaceForRefname(pstate, lfirst(l), refname);
181 elog(ERROR, "Table reference \"%s\" is ambiguous", refname);
185 elog(ERROR, "scanNameSpaceForRefname: unexpected node type %d",
191 * Recursively search a namespace for a relation RTE matching the
192 * given relation OID. Return the node if a unique match, or NULL
193 * if no match. Raise error if multiple matches (which shouldn't
194 * happen if the namespace was checked correctly when it was created).
196 * The top level of p_namespace is a list, and we recurse into any joins
197 * that are not subqueries.
199 * See the comments for refnameRangeTblEntry to understand why this
200 * acts the way it does.
203 scanNameSpaceForRelid(ParseState *pstate, Node *nsnode, Oid relid)
210 if (IsA(nsnode, RangeTblRef))
212 int varno = ((RangeTblRef *) nsnode)->rtindex;
213 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
215 /* yes, the test for alias==NULL should be there... */
216 if (rte->rtekind == RTE_RELATION &&
217 rte->relid == relid &&
219 result = (Node *) rte;
221 else if (IsA(nsnode, JoinExpr))
223 JoinExpr *j = (JoinExpr *) nsnode;
228 * Tables within an aliased join are invisible from outside
229 * the join, according to the scope rules of SQL92 (the join
230 * is considered a subquery). So, stop here.
234 result = scanNameSpaceForRelid(pstate, j->larg, relid);
235 newresult = scanNameSpaceForRelid(pstate, j->rarg, relid);
239 elog(ERROR, "Table reference %u is ambiguous", relid);
241 else if (IsA(nsnode, List))
245 foreach(l, (List *) nsnode)
247 newresult = scanNameSpaceForRelid(pstate, lfirst(l), relid);
251 elog(ERROR, "Table reference %u is ambiguous", relid);
255 elog(ERROR, "scanNameSpaceForRelid: unexpected node type %d",
261 * Recursively check for name conflicts between two namespaces or
262 * namespace subtrees. Raise an error if any is found.
264 * Works by recursively scanning namespace1 for RTEs and join nodes,
265 * and for each one recursively scanning namespace2 for a match.
267 * Note: we assume that each given argument does not contain conflicts
268 * itself; we just want to know if the two can be merged together.
270 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
271 * they have the same eref->aliasname (ie, same relation name), if they
272 * are for different relation OIDs (implying they are in different schemas).
275 checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
278 if (namespace1 == NULL)
280 if (IsA(namespace1, RangeTblRef))
282 int varno = ((RangeTblRef *) namespace1)->rtindex;
283 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
285 if (rte->rtekind == RTE_RELATION && rte->alias == NULL)
286 scanNameSpaceForConflict(pstate, namespace2,
287 rte, rte->eref->aliasname);
289 scanNameSpaceForConflict(pstate, namespace2,
290 NULL, rte->eref->aliasname);
292 else if (IsA(namespace1, JoinExpr))
294 JoinExpr *j = (JoinExpr *) namespace1;
298 scanNameSpaceForConflict(pstate, namespace2,
299 NULL, j->alias->aliasname);
302 * Tables within an aliased join are invisible from outside
303 * the join, according to the scope rules of SQL92 (the join
304 * is considered a subquery). So, stop here.
308 checkNameSpaceConflicts(pstate, j->larg, namespace2);
309 checkNameSpaceConflicts(pstate, j->rarg, namespace2);
311 else if (IsA(namespace1, List))
315 foreach(l, (List *) namespace1)
316 checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
319 elog(ERROR, "checkNameSpaceConflicts: unexpected node type %d",
320 nodeTag(namespace1));
324 * Subroutine for checkNameSpaceConflicts: scan namespace2
327 scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
328 RangeTblEntry *rte1, const char *aliasname1)
332 if (IsA(nsnode, RangeTblRef))
334 int varno = ((RangeTblRef *) nsnode)->rtindex;
335 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
337 if (strcmp(rte->eref->aliasname, aliasname1) != 0)
338 return; /* definitely no conflict */
339 if (rte->rtekind == RTE_RELATION && rte->alias == NULL &&
340 rte1 != NULL && rte->relid != rte1->relid)
341 return; /* no conflict per SQL92 rule */
342 elog(ERROR, "Table name \"%s\" specified more than once",
345 else if (IsA(nsnode, JoinExpr))
347 JoinExpr *j = (JoinExpr *) nsnode;
351 if (strcmp(j->alias->aliasname, aliasname1) == 0)
352 elog(ERROR, "Table name \"%s\" specified more than once",
356 * Tables within an aliased join are invisible from outside
357 * the join, according to the scope rules of SQL92 (the join
358 * is considered a subquery). So, stop here.
362 scanNameSpaceForConflict(pstate, j->larg, rte1, aliasname1);
363 scanNameSpaceForConflict(pstate, j->rarg, rte1, aliasname1);
365 else if (IsA(nsnode, List))
369 foreach(l, (List *) nsnode)
370 scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1);
373 elog(ERROR, "scanNameSpaceForConflict: unexpected node type %d",
378 * given an RTE, return RT index (starting with 1) of the entry,
379 * and optionally get its nesting depth (0 = current). If sublevels_up
380 * is NULL, only consider rels at the current nesting level.
381 * Raises error if RTE not found.
384 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
392 while (pstate != NULL)
395 foreach(temp, pstate->p_rtable)
397 if (rte == (RangeTblEntry *) lfirst(temp))
401 pstate = pstate->parentParseState;
408 elog(ERROR, "RTERangeTablePosn: RTE not found (internal error)");
409 return 0; /* keep compiler quiet */
414 * Search the column names of a single RTE for the given name.
415 * If found, return an appropriate Var node, else return NULL.
416 * If the name proves ambiguous within this RTE, raise error.
418 * Side effect: if we find a match, mark the RTE as requiring read access.
419 * See comments in setTargetTable().
421 * NOTE: if the RTE is for a join, marking it as requiring read access does
422 * nothing. It might seem that we need to propagate the mark to all the
423 * contained RTEs, but that is not necessary. This is so because a join
424 * expression can only appear in a FROM clause, and any table named in
425 * FROM will be marked checkForRead from the beginning.
428 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
435 * Scan the user column names (or aliases) for a match. Complain if
438 * Note: because eref->colnames may include names of dropped columns, we
439 * need to check for non-droppedness before accepting a match. This
440 * takes an extra cache lookup, but we can skip the lookup most of the
441 * time by exploiting the knowledge that dropped columns are assigned
442 * dummy names starting with '.', which is an unusual choice for
443 * actual column names.
445 * Should the user try to fool us by altering pg_attribute.attname for a
446 * dropped column, we'll still catch it by virtue of the checks in
447 * get_rte_attribute_type(), which is called by make_var(). That
448 * routine has to do a cache lookup anyway, so the check there is
451 foreach(c, rte->eref->colnames)
454 if (strcmp(strVal(lfirst(c)), colname) == 0)
456 if (colname[0] == '.' && /* see note above */
457 get_rte_attribute_is_dropped(rte, attnum))
460 elog(ERROR, "Column reference \"%s\" is ambiguous", colname);
461 result = (Node *) make_var(pstate, rte, attnum);
462 rte->checkForRead = true;
467 * If we have a unique match, return it. Note that this allows a user
468 * alias to override a system column name (such as OID) without error.
474 * If the RTE represents a real table, consider system column names.
476 if (rte->rtekind == RTE_RELATION)
478 /* quick check to see if name could be a system column */
479 attnum = specialAttNum(colname);
480 if (attnum != InvalidAttrNumber)
482 /* now check to see if column actually is defined */
483 if (SearchSysCacheExists(ATTNUM,
484 ObjectIdGetDatum(rte->relid),
485 Int16GetDatum(attnum),
488 result = (Node *) make_var(pstate, rte, attnum);
489 rte->checkForRead = true;
499 * Search for an unqualified column name.
500 * If found, return the appropriate Var node (or expression).
501 * If not found, return NULL. If the name proves ambiguous, raise error.
504 colnameToVar(ParseState *pstate, char *colname)
507 ParseState *orig_pstate = pstate;
510 while (pstate != NULL)
515 * We need to look only at top-level namespace items, and even for
516 * those, ignore RTEs that are marked as not inFromCl and not the
517 * query's target relation.
519 foreach(ns, pstate->p_namespace)
521 Node *nsnode = (Node *) lfirst(ns);
522 Node *newresult = NULL;
524 if (IsA(nsnode, RangeTblRef))
526 int varno = ((RangeTblRef *) nsnode)->rtindex;
527 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
529 if (!rte->inFromCl &&
530 rte != pstate->p_target_rangetblentry)
533 /* use orig_pstate here to get the right sublevels_up */
534 newresult = scanRTEForColumn(orig_pstate, rte, colname);
536 else if (IsA(nsnode, JoinExpr))
538 int varno = ((JoinExpr *) nsnode)->rtindex;
539 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
541 /* joins are always inFromCl, so no need to check */
543 /* use orig_pstate here to get the right sublevels_up */
544 newresult = scanRTEForColumn(orig_pstate, rte, colname);
547 elog(ERROR, "colnameToVar: unexpected node type %d",
553 elog(ERROR, "Column reference \"%s\" is ambiguous",
562 pstate = pstate->parentParseState;
571 * Search for a qualified column name: either refname.colname or
572 * schemaname.relname.colname.
574 * If found, return the appropriate Var node.
575 * If not found, return NULL. If the name proves ambiguous, raise error.
578 qualifiedNameToVar(ParseState *pstate,
587 rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
593 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
596 return scanRTEForColumn(pstate, rte, colname);
600 * Add an entry for a relation to the pstate's range table (p_rtable).
602 * If pstate is NULL, we just build an RTE and return it without adding it
605 * Note: formerly this checked for refname conflicts, but that's wrong.
606 * Caller is responsible for checking for conflicts in the appropriate scope.
609 addRangeTableEntry(ParseState *pstate,
615 RangeTblEntry *rte = makeNode(RangeTblEntry);
616 char *refname = alias ? alias->aliasname : relation->relname;
624 rte->rtekind = RTE_RELATION;
628 * Get the rel's OID. This access also ensures that we have an
629 * up-to-date relcache entry for the rel. Since this is typically the
630 * first access to a rel in a statement, be careful to get the right
631 * access level depending on whether we're doing SELECT FOR UPDATE.
633 lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
634 rel = heap_openrv(relation, lockmode);
635 rte->relid = RelationGetRelid(rel);
637 eref = alias ? (Alias *) copyObject(alias) : makeAlias(refname, NIL);
638 numaliases = length(eref->colnames);
641 * Since the rel is open anyway, let's check that the number of column
642 * aliases is reasonable. - Thomas 2000-02-04
644 maxattrs = RelationGetNumberOfAttributes(rel);
645 if (maxattrs < numaliases)
646 elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
647 RelationGetRelationName(rel), maxattrs, numaliases);
649 /* fill in any unspecified alias columns using actual column names */
650 for (varattno = numaliases; varattno < maxattrs; varattno++)
654 attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
655 eref->colnames = lappend(eref->colnames, makeString(attrname));
660 * Drop the rel refcount, but keep the access lock till end of
661 * transaction so that the table can't be deleted or have its schema
662 * modified underneath us.
664 heap_close(rel, NoLock);
668 * - this RTE should be expanded to include descendant tables,
669 * - this RTE is in the FROM clause,
670 * - this RTE should be checked for read/write access rights.
672 * The initial default on access checks is always check-for-READ-access,
673 * which is the right thing for all except target tables.
677 rte->inFromCl = inFromCl;
678 rte->checkForRead = true;
679 rte->checkForWrite = false;
681 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
684 * Add completed RTE to pstate's range table list, but not to join
685 * list nor namespace --- caller must do that if appropriate.
688 pstate->p_rtable = lappend(pstate->p_rtable, rte);
694 * Add an entry for a relation to the pstate's range table (p_rtable).
696 * This is just like addRangeTableEntry() except that it makes an RTE
697 * given a relation OID instead of a RangeVar reference.
699 * Note that an alias clause *must* be supplied.
702 addRangeTableEntryForRelation(ParseState *pstate,
708 RangeTblEntry *rte = makeNode(RangeTblEntry);
709 char *refname = alias->aliasname;
717 rte->rtekind = RTE_RELATION;
721 * Get the rel's relcache entry. This access ensures that we have an
722 * up-to-date relcache entry for the rel. Since this is typically the
723 * first access to a rel in a statement, be careful to get the right
724 * access level depending on whether we're doing SELECT FOR UPDATE.
726 lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
727 rel = heap_open(relid, lockmode);
730 eref = (Alias *) copyObject(alias);
731 numaliases = length(eref->colnames);
734 * Since the rel is open anyway, let's check that the number of column
735 * aliases is reasonable. - Thomas 2000-02-04
737 maxattrs = RelationGetNumberOfAttributes(rel);
738 if (maxattrs < numaliases)
739 elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
740 RelationGetRelationName(rel), maxattrs, numaliases);
742 /* fill in any unspecified alias columns using actual column names */
743 for (varattno = numaliases; varattno < maxattrs; varattno++)
747 attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
748 eref->colnames = lappend(eref->colnames, makeString(attrname));
753 * Drop the rel refcount, but keep the access lock till end of
754 * transaction so that the table can't be deleted or have its schema
755 * modified underneath us.
757 heap_close(rel, NoLock);
761 * - this RTE should be expanded to include descendant tables,
762 * - this RTE is in the FROM clause,
763 * - this RTE should be checked for read/write access rights.
765 * The initial default on access checks is always check-for-READ-access,
766 * which is the right thing for all except target tables.
770 rte->inFromCl = inFromCl;
771 rte->checkForRead = true;
772 rte->checkForWrite = false;
774 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
777 * Add completed RTE to pstate's range table list, but not to join
778 * list nor namespace --- caller must do that if appropriate.
781 pstate->p_rtable = lappend(pstate->p_rtable, rte);
787 * Add an entry for a subquery to the pstate's range table (p_rtable).
789 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
790 * Note that an alias clause *must* be supplied.
793 addRangeTableEntryForSubquery(ParseState *pstate,
798 RangeTblEntry *rte = makeNode(RangeTblEntry);
799 char *refname = alias->aliasname;
805 rte->rtekind = RTE_SUBQUERY;
806 rte->relid = InvalidOid;
807 rte->subquery = subquery;
810 eref = copyObject(alias);
811 numaliases = length(eref->colnames);
813 /* fill in any unspecified alias columns */
815 foreach(tlistitem, subquery->targetList)
817 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
819 if (te->resdom->resjunk)
822 Assert(varattno == te->resdom->resno);
823 if (varattno > numaliases)
827 attrname = pstrdup(te->resdom->resname);
828 eref->colnames = lappend(eref->colnames, makeString(attrname));
831 if (varattno < numaliases)
832 elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
833 refname, varattno, numaliases);
839 * - this RTE should be expanded to include descendant tables,
840 * - this RTE is in the FROM clause,
841 * - this RTE should be checked for read/write access rights.
843 * Subqueries are never checked for access rights.
846 rte->inh = false; /* never true for subqueries */
847 rte->inFromCl = inFromCl;
848 rte->checkForRead = false;
849 rte->checkForWrite = false;
851 rte->checkAsUser = InvalidOid;
854 * Add completed RTE to pstate's range table list, but not to join
855 * list nor namespace --- caller must do that if appropriate.
858 pstate->p_rtable = lappend(pstate->p_rtable, rte);
864 * Add an entry for a function to the pstate's range table (p_rtable).
866 * This is just like addRangeTableEntry() except that it makes a function RTE.
869 addRangeTableEntryForFunction(ParseState *pstate,
872 RangeFunction *rangefunc,
875 RangeTblEntry *rte = makeNode(RangeTblEntry);
876 Oid funcrettype = exprType(funcexpr);
878 Alias *alias = rangefunc->alias;
879 List *coldeflist = rangefunc->coldeflist;
884 rte->rtekind = RTE_FUNCTION;
885 rte->relid = InvalidOid;
886 rte->subquery = NULL;
887 rte->funcexpr = funcexpr;
888 rte->coldeflist = coldeflist;
891 eref = alias ? (Alias *) copyObject(alias) : makeAlias(funcname, NIL);
894 numaliases = length(eref->colnames);
897 * Now determine if the function returns a simple or composite type,
898 * and check/add column aliases.
900 if (coldeflist != NIL)
903 * we *only* allow a coldeflist for functions returning a RECORD
906 if (funcrettype != RECORDOID)
907 elog(ERROR, "A column definition list is only allowed for functions returning RECORD");
912 * ... and a coldeflist is *required* for functions returning a
915 if (funcrettype == RECORDOID)
916 elog(ERROR, "A column definition list is required for functions returning RECORD");
919 functyptype = get_typtype(funcrettype);
921 if (functyptype == 'c')
924 * Named composite data type, i.e. a table's row type
926 Oid funcrelid = typeidTypeRelid(funcrettype);
930 if (!OidIsValid(funcrelid))
931 elog(ERROR, "Invalid typrelid for complex type %u",
935 * Get the rel's relcache entry. This access ensures that we have
936 * an up-to-date relcache entry for the rel.
938 rel = relation_open(funcrelid, AccessShareLock);
941 * Since the rel is open anyway, let's check that the number of
942 * column aliases is reasonable.
944 maxattrs = RelationGetNumberOfAttributes(rel);
945 if (maxattrs < numaliases)
946 elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
947 RelationGetRelationName(rel), maxattrs, numaliases);
949 /* fill in alias columns using actual column names */
950 for (varattno = numaliases; varattno < maxattrs; varattno++)
954 attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
955 eref->colnames = lappend(eref->colnames, makeString(attrname));
959 * Drop the rel refcount, but keep the access lock till end of
960 * transaction so that the table can't be deleted or have its
961 * schema modified underneath us.
963 relation_close(rel, NoLock);
965 else if (functyptype == 'b' || functyptype == 'd')
968 * Must be a base data type, i.e. scalar. Just add one alias
969 * column named for the function.
972 elog(ERROR, "Too many column aliases specified for function %s",
975 eref->colnames = makeList1(makeString(eref->aliasname));
977 else if (functyptype == 'p' && funcrettype == RECORDOID)
981 /* Use the column definition list to form the alias list */
982 eref->colnames = NIL;
983 foreach(col, coldeflist)
985 ColumnDef *n = lfirst(col);
988 attrname = pstrdup(n->colname);
989 eref->colnames = lappend(eref->colnames, makeString(attrname));
993 elog(ERROR, "Unknown kind of return type specified for function %s",
998 * - this RTE should be expanded to include descendant tables,
999 * - this RTE is in the FROM clause,
1000 * - this RTE should be checked for read/write access rights.
1003 rte->inh = false; /* never true for functions */
1004 rte->inFromCl = inFromCl;
1005 rte->checkForRead = true;
1006 rte->checkForWrite = false;
1008 rte->checkAsUser = InvalidOid;
1011 * Add completed RTE to pstate's range table list, but not to join
1012 * list nor namespace --- caller must do that if appropriate.
1015 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1021 * Add an entry for a join to the pstate's range table (p_rtable).
1023 * This is much like addRangeTableEntry() except that it makes a join RTE.
1026 addRangeTableEntryForJoin(ParseState *pstate,
1033 RangeTblEntry *rte = makeNode(RangeTblEntry);
1037 rte->rtekind = RTE_JOIN;
1038 rte->relid = InvalidOid;
1039 rte->subquery = NULL;
1040 rte->jointype = jointype;
1041 rte->joinaliasvars = aliasvars;
1044 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1045 numaliases = length(eref->colnames);
1047 /* fill in any unspecified alias columns */
1048 if (numaliases < length(colnames))
1050 while (numaliases-- > 0)
1051 colnames = lnext(colnames);
1052 eref->colnames = nconc(eref->colnames, colnames);
1059 * - this RTE should be expanded to include descendant tables,
1060 * - this RTE is in the FROM clause,
1061 * - this RTE should be checked for read/write access rights.
1063 * Joins are never checked for access rights.
1066 rte->inh = false; /* never true for joins */
1067 rte->inFromCl = inFromCl;
1068 rte->checkForRead = false;
1069 rte->checkForWrite = false;
1071 rte->checkAsUser = InvalidOid;
1074 * Add completed RTE to pstate's range table list, but not to join
1075 * list nor namespace --- caller must do that if appropriate.
1078 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1084 * Has the specified refname been selected FOR UPDATE?
1087 isForUpdate(ParseState *pstate, char *refname)
1089 /* Outer loop to check parent query levels as well as this one */
1090 while (pstate != NULL)
1092 if (pstate->p_forUpdate != NIL)
1094 if (lfirst(pstate->p_forUpdate) == NULL)
1096 /* all tables used in query */
1101 /* just the named tables */
1104 foreach(l, pstate->p_forUpdate)
1106 char *rname = strVal(lfirst(l));
1108 if (strcmp(refname, rname) == 0)
1113 pstate = pstate->parentParseState;
1119 * Add the given RTE as a top-level entry in the pstate's join list
1120 * and/or name space list. (We assume caller has checked for any
1121 * namespace conflict.)
1124 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1125 bool addToJoinList, bool addToNameSpace)
1127 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1128 RangeTblRef *rtr = makeNode(RangeTblRef);
1130 rtr->rtindex = rtindex;
1133 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1135 pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1139 * Add a POSTQUEL-style implicit RTE.
1141 * We assume caller has already checked that there is no RTE or join with
1142 * a conflicting name.
1145 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1149 rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1150 addRTEtoQuery(pstate, rte, true, true);
1151 warnAutoRange(pstate, relation);
1158 * Given a rangetable entry, create lists of its column names (aliases if
1159 * provided, else real names) and Vars for each column. Only user columns
1160 * are considered, since this is primarily used to expand '*' and determine
1161 * the contents of JOIN tables.
1163 * If only one of the two kinds of output list is needed, pass NULL for the
1164 * output pointer for the unwanted one.
1167 expandRTE(ParseState *pstate, RangeTblEntry *rte,
1168 List **colnames, List **colvars)
1179 /* Need the RT index of the entry for creating Vars */
1180 rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1182 switch (rte->rtekind)
1186 /* Ordinary relation RTE */
1191 rel = heap_open(rte->relid, AccessShareLock);
1192 maxattrs = RelationGetNumberOfAttributes(rel);
1193 numaliases = length(rte->eref->colnames);
1195 for (varattno = 0; varattno < maxattrs; varattno++)
1197 Form_pg_attribute attr = rel->rd_att->attrs[varattno];
1199 if (attr->attisdropped)
1206 if (varattno < numaliases)
1207 label = strVal(nth(varattno, rte->eref->colnames));
1209 label = NameStr(attr->attname);
1210 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1217 varnode = makeVar(rtindex, attr->attnum,
1218 attr->atttypid, attr->atttypmod,
1221 *colvars = lappend(*colvars, varnode);
1225 heap_close(rel, AccessShareLock);
1231 List *aliasp = rte->eref->colnames;
1235 foreach(tlistitem, rte->subquery->targetList)
1237 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1239 if (te->resdom->resjunk)
1242 Assert(varattno == te->resdom->resno);
1246 /* Assume there is one alias per target item */
1247 char *label = strVal(lfirst(aliasp));
1249 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1250 aliasp = lnext(aliasp);
1257 varnode = makeVar(rtindex, varattno,
1258 te->resdom->restype,
1259 te->resdom->restypmod,
1262 *colvars = lappend(*colvars, varnode);
1270 Oid funcrettype = exprType(rte->funcexpr);
1271 char functyptype = get_typtype(funcrettype);
1272 List *coldeflist = rte->coldeflist;
1274 if (functyptype == 'c')
1277 * Composite data type, i.e. a table's row type Same
1278 * as ordinary relation RTE
1280 Oid funcrelid = typeidTypeRelid(funcrettype);
1285 if (!OidIsValid(funcrelid))
1286 elog(ERROR, "Invalid typrelid for complex type %u",
1289 rel = relation_open(funcrelid, AccessShareLock);
1290 maxattrs = RelationGetNumberOfAttributes(rel);
1291 numaliases = length(rte->eref->colnames);
1293 for (varattno = 0; varattno < maxattrs; varattno++)
1295 Form_pg_attribute attr = rel->rd_att->attrs[varattno];
1297 if (attr->attisdropped)
1304 if (varattno < numaliases)
1305 label = strVal(nth(varattno, rte->eref->colnames));
1307 label = NameStr(attr->attname);
1308 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1315 varnode = makeVar(rtindex,
1321 *colvars = lappend(*colvars, varnode);
1325 relation_close(rel, AccessShareLock);
1327 else if (functyptype == 'b' || functyptype == 'd')
1330 * Must be a base data type, i.e. scalar
1333 *colnames = lappend(*colnames,
1334 lfirst(rte->eref->colnames));
1340 varnode = makeVar(rtindex, 1,
1344 *colvars = lappend(*colvars, varnode);
1347 else if (functyptype == 'p' && funcrettype == RECORDOID)
1352 foreach(col, coldeflist)
1354 ColumnDef *colDef = lfirst(col);
1361 attrname = pstrdup(colDef->colname);
1362 *colnames = lappend(*colnames, makeString(attrname));
1370 atttypid = typenameTypeId(colDef->typename);
1372 varnode = makeVar(rtindex,
1378 *colvars = lappend(*colvars, varnode);
1383 elog(ERROR, "Unknown kind of return type specified for function");
1389 List *aliasp = rte->eref->colnames;
1390 List *aliasvars = rte->joinaliasvars;
1400 char *label = strVal(lfirst(aliasp));
1402 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1407 Node *aliasvar = (Node *) lfirst(aliasvars);
1410 varnode = makeVar(rtindex, varattno,
1412 exprTypmod(aliasvar),
1415 *colvars = lappend(*colvars, varnode);
1418 aliasp = lnext(aliasp);
1419 aliasvars = lnext(aliasvars);
1421 Assert(aliasvars == NIL);
1425 elog(ERROR, "expandRTE: unsupported RTE kind %d",
1426 (int) rte->rtekind);
1432 * Workhorse for "*" expansion: produce a list of targetentries
1433 * for the attributes of the rte
1436 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte)
1440 List *te_list = NIL;
1442 expandRTE(pstate, rte, &names, &vars);
1446 char *label = strVal(lfirst(names));
1447 Node *varnode = (Node *) lfirst(vars);
1448 TargetEntry *te = makeNode(TargetEntry);
1450 te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1452 exprTypmod(varnode),
1455 te->expr = (Expr *) varnode;
1456 te_list = lappend(te_list, te);
1458 names = lnext(names);
1462 Assert(vars == NIL); /* lists not same length? */
1468 * get_rte_attribute_name
1469 * Get an attribute name from a RangeTblEntry
1471 * This is unlike get_attname() because we use aliases if available.
1472 * In particular, it will work on an RTE for a subselect or join, whereas
1473 * get_attname() only works on real relations.
1475 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1476 * occurs when a Var represents a whole tuple of a relation.
1479 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1483 if (attnum == InvalidAttrNumber)
1487 * If there is a user-written column alias, use it.
1490 attnum > 0 && attnum <= length(rte->alias->colnames))
1491 return strVal(nth(attnum - 1, rte->alias->colnames));
1494 * If the RTE is a relation, go to the system catalogs not the
1495 * eref->colnames list. This is a little slower but it will give the
1496 * right answer if the column has been renamed since the eref list was
1497 * built (which can easily happen for rules).
1499 if (rte->rtekind == RTE_RELATION)
1501 attname = get_attname(rte->relid, attnum);
1502 if (attname == NULL)
1503 elog(ERROR, "cache lookup of attribute %d in relation %u failed",
1504 attnum, rte->relid);
1509 * Otherwise use the column name from eref. There should always be
1512 if (attnum > 0 && attnum <= length(rte->eref->colnames))
1513 return strVal(nth(attnum - 1, rte->eref->colnames));
1515 elog(ERROR, "Invalid attnum %d for rangetable entry %s",
1516 attnum, rte->eref->aliasname);
1517 return NULL; /* keep compiler quiet */
1521 * get_rte_attribute_type
1522 * Get attribute type information from a RangeTblEntry
1525 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1526 Oid *vartype, int32 *vartypmod)
1528 switch (rte->rtekind)
1532 /* Plain relation RTE --- get the attribute's type info */
1534 Form_pg_attribute att_tup;
1536 tp = SearchSysCache(ATTNUM,
1537 ObjectIdGetDatum(rte->relid),
1538 Int16GetDatum(attnum),
1540 /* this shouldn't happen... */
1541 if (!HeapTupleIsValid(tp))
1542 elog(ERROR, "Relation \"%s\" does not have attribute %d",
1543 get_rel_name(rte->relid), attnum);
1544 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1547 * If dropped column, pretend it ain't there. See notes
1548 * in scanRTEForColumn.
1550 if (att_tup->attisdropped)
1551 elog(ERROR, "Relation \"%s\" has no column \"%s\"",
1552 get_rel_name(rte->relid), NameStr(att_tup->attname));
1553 *vartype = att_tup->atttypid;
1554 *vartypmod = att_tup->atttypmod;
1555 ReleaseSysCache(tp);
1560 /* Subselect RTE --- get type info from subselect's tlist */
1563 foreach(tlistitem, rte->subquery->targetList)
1565 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1567 if (te->resdom->resjunk || te->resdom->resno != attnum)
1569 *vartype = te->resdom->restype;
1570 *vartypmod = te->resdom->restypmod;
1573 /* falling off end of list shouldn't happen... */
1574 elog(ERROR, "Subquery %s does not have attribute %d",
1575 rte->eref->aliasname, attnum);
1581 Oid funcrettype = exprType(rte->funcexpr);
1582 char functyptype = get_typtype(funcrettype);
1583 List *coldeflist = rte->coldeflist;
1585 if (functyptype == 'c')
1588 * Composite data type, i.e. a table's row type Same
1589 * as ordinary relation RTE
1591 Oid funcrelid = typeidTypeRelid(funcrettype);
1593 Form_pg_attribute att_tup;
1595 if (!OidIsValid(funcrelid))
1596 elog(ERROR, "Invalid typrelid for complex type %u",
1599 tp = SearchSysCache(ATTNUM,
1600 ObjectIdGetDatum(funcrelid),
1601 Int16GetDatum(attnum),
1603 /* this shouldn't happen... */
1604 if (!HeapTupleIsValid(tp))
1605 elog(ERROR, "Relation \"%s\" does not have attribute %d",
1606 get_rel_name(funcrelid), attnum);
1607 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1610 * If dropped column, pretend it ain't there. See
1611 * notes in scanRTEForColumn.
1613 if (att_tup->attisdropped)
1614 elog(ERROR, "Relation \"%s\" has no column \"%s\"",
1615 get_rel_name(funcrelid),
1616 NameStr(att_tup->attname));
1617 *vartype = att_tup->atttypid;
1618 *vartypmod = att_tup->atttypmod;
1619 ReleaseSysCache(tp);
1621 else if (functyptype == 'b' || functyptype == 'd')
1624 * Must be a base data type, i.e. scalar
1626 *vartype = funcrettype;
1629 else if (functyptype == 'p' && funcrettype == RECORDOID)
1631 ColumnDef *colDef = nth(attnum - 1, coldeflist);
1633 *vartype = typenameTypeId(colDef->typename);
1637 elog(ERROR, "Unknown kind of return type specified for function");
1643 * Join RTE --- get type info from join RTE's alias
1648 Assert(attnum > 0 && attnum <= length(rte->joinaliasvars));
1649 aliasvar = (Node *) nth(attnum - 1, rte->joinaliasvars);
1650 *vartype = exprType(aliasvar);
1651 *vartypmod = exprTypmod(aliasvar);
1655 elog(ERROR, "get_rte_attribute_type: unsupported RTE kind %d",
1656 (int) rte->rtekind);
1661 * get_rte_attribute_is_dropped
1662 * Check whether attempted attribute ref is to a dropped column
1665 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
1669 switch (rte->rtekind)
1673 /* Plain relation RTE --- get the attribute's type info */
1675 Form_pg_attribute att_tup;
1677 tp = SearchSysCache(ATTNUM,
1678 ObjectIdGetDatum(rte->relid),
1679 Int16GetDatum(attnum),
1681 /* this shouldn't happen... */
1682 if (!HeapTupleIsValid(tp))
1683 elog(ERROR, "Relation \"%s\" does not have attribute %d",
1684 get_rel_name(rte->relid), attnum);
1685 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1686 result = att_tup->attisdropped;
1687 ReleaseSysCache(tp);
1692 /* Subselect and join RTEs never have dropped columns */
1698 Oid funcrettype = exprType(rte->funcexpr);
1699 Oid funcrelid = typeidTypeRelid(funcrettype);
1701 if (OidIsValid(funcrelid))
1704 * Composite data type, i.e. a table's row type Same
1705 * as ordinary relation RTE
1708 Form_pg_attribute att_tup;
1710 tp = SearchSysCache(ATTNUM,
1711 ObjectIdGetDatum(funcrelid),
1712 Int16GetDatum(attnum),
1714 /* this shouldn't happen... */
1715 if (!HeapTupleIsValid(tp))
1716 elog(ERROR, "Relation %s does not have attribute %d",
1717 get_rel_name(funcrelid), attnum);
1718 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1719 result = att_tup->attisdropped;
1720 ReleaseSysCache(tp);
1725 * Must be a base data type, i.e. scalar
1732 elog(ERROR, "get_rte_attribute_is_dropped: unsupported RTE kind %d",
1733 (int) rte->rtekind);
1734 result = false; /* keep compiler quiet */
1741 * given relation and att name, return id of variable
1743 * This should only be used if the relation is already
1744 * heap_open()'ed. Use the cache version get_attnum()
1745 * for access to non-opened relations.
1748 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1752 for (i = 0; i < rd->rd_rel->relnatts; i++)
1754 Form_pg_attribute att = rd->rd_att->attrs[i];
1756 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1762 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1764 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1770 elog(ERROR, "Relation \"%s\" has no column \"%s\"",
1771 RelationGetRelationName(rd), attname);
1772 return InvalidAttrNumber; /* lint */
1777 * Check attribute name to see if it is "special", e.g. "oid".
1778 * - thomas 2000-02-07
1780 * Note: this only discovers whether the name could be a system attribute.
1781 * Caller needs to verify that it really is an attribute of the rel,
1782 * at least in the case of "oid", which is now optional.
1785 specialAttNum(const char *attname)
1787 Form_pg_attribute sysatt;
1789 sysatt = SystemAttributeByName(attname,
1790 true /* "oid" will be accepted */ );
1792 return sysatt->attnum;
1793 return InvalidAttrNumber;
1798 * given attribute id, return name of that attribute
1800 * This should only be used if the relation is already
1801 * heap_open()'ed. Use the cache version get_atttype()
1802 * for access to non-opened relations.
1805 attnumAttName(Relation rd, int attid)
1809 Form_pg_attribute sysatt;
1811 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1812 return &sysatt->attname;
1814 if (attid > rd->rd_att->natts)
1815 elog(ERROR, "attnumAttName: invalid attribute number %d", attid);
1816 return &rd->rd_att->attrs[attid - 1]->attname;
1820 * given attribute id, return type of that attribute
1822 * This should only be used if the relation is already
1823 * heap_open()'ed. Use the cache version get_atttype()
1824 * for access to non-opened relations.
1827 attnumTypeId(Relation rd, int attid)
1831 Form_pg_attribute sysatt;
1833 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1834 return sysatt->atttypid;
1836 if (attid > rd->rd_att->natts)
1837 elog(ERROR, "attnumTypeId: invalid attribute number %d", attid);
1838 return rd->rd_att->attrs[attid - 1]->atttypid;
1842 * Generate a warning about an implicit RTE, if appropriate.
1844 * Our current theory on this is that we should allow "SELECT foo.*"
1845 * but warn about a mixture of explicit and implicit RTEs.
1848 warnAutoRange(ParseState *pstate, RangeVar *relation)
1850 bool foundInFromCl = false;
1853 foreach(temp, pstate->p_rtable)
1855 RangeTblEntry *rte = lfirst(temp);
1859 foundInFromCl = true;
1864 elog(NOTICE, "Adding missing FROM-clause entry%s for table \"%s\"",
1865 pstate->parentParseState != NULL ? " in subquery" : "",