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.107 2005/04/28 21:47:14 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 isLockedRel(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 */
599 Assert(rte->inFromCl);
601 /* use orig_pstate here to get the right sublevels_up */
602 newresult = scanRTEForColumn(orig_pstate, rte, colname);
605 elog(ERROR, "unrecognized node type: %d",
606 (int) nodeTag(nsnode));
612 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
613 errmsg("column reference \"%s\" is ambiguous",
619 if (result != NULL || localonly)
620 break; /* found, or don't want to look at parent */
622 pstate = pstate->parentParseState;
631 * Search for a qualified column name: either refname.colname or
632 * schemaname.relname.colname.
634 * If found, return the appropriate Var node.
635 * If not found, return NULL. If the name proves ambiguous, raise error.
638 qualifiedNameToVar(ParseState *pstate,
647 rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
653 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
656 return scanRTEForColumn(pstate, rte, colname);
660 * buildRelationAliases
661 * Construct the eref column name list for a relation RTE.
662 * This code is also used for the case of a function RTE returning
663 * a named composite type.
665 * tupdesc: the physical column information
666 * alias: the user-supplied alias, or NULL if none
667 * eref: the eref Alias to store column names in
669 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
670 * empty strings for any dropped columns, so that it will be one-to-one with
671 * physical column numbers.
674 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
676 int maxattrs = tupdesc->natts;
682 Assert(eref->colnames == NIL);
686 aliaslc = list_head(alias->colnames);
687 numaliases = list_length(alias->colnames);
688 /* We'll rebuild the alias colname list */
689 alias->colnames = NIL;
697 for (varattno = 0; varattno < maxattrs; varattno++)
699 Form_pg_attribute attr = tupdesc->attrs[varattno];
702 if (attr->attisdropped)
704 /* Always insert an empty string for a dropped column */
705 attrname = makeString(pstrdup(""));
707 alias->colnames = lappend(alias->colnames, attrname);
712 /* Use the next user-supplied alias */
713 attrname = (Value *) lfirst(aliaslc);
714 aliaslc = lnext(aliaslc);
715 alias->colnames = lappend(alias->colnames, attrname);
719 attrname = makeString(pstrdup(NameStr(attr->attname)));
720 /* we're done with the alias if any */
723 eref->colnames = lappend(eref->colnames, attrname);
726 /* Too many user-supplied aliases? */
729 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
730 errmsg("table \"%s\" has %d columns available but %d columns specified",
731 eref->aliasname, maxattrs - numdropped, numaliases)));
735 * Add an entry for a relation to the pstate's range table (p_rtable).
737 * If pstate is NULL, we just build an RTE and return it without adding it
740 * Note: formerly this checked for refname conflicts, but that's wrong.
741 * Caller is responsible for checking for conflicts in the appropriate scope.
744 addRangeTableEntry(ParseState *pstate,
750 RangeTblEntry *rte = makeNode(RangeTblEntry);
751 char *refname = alias ? alias->aliasname : relation->relname;
755 rte->rtekind = RTE_RELATION;
759 * Get the rel's OID. This access also ensures that we have an
760 * up-to-date relcache entry for the rel. Since this is typically the
761 * first access to a rel in a statement, be careful to get the right
762 * access level depending on whether we're doing SELECT FOR UPDATE/SHARE.
764 lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
765 rel = heap_openrv(relation, lockmode);
766 rte->relid = RelationGetRelid(rel);
769 * Build the list of effective column names using user-supplied
770 * aliases and/or actual column names.
772 rte->eref = makeAlias(refname, NIL);
773 buildRelationAliases(rel->rd_att, alias, rte->eref);
776 * Drop the rel refcount, but keep the access lock till end of
777 * transaction so that the table can't be deleted or have its schema
778 * modified underneath us.
780 heap_close(rel, NoLock);
784 * - this RTE should be expanded to include descendant tables,
785 * - this RTE is in the FROM clause,
786 * - this RTE should be checked for appropriate access rights.
788 * The initial default on access checks is always check-for-READ-access,
789 * which is the right thing for all except target tables.
793 rte->inFromCl = inFromCl;
795 rte->requiredPerms = ACL_SELECT;
796 rte->checkAsUser = 0; /* not set-uid by default, either */
799 * Add completed RTE to pstate's range table list, but not to join
800 * list nor namespace --- caller must do that if appropriate.
803 pstate->p_rtable = lappend(pstate->p_rtable, rte);
809 * Add an entry for a relation to the pstate's range table (p_rtable).
811 * This is just like addRangeTableEntry() except that it makes an RTE
812 * given an already-open relation instead of a RangeVar reference.
815 addRangeTableEntryForRelation(ParseState *pstate,
821 RangeTblEntry *rte = makeNode(RangeTblEntry);
822 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
824 rte->rtekind = RTE_RELATION;
826 rte->relid = RelationGetRelid(rel);
829 * Build the list of effective column names using user-supplied
830 * aliases and/or actual column names.
832 rte->eref = makeAlias(refname, NIL);
833 buildRelationAliases(rel->rd_att, alias, rte->eref);
837 * - this RTE should be expanded to include descendant tables,
838 * - this RTE is in the FROM clause,
839 * - this RTE should be checked for appropriate access rights.
841 * The initial default on access checks is always check-for-READ-access,
842 * which is the right thing for all except target tables.
846 rte->inFromCl = inFromCl;
848 rte->requiredPerms = ACL_SELECT;
849 rte->checkAsUser = 0; /* not set-uid by default, either */
852 * Add completed RTE to pstate's range table list, but not to join
853 * list nor namespace --- caller must do that if appropriate.
856 pstate->p_rtable = lappend(pstate->p_rtable, rte);
862 * Add an entry for a subquery to the pstate's range table (p_rtable).
864 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
865 * Note that an alias clause *must* be supplied.
868 addRangeTableEntryForSubquery(ParseState *pstate,
873 RangeTblEntry *rte = makeNode(RangeTblEntry);
874 char *refname = alias->aliasname;
880 rte->rtekind = RTE_SUBQUERY;
881 rte->relid = InvalidOid;
882 rte->subquery = subquery;
885 eref = copyObject(alias);
886 numaliases = list_length(eref->colnames);
888 /* fill in any unspecified alias columns */
890 foreach(tlistitem, subquery->targetList)
892 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
897 Assert(varattno == te->resno);
898 if (varattno > numaliases)
902 attrname = pstrdup(te->resname);
903 eref->colnames = lappend(eref->colnames, makeString(attrname));
906 if (varattno < numaliases)
908 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
909 errmsg("table \"%s\" has %d columns available but %d columns specified",
910 refname, varattno, numaliases)));
916 * - this RTE should be expanded to include descendant tables,
917 * - this RTE is in the FROM clause,
918 * - this RTE should be checked for appropriate access rights.
920 * Subqueries are never checked for access rights.
923 rte->inh = false; /* never true for subqueries */
924 rte->inFromCl = inFromCl;
926 rte->requiredPerms = 0;
927 rte->checkAsUser = 0;
930 * Add completed RTE to pstate's range table list, but not to join
931 * list nor namespace --- caller must do that if appropriate.
934 pstate->p_rtable = lappend(pstate->p_rtable, rte);
940 * Add an entry for a function to the pstate's range table (p_rtable).
942 * This is just like addRangeTableEntry() except that it makes a function RTE.
945 addRangeTableEntryForFunction(ParseState *pstate,
948 RangeFunction *rangefunc,
951 RangeTblEntry *rte = makeNode(RangeTblEntry);
952 TypeFuncClass functypclass;
955 Alias *alias = rangefunc->alias;
956 List *coldeflist = rangefunc->coldeflist;
959 rte->rtekind = RTE_FUNCTION;
960 rte->relid = InvalidOid;
961 rte->subquery = NULL;
962 rte->funcexpr = funcexpr;
963 rte->coldeflist = coldeflist;
966 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
970 * Now determine if the function returns a simple or composite type.
972 functypclass = get_expr_result_type(funcexpr,
977 * A coldeflist is required if the function returns RECORD and hasn't
978 * got a predetermined record type, and is prohibited otherwise.
980 if (coldeflist != NIL)
982 if (functypclass != TYPEFUNC_RECORD)
984 (errcode(ERRCODE_SYNTAX_ERROR),
985 errmsg("a column definition list is only allowed for functions returning \"record\"")));
989 if (functypclass == TYPEFUNC_RECORD)
991 (errcode(ERRCODE_SYNTAX_ERROR),
992 errmsg("a column definition list is required for functions returning \"record\"")));
995 if (functypclass == TYPEFUNC_COMPOSITE)
997 /* Composite data type, e.g. a table's row type */
999 /* Build the column alias list */
1000 buildRelationAliases(tupdesc, alias, eref);
1002 else if (functypclass == TYPEFUNC_SCALAR)
1004 /* Base data type, i.e. scalar */
1005 /* Just add one alias column named for the function. */
1006 if (alias && alias->colnames != NIL)
1008 if (list_length(alias->colnames) != 1)
1010 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1011 errmsg("too many column aliases specified for function %s",
1013 eref->colnames = copyObject(alias->colnames);
1016 eref->colnames = list_make1(makeString(eref->aliasname));
1018 else if (functypclass == TYPEFUNC_RECORD)
1022 /* Use the column definition list to form the alias list */
1023 foreach(col, coldeflist)
1025 ColumnDef *n = lfirst(col);
1028 attrname = pstrdup(n->colname);
1029 eref->colnames = lappend(eref->colnames, makeString(attrname));
1034 (errcode(ERRCODE_DATATYPE_MISMATCH),
1035 errmsg("function \"%s\" in FROM has unsupported return type %s",
1036 funcname, format_type_be(funcrettype))));
1040 * - this RTE should be expanded to include descendant tables,
1041 * - this RTE is in the FROM clause,
1042 * - this RTE should be checked for appropriate access rights.
1044 * Functions are never checked for access rights (at least, not by
1045 * the RTE permissions mechanism).
1048 rte->inh = false; /* never true for functions */
1049 rte->inFromCl = inFromCl;
1051 rte->requiredPerms = 0;
1052 rte->checkAsUser = 0;
1055 * Add completed RTE to pstate's range table list, but not to join
1056 * list nor namespace --- caller must do that if appropriate.
1059 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1065 * Add an entry for a join to the pstate's range table (p_rtable).
1067 * This is much like addRangeTableEntry() except that it makes a join RTE.
1070 addRangeTableEntryForJoin(ParseState *pstate,
1077 RangeTblEntry *rte = makeNode(RangeTblEntry);
1081 rte->rtekind = RTE_JOIN;
1082 rte->relid = InvalidOid;
1083 rte->subquery = NULL;
1084 rte->jointype = jointype;
1085 rte->joinaliasvars = aliasvars;
1088 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1089 numaliases = list_length(eref->colnames);
1091 /* fill in any unspecified alias columns */
1092 if (numaliases < list_length(colnames))
1093 eref->colnames = list_concat(eref->colnames,
1094 list_copy_tail(colnames, numaliases));
1100 * - this RTE should be expanded to include descendant tables,
1101 * - this RTE is in the FROM clause,
1102 * - this RTE should be checked for appropriate access rights.
1104 * Joins are never checked for access rights.
1107 rte->inh = false; /* never true for joins */
1108 rte->inFromCl = inFromCl;
1110 rte->requiredPerms = 0;
1111 rte->checkAsUser = 0;
1114 * Add completed RTE to pstate's range table list, but not to join
1115 * list nor namespace --- caller must do that if appropriate.
1118 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1124 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1127 isLockedRel(ParseState *pstate, char *refname)
1129 /* Outer loop to check parent query levels as well as this one */
1130 while (pstate != NULL)
1132 if (pstate->p_lockedRels != NIL)
1134 if (linitial(pstate->p_lockedRels) == NULL)
1136 /* all tables used in query */
1141 /* just the named tables */
1144 foreach(l, pstate->p_lockedRels)
1146 char *rname = strVal(lfirst(l));
1148 if (strcmp(refname, rname) == 0)
1153 pstate = pstate->parentParseState;
1159 * Add the given RTE as a top-level entry in the pstate's join list
1160 * and/or name space list. (We assume caller has checked for any
1161 * namespace conflict.)
1164 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1165 bool addToJoinList, bool addToNameSpace)
1167 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1168 RangeTblRef *rtr = makeNode(RangeTblRef);
1170 rtr->rtindex = rtindex;
1173 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1175 pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1179 * Add a POSTQUEL-style implicit RTE.
1181 * We assume caller has already checked that there is no RTE or join with
1182 * a conflicting name.
1185 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1189 rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1190 addRTEtoQuery(pstate, rte, true, true);
1191 warnAutoRange(pstate, relation);
1197 * expandRTE -- expand the columns of a rangetable entry
1199 * This creates lists of an RTE's column names (aliases if provided, else
1200 * real names) and Vars for each column. Only user columns are considered.
1201 * If include_dropped is FALSE then dropped columns are omitted from the
1202 * results. If include_dropped is TRUE then empty strings and NULL constants
1203 * (not Vars!) are returned for dropped columns.
1205 * The target RTE is the rtindex'th entry of rtable. (The whole rangetable
1206 * must be passed since we need it to determine dropped-ness for JOIN columns.)
1207 * sublevels_up is the varlevelsup value to use in the created Vars.
1209 * The output lists go into *colnames and *colvars.
1210 * If only one of the two kinds of output list is needed, pass NULL for the
1211 * output pointer for the unwanted one.
1214 expandRTE(List *rtable, int rtindex, int sublevels_up,
1215 bool include_dropped,
1216 List **colnames, List **colvars)
1218 RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1226 switch (rte->rtekind)
1229 /* Ordinary relation RTE */
1230 expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1231 include_dropped, colnames, colvars);
1236 ListCell *aliasp_item = list_head(rte->eref->colnames);
1237 ListCell *tlistitem;
1240 foreach(tlistitem, rte->subquery->targetList)
1242 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1247 Assert(varattno == te->resno);
1251 /* Assume there is one alias per target item */
1252 char *label = strVal(lfirst(aliasp_item));
1254 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1255 aliasp_item = lnext(aliasp_item);
1262 varnode = makeVar(rtindex, varattno,
1263 exprType((Node *) te->expr),
1264 exprTypmod((Node *) te->expr),
1267 *colvars = lappend(*colvars, varnode);
1275 TypeFuncClass functypclass;
1279 functypclass = get_expr_result_type(rte->funcexpr,
1282 if (functypclass == TYPEFUNC_COMPOSITE)
1284 /* Composite data type, e.g. a table's row type */
1286 expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1287 include_dropped, colnames, colvars);
1289 else if (functypclass == TYPEFUNC_SCALAR)
1291 /* Base data type, i.e. scalar */
1293 *colnames = lappend(*colnames,
1294 linitial(rte->eref->colnames));
1300 varnode = makeVar(rtindex, 1,
1304 *colvars = lappend(*colvars, varnode);
1307 else if (functypclass == TYPEFUNC_RECORD)
1309 List *coldeflist = rte->coldeflist;
1313 foreach(col, coldeflist)
1315 ColumnDef *colDef = lfirst(col);
1322 attrname = pstrdup(colDef->colname);
1323 *colnames = lappend(*colnames, makeString(attrname));
1331 atttypid = typenameTypeId(colDef->typename);
1333 varnode = makeVar(rtindex,
1339 *colvars = lappend(*colvars, varnode);
1345 /* addRangeTableEntryForFunction should've caught this */
1346 elog(ERROR, "function in FROM has unsupported return type");
1356 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1359 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1364 * During ordinary parsing, there will never be any
1365 * deleted columns in the join; but we have to check
1366 * since this routine is also used by the rewriter,
1367 * and joins found in stored rules might have join
1368 * columns for since-deleted columns.
1370 if (get_rte_attribute_is_dropped(rtable, rtindex,
1373 if (include_dropped)
1376 *colnames = lappend(*colnames,
1377 makeString(pstrdup("")));
1381 * can't use atttypid here, but it doesn't
1382 * really matter what type the Const
1385 *colvars = lappend(*colvars,
1386 makeNullConst(INT4OID));
1394 char *label = strVal(lfirst(colname));
1396 *colnames = lappend(*colnames,
1397 makeString(pstrdup(label)));
1402 Node *avar = (Node *) lfirst(aliasvar);
1405 varnode = makeVar(rtindex, varattno,
1410 *colvars = lappend(*colvars, varnode);
1416 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1421 * expandRelation -- expandRTE subroutine
1424 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1425 bool include_dropped,
1426 List **colnames, List **colvars)
1430 /* Get the tupledesc and turn it over to expandTupleDesc */
1431 rel = relation_open(relid, AccessShareLock);
1432 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1434 relation_close(rel, AccessShareLock);
1438 * expandTupleDesc -- expandRTE subroutine
1441 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1442 int rtindex, int sublevels_up,
1443 bool include_dropped,
1444 List **colnames, List **colvars)
1446 int maxattrs = tupdesc->natts;
1447 int numaliases = list_length(eref->colnames);
1450 for (varattno = 0; varattno < maxattrs; varattno++)
1452 Form_pg_attribute attr = tupdesc->attrs[varattno];
1454 if (attr->attisdropped)
1456 if (include_dropped)
1459 *colnames = lappend(*colnames, makeString(pstrdup("")));
1463 * can't use atttypid here, but it doesn't really
1464 * matter what type the Const claims to be.
1466 *colvars = lappend(*colvars, makeNullConst(INT4OID));
1476 if (varattno < numaliases)
1477 label = strVal(list_nth(eref->colnames, varattno));
1479 label = NameStr(attr->attname);
1480 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1487 varnode = makeVar(rtindex, attr->attnum,
1488 attr->atttypid, attr->atttypmod,
1491 *colvars = lappend(*colvars, varnode);
1498 * Workhorse for "*" expansion: produce a list of targetentries
1499 * for the attributes of the rte
1502 expandRelAttrs(ParseState *pstate, List *rtable, int rtindex, int sublevels_up)
1508 List *te_list = NIL;
1510 expandRTE(rtable, rtindex, sublevels_up, false, &names, &vars);
1512 forboth(name, names, var, vars)
1514 char *label = strVal(lfirst(name));
1515 Node *varnode = (Node *) lfirst(var);
1518 te = makeTargetEntry((Expr *) varnode,
1519 (AttrNumber) pstate->p_next_resno++,
1522 te_list = lappend(te_list, te);
1525 Assert(name == NULL && var == NULL); /* lists not the same
1532 * get_rte_attribute_name
1533 * Get an attribute name from a RangeTblEntry
1535 * This is unlike get_attname() because we use aliases if available.
1536 * In particular, it will work on an RTE for a subselect or join, whereas
1537 * get_attname() only works on real relations.
1539 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1540 * occurs when a Var represents a whole tuple of a relation.
1543 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1545 if (attnum == InvalidAttrNumber)
1549 * If there is a user-written column alias, use it.
1552 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1553 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1556 * If the RTE is a relation, go to the system catalogs not the
1557 * eref->colnames list. This is a little slower but it will give the
1558 * right answer if the column has been renamed since the eref list was
1559 * built (which can easily happen for rules).
1561 if (rte->rtekind == RTE_RELATION)
1562 return get_relid_attribute_name(rte->relid, attnum);
1565 * Otherwise use the column name from eref. There should always be
1568 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1569 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1571 /* else caller gave us a bogus attnum */
1572 elog(ERROR, "invalid attnum %d for rangetable entry %s",
1573 attnum, rte->eref->aliasname);
1574 return NULL; /* keep compiler quiet */
1578 * get_rte_attribute_type
1579 * Get attribute type information from a RangeTblEntry
1582 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1583 Oid *vartype, int32 *vartypmod)
1585 switch (rte->rtekind)
1589 /* Plain relation RTE --- get the attribute's type info */
1591 Form_pg_attribute att_tup;
1593 tp = SearchSysCache(ATTNUM,
1594 ObjectIdGetDatum(rte->relid),
1595 Int16GetDatum(attnum),
1597 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1598 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1599 attnum, rte->relid);
1600 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1603 * If dropped column, pretend it ain't there. See notes
1604 * in scanRTEForColumn.
1606 if (att_tup->attisdropped)
1608 (errcode(ERRCODE_UNDEFINED_COLUMN),
1609 errmsg("column \"%s\" of relation \"%s\" does not exist",
1610 NameStr(att_tup->attname),
1611 get_rel_name(rte->relid))));
1612 *vartype = att_tup->atttypid;
1613 *vartypmod = att_tup->atttypmod;
1614 ReleaseSysCache(tp);
1619 /* Subselect RTE --- get type info from subselect's tlist */
1620 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1623 if (te == NULL || te->resjunk)
1624 elog(ERROR, "subquery %s does not have attribute %d",
1625 rte->eref->aliasname, attnum);
1626 *vartype = exprType((Node *) te->expr);
1627 *vartypmod = exprTypmod((Node *) te->expr);
1633 TypeFuncClass functypclass;
1637 functypclass = get_expr_result_type(rte->funcexpr,
1641 if (functypclass == TYPEFUNC_COMPOSITE)
1643 /* Composite data type, e.g. a table's row type */
1644 Form_pg_attribute att_tup;
1647 /* this is probably a can't-happen case */
1648 if (attnum < 1 || attnum > tupdesc->natts)
1650 (errcode(ERRCODE_UNDEFINED_COLUMN),
1651 errmsg("column %d of relation \"%s\" does not exist",
1653 rte->eref->aliasname)));
1655 att_tup = tupdesc->attrs[attnum - 1];
1658 * If dropped column, pretend it ain't there. See
1659 * notes in scanRTEForColumn.
1661 if (att_tup->attisdropped)
1663 (errcode(ERRCODE_UNDEFINED_COLUMN),
1664 errmsg("column \"%s\" of relation \"%s\" does not exist",
1665 NameStr(att_tup->attname),
1666 rte->eref->aliasname)));
1667 *vartype = att_tup->atttypid;
1668 *vartypmod = att_tup->atttypmod;
1670 else if (functypclass == TYPEFUNC_SCALAR)
1672 /* Base data type, i.e. scalar */
1673 *vartype = funcrettype;
1676 else if (functypclass == TYPEFUNC_RECORD)
1678 ColumnDef *colDef = list_nth(rte->coldeflist, attnum - 1);
1680 *vartype = typenameTypeId(colDef->typename);
1685 /* addRangeTableEntryForFunction should've caught this */
1686 elog(ERROR, "function in FROM has unsupported return type");
1693 * Join RTE --- get type info from join RTE's alias
1698 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1699 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1700 *vartype = exprType(aliasvar);
1701 *vartypmod = exprTypmod(aliasvar);
1705 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1710 * get_rte_attribute_is_dropped
1711 * Check whether attempted attribute ref is to a dropped column
1714 get_rte_attribute_is_dropped(List *rtable, int rtindex, AttrNumber attnum)
1716 RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1719 switch (rte->rtekind)
1724 * Plain relation RTE --- get the attribute's catalog
1728 Form_pg_attribute att_tup;
1730 tp = SearchSysCache(ATTNUM,
1731 ObjectIdGetDatum(rte->relid),
1732 Int16GetDatum(attnum),
1734 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1735 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1736 attnum, rte->relid);
1737 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1738 result = att_tup->attisdropped;
1739 ReleaseSysCache(tp);
1743 /* Subselect RTEs never have dropped columns */
1749 * A join RTE would not have dropped columns when
1750 * constructed, but one in a stored rule might contain
1751 * columns that were dropped from the underlying tables,
1752 * if said columns are nowhere explicitly referenced in
1753 * the rule. So we have to recursively look at the
1754 * referenced column.
1759 attnum > list_length(rte->joinaliasvars))
1760 elog(ERROR, "invalid varattno %d", attnum);
1761 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1764 * If the list item isn't a simple Var, then it must
1765 * represent a merged column, ie a USING column, and so it
1766 * couldn't possibly be dropped (since it's referenced in
1769 if (!IsA(aliasvar, Var))
1772 result = get_rte_attribute_is_dropped(rtable,
1774 aliasvar->varattno);
1780 Oid funcrettype = exprType(rte->funcexpr);
1781 Oid funcrelid = typeidTypeRelid(funcrettype);
1783 if (OidIsValid(funcrelid))
1786 * Composite data type, i.e. a table's row type
1788 * Same as ordinary relation RTE
1791 Form_pg_attribute att_tup;
1793 tp = SearchSysCache(ATTNUM,
1794 ObjectIdGetDatum(funcrelid),
1795 Int16GetDatum(attnum),
1797 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1798 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1800 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1801 result = att_tup->attisdropped;
1802 ReleaseSysCache(tp);
1807 * Must be a base data type, i.e. scalar
1814 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1815 result = false; /* keep compiler quiet */
1822 * Given a targetlist and a resno, return the matching TargetEntry
1824 * Returns NULL if resno is not present in list.
1826 * Note: we need to search, rather than just indexing with list_nth(),
1827 * because not all tlists are sorted by resno.
1830 get_tle_by_resno(List *tlist, AttrNumber resno)
1836 TargetEntry *tle = (TargetEntry *) lfirst(l);
1838 if (tle->resno == resno)
1845 * given relation and att name, return id of variable
1847 * This should only be used if the relation is already
1848 * heap_open()'ed. Use the cache version get_attnum()
1849 * for access to non-opened relations.
1852 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1856 for (i = 0; i < rd->rd_rel->relnatts; i++)
1858 Form_pg_attribute att = rd->rd_att->attrs[i];
1860 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1866 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1868 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1875 (errcode(ERRCODE_UNDEFINED_COLUMN),
1876 errmsg("column \"%s\" of relation \"%s\" does not exist",
1877 attname, RelationGetRelationName(rd))));
1878 return InvalidAttrNumber; /* keep compiler quiet */
1883 * Check attribute name to see if it is "special", e.g. "oid".
1884 * - thomas 2000-02-07
1886 * Note: this only discovers whether the name could be a system attribute.
1887 * Caller needs to verify that it really is an attribute of the rel,
1888 * at least in the case of "oid", which is now optional.
1891 specialAttNum(const char *attname)
1893 Form_pg_attribute sysatt;
1895 sysatt = SystemAttributeByName(attname,
1896 true /* "oid" will be accepted */ );
1898 return sysatt->attnum;
1899 return InvalidAttrNumber;
1904 * given attribute id, return name of that attribute
1906 * This should only be used if the relation is already
1907 * heap_open()'ed. Use the cache version get_atttype()
1908 * for access to non-opened relations.
1911 attnumAttName(Relation rd, int attid)
1915 Form_pg_attribute sysatt;
1917 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1918 return &sysatt->attname;
1920 if (attid > rd->rd_att->natts)
1921 elog(ERROR, "invalid attribute number %d", attid);
1922 return &rd->rd_att->attrs[attid - 1]->attname;
1926 * given attribute id, return type of that attribute
1928 * This should only be used if the relation is already
1929 * heap_open()'ed. Use the cache version get_atttype()
1930 * for access to non-opened relations.
1933 attnumTypeId(Relation rd, int attid)
1937 Form_pg_attribute sysatt;
1939 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1940 return sysatt->atttypid;
1942 if (attid > rd->rd_att->natts)
1943 elog(ERROR, "invalid attribute number %d", attid);
1944 return rd->rd_att->attrs[attid - 1]->atttypid;
1948 * Generate a warning or error about an implicit RTE, if appropriate.
1950 * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
1954 warnAutoRange(ParseState *pstate, RangeVar *relation)
1956 if (!add_missing_from)
1958 if (pstate->parentParseState != NULL)
1960 (errcode(ERRCODE_UNDEFINED_TABLE),
1961 errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1962 relation->relname)));
1965 (errcode(ERRCODE_UNDEFINED_TABLE),
1966 errmsg("missing FROM-clause entry for table \"%s\"",
1967 relation->relname)));
1971 /* just issue a warning */
1972 if (pstate->parentParseState != NULL)
1974 (errcode(ERRCODE_UNDEFINED_TABLE),
1975 errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
1976 relation->relname)));
1979 (errcode(ERRCODE_UNDEFINED_TABLE),
1980 errmsg("adding missing FROM-clause entry for table \"%s\"",
1981 relation->relname)));