1 /*-------------------------------------------------------------------------
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2006, 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.123 2006/04/30 18:30:39 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 RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
39 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid);
40 static bool isLockedRel(ParseState *pstate, char *refname);
41 static void expandRelation(Oid relid, Alias *eref,
42 int rtindex, int sublevels_up,
44 List **colnames, List **colvars);
45 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
46 int rtindex, int sublevels_up,
48 List **colnames, List **colvars);
49 static int specialAttNum(const char *attname);
50 static void warnAutoRange(ParseState *pstate, RangeVar *relation,
55 * refnameRangeTblEntry
56 * Given a possibly-qualified refname, look to see if it matches any RTE.
57 * If so, return a pointer to the RangeTblEntry; else return NULL.
59 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
60 * If sublevels_up is NULL, only consider items at the current nesting
63 * An unqualified refname (schemaname == NULL) can match any RTE with matching
64 * alias, or matching unqualified relname in the case of alias-less relation
65 * RTEs. It is possible that such a refname matches multiple RTEs in the
66 * nearest nesting level that has a match; if so, we report an error via
69 * A qualified refname (schemaname != NULL) can only match a relation RTE
70 * that (a) has no alias and (b) is for the same relation identified by
71 * schemaname.refname. In this case we convert schemaname.refname to a
72 * relation OID and search by relid, rather than by alias name. This is
73 * peculiar, but it's what SQL92 says to do.
76 refnameRangeTblEntry(ParseState *pstate,
77 const char *schemaname,
81 Oid relId = InvalidOid;
86 if (schemaname != NULL)
90 namespaceId = LookupExplicitNamespace(schemaname);
91 relId = get_relname_relid(refname, namespaceId);
92 if (!OidIsValid(relId))
96 while (pstate != NULL)
98 RangeTblEntry *result;
100 if (OidIsValid(relId))
101 result = scanNameSpaceForRelid(pstate, relId);
103 result = scanNameSpaceForRefname(pstate, refname);
113 pstate = pstate->parentParseState;
119 * Search the query's table namespace for an RTE matching the
120 * given unqualified refname. Return the RTE if a unique match, or NULL
121 * if no match. Raise error if multiple matches.
123 static RangeTblEntry *
124 scanNameSpaceForRefname(ParseState *pstate, const char *refname)
126 RangeTblEntry *result = NULL;
129 foreach(l, pstate->p_relnamespace)
131 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
133 if (strcmp(rte->eref->aliasname, refname) == 0)
137 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
138 errmsg("table reference \"%s\" is ambiguous",
147 * Search the query's table namespace for a relation RTE matching the
148 * given relation OID. Return the RTE if a unique match, or NULL
149 * if no match. Raise error if multiple matches (which shouldn't
150 * happen if the namespace was checked correctly when it was created).
152 * See the comments for refnameRangeTblEntry to understand why this
153 * acts the way it does.
155 static RangeTblEntry *
156 scanNameSpaceForRelid(ParseState *pstate, Oid relid)
158 RangeTblEntry *result = NULL;
161 foreach(l, pstate->p_relnamespace)
163 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
165 /* yes, the test for alias == NULL should be there... */
166 if (rte->rtekind == RTE_RELATION &&
167 rte->relid == relid &&
172 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
173 errmsg("table reference %u is ambiguous",
183 * See if any RangeTblEntry could possibly match the RangeVar.
184 * If so, return a pointer to the RangeTblEntry; else return NULL.
186 * This is different from refnameRangeTblEntry in that it considers every
187 * entry in the ParseState's rangetable(s), not only those that are currently
188 * visible in the p_relnamespace lists. This behavior is invalid per the SQL
189 * spec, and it may give ambiguous results (there might be multiple equally
190 * valid matches, but only one will be returned). This must be used ONLY
191 * as a heuristic in giving suitable error messages. See warnAutoRange.
193 * Notice that we consider both matches on actual relation name and matches
196 static RangeTblEntry *
197 searchRangeTable(ParseState *pstate, RangeVar *relation)
199 Oid relId = RangeVarGetRelid(relation, true);
200 char *refname = relation->relname;
202 while (pstate != NULL)
206 foreach(l, pstate->p_rtable)
208 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
210 if (OidIsValid(relId) &&
211 rte->rtekind == RTE_RELATION &&
214 if (strcmp(rte->eref->aliasname, refname) == 0)
218 pstate = pstate->parentParseState;
224 * Check for relation-name conflicts between two relnamespace lists.
225 * Raise an error if any is found.
227 * Note: we assume that each given argument does not contain conflicts
228 * itself; we just want to know if the two can be merged together.
230 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
231 * they have the same eref->aliasname (ie, same relation name), if they
232 * are for different relation OIDs (implying they are in different schemas).
235 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
240 foreach(l1, namespace1)
242 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
243 const char *aliasname1 = rte1->eref->aliasname;
246 foreach(l2, namespace2)
248 RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
250 if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
251 continue; /* definitely no conflict */
252 if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
253 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
254 rte1->relid != rte2->relid)
255 continue; /* no conflict per SQL92 rule */
257 (errcode(ERRCODE_DUPLICATE_ALIAS),
258 errmsg("table name \"%s\" specified more than once",
265 * given an RTE, return RT index (starting with 1) of the entry,
266 * and optionally get its nesting depth (0 = current). If sublevels_up
267 * is NULL, only consider rels at the current nesting level.
268 * Raises error if RTE not found.
271 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
279 while (pstate != NULL)
282 foreach(l, pstate->p_rtable)
284 if (rte == (RangeTblEntry *) lfirst(l))
288 pstate = pstate->parentParseState;
295 elog(ERROR, "RTE not found (internal error)");
296 return 0; /* keep compiler quiet */
300 * Given an RT index and nesting depth, find the corresponding RTE.
301 * This is the inverse of RTERangeTablePosn.
304 GetRTEByRangeTablePosn(ParseState *pstate,
308 while (sublevels_up-- > 0)
310 pstate = pstate->parentParseState;
311 Assert(pstate != NULL);
313 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
314 return rt_fetch(varno, pstate->p_rtable);
319 * Search the column names of a single RTE for the given name.
320 * If found, return an appropriate Var node, else return NULL.
321 * If the name proves ambiguous within this RTE, raise error.
323 * Side effect: if we find a match, mark the RTE as requiring read access.
324 * See comments in setTargetTable().
326 * NOTE: if the RTE is for a join, marking it as requiring read access does
327 * nothing. It might seem that we need to propagate the mark to all the
328 * contained RTEs, but that is not necessary. This is so because a join
329 * expression can only appear in a FROM clause, and any table named in
330 * FROM will be marked as requiring read access from the beginning.
333 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
341 * Scan the user column names (or aliases) for a match. Complain if
344 * Note: eref->colnames may include entries for dropped columns, but those
345 * will be empty strings that cannot match any legal SQL identifier, so we
346 * don't bother to test for that case here.
348 * Should this somehow go wrong and we try to access a dropped column,
349 * we'll still catch it by virtue of the checks in
350 * get_rte_attribute_type(), which is called by make_var(). That routine
351 * has to do a cache lookup anyway, so the check there is cheap.
353 foreach(c, rte->eref->colnames)
356 if (strcmp(strVal(lfirst(c)), colname) == 0)
360 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
361 errmsg("column reference \"%s\" is ambiguous",
363 parser_errposition(pstate, location)));
364 result = (Node *) make_var(pstate, rte, attnum);
365 /* Require read access */
366 rte->requiredPerms |= ACL_SELECT;
371 * If we have a unique match, return it. Note that this allows a user
372 * alias to override a system column name (such as OID) without error.
378 * If the RTE represents a real table, consider system column names.
380 if (rte->rtekind == RTE_RELATION)
382 /* quick check to see if name could be a system column */
383 attnum = specialAttNum(colname);
384 if (attnum != InvalidAttrNumber)
386 /* now check to see if column actually is defined */
387 if (SearchSysCacheExists(ATTNUM,
388 ObjectIdGetDatum(rte->relid),
389 Int16GetDatum(attnum),
392 result = (Node *) make_var(pstate, rte, attnum);
393 /* Require read access */
394 rte->requiredPerms |= ACL_SELECT;
404 * Search for an unqualified column name.
405 * If found, return the appropriate Var node (or expression).
406 * If not found, return NULL. If the name proves ambiguous, raise error.
407 * If localonly is true, only names in the innermost query are considered.
410 colNameToVar(ParseState *pstate, char *colname, bool localonly,
414 ParseState *orig_pstate = pstate;
416 while (pstate != NULL)
420 foreach(l, pstate->p_varnamespace)
422 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
425 /* use orig_pstate here to get the right sublevels_up */
426 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
432 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
433 errmsg("column reference \"%s\" is ambiguous",
435 parser_errposition(orig_pstate, location)));
440 if (result != NULL || localonly)
441 break; /* found, or don't want to look at parent */
443 pstate = pstate->parentParseState;
451 * Search for a qualified column name: either refname.colname or
452 * schemaname.relname.colname.
454 * If found, return the appropriate Var node.
455 * If not found, return NULL. If the name proves ambiguous, raise error.
458 qualifiedNameToVar(ParseState *pstate,
468 rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
474 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname),
478 return scanRTEForColumn(pstate, rte, colname, location);
482 * buildRelationAliases
483 * Construct the eref column name list for a relation RTE.
484 * This code is also used for the case of a function RTE returning
485 * a named composite type.
487 * tupdesc: the physical column information
488 * alias: the user-supplied alias, or NULL if none
489 * eref: the eref Alias to store column names in
491 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
492 * empty strings for any dropped columns, so that it will be one-to-one with
493 * physical column numbers.
496 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
498 int maxattrs = tupdesc->natts;
504 Assert(eref->colnames == NIL);
508 aliaslc = list_head(alias->colnames);
509 numaliases = list_length(alias->colnames);
510 /* We'll rebuild the alias colname list */
511 alias->colnames = NIL;
519 for (varattno = 0; varattno < maxattrs; varattno++)
521 Form_pg_attribute attr = tupdesc->attrs[varattno];
524 if (attr->attisdropped)
526 /* Always insert an empty string for a dropped column */
527 attrname = makeString(pstrdup(""));
529 alias->colnames = lappend(alias->colnames, attrname);
534 /* Use the next user-supplied alias */
535 attrname = (Value *) lfirst(aliaslc);
536 aliaslc = lnext(aliaslc);
537 alias->colnames = lappend(alias->colnames, attrname);
541 attrname = makeString(pstrdup(NameStr(attr->attname)));
542 /* we're done with the alias if any */
545 eref->colnames = lappend(eref->colnames, attrname);
548 /* Too many user-supplied aliases? */
551 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
552 errmsg("table \"%s\" has %d columns available but %d columns specified",
553 eref->aliasname, maxattrs - numdropped, numaliases)));
557 * buildScalarFunctionAlias
558 * Construct the eref column name list for a function RTE,
559 * when the function returns a scalar type (not composite or RECORD).
561 * funcexpr: transformed expression tree for the function call
562 * funcname: function name (used only for error message)
563 * alias: the user-supplied alias, or NULL if none
564 * eref: the eref Alias to store column names in
566 * eref->colnames is filled in.
569 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
570 Alias *alias, Alias *eref)
574 Assert(eref->colnames == NIL);
576 /* Use user-specified column alias if there is one. */
577 if (alias && alias->colnames != NIL)
579 if (list_length(alias->colnames) != 1)
581 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
582 errmsg("too many column aliases specified for function %s",
584 eref->colnames = copyObject(alias->colnames);
589 * If the expression is a simple function call, and the function has a
590 * single OUT parameter that is named, use the parameter's name.
592 if (funcexpr && IsA(funcexpr, FuncExpr))
594 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
597 eref->colnames = list_make1(makeString(pname));
603 * Otherwise use the previously-determined alias (not necessarily the
606 eref->colnames = list_make1(makeString(eref->aliasname));
610 * Add an entry for a relation to the pstate's range table (p_rtable).
612 * If pstate is NULL, we just build an RTE and return it without adding it
615 * Note: formerly this checked for refname conflicts, but that's wrong.
616 * Caller is responsible for checking for conflicts in the appropriate scope.
619 addRangeTableEntry(ParseState *pstate,
625 RangeTblEntry *rte = makeNode(RangeTblEntry);
626 char *refname = alias ? alias->aliasname : relation->relname;
630 rte->rtekind = RTE_RELATION;
634 * Get the rel's OID. This access also ensures that we have an up-to-date
635 * relcache entry for the rel. Since this is typically the first access
636 * to a rel in a statement, be careful to get the right access level
637 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
639 lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
640 rel = heap_openrv(relation, lockmode);
641 rte->relid = RelationGetRelid(rel);
644 * Build the list of effective column names using user-supplied aliases
645 * and/or actual column names.
647 rte->eref = makeAlias(refname, NIL);
648 buildRelationAliases(rel->rd_att, alias, rte->eref);
651 * Drop the rel refcount, but keep the access lock till end of transaction
652 * so that the table can't be deleted or have its schema modified
655 heap_close(rel, NoLock);
659 * - this RTE should be expanded to include descendant tables,
660 * - this RTE is in the FROM clause,
661 * - this RTE should be checked for appropriate access rights.
663 * The initial default on access checks is always check-for-READ-access,
664 * which is the right thing for all except target tables.
668 rte->inFromCl = inFromCl;
670 rte->requiredPerms = ACL_SELECT;
671 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
674 * Add completed RTE to pstate's range table list, but not to join list
675 * nor namespace --- caller must do that if appropriate.
678 pstate->p_rtable = lappend(pstate->p_rtable, rte);
684 * Add an entry for a relation to the pstate's range table (p_rtable).
686 * This is just like addRangeTableEntry() except that it makes an RTE
687 * given an already-open relation instead of a RangeVar reference.
690 addRangeTableEntryForRelation(ParseState *pstate,
696 RangeTblEntry *rte = makeNode(RangeTblEntry);
697 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
699 rte->rtekind = RTE_RELATION;
701 rte->relid = RelationGetRelid(rel);
704 * Build the list of effective column names using user-supplied aliases
705 * and/or actual column names.
707 rte->eref = makeAlias(refname, NIL);
708 buildRelationAliases(rel->rd_att, alias, rte->eref);
712 * - this RTE should be expanded to include descendant tables,
713 * - this RTE is in the FROM clause,
714 * - this RTE should be checked for appropriate access rights.
716 * The initial default on access checks is always check-for-READ-access,
717 * which is the right thing for all except target tables.
721 rte->inFromCl = inFromCl;
723 rte->requiredPerms = ACL_SELECT;
724 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
727 * Add completed RTE to pstate's range table list, but not to join list
728 * nor namespace --- caller must do that if appropriate.
731 pstate->p_rtable = lappend(pstate->p_rtable, rte);
737 * Add an entry for a subquery to the pstate's range table (p_rtable).
739 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
740 * Note that an alias clause *must* be supplied.
743 addRangeTableEntryForSubquery(ParseState *pstate,
748 RangeTblEntry *rte = makeNode(RangeTblEntry);
749 char *refname = alias->aliasname;
755 rte->rtekind = RTE_SUBQUERY;
756 rte->relid = InvalidOid;
757 rte->subquery = subquery;
760 eref = copyObject(alias);
761 numaliases = list_length(eref->colnames);
763 /* fill in any unspecified alias columns */
765 foreach(tlistitem, subquery->targetList)
767 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
772 Assert(varattno == te->resno);
773 if (varattno > numaliases)
777 attrname = pstrdup(te->resname);
778 eref->colnames = lappend(eref->colnames, makeString(attrname));
781 if (varattno < numaliases)
783 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
784 errmsg("table \"%s\" has %d columns available but %d columns specified",
785 refname, varattno, numaliases)));
791 * - this RTE should be expanded to include descendant tables,
792 * - this RTE is in the FROM clause,
793 * - this RTE should be checked for appropriate access rights.
795 * Subqueries are never checked for access rights.
798 rte->inh = false; /* never true for subqueries */
799 rte->inFromCl = inFromCl;
801 rte->requiredPerms = 0;
802 rte->checkAsUser = InvalidOid;
805 * Add completed RTE to pstate's range table list, but not to join list
806 * nor namespace --- caller must do that if appropriate.
809 pstate->p_rtable = lappend(pstate->p_rtable, rte);
815 * Add an entry for a function to the pstate's range table (p_rtable).
817 * This is just like addRangeTableEntry() except that it makes a function RTE.
820 addRangeTableEntryForFunction(ParseState *pstate,
823 RangeFunction *rangefunc,
826 RangeTblEntry *rte = makeNode(RangeTblEntry);
827 TypeFuncClass functypclass;
830 Alias *alias = rangefunc->alias;
831 List *coldeflist = rangefunc->coldeflist;
834 rte->rtekind = RTE_FUNCTION;
835 rte->relid = InvalidOid;
836 rte->subquery = NULL;
837 rte->funcexpr = funcexpr;
838 rte->funccoltypes = NIL;
839 rte->funccoltypmods = NIL;
842 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
846 * Now determine if the function returns a simple or composite type.
848 functypclass = get_expr_result_type(funcexpr,
853 * A coldeflist is required if the function returns RECORD and hasn't got
854 * a predetermined record type, and is prohibited otherwise.
856 if (coldeflist != NIL)
858 if (functypclass != TYPEFUNC_RECORD)
860 (errcode(ERRCODE_SYNTAX_ERROR),
861 errmsg("a column definition list is only allowed for functions returning \"record\"")));
865 if (functypclass == TYPEFUNC_RECORD)
867 (errcode(ERRCODE_SYNTAX_ERROR),
868 errmsg("a column definition list is required for functions returning \"record\"")));
871 if (functypclass == TYPEFUNC_COMPOSITE)
873 /* Composite data type, e.g. a table's row type */
875 /* Build the column alias list */
876 buildRelationAliases(tupdesc, alias, eref);
878 else if (functypclass == TYPEFUNC_SCALAR)
880 /* Base data type, i.e. scalar */
881 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
883 else if (functypclass == TYPEFUNC_RECORD)
888 * Use the column definition list to form the alias list and
889 * funccoltypes/funccoltypmods lists.
891 foreach(col, coldeflist)
893 ColumnDef *n = (ColumnDef *) lfirst(col);
898 attrname = pstrdup(n->colname);
899 if (n->typename->setof)
901 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
902 errmsg("column \"%s\" cannot be declared SETOF",
904 eref->colnames = lappend(eref->colnames, makeString(attrname));
905 attrtype = typenameTypeId(pstate, n->typename);
906 attrtypmod = n->typename->typmod;
907 rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
908 rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
913 (errcode(ERRCODE_DATATYPE_MISMATCH),
914 errmsg("function \"%s\" in FROM has unsupported return type %s",
915 funcname, format_type_be(funcrettype))));
919 * - this RTE should be expanded to include descendant tables,
920 * - this RTE is in the FROM clause,
921 * - this RTE should be checked for appropriate access rights.
923 * Functions are never checked for access rights (at least, not by
924 * the RTE permissions mechanism).
927 rte->inh = false; /* never true for functions */
928 rte->inFromCl = inFromCl;
930 rte->requiredPerms = 0;
931 rte->checkAsUser = InvalidOid;
934 * Add completed RTE to pstate's range table list, but not to join list
935 * nor namespace --- caller must do that if appropriate.
938 pstate->p_rtable = lappend(pstate->p_rtable, rte);
944 * Add an entry for a join to the pstate's range table (p_rtable).
946 * This is much like addRangeTableEntry() except that it makes a join RTE.
949 addRangeTableEntryForJoin(ParseState *pstate,
956 RangeTblEntry *rte = makeNode(RangeTblEntry);
960 rte->rtekind = RTE_JOIN;
961 rte->relid = InvalidOid;
962 rte->subquery = NULL;
963 rte->jointype = jointype;
964 rte->joinaliasvars = aliasvars;
967 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
968 numaliases = list_length(eref->colnames);
970 /* fill in any unspecified alias columns */
971 if (numaliases < list_length(colnames))
972 eref->colnames = list_concat(eref->colnames,
973 list_copy_tail(colnames, numaliases));
979 * - this RTE should be expanded to include descendant tables,
980 * - this RTE is in the FROM clause,
981 * - this RTE should be checked for appropriate access rights.
983 * Joins are never checked for access rights.
986 rte->inh = false; /* never true for joins */
987 rte->inFromCl = inFromCl;
989 rte->requiredPerms = 0;
990 rte->checkAsUser = InvalidOid;
993 * Add completed RTE to pstate's range table list, but not to join list
994 * nor namespace --- caller must do that if appropriate.
997 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1003 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1005 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1008 isLockedRel(ParseState *pstate, char *refname)
1010 /* Outer loop to check parent query levels as well as this one */
1011 while (pstate != NULL)
1015 foreach(l, pstate->p_locking_clause)
1017 LockingClause *lc = (LockingClause *) lfirst(l);
1019 if (lc->lockedRels == NIL)
1021 /* all tables used in query */
1026 /* just the named tables */
1029 foreach(l2, lc->lockedRels)
1031 char *rname = strVal(lfirst(l2));
1033 if (strcmp(refname, rname) == 0)
1038 pstate = pstate->parentParseState;
1044 * Add the given RTE as a top-level entry in the pstate's join list
1045 * and/or name space lists. (We assume caller has checked for any
1046 * namespace conflicts.)
1049 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1051 bool addToRelNameSpace, bool addToVarNameSpace)
1055 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1056 RangeTblRef *rtr = makeNode(RangeTblRef);
1058 rtr->rtindex = rtindex;
1059 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1061 if (addToRelNameSpace)
1062 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1063 if (addToVarNameSpace)
1064 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1068 * Add a POSTQUEL-style implicit RTE.
1070 * We assume caller has already checked that there is no RTE or join with
1071 * a conflicting name.
1074 addImplicitRTE(ParseState *pstate, RangeVar *relation, int location)
1078 /* issue warning or error as needed */
1079 warnAutoRange(pstate, relation, location);
1081 * Note that we set inFromCl true, so that the RTE will be listed
1082 * explicitly if the parsetree is ever decompiled by ruleutils.c. This
1083 * provides a migration path for views/rules that were originally written
1084 * with implicit-RTE syntax.
1086 rte = addRangeTableEntry(pstate, relation, NULL, false, true);
1087 /* Add to joinlist and relnamespace, but not varnamespace */
1088 addRTEtoQuery(pstate, rte, true, true, false);
1094 * expandRTE -- expand the columns of a rangetable entry
1096 * This creates lists of an RTE's column names (aliases if provided, else
1097 * real names) and Vars for each column. Only user columns are considered.
1098 * If include_dropped is FALSE then dropped columns are omitted from the
1099 * results. If include_dropped is TRUE then empty strings and NULL constants
1100 * (not Vars!) are returned for dropped columns.
1102 * rtindex and sublevels_up are the varno and varlevelsup values to use
1103 * in the created Vars. Ordinarily rtindex should match the actual position
1104 * of the RTE in its rangetable.
1106 * The output lists go into *colnames and *colvars.
1107 * If only one of the two kinds of output list is needed, pass NULL for the
1108 * output pointer for the unwanted one.
1111 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1112 bool include_dropped,
1113 List **colnames, List **colvars)
1122 switch (rte->rtekind)
1125 /* Ordinary relation RTE */
1126 expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1127 include_dropped, colnames, colvars);
1132 ListCell *aliasp_item = list_head(rte->eref->colnames);
1133 ListCell *tlistitem;
1136 foreach(tlistitem, rte->subquery->targetList)
1138 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1143 Assert(varattno == te->resno);
1147 /* Assume there is one alias per target item */
1148 char *label = strVal(lfirst(aliasp_item));
1150 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1151 aliasp_item = lnext(aliasp_item);
1158 varnode = makeVar(rtindex, varattno,
1159 exprType((Node *) te->expr),
1160 exprTypmod((Node *) te->expr),
1163 *colvars = lappend(*colvars, varnode);
1171 TypeFuncClass functypclass;
1175 functypclass = get_expr_result_type(rte->funcexpr,
1178 if (functypclass == TYPEFUNC_COMPOSITE)
1180 /* Composite data type, e.g. a table's row type */
1182 expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1183 include_dropped, colnames, colvars);
1185 else if (functypclass == TYPEFUNC_SCALAR)
1187 /* Base data type, i.e. scalar */
1189 *colnames = lappend(*colnames,
1190 linitial(rte->eref->colnames));
1196 varnode = makeVar(rtindex, 1,
1200 *colvars = lappend(*colvars, varnode);
1203 else if (functypclass == TYPEFUNC_RECORD)
1206 *colnames = copyObject(rte->eref->colnames);
1213 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1215 Oid attrtype = lfirst_oid(l1);
1216 int32 attrtypmod = lfirst_int(l2);
1220 varnode = makeVar(rtindex,
1225 *colvars = lappend(*colvars, varnode);
1231 /* addRangeTableEntryForFunction should've caught this */
1232 elog(ERROR, "function in FROM has unsupported return type");
1242 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1245 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1247 Node *avar = (Node *) lfirst(aliasvar);
1252 * During ordinary parsing, there will never be any
1253 * deleted columns in the join; but we have to check since
1254 * this routine is also used by the rewriter, and joins
1255 * found in stored rules might have join columns for
1256 * since-deleted columns. This will be signaled by a NULL
1257 * Const in the alias-vars list.
1259 if (IsA(avar, Const))
1261 if (include_dropped)
1264 *colnames = lappend(*colnames,
1265 makeString(pstrdup("")));
1267 *colvars = lappend(*colvars,
1275 char *label = strVal(lfirst(colname));
1277 *colnames = lappend(*colnames,
1278 makeString(pstrdup(label)));
1285 varnode = makeVar(rtindex, varattno,
1290 *colvars = lappend(*colvars, varnode);
1296 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1301 * expandRelation -- expandRTE subroutine
1304 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1305 bool include_dropped,
1306 List **colnames, List **colvars)
1310 /* Get the tupledesc and turn it over to expandTupleDesc */
1311 rel = relation_open(relid, AccessShareLock);
1312 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1314 relation_close(rel, AccessShareLock);
1318 * expandTupleDesc -- expandRTE subroutine
1321 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1322 int rtindex, int sublevels_up,
1323 bool include_dropped,
1324 List **colnames, List **colvars)
1326 int maxattrs = tupdesc->natts;
1327 int numaliases = list_length(eref->colnames);
1330 for (varattno = 0; varattno < maxattrs; varattno++)
1332 Form_pg_attribute attr = tupdesc->attrs[varattno];
1334 if (attr->attisdropped)
1336 if (include_dropped)
1339 *colnames = lappend(*colnames, makeString(pstrdup("")));
1343 * can't use atttypid here, but it doesn't really matter
1344 * what type the Const claims to be.
1346 *colvars = lappend(*colvars, makeNullConst(INT4OID));
1356 if (varattno < numaliases)
1357 label = strVal(list_nth(eref->colnames, varattno));
1359 label = NameStr(attr->attname);
1360 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1367 varnode = makeVar(rtindex, attr->attnum,
1368 attr->atttypid, attr->atttypmod,
1371 *colvars = lappend(*colvars, varnode);
1378 * Workhorse for "*" expansion: produce a list of targetentries
1379 * for the attributes of the rte
1381 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1382 * fields of the Vars produced. pstate->p_next_resno determines the resnos
1383 * assigned to the TLEs.
1386 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1387 int rtindex, int sublevels_up)
1393 List *te_list = NIL;
1395 expandRTE(rte, rtindex, sublevels_up, false,
1398 forboth(name, names, var, vars)
1400 char *label = strVal(lfirst(name));
1401 Node *varnode = (Node *) lfirst(var);
1404 te = makeTargetEntry((Expr *) varnode,
1405 (AttrNumber) pstate->p_next_resno++,
1408 te_list = lappend(te_list, te);
1411 Assert(name == NULL && var == NULL); /* lists not the same length? */
1417 * get_rte_attribute_name
1418 * Get an attribute name from a RangeTblEntry
1420 * This is unlike get_attname() because we use aliases if available.
1421 * In particular, it will work on an RTE for a subselect or join, whereas
1422 * get_attname() only works on real relations.
1424 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1425 * occurs when a Var represents a whole tuple of a relation.
1428 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1430 if (attnum == InvalidAttrNumber)
1434 * If there is a user-written column alias, use it.
1437 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1438 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1441 * If the RTE is a relation, go to the system catalogs not the
1442 * eref->colnames list. This is a little slower but it will give the
1443 * right answer if the column has been renamed since the eref list was
1444 * built (which can easily happen for rules).
1446 if (rte->rtekind == RTE_RELATION)
1447 return get_relid_attribute_name(rte->relid, attnum);
1450 * Otherwise use the column name from eref. There should always be one.
1452 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1453 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1455 /* else caller gave us a bogus attnum */
1456 elog(ERROR, "invalid attnum %d for rangetable entry %s",
1457 attnum, rte->eref->aliasname);
1458 return NULL; /* keep compiler quiet */
1462 * get_rte_attribute_type
1463 * Get attribute type information from a RangeTblEntry
1466 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1467 Oid *vartype, int32 *vartypmod)
1469 switch (rte->rtekind)
1473 /* Plain relation RTE --- get the attribute's type info */
1475 Form_pg_attribute att_tup;
1477 tp = SearchSysCache(ATTNUM,
1478 ObjectIdGetDatum(rte->relid),
1479 Int16GetDatum(attnum),
1481 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1482 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1483 attnum, rte->relid);
1484 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1487 * If dropped column, pretend it ain't there. See notes in
1490 if (att_tup->attisdropped)
1492 (errcode(ERRCODE_UNDEFINED_COLUMN),
1493 errmsg("column \"%s\" of relation \"%s\" does not exist",
1494 NameStr(att_tup->attname),
1495 get_rel_name(rte->relid))));
1496 *vartype = att_tup->atttypid;
1497 *vartypmod = att_tup->atttypmod;
1498 ReleaseSysCache(tp);
1503 /* Subselect RTE --- get type info from subselect's tlist */
1504 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1507 if (te == NULL || te->resjunk)
1508 elog(ERROR, "subquery %s does not have attribute %d",
1509 rte->eref->aliasname, attnum);
1510 *vartype = exprType((Node *) te->expr);
1511 *vartypmod = exprTypmod((Node *) te->expr);
1517 TypeFuncClass functypclass;
1521 functypclass = get_expr_result_type(rte->funcexpr,
1525 if (functypclass == TYPEFUNC_COMPOSITE)
1527 /* Composite data type, e.g. a table's row type */
1528 Form_pg_attribute att_tup;
1531 /* this is probably a can't-happen case */
1532 if (attnum < 1 || attnum > tupdesc->natts)
1534 (errcode(ERRCODE_UNDEFINED_COLUMN),
1535 errmsg("column %d of relation \"%s\" does not exist",
1537 rte->eref->aliasname)));
1539 att_tup = tupdesc->attrs[attnum - 1];
1542 * If dropped column, pretend it ain't there. See notes
1543 * in scanRTEForColumn.
1545 if (att_tup->attisdropped)
1547 (errcode(ERRCODE_UNDEFINED_COLUMN),
1548 errmsg("column \"%s\" of relation \"%s\" does not exist",
1549 NameStr(att_tup->attname),
1550 rte->eref->aliasname)));
1551 *vartype = att_tup->atttypid;
1552 *vartypmod = att_tup->atttypmod;
1554 else if (functypclass == TYPEFUNC_SCALAR)
1556 /* Base data type, i.e. scalar */
1557 *vartype = funcrettype;
1560 else if (functypclass == TYPEFUNC_RECORD)
1562 *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
1563 *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
1567 /* addRangeTableEntryForFunction should've caught this */
1568 elog(ERROR, "function in FROM has unsupported return type");
1575 * Join RTE --- get type info from join RTE's alias variable
1579 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1580 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1581 *vartype = exprType(aliasvar);
1582 *vartypmod = exprTypmod(aliasvar);
1586 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1591 * get_rte_attribute_is_dropped
1592 * Check whether attempted attribute ref is to a dropped column
1595 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
1599 switch (rte->rtekind)
1604 * Plain relation RTE --- get the attribute's catalog entry
1607 Form_pg_attribute att_tup;
1609 tp = SearchSysCache(ATTNUM,
1610 ObjectIdGetDatum(rte->relid),
1611 Int16GetDatum(attnum),
1613 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1614 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1615 attnum, rte->relid);
1616 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1617 result = att_tup->attisdropped;
1618 ReleaseSysCache(tp);
1622 /* Subselect RTEs never have dropped columns */
1628 * A join RTE would not have dropped columns when constructed,
1629 * but one in a stored rule might contain columns that were
1630 * dropped from the underlying tables, if said columns are
1631 * nowhere explicitly referenced in the rule. This will be
1632 * signaled to us by a NULL Const in the joinaliasvars list.
1637 attnum > list_length(rte->joinaliasvars))
1638 elog(ERROR, "invalid varattno %d", attnum);
1639 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1641 result = IsA(aliasvar, Const);
1647 Oid funcrettype = exprType(rte->funcexpr);
1648 Oid funcrelid = typeidTypeRelid(funcrettype);
1650 if (OidIsValid(funcrelid))
1653 * Composite data type, i.e. a table's row type
1655 * Same as ordinary relation RTE
1658 Form_pg_attribute att_tup;
1660 tp = SearchSysCache(ATTNUM,
1661 ObjectIdGetDatum(funcrelid),
1662 Int16GetDatum(attnum),
1664 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1665 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1667 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1668 result = att_tup->attisdropped;
1669 ReleaseSysCache(tp);
1674 * Must be a base data type, i.e. scalar
1681 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1682 result = false; /* keep compiler quiet */
1689 * Given a targetlist and a resno, return the matching TargetEntry
1691 * Returns NULL if resno is not present in list.
1693 * Note: we need to search, rather than just indexing with list_nth(),
1694 * because not all tlists are sorted by resno.
1697 get_tle_by_resno(List *tlist, AttrNumber resno)
1703 TargetEntry *tle = (TargetEntry *) lfirst(l);
1705 if (tle->resno == resno)
1712 * Given a Query and rangetable index, return relation's RowMarkClause if any
1714 * Returns NULL if relation is not selected FOR UPDATE/SHARE
1717 get_rowmark(Query *qry, Index rtindex)
1721 foreach(l, qry->rowMarks)
1723 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1725 if (rc->rti == rtindex)
1732 * given relation and att name, return attnum of variable
1734 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
1736 * This should only be used if the relation is already
1737 * heap_open()'ed. Use the cache version get_attnum()
1738 * for access to non-opened relations.
1741 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1745 for (i = 0; i < rd->rd_rel->relnatts; i++)
1747 Form_pg_attribute att = rd->rd_att->attrs[i];
1749 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1755 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1757 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1763 return InvalidAttrNumber;
1768 * Check attribute name to see if it is "special", e.g. "oid".
1769 * - thomas 2000-02-07
1771 * Note: this only discovers whether the name could be a system attribute.
1772 * Caller needs to verify that it really is an attribute of the rel,
1773 * at least in the case of "oid", which is now optional.
1776 specialAttNum(const char *attname)
1778 Form_pg_attribute sysatt;
1780 sysatt = SystemAttributeByName(attname,
1781 true /* "oid" will be accepted */ );
1783 return sysatt->attnum;
1784 return InvalidAttrNumber;
1789 * given attribute id, return name of that attribute
1791 * This should only be used if the relation is already
1792 * heap_open()'ed. Use the cache version get_atttype()
1793 * for access to non-opened relations.
1796 attnumAttName(Relation rd, int attid)
1800 Form_pg_attribute sysatt;
1802 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1803 return &sysatt->attname;
1805 if (attid > rd->rd_att->natts)
1806 elog(ERROR, "invalid attribute number %d", attid);
1807 return &rd->rd_att->attrs[attid - 1]->attname;
1811 * given attribute id, return type of that attribute
1813 * This should only be used if the relation is already
1814 * heap_open()'ed. Use the cache version get_atttype()
1815 * for access to non-opened relations.
1818 attnumTypeId(Relation rd, int attid)
1822 Form_pg_attribute sysatt;
1824 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1825 return sysatt->atttypid;
1827 if (attid > rd->rd_att->natts)
1828 elog(ERROR, "invalid attribute number %d", attid);
1829 return rd->rd_att->attrs[attid - 1]->atttypid;
1833 * Generate a warning or error about an implicit RTE, if appropriate.
1835 * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
1839 warnAutoRange(ParseState *pstate, RangeVar *relation, int location)
1843 const char *badAlias = NULL;
1846 * Check to see if there are any potential matches in the query's
1847 * rangetable. This affects the message we provide.
1849 rte = searchRangeTable(pstate, relation);
1852 * If we found a match that has an alias and the alias is visible in
1853 * the namespace, then the problem is probably use of the relation's
1854 * real name instead of its alias, ie "SELECT foo.* FROM foo f".
1855 * This mistake is common enough to justify a specific hint.
1857 * If we found a match that doesn't meet those criteria, assume the
1858 * problem is illegal use of a relation outside its scope, as in the
1859 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
1861 if (rte && rte->alias &&
1862 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
1863 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
1864 &sublevels_up) == rte)
1865 badAlias = rte->eref->aliasname;
1867 if (!add_missing_from)
1871 (errcode(ERRCODE_UNDEFINED_TABLE),
1872 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
1875 errhint("Perhaps you meant to reference the table alias \"%s\".",
1877 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
1878 rte->eref->aliasname)),
1879 parser_errposition(pstate, location)));
1882 (errcode(ERRCODE_UNDEFINED_TABLE),
1883 (pstate->parentParseState ?
1884 errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1885 relation->relname) :
1886 errmsg("missing FROM-clause entry for table \"%s\"",
1887 relation->relname)),
1888 parser_errposition(pstate, location)));
1892 /* just issue a warning */
1894 (errcode(ERRCODE_UNDEFINED_TABLE),
1895 (pstate->parentParseState ?
1896 errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
1897 relation->relname) :
1898 errmsg("adding missing FROM-clause entry for table \"%s\"",
1899 relation->relname)),
1901 errhint("Perhaps you meant to reference the table alias \"%s\".",
1904 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
1905 rte->eref->aliasname) : 0)),
1906 parser_errposition(pstate, location)));