1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2005, 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.103 2005/03/31 22:46:13 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "catalog/heap.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_type.h"
24 #include "nodes/makefuncs.h"
25 #include "parser/parsetree.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
35 bool add_missing_from;
37 static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
39 static Node *scanNameSpaceForRelid(ParseState *pstate, Node *nsnode,
41 static void scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
42 RangeTblEntry *rte1, const char *aliasname1);
43 static bool isForUpdate(ParseState *pstate, char *refname);
44 static void expandRelation(Oid relid, Alias *eref,
45 int rtindex, int sublevels_up,
47 List **colnames, List **colvars);
48 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
49 int rtindex, int sublevels_up,
51 List **colnames, List **colvars);
52 static int specialAttNum(const char *attname);
53 static void warnAutoRange(ParseState *pstate, RangeVar *relation);
57 * refnameRangeTblEntry
58 * Given a possibly-qualified refname, look to see if it matches any RTE.
59 * If so, return a pointer to the RangeTblEntry; else return NULL.
61 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
62 * If sublevels_up is NULL, only consider items at the current nesting
65 * An unqualified refname (schemaname == NULL) can match any RTE with matching
66 * alias, or matching unqualified relname in the case of alias-less relation
67 * RTEs. It is possible that such a refname matches multiple RTEs in the
68 * nearest nesting level that has a match; if so, we report an error via
71 * A qualified refname (schemaname != NULL) can only match a relation RTE
72 * that (a) has no alias and (b) is for the same relation identified by
73 * schemaname.refname. In this case we convert schemaname.refname to a
74 * relation OID and search by relid, rather than by alias name. This is
75 * peculiar, but it's what SQL92 says to do.
78 refnameRangeTblEntry(ParseState *pstate,
79 const char *schemaname,
83 Oid relId = InvalidOid;
88 if (schemaname != NULL)
92 namespaceId = LookupExplicitNamespace(schemaname);
93 relId = get_relname_relid(refname, namespaceId);
94 if (!OidIsValid(relId))
98 while (pstate != NULL)
102 if (OidIsValid(relId))
103 nsnode = scanNameSpaceForRelid(pstate,
104 (Node *) pstate->p_namespace,
107 nsnode = scanNameSpaceForRefname(pstate,
108 (Node *) pstate->p_namespace,
113 /* should get an RTE or JoinExpr */
114 if (IsA(nsnode, RangeTblEntry))
115 return (RangeTblEntry *) nsnode;
116 Assert(IsA(nsnode, JoinExpr));
117 return rt_fetch(((JoinExpr *) nsnode)->rtindex, pstate->p_rtable);
120 pstate = pstate->parentParseState;
130 * Recursively search a namespace for an RTE or joinexpr matching the
131 * given unqualified refname. Return the node if a unique match, or NULL
132 * if no match. Raise error if multiple matches.
134 * The top level of p_namespace is a list, and we recurse into any joins
135 * that are not subqueries.
138 scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
146 if (IsA(nsnode, RangeTblRef))
148 int varno = ((RangeTblRef *) nsnode)->rtindex;
149 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
151 if (strcmp(rte->eref->aliasname, refname) == 0)
152 result = (Node *) rte;
154 else if (IsA(nsnode, JoinExpr))
156 JoinExpr *j = (JoinExpr *) nsnode;
160 if (strcmp(j->alias->aliasname, refname) == 0)
161 return (Node *) j; /* matched a join alias */
164 * Tables within an aliased join are invisible from outside
165 * the join, according to the scope rules of SQL92 (the join
166 * is considered a subquery). So, stop here.
170 result = scanNameSpaceForRefname(pstate, j->larg, refname);
171 newresult = scanNameSpaceForRefname(pstate, j->rarg, refname);
176 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
177 errmsg("table reference \"%s\" is ambiguous",
180 else if (IsA(nsnode, List))
184 foreach(l, (List *) nsnode)
186 newresult = scanNameSpaceForRefname(pstate, lfirst(l), refname);
191 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
192 errmsg("table reference \"%s\" is ambiguous",
197 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
202 * Recursively search a namespace for a relation RTE matching the
203 * given relation OID. Return the node if a unique match, or NULL
204 * if no match. Raise error if multiple matches (which shouldn't
205 * happen if the namespace was checked correctly when it was created).
207 * The top level of p_namespace is a list, and we recurse into any joins
208 * that are not subqueries.
210 * See the comments for refnameRangeTblEntry to understand why this
211 * acts the way it does.
214 scanNameSpaceForRelid(ParseState *pstate, Node *nsnode, Oid relid)
221 if (IsA(nsnode, RangeTblRef))
223 int varno = ((RangeTblRef *) nsnode)->rtindex;
224 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
226 /* yes, the test for alias==NULL should be there... */
227 if (rte->rtekind == RTE_RELATION &&
228 rte->relid == relid &&
230 result = (Node *) rte;
232 else if (IsA(nsnode, JoinExpr))
234 JoinExpr *j = (JoinExpr *) nsnode;
239 * Tables within an aliased join are invisible from outside
240 * the join, according to the scope rules of SQL92 (the join
241 * is considered a subquery). So, stop here.
245 result = scanNameSpaceForRelid(pstate, j->larg, relid);
246 newresult = scanNameSpaceForRelid(pstate, j->rarg, relid);
251 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
252 errmsg("table reference %u is ambiguous",
255 else if (IsA(nsnode, List))
259 foreach(l, (List *) nsnode)
261 newresult = scanNameSpaceForRelid(pstate, lfirst(l), relid);
266 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
267 errmsg("table reference %u is ambiguous",
272 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
277 * Recursively check for name conflicts between two namespaces or
278 * namespace subtrees. Raise an error if any is found.
280 * Works by recursively scanning namespace1 for RTEs and join nodes,
281 * and for each one recursively scanning namespace2 for a match.
283 * Note: we assume that each given argument does not contain conflicts
284 * itself; we just want to know if the two can be merged together.
286 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
287 * they have the same eref->aliasname (ie, same relation name), if they
288 * are for different relation OIDs (implying they are in different schemas).
291 checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
294 if (namespace1 == NULL)
296 if (IsA(namespace1, RangeTblRef))
298 int varno = ((RangeTblRef *) namespace1)->rtindex;
299 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
301 if (rte->rtekind == RTE_RELATION && rte->alias == NULL)
302 scanNameSpaceForConflict(pstate, namespace2,
303 rte, rte->eref->aliasname);
305 scanNameSpaceForConflict(pstate, namespace2,
306 NULL, rte->eref->aliasname);
308 else if (IsA(namespace1, JoinExpr))
310 JoinExpr *j = (JoinExpr *) namespace1;
314 scanNameSpaceForConflict(pstate, namespace2,
315 NULL, j->alias->aliasname);
318 * Tables within an aliased join are invisible from outside
319 * the join, according to the scope rules of SQL92 (the join
320 * is considered a subquery). So, stop here.
324 checkNameSpaceConflicts(pstate, j->larg, namespace2);
325 checkNameSpaceConflicts(pstate, j->rarg, namespace2);
327 else if (IsA(namespace1, List))
331 foreach(l, (List *) namespace1)
332 checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
335 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(namespace1));
339 * Subroutine for checkNameSpaceConflicts: scan namespace2
342 scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
343 RangeTblEntry *rte1, const char *aliasname1)
347 if (IsA(nsnode, RangeTblRef))
349 int varno = ((RangeTblRef *) nsnode)->rtindex;
350 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
352 if (strcmp(rte->eref->aliasname, aliasname1) != 0)
353 return; /* definitely no conflict */
354 if (rte->rtekind == RTE_RELATION && rte->alias == NULL &&
355 rte1 != NULL && rte->relid != rte1->relid)
356 return; /* no conflict per SQL92 rule */
358 (errcode(ERRCODE_DUPLICATE_ALIAS),
359 errmsg("table name \"%s\" specified more than once",
362 else if (IsA(nsnode, JoinExpr))
364 JoinExpr *j = (JoinExpr *) nsnode;
368 if (strcmp(j->alias->aliasname, aliasname1) == 0)
370 (errcode(ERRCODE_DUPLICATE_ALIAS),
371 errmsg("table name \"%s\" specified more than once",
375 * Tables within an aliased join are invisible from outside
376 * the join, according to the scope rules of SQL92 (the join
377 * is considered a subquery). So, stop here.
381 scanNameSpaceForConflict(pstate, j->larg, rte1, aliasname1);
382 scanNameSpaceForConflict(pstate, j->rarg, rte1, aliasname1);
384 else if (IsA(nsnode, List))
388 foreach(l, (List *) nsnode)
389 scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1);
392 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
396 * given an RTE, return RT index (starting with 1) of the entry,
397 * and optionally get its nesting depth (0 = current). If sublevels_up
398 * is NULL, only consider rels at the current nesting level.
399 * Raises error if RTE not found.
402 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
410 while (pstate != NULL)
413 foreach(l, pstate->p_rtable)
415 if (rte == (RangeTblEntry *) lfirst(l))
419 pstate = pstate->parentParseState;
426 elog(ERROR, "RTE not found (internal error)");
427 return 0; /* keep compiler quiet */
431 * Given an RT index and nesting depth, find the corresponding RTE.
432 * This is the inverse of RTERangeTablePosn.
435 GetRTEByRangeTablePosn(ParseState *pstate,
439 while (sublevels_up-- > 0)
441 pstate = pstate->parentParseState;
442 Assert(pstate != NULL);
444 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
445 return rt_fetch(varno, pstate->p_rtable);
449 * GetLevelNRangeTable
450 * Get the rangetable list for the N'th query level up from current.
453 GetLevelNRangeTable(ParseState *pstate, int sublevels_up)
457 while (pstate != NULL)
459 if (index == sublevels_up)
460 return pstate->p_rtable;
462 pstate = pstate->parentParseState;
465 elog(ERROR, "rangetable not found (internal error)");
466 return NIL; /* keep compiler quiet */
471 * Search the column names of a single RTE for the given name.
472 * If found, return an appropriate Var node, else return NULL.
473 * If the name proves ambiguous within this RTE, raise error.
475 * Side effect: if we find a match, mark the RTE as requiring read access.
476 * See comments in setTargetTable().
478 * NOTE: if the RTE is for a join, marking it as requiring read access does
479 * nothing. It might seem that we need to propagate the mark to all the
480 * contained RTEs, but that is not necessary. This is so because a join
481 * expression can only appear in a FROM clause, and any table named in
482 * FROM will be marked as requiring read access from the beginning.
485 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
492 * Scan the user column names (or aliases) for a match. Complain if
495 * Note: eref->colnames may include entries for dropped columns, but
496 * those will be empty strings that cannot match any legal SQL
497 * identifier, so we don't bother to test for that case here.
499 * Should this somehow go wrong and we try to access a dropped column,
500 * we'll still catch it by virtue of the checks in
501 * get_rte_attribute_type(), which is called by make_var(). That
502 * routine has to do a cache lookup anyway, so the check there is
505 foreach(c, rte->eref->colnames)
508 if (strcmp(strVal(lfirst(c)), colname) == 0)
512 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
513 errmsg("column reference \"%s\" is ambiguous",
515 result = (Node *) make_var(pstate, rte, attnum);
516 /* Require read access */
517 rte->requiredPerms |= ACL_SELECT;
522 * If we have a unique match, return it. Note that this allows a user
523 * alias to override a system column name (such as OID) without error.
529 * If the RTE represents a real table, consider system column names.
531 if (rte->rtekind == RTE_RELATION)
533 /* quick check to see if name could be a system column */
534 attnum = specialAttNum(colname);
535 if (attnum != InvalidAttrNumber)
537 /* now check to see if column actually is defined */
538 if (SearchSysCacheExists(ATTNUM,
539 ObjectIdGetDatum(rte->relid),
540 Int16GetDatum(attnum),
543 result = (Node *) make_var(pstate, rte, attnum);
544 /* Require read access */
545 rte->requiredPerms |= ACL_SELECT;
555 * Search for an unqualified column name.
556 * If found, return the appropriate Var node (or expression).
557 * If not found, return NULL. If the name proves ambiguous, raise error.
558 * If localonly is true, only names in the innermost query are considered.
561 colNameToVar(ParseState *pstate, char *colname, bool localonly)
564 ParseState *orig_pstate = pstate;
567 while (pstate != NULL)
572 * We need to look only at top-level namespace items, and even for
573 * those, ignore RTEs that are marked as not inFromCl and not the
574 * query's target relation.
576 foreach(ns, pstate->p_namespace)
578 Node *nsnode = (Node *) lfirst(ns);
579 Node *newresult = NULL;
581 if (IsA(nsnode, RangeTblRef))
583 int varno = ((RangeTblRef *) nsnode)->rtindex;
584 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
586 if (!rte->inFromCl &&
587 rte != pstate->p_target_rangetblentry)
590 /* use orig_pstate here to get the right sublevels_up */
591 newresult = scanRTEForColumn(orig_pstate, rte, colname);
593 else if (IsA(nsnode, JoinExpr))
595 int varno = ((JoinExpr *) nsnode)->rtindex;
596 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
598 /* joins are always inFromCl, so no need to check */
600 /* use orig_pstate here to get the right sublevels_up */
601 newresult = scanRTEForColumn(orig_pstate, rte, colname);
604 elog(ERROR, "unrecognized node type: %d",
605 (int) nodeTag(nsnode));
611 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
612 errmsg("column reference \"%s\" is ambiguous",
618 if (result != NULL || localonly)
619 break; /* found, or don't want to look at parent */
621 pstate = pstate->parentParseState;
630 * Search for a qualified column name: either refname.colname or
631 * schemaname.relname.colname.
633 * If found, return the appropriate Var node.
634 * If not found, return NULL. If the name proves ambiguous, raise error.
637 qualifiedNameToVar(ParseState *pstate,
646 rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
652 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
655 return scanRTEForColumn(pstate, rte, colname);
659 * buildRelationAliases
660 * Construct the eref column name list for a relation RTE.
661 * This code is also used for the case of a function RTE returning
662 * a named composite type.
664 * tupdesc: the physical column information
665 * alias: the user-supplied alias, or NULL if none
666 * eref: the eref Alias to store column names in
668 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
669 * empty strings for any dropped columns, so that it will be one-to-one with
670 * physical column numbers.
673 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
675 int maxattrs = tupdesc->natts;
681 Assert(eref->colnames == NIL);
685 aliaslc = list_head(alias->colnames);
686 numaliases = list_length(alias->colnames);
687 /* We'll rebuild the alias colname list */
688 alias->colnames = NIL;
696 for (varattno = 0; varattno < maxattrs; varattno++)
698 Form_pg_attribute attr = tupdesc->attrs[varattno];
701 if (attr->attisdropped)
703 /* Always insert an empty string for a dropped column */
704 attrname = makeString(pstrdup(""));
706 alias->colnames = lappend(alias->colnames, attrname);
711 /* Use the next user-supplied alias */
712 attrname = (Value *) lfirst(aliaslc);
713 aliaslc = lnext(aliaslc);
714 alias->colnames = lappend(alias->colnames, attrname);
718 attrname = makeString(pstrdup(NameStr(attr->attname)));
719 /* we're done with the alias if any */
722 eref->colnames = lappend(eref->colnames, attrname);
725 /* Too many user-supplied aliases? */
728 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
729 errmsg("table \"%s\" has %d columns available but %d columns specified",
730 eref->aliasname, maxattrs - numdropped, numaliases)));
734 * Add an entry for a relation to the pstate's range table (p_rtable).
736 * If pstate is NULL, we just build an RTE and return it without adding it
739 * Note: formerly this checked for refname conflicts, but that's wrong.
740 * Caller is responsible for checking for conflicts in the appropriate scope.
743 addRangeTableEntry(ParseState *pstate,
749 RangeTblEntry *rte = makeNode(RangeTblEntry);
750 char *refname = alias ? alias->aliasname : relation->relname;
754 rte->rtekind = RTE_RELATION;
758 * Get the rel's OID. This access also ensures that we have an
759 * up-to-date relcache entry for the rel. Since this is typically the
760 * first access to a rel in a statement, be careful to get the right
761 * access level depending on whether we're doing SELECT FOR UPDATE.
763 lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
764 rel = heap_openrv(relation, lockmode);
765 rte->relid = RelationGetRelid(rel);
768 * Build the list of effective column names using user-supplied
769 * aliases and/or actual column names.
771 rte->eref = makeAlias(refname, NIL);
772 buildRelationAliases(rel->rd_att, alias, rte->eref);
775 * Drop the rel refcount, but keep the access lock till end of
776 * transaction so that the table can't be deleted or have its schema
777 * modified underneath us.
779 heap_close(rel, NoLock);
783 * - this RTE should be expanded to include descendant tables,
784 * - this RTE is in the FROM clause,
785 * - this RTE should be checked for appropriate access rights.
787 * The initial default on access checks is always check-for-READ-access,
788 * which is the right thing for all except target tables.
792 rte->inFromCl = inFromCl;
794 rte->requiredPerms = ACL_SELECT;
795 rte->checkAsUser = 0; /* not set-uid by default, either */
798 * Add completed RTE to pstate's range table list, but not to join
799 * list nor namespace --- caller must do that if appropriate.
802 pstate->p_rtable = lappend(pstate->p_rtable, rte);
808 * Add an entry for a relation to the pstate's range table (p_rtable).
810 * This is just like addRangeTableEntry() except that it makes an RTE
811 * given a relation OID instead of a RangeVar reference.
813 * Note that an alias clause *must* be supplied.
816 addRangeTableEntryForRelation(ParseState *pstate,
822 RangeTblEntry *rte = makeNode(RangeTblEntry);
823 char *refname = alias->aliasname;
827 rte->rtekind = RTE_RELATION;
831 * Get the rel's relcache entry. This access ensures that we have an
832 * up-to-date relcache entry for the rel. Since this is typically the
833 * first access to a rel in a statement, be careful to get the right
834 * access level depending on whether we're doing SELECT FOR UPDATE.
836 lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
837 rel = heap_open(relid, lockmode);
841 * Build the list of effective column names using user-supplied
842 * aliases and/or actual column names.
844 rte->eref = makeAlias(refname, NIL);
845 buildRelationAliases(rel->rd_att, alias, rte->eref);
848 * Drop the rel refcount, but keep the access lock till end of
849 * transaction so that the table can't be deleted or have its schema
850 * modified underneath us.
852 heap_close(rel, NoLock);
856 * - this RTE should be expanded to include descendant tables,
857 * - this RTE is in the FROM clause,
858 * - this RTE should be checked for appropriate access rights.
860 * The initial default on access checks is always check-for-READ-access,
861 * which is the right thing for all except target tables.
865 rte->inFromCl = inFromCl;
867 rte->requiredPerms = ACL_SELECT;
868 rte->checkAsUser = 0; /* not set-uid by default, either */
871 * Add completed RTE to pstate's range table list, but not to join
872 * list nor namespace --- caller must do that if appropriate.
875 pstate->p_rtable = lappend(pstate->p_rtable, rte);
881 * Add an entry for a subquery to the pstate's range table (p_rtable).
883 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
884 * Note that an alias clause *must* be supplied.
887 addRangeTableEntryForSubquery(ParseState *pstate,
892 RangeTblEntry *rte = makeNode(RangeTblEntry);
893 char *refname = alias->aliasname;
899 rte->rtekind = RTE_SUBQUERY;
900 rte->relid = InvalidOid;
901 rte->subquery = subquery;
904 eref = copyObject(alias);
905 numaliases = list_length(eref->colnames);
907 /* fill in any unspecified alias columns */
909 foreach(tlistitem, subquery->targetList)
911 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
913 if (te->resdom->resjunk)
916 Assert(varattno == te->resdom->resno);
917 if (varattno > numaliases)
921 attrname = pstrdup(te->resdom->resname);
922 eref->colnames = lappend(eref->colnames, makeString(attrname));
925 if (varattno < numaliases)
927 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
928 errmsg("table \"%s\" has %d columns available but %d columns specified",
929 refname, varattno, numaliases)));
935 * - this RTE should be expanded to include descendant tables,
936 * - this RTE is in the FROM clause,
937 * - this RTE should be checked for appropriate access rights.
939 * Subqueries are never checked for access rights.
942 rte->inh = false; /* never true for subqueries */
943 rte->inFromCl = inFromCl;
945 rte->requiredPerms = 0;
946 rte->checkAsUser = 0;
949 * Add completed RTE to pstate's range table list, but not to join
950 * list nor namespace --- caller must do that if appropriate.
953 pstate->p_rtable = lappend(pstate->p_rtable, rte);
959 * Add an entry for a function to the pstate's range table (p_rtable).
961 * This is just like addRangeTableEntry() except that it makes a function RTE.
964 addRangeTableEntryForFunction(ParseState *pstate,
967 RangeFunction *rangefunc,
970 RangeTblEntry *rte = makeNode(RangeTblEntry);
971 TypeFuncClass functypclass;
974 Alias *alias = rangefunc->alias;
975 List *coldeflist = rangefunc->coldeflist;
978 rte->rtekind = RTE_FUNCTION;
979 rte->relid = InvalidOid;
980 rte->subquery = NULL;
981 rte->funcexpr = funcexpr;
982 rte->coldeflist = coldeflist;
985 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
989 * Now determine if the function returns a simple or composite type.
991 functypclass = get_expr_result_type(funcexpr,
996 * A coldeflist is required if the function returns RECORD and hasn't
997 * got a predetermined record type, and is prohibited otherwise.
999 if (coldeflist != NIL)
1001 if (functypclass != TYPEFUNC_RECORD)
1003 (errcode(ERRCODE_SYNTAX_ERROR),
1004 errmsg("a column definition list is only allowed for functions returning \"record\"")));
1008 if (functypclass == TYPEFUNC_RECORD)
1010 (errcode(ERRCODE_SYNTAX_ERROR),
1011 errmsg("a column definition list is required for functions returning \"record\"")));
1014 if (functypclass == TYPEFUNC_COMPOSITE)
1016 /* Composite data type, e.g. a table's row type */
1018 /* Build the column alias list */
1019 buildRelationAliases(tupdesc, alias, eref);
1021 else if (functypclass == TYPEFUNC_SCALAR)
1023 /* Base data type, i.e. scalar */
1024 /* Just add one alias column named for the function. */
1025 if (alias && alias->colnames != NIL)
1027 if (list_length(alias->colnames) != 1)
1029 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1030 errmsg("too many column aliases specified for function %s",
1032 eref->colnames = copyObject(alias->colnames);
1035 eref->colnames = list_make1(makeString(eref->aliasname));
1037 else if (functypclass == TYPEFUNC_RECORD)
1041 /* Use the column definition list to form the alias list */
1042 foreach(col, coldeflist)
1044 ColumnDef *n = lfirst(col);
1047 attrname = pstrdup(n->colname);
1048 eref->colnames = lappend(eref->colnames, makeString(attrname));
1053 (errcode(ERRCODE_DATATYPE_MISMATCH),
1054 errmsg("function \"%s\" in FROM has unsupported return type %s",
1055 funcname, format_type_be(funcrettype))));
1059 * - this RTE should be expanded to include descendant tables,
1060 * - this RTE is in the FROM clause,
1061 * - this RTE should be checked for appropriate access rights.
1063 * Functions are never checked for access rights (at least, not by
1064 * the RTE permissions mechanism).
1067 rte->inh = false; /* never true for functions */
1068 rte->inFromCl = inFromCl;
1070 rte->requiredPerms = 0;
1071 rte->checkAsUser = 0;
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 * Add an entry for a join to the pstate's range table (p_rtable).
1086 * This is much like addRangeTableEntry() except that it makes a join RTE.
1089 addRangeTableEntryForJoin(ParseState *pstate,
1096 RangeTblEntry *rte = makeNode(RangeTblEntry);
1100 rte->rtekind = RTE_JOIN;
1101 rte->relid = InvalidOid;
1102 rte->subquery = NULL;
1103 rte->jointype = jointype;
1104 rte->joinaliasvars = aliasvars;
1107 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1108 numaliases = list_length(eref->colnames);
1110 /* fill in any unspecified alias columns */
1111 if (numaliases < list_length(colnames))
1112 eref->colnames = list_concat(eref->colnames,
1113 list_copy_tail(colnames, numaliases));
1119 * - this RTE should be expanded to include descendant tables,
1120 * - this RTE is in the FROM clause,
1121 * - this RTE should be checked for appropriate access rights.
1123 * Joins are never checked for access rights.
1126 rte->inh = false; /* never true for joins */
1127 rte->inFromCl = inFromCl;
1129 rte->requiredPerms = 0;
1130 rte->checkAsUser = 0;
1133 * Add completed RTE to pstate's range table list, but not to join
1134 * list nor namespace --- caller must do that if appropriate.
1137 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1143 * Has the specified refname been selected FOR UPDATE?
1146 isForUpdate(ParseState *pstate, char *refname)
1148 /* Outer loop to check parent query levels as well as this one */
1149 while (pstate != NULL)
1151 if (pstate->p_forUpdate != NIL)
1153 if (linitial(pstate->p_forUpdate) == NULL)
1155 /* all tables used in query */
1160 /* just the named tables */
1163 foreach(l, pstate->p_forUpdate)
1165 char *rname = strVal(lfirst(l));
1167 if (strcmp(refname, rname) == 0)
1172 pstate = pstate->parentParseState;
1178 * Add the given RTE as a top-level entry in the pstate's join list
1179 * and/or name space list. (We assume caller has checked for any
1180 * namespace conflict.)
1183 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1184 bool addToJoinList, bool addToNameSpace)
1186 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1187 RangeTblRef *rtr = makeNode(RangeTblRef);
1189 rtr->rtindex = rtindex;
1192 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1194 pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1198 * Add a POSTQUEL-style implicit RTE.
1200 * We assume caller has already checked that there is no RTE or join with
1201 * a conflicting name.
1204 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1208 rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1209 addRTEtoQuery(pstate, rte, true, true);
1210 warnAutoRange(pstate, relation);
1216 * expandRTE -- expand the columns of a rangetable entry
1218 * This creates lists of an RTE's column names (aliases if provided, else
1219 * real names) and Vars for each column. Only user columns are considered.
1220 * If include_dropped is FALSE then dropped columns are omitted from the
1221 * results. If include_dropped is TRUE then empty strings and NULL constants
1222 * (not Vars!) are returned for dropped columns.
1224 * The target RTE is the rtindex'th entry of rtable. (The whole rangetable
1225 * must be passed since we need it to determine dropped-ness for JOIN columns.)
1226 * sublevels_up is the varlevelsup value to use in the created Vars.
1228 * The output lists go into *colnames and *colvars.
1229 * If only one of the two kinds of output list is needed, pass NULL for the
1230 * output pointer for the unwanted one.
1233 expandRTE(List *rtable, int rtindex, int sublevels_up,
1234 bool include_dropped,
1235 List **colnames, List **colvars)
1237 RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1245 switch (rte->rtekind)
1248 /* Ordinary relation RTE */
1249 expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1250 include_dropped, colnames, colvars);
1255 ListCell *aliasp_item = list_head(rte->eref->colnames);
1256 ListCell *tlistitem;
1259 foreach(tlistitem, rte->subquery->targetList)
1261 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1263 if (te->resdom->resjunk)
1266 Assert(varattno == te->resdom->resno);
1270 /* Assume there is one alias per target item */
1271 char *label = strVal(lfirst(aliasp_item));
1273 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1274 aliasp_item = lnext(aliasp_item);
1281 varnode = makeVar(rtindex, varattno,
1282 te->resdom->restype,
1283 te->resdom->restypmod,
1286 *colvars = lappend(*colvars, varnode);
1294 TypeFuncClass functypclass;
1298 functypclass = get_expr_result_type(rte->funcexpr,
1301 if (functypclass == TYPEFUNC_COMPOSITE)
1303 /* Composite data type, e.g. a table's row type */
1305 expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1306 include_dropped, colnames, colvars);
1308 else if (functypclass == TYPEFUNC_SCALAR)
1310 /* Base data type, i.e. scalar */
1312 *colnames = lappend(*colnames,
1313 linitial(rte->eref->colnames));
1319 varnode = makeVar(rtindex, 1,
1323 *colvars = lappend(*colvars, varnode);
1326 else if (functypclass == TYPEFUNC_RECORD)
1328 List *coldeflist = rte->coldeflist;
1332 foreach(col, coldeflist)
1334 ColumnDef *colDef = lfirst(col);
1341 attrname = pstrdup(colDef->colname);
1342 *colnames = lappend(*colnames, makeString(attrname));
1350 atttypid = typenameTypeId(colDef->typename);
1352 varnode = makeVar(rtindex,
1358 *colvars = lappend(*colvars, varnode);
1364 /* addRangeTableEntryForFunction should've caught this */
1365 elog(ERROR, "function in FROM has unsupported return type");
1375 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1378 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1383 * During ordinary parsing, there will never be any
1384 * deleted columns in the join; but we have to check
1385 * since this routine is also used by the rewriter,
1386 * and joins found in stored rules might have join
1387 * columns for since-deleted columns.
1389 if (get_rte_attribute_is_dropped(rtable, rtindex,
1392 if (include_dropped)
1395 *colnames = lappend(*colnames,
1396 makeString(pstrdup("")));
1400 * can't use atttypid here, but it doesn't
1401 * really matter what type the Const
1404 *colvars = lappend(*colvars,
1405 makeNullConst(INT4OID));
1413 char *label = strVal(lfirst(colname));
1415 *colnames = lappend(*colnames,
1416 makeString(pstrdup(label)));
1421 Node *avar = (Node *) lfirst(aliasvar);
1424 varnode = makeVar(rtindex, varattno,
1429 *colvars = lappend(*colvars, varnode);
1435 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1440 * expandRelation -- expandRTE subroutine
1443 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1444 bool include_dropped,
1445 List **colnames, List **colvars)
1449 /* Get the tupledesc and turn it over to expandTupleDesc */
1450 rel = relation_open(relid, AccessShareLock);
1451 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1453 relation_close(rel, AccessShareLock);
1457 * expandTupleDesc -- expandRTE subroutine
1460 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1461 int rtindex, int sublevels_up,
1462 bool include_dropped,
1463 List **colnames, List **colvars)
1465 int maxattrs = tupdesc->natts;
1466 int numaliases = list_length(eref->colnames);
1469 for (varattno = 0; varattno < maxattrs; varattno++)
1471 Form_pg_attribute attr = tupdesc->attrs[varattno];
1473 if (attr->attisdropped)
1475 if (include_dropped)
1478 *colnames = lappend(*colnames, makeString(pstrdup("")));
1482 * can't use atttypid here, but it doesn't really
1483 * matter what type the Const claims to be.
1485 *colvars = lappend(*colvars, makeNullConst(INT4OID));
1495 if (varattno < numaliases)
1496 label = strVal(list_nth(eref->colnames, varattno));
1498 label = NameStr(attr->attname);
1499 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1506 varnode = makeVar(rtindex, attr->attnum,
1507 attr->atttypid, attr->atttypmod,
1510 *colvars = lappend(*colvars, varnode);
1517 * Workhorse for "*" expansion: produce a list of targetentries
1518 * for the attributes of the rte
1521 expandRelAttrs(ParseState *pstate, List *rtable, int rtindex, int sublevels_up)
1527 List *te_list = NIL;
1529 expandRTE(rtable, rtindex, sublevels_up, false, &names, &vars);
1531 forboth(name, names, var, vars)
1533 char *label = strVal(lfirst(name));
1534 Node *varnode = (Node *) lfirst(var);
1535 TargetEntry *te = makeNode(TargetEntry);
1537 te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1539 exprTypmod(varnode),
1542 te->expr = (Expr *) varnode;
1543 te_list = lappend(te_list, te);
1546 Assert(name == NULL && var == NULL); /* lists not the same
1553 * get_rte_attribute_name
1554 * Get an attribute name from a RangeTblEntry
1556 * This is unlike get_attname() because we use aliases if available.
1557 * In particular, it will work on an RTE for a subselect or join, whereas
1558 * get_attname() only works on real relations.
1560 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1561 * occurs when a Var represents a whole tuple of a relation.
1564 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1566 if (attnum == InvalidAttrNumber)
1570 * If there is a user-written column alias, use it.
1573 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1574 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1577 * If the RTE is a relation, go to the system catalogs not the
1578 * eref->colnames list. This is a little slower but it will give the
1579 * right answer if the column has been renamed since the eref list was
1580 * built (which can easily happen for rules).
1582 if (rte->rtekind == RTE_RELATION)
1583 return get_relid_attribute_name(rte->relid, attnum);
1586 * Otherwise use the column name from eref. There should always be
1589 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1590 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1592 /* else caller gave us a bogus attnum */
1593 elog(ERROR, "invalid attnum %d for rangetable entry %s",
1594 attnum, rte->eref->aliasname);
1595 return NULL; /* keep compiler quiet */
1599 * get_rte_attribute_type
1600 * Get attribute type information from a RangeTblEntry
1603 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1604 Oid *vartype, int32 *vartypmod)
1606 switch (rte->rtekind)
1610 /* Plain relation RTE --- get the attribute's type info */
1612 Form_pg_attribute att_tup;
1614 tp = SearchSysCache(ATTNUM,
1615 ObjectIdGetDatum(rte->relid),
1616 Int16GetDatum(attnum),
1618 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1619 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1620 attnum, rte->relid);
1621 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1624 * If dropped column, pretend it ain't there. See notes
1625 * in scanRTEForColumn.
1627 if (att_tup->attisdropped)
1629 (errcode(ERRCODE_UNDEFINED_COLUMN),
1630 errmsg("column \"%s\" of relation \"%s\" does not exist",
1631 NameStr(att_tup->attname),
1632 get_rel_name(rte->relid))));
1633 *vartype = att_tup->atttypid;
1634 *vartypmod = att_tup->atttypmod;
1635 ReleaseSysCache(tp);
1640 /* Subselect RTE --- get type info from subselect's tlist */
1641 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1644 if (te == NULL || te->resdom->resjunk)
1645 elog(ERROR, "subquery %s does not have attribute %d",
1646 rte->eref->aliasname, attnum);
1647 *vartype = te->resdom->restype;
1648 *vartypmod = te->resdom->restypmod;
1654 TypeFuncClass functypclass;
1658 functypclass = get_expr_result_type(rte->funcexpr,
1662 if (functypclass == TYPEFUNC_COMPOSITE)
1664 /* Composite data type, e.g. a table's row type */
1665 Form_pg_attribute att_tup;
1668 /* this is probably a can't-happen case */
1669 if (attnum < 1 || attnum > tupdesc->natts)
1671 (errcode(ERRCODE_UNDEFINED_COLUMN),
1672 errmsg("column %d of relation \"%s\" does not exist",
1674 rte->eref->aliasname)));
1676 att_tup = tupdesc->attrs[attnum - 1];
1679 * If dropped column, pretend it ain't there. See
1680 * notes in scanRTEForColumn.
1682 if (att_tup->attisdropped)
1684 (errcode(ERRCODE_UNDEFINED_COLUMN),
1685 errmsg("column \"%s\" of relation \"%s\" does not exist",
1686 NameStr(att_tup->attname),
1687 rte->eref->aliasname)));
1688 *vartype = att_tup->atttypid;
1689 *vartypmod = att_tup->atttypmod;
1691 else if (functypclass == TYPEFUNC_SCALAR)
1693 /* Base data type, i.e. scalar */
1694 *vartype = funcrettype;
1697 else if (functypclass == TYPEFUNC_RECORD)
1699 ColumnDef *colDef = list_nth(rte->coldeflist, attnum - 1);
1701 *vartype = typenameTypeId(colDef->typename);
1706 /* addRangeTableEntryForFunction should've caught this */
1707 elog(ERROR, "function in FROM has unsupported return type");
1714 * Join RTE --- get type info from join RTE's alias
1719 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1720 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1721 *vartype = exprType(aliasvar);
1722 *vartypmod = exprTypmod(aliasvar);
1726 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1731 * get_rte_attribute_is_dropped
1732 * Check whether attempted attribute ref is to a dropped column
1735 get_rte_attribute_is_dropped(List *rtable, int rtindex, AttrNumber attnum)
1737 RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1740 switch (rte->rtekind)
1745 * Plain relation RTE --- get the attribute's catalog
1749 Form_pg_attribute att_tup;
1751 tp = SearchSysCache(ATTNUM,
1752 ObjectIdGetDatum(rte->relid),
1753 Int16GetDatum(attnum),
1755 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1756 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1757 attnum, rte->relid);
1758 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1759 result = att_tup->attisdropped;
1760 ReleaseSysCache(tp);
1764 /* Subselect RTEs never have dropped columns */
1770 * A join RTE would not have dropped columns when
1771 * constructed, but one in a stored rule might contain
1772 * columns that were dropped from the underlying tables,
1773 * if said columns are nowhere explicitly referenced in
1774 * the rule. So we have to recursively look at the
1775 * referenced column.
1780 attnum > list_length(rte->joinaliasvars))
1781 elog(ERROR, "invalid varattno %d", attnum);
1782 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1785 * If the list item isn't a simple Var, then it must
1786 * represent a merged column, ie a USING column, and so it
1787 * couldn't possibly be dropped (since it's referenced in
1790 if (!IsA(aliasvar, Var))
1793 result = get_rte_attribute_is_dropped(rtable,
1795 aliasvar->varattno);
1801 Oid funcrettype = exprType(rte->funcexpr);
1802 Oid funcrelid = typeidTypeRelid(funcrettype);
1804 if (OidIsValid(funcrelid))
1807 * Composite data type, i.e. a table's row type
1809 * Same as ordinary relation RTE
1812 Form_pg_attribute att_tup;
1814 tp = SearchSysCache(ATTNUM,
1815 ObjectIdGetDatum(funcrelid),
1816 Int16GetDatum(attnum),
1818 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1819 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1821 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1822 result = att_tup->attisdropped;
1823 ReleaseSysCache(tp);
1828 * Must be a base data type, i.e. scalar
1835 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1836 result = false; /* keep compiler quiet */
1843 * Given a targetlist and a resno, return the matching TargetEntry
1845 * Returns NULL if resno is not present in list.
1847 * Note: we need to search, rather than just indexing with list_nth(),
1848 * because not all tlists are sorted by resno.
1851 get_tle_by_resno(List *tlist, AttrNumber resno)
1857 TargetEntry *tle = (TargetEntry *) lfirst(l);
1859 if (tle->resdom->resno == resno)
1866 * given relation and att name, return id of variable
1868 * This should only be used if the relation is already
1869 * heap_open()'ed. Use the cache version get_attnum()
1870 * for access to non-opened relations.
1873 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1877 for (i = 0; i < rd->rd_rel->relnatts; i++)
1879 Form_pg_attribute att = rd->rd_att->attrs[i];
1881 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1887 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1889 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1896 (errcode(ERRCODE_UNDEFINED_COLUMN),
1897 errmsg("column \"%s\" of relation \"%s\" does not exist",
1898 attname, RelationGetRelationName(rd))));
1899 return InvalidAttrNumber; /* keep compiler quiet */
1904 * Check attribute name to see if it is "special", e.g. "oid".
1905 * - thomas 2000-02-07
1907 * Note: this only discovers whether the name could be a system attribute.
1908 * Caller needs to verify that it really is an attribute of the rel,
1909 * at least in the case of "oid", which is now optional.
1912 specialAttNum(const char *attname)
1914 Form_pg_attribute sysatt;
1916 sysatt = SystemAttributeByName(attname,
1917 true /* "oid" will be accepted */ );
1919 return sysatt->attnum;
1920 return InvalidAttrNumber;
1925 * given attribute id, return name of that attribute
1927 * This should only be used if the relation is already
1928 * heap_open()'ed. Use the cache version get_atttype()
1929 * for access to non-opened relations.
1932 attnumAttName(Relation rd, int attid)
1936 Form_pg_attribute sysatt;
1938 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1939 return &sysatt->attname;
1941 if (attid > rd->rd_att->natts)
1942 elog(ERROR, "invalid attribute number %d", attid);
1943 return &rd->rd_att->attrs[attid - 1]->attname;
1947 * given attribute id, return type of that attribute
1949 * This should only be used if the relation is already
1950 * heap_open()'ed. Use the cache version get_atttype()
1951 * for access to non-opened relations.
1954 attnumTypeId(Relation rd, int attid)
1958 Form_pg_attribute sysatt;
1960 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1961 return sysatt->atttypid;
1963 if (attid > rd->rd_att->natts)
1964 elog(ERROR, "invalid attribute number %d", attid);
1965 return rd->rd_att->attrs[attid - 1]->atttypid;
1969 * Generate a warning or error about an implicit RTE, if appropriate.
1971 * If ADD_MISSING_FROM is not enabled, raise an error.
1973 * Our current theory on warnings is that we should allow "SELECT foo.*"
1974 * but warn about a mixture of explicit and implicit RTEs.
1977 warnAutoRange(ParseState *pstate, RangeVar *relation)
1979 bool foundInFromCl = false;
1982 if (!add_missing_from)
1984 if (pstate->parentParseState != NULL)
1986 (errcode(ERRCODE_UNDEFINED_TABLE),
1987 errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1988 relation->relname)));
1991 (errcode(ERRCODE_UNDEFINED_TABLE),
1992 errmsg("missing FROM-clause entry for table \"%s\"",
1993 relation->relname)));
1996 foreach(temp, pstate->p_rtable)
1998 RangeTblEntry *rte = lfirst(temp);
2002 foundInFromCl = true;
2008 if (pstate->parentParseState != NULL)
2010 (errcode(ERRCODE_UNDEFINED_TABLE),
2011 errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
2012 relation->relname)));
2015 (errcode(ERRCODE_UNDEFINED_TABLE),
2016 errmsg("adding missing FROM-clause entry for table \"%s\"",
2017 relation->relname)));