Fix xslt_process() to ensure that it inserts a NULL terminator after the
[PostgreSQL.git] / src / backend / parser / parse_relation.c
blob266e931d6c9d25672aa8e5efdaa2ed9fe91e0e45
1 /*-------------------------------------------------------------------------
3 * parse_relation.c
4 * parser support routines dealing with relations
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include <ctype.h>
19 #include "access/heapam.h"
20 #include "access/sysattr.h"
21 #include "catalog/heap.h"
22 #include "catalog/namespace.h"
23 #include "catalog/pg_type.h"
24 #include "funcapi.h"
25 #include "nodes/makefuncs.h"
26 #include "nodes/nodeFuncs.h"
27 #include "parser/parsetree.h"
28 #include "parser/parse_relation.h"
29 #include "parser/parse_type.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/syscache.h"
35 /* GUC parameter */
36 bool add_missing_from;
38 static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
39 const char *refname, int location);
40 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
41 int location);
42 static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
43 int rtindex, AttrNumber col);
44 static bool isLockedRel(ParseState *pstate, char *refname);
45 static void expandRelation(Oid relid, Alias *eref,
46 int rtindex, int sublevels_up,
47 int location, bool include_dropped,
48 List **colnames, List **colvars);
49 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
50 int rtindex, int sublevels_up,
51 int location, bool include_dropped,
52 List **colnames, List **colvars);
53 static int specialAttNum(const char *attname);
54 static void warnAutoRange(ParseState *pstate, RangeVar *relation);
58 * refnameRangeTblEntry
59 * Given a possibly-qualified refname, look to see if it matches any RTE.
60 * If so, return a pointer to the RangeTblEntry; else return NULL.
62 * Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
63 * If sublevels_up is NULL, only consider items at the current nesting
64 * level.
66 * An unqualified refname (schemaname == NULL) can match any RTE with matching
67 * alias, or matching unqualified relname in the case of alias-less relation
68 * RTEs. It is possible that such a refname matches multiple RTEs in the
69 * nearest nesting level that has a match; if so, we report an error via
70 * ereport().
72 * A qualified refname (schemaname != NULL) can only match a relation RTE
73 * that (a) has no alias and (b) is for the same relation identified by
74 * schemaname.refname. In this case we convert schemaname.refname to a
75 * relation OID and search by relid, rather than by alias name. This is
76 * peculiar, but it's what SQL92 says to do.
78 RangeTblEntry *
79 refnameRangeTblEntry(ParseState *pstate,
80 const char *schemaname,
81 const char *refname,
82 int location,
83 int *sublevels_up)
85 Oid relId = InvalidOid;
87 if (sublevels_up)
88 *sublevels_up = 0;
90 if (schemaname != NULL)
92 Oid namespaceId;
94 namespaceId = LookupExplicitNamespace(schemaname);
95 relId = get_relname_relid(refname, namespaceId);
96 if (!OidIsValid(relId))
97 return NULL;
100 while (pstate != NULL)
102 RangeTblEntry *result;
104 if (OidIsValid(relId))
105 result = scanNameSpaceForRelid(pstate, relId, location);
106 else
107 result = scanNameSpaceForRefname(pstate, refname, location);
109 if (result)
110 return result;
112 if (sublevels_up)
113 (*sublevels_up)++;
114 else
115 break;
117 pstate = pstate->parentParseState;
119 return NULL;
123 * Search the query's table namespace for an RTE matching the
124 * given unqualified refname. Return the RTE if a unique match, or NULL
125 * if no match. Raise error if multiple matches.
127 static RangeTblEntry *
128 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
130 RangeTblEntry *result = NULL;
131 ListCell *l;
133 foreach(l, pstate->p_relnamespace)
135 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
137 if (strcmp(rte->eref->aliasname, refname) == 0)
139 if (result)
140 ereport(ERROR,
141 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
142 errmsg("table reference \"%s\" is ambiguous",
143 refname),
144 parser_errposition(pstate, location)));
145 result = rte;
148 return result;
152 * Search the query's table namespace for a relation RTE matching the
153 * given relation OID. Return the RTE if a unique match, or NULL
154 * if no match. Raise error if multiple matches (which shouldn't
155 * happen if the namespace was checked correctly when it was created).
157 * See the comments for refnameRangeTblEntry to understand why this
158 * acts the way it does.
160 static RangeTblEntry *
161 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
163 RangeTblEntry *result = NULL;
164 ListCell *l;
166 foreach(l, pstate->p_relnamespace)
168 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
170 /* yes, the test for alias == NULL should be there... */
171 if (rte->rtekind == RTE_RELATION &&
172 rte->relid == relid &&
173 rte->alias == NULL)
175 if (result)
176 ereport(ERROR,
177 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
178 errmsg("table reference %u is ambiguous",
179 relid),
180 parser_errposition(pstate, location)));
181 result = rte;
184 return result;
188 * Search the query's CTE namespace for a CTE matching the given unqualified
189 * refname. Return the CTE (and its levelsup count) if a match, or NULL
190 * if no match. We need not worry about multiple matches, since parse_cte.c
191 * rejects WITH lists containing duplicate CTE names.
193 CommonTableExpr *
194 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
195 Index *ctelevelsup)
197 Index levelsup;
199 for (levelsup = 0;
200 pstate != NULL;
201 pstate = pstate->parentParseState, levelsup++)
203 ListCell *lc;
205 foreach(lc, pstate->p_ctenamespace)
207 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
209 if (strcmp(cte->ctename, refname) == 0)
211 *ctelevelsup = levelsup;
212 return cte;
216 return NULL;
220 * Search for a possible "future CTE", that is one that is not yet in scope
221 * according to the WITH scoping rules. This has nothing to do with valid
222 * SQL semantics, but it's important for error reporting purposes.
224 static bool
225 isFutureCTE(ParseState *pstate, const char *refname)
227 for (; pstate != NULL; pstate = pstate->parentParseState)
229 ListCell *lc;
231 foreach(lc, pstate->p_future_ctes)
233 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
235 if (strcmp(cte->ctename, refname) == 0)
236 return true;
239 return false;
243 * searchRangeTable
244 * See if any RangeTblEntry could possibly match the RangeVar.
245 * If so, return a pointer to the RangeTblEntry; else return NULL.
247 * This is different from refnameRangeTblEntry in that it considers every
248 * entry in the ParseState's rangetable(s), not only those that are currently
249 * visible in the p_relnamespace lists. This behavior is invalid per the SQL
250 * spec, and it may give ambiguous results (there might be multiple equally
251 * valid matches, but only one will be returned). This must be used ONLY
252 * as a heuristic in giving suitable error messages. See warnAutoRange.
254 * Notice that we consider both matches on actual relation (or CTE) name
255 * and matches on alias.
257 static RangeTblEntry *
258 searchRangeTable(ParseState *pstate, RangeVar *relation)
260 const char *refname = relation->relname;
261 Oid relId = InvalidOid;
262 CommonTableExpr *cte = NULL;
263 Index ctelevelsup = 0;
264 Index levelsup;
267 * If it's an unqualified name, check for possible CTE matches. A CTE
268 * hides any real relation matches. If no CTE, look for a matching
269 * relation.
271 if (!relation->schemaname)
272 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
273 if (!cte)
274 relId = RangeVarGetRelid(relation, true);
276 /* Now look for RTEs matching either the relation/CTE or the alias */
277 for (levelsup = 0;
278 pstate != NULL;
279 pstate = pstate->parentParseState, levelsup++)
281 ListCell *l;
283 foreach(l, pstate->p_rtable)
285 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
287 if (rte->rtekind == RTE_RELATION &&
288 OidIsValid(relId) &&
289 rte->relid == relId)
290 return rte;
291 if (rte->rtekind == RTE_CTE &&
292 cte != NULL &&
293 rte->ctelevelsup + levelsup == ctelevelsup &&
294 strcmp(rte->ctename, refname) == 0)
295 return rte;
296 if (strcmp(rte->eref->aliasname, refname) == 0)
297 return rte;
300 return NULL;
304 * Check for relation-name conflicts between two relnamespace lists.
305 * Raise an error if any is found.
307 * Note: we assume that each given argument does not contain conflicts
308 * itself; we just want to know if the two can be merged together.
310 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
311 * they have the same eref->aliasname (ie, same relation name), if they
312 * are for different relation OIDs (implying they are in different schemas).
314 void
315 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
316 List *namespace2)
318 ListCell *l1;
320 foreach(l1, namespace1)
322 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
323 const char *aliasname1 = rte1->eref->aliasname;
324 ListCell *l2;
326 foreach(l2, namespace2)
328 RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
330 if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
331 continue; /* definitely no conflict */
332 if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
333 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
334 rte1->relid != rte2->relid)
335 continue; /* no conflict per SQL92 rule */
336 ereport(ERROR,
337 (errcode(ERRCODE_DUPLICATE_ALIAS),
338 errmsg("table name \"%s\" specified more than once",
339 aliasname1)));
345 * given an RTE, return RT index (starting with 1) of the entry,
346 * and optionally get its nesting depth (0 = current). If sublevels_up
347 * is NULL, only consider rels at the current nesting level.
348 * Raises error if RTE not found.
351 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
353 int index;
354 ListCell *l;
356 if (sublevels_up)
357 *sublevels_up = 0;
359 while (pstate != NULL)
361 index = 1;
362 foreach(l, pstate->p_rtable)
364 if (rte == (RangeTblEntry *) lfirst(l))
365 return index;
366 index++;
368 pstate = pstate->parentParseState;
369 if (sublevels_up)
370 (*sublevels_up)++;
371 else
372 break;
375 elog(ERROR, "RTE not found (internal error)");
376 return 0; /* keep compiler quiet */
380 * Given an RT index and nesting depth, find the corresponding RTE.
381 * This is the inverse of RTERangeTablePosn.
383 RangeTblEntry *
384 GetRTEByRangeTablePosn(ParseState *pstate,
385 int varno,
386 int sublevels_up)
388 while (sublevels_up-- > 0)
390 pstate = pstate->parentParseState;
391 Assert(pstate != NULL);
393 Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
394 return rt_fetch(varno, pstate->p_rtable);
398 * Fetch the CTE for a CTE-reference RTE.
400 * rtelevelsup is the number of query levels above the given pstate that the
401 * RTE came from. Callers that don't have this information readily available
402 * may pass -1 instead.
404 CommonTableExpr *
405 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
407 Index levelsup;
408 ListCell *lc;
410 /* Determine RTE's levelsup if caller didn't know it */
411 if (rtelevelsup < 0)
412 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
414 Assert(rte->rtekind == RTE_CTE);
415 levelsup = rte->ctelevelsup + rtelevelsup;
416 while (levelsup-- > 0)
418 pstate = pstate->parentParseState;
419 if (!pstate) /* shouldn't happen */
420 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
422 foreach(lc, pstate->p_ctenamespace)
424 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
426 if (strcmp(cte->ctename, rte->ctename) == 0)
427 return cte;
429 /* shouldn't happen */
430 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
431 return NULL; /* keep compiler quiet */
435 * scanRTEForColumn
436 * Search the column names of a single RTE for the given name.
437 * If found, return an appropriate Var node, else return NULL.
438 * If the name proves ambiguous within this RTE, raise error.
440 * Side effect: if we find a match, mark the RTE as requiring read access
441 * for the column.
443 Node *
444 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
445 int location)
447 Node *result = NULL;
448 int attnum = 0;
449 Var *var;
450 ListCell *c;
453 * Scan the user column names (or aliases) for a match. Complain if
454 * multiple matches.
456 * Note: eref->colnames may include entries for dropped columns, but those
457 * will be empty strings that cannot match any legal SQL identifier, so we
458 * don't bother to test for that case here.
460 * Should this somehow go wrong and we try to access a dropped column,
461 * we'll still catch it by virtue of the checks in
462 * get_rte_attribute_type(), which is called by make_var(). That routine
463 * has to do a cache lookup anyway, so the check there is cheap.
465 foreach(c, rte->eref->colnames)
467 attnum++;
468 if (strcmp(strVal(lfirst(c)), colname) == 0)
470 if (result)
471 ereport(ERROR,
472 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
473 errmsg("column reference \"%s\" is ambiguous",
474 colname),
475 parser_errposition(pstate, location)));
476 var = make_var(pstate, rte, attnum, location);
477 /* Require read access to the column */
478 markVarForSelectPriv(pstate, var, rte);
479 result = (Node *) var;
484 * If we have a unique match, return it. Note that this allows a user
485 * alias to override a system column name (such as OID) without error.
487 if (result)
488 return result;
491 * If the RTE represents a real table, consider system column names.
493 if (rte->rtekind == RTE_RELATION)
495 /* quick check to see if name could be a system column */
496 attnum = specialAttNum(colname);
497 if (attnum != InvalidAttrNumber)
499 /* now check to see if column actually is defined */
500 if (SearchSysCacheExists(ATTNUM,
501 ObjectIdGetDatum(rte->relid),
502 Int16GetDatum(attnum),
503 0, 0))
505 var = make_var(pstate, rte, attnum, location);
506 /* Require read access to the column */
507 markVarForSelectPriv(pstate, var, rte);
508 result = (Node *) var;
513 return result;
517 * colNameToVar
518 * Search for an unqualified column name.
519 * If found, return the appropriate Var node (or expression).
520 * If not found, return NULL. If the name proves ambiguous, raise error.
521 * If localonly is true, only names in the innermost query are considered.
523 Node *
524 colNameToVar(ParseState *pstate, char *colname, bool localonly,
525 int location)
527 Node *result = NULL;
528 ParseState *orig_pstate = pstate;
530 while (pstate != NULL)
532 ListCell *l;
534 foreach(l, pstate->p_varnamespace)
536 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
537 Node *newresult;
539 /* use orig_pstate here to get the right sublevels_up */
540 newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
542 if (newresult)
544 if (result)
545 ereport(ERROR,
546 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
547 errmsg("column reference \"%s\" is ambiguous",
548 colname),
549 parser_errposition(orig_pstate, location)));
550 result = newresult;
554 if (result != NULL || localonly)
555 break; /* found, or don't want to look at parent */
557 pstate = pstate->parentParseState;
560 return result;
564 * qualifiedNameToVar
565 * Search for a qualified column name: either refname.colname or
566 * schemaname.relname.colname.
568 * If found, return the appropriate Var node.
569 * If not found, return NULL. If the name proves ambiguous, raise error.
571 Node *
572 qualifiedNameToVar(ParseState *pstate,
573 char *schemaname,
574 char *refname,
575 char *colname,
576 bool implicitRTEOK,
577 int location)
579 RangeTblEntry *rte;
580 int sublevels_up;
582 rte = refnameRangeTblEntry(pstate, schemaname, refname, location,
583 &sublevels_up);
585 if (rte == NULL)
587 if (!implicitRTEOK)
588 return NULL;
589 rte = addImplicitRTE(pstate,
590 makeRangeVar(schemaname, refname, location));
593 return scanRTEForColumn(pstate, rte, colname, location);
597 * markRTEForSelectPriv
598 * Mark the specified column of an RTE as requiring SELECT privilege
600 * col == InvalidAttrNumber means a "whole row" reference
602 * The caller should pass the actual RTE if it has it handy; otherwise pass
603 * NULL, and we'll look it up here. (This uglification of the API is
604 * worthwhile because nearly all external callers have the RTE at hand.)
606 static void
607 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
608 int rtindex, AttrNumber col)
610 if (rte == NULL)
611 rte = rt_fetch(rtindex, pstate->p_rtable);
613 if (rte->rtekind == RTE_RELATION)
615 /* Make sure the rel as a whole is marked for SELECT access */
616 rte->requiredPerms |= ACL_SELECT;
617 /* Must offset the attnum to fit in a bitmapset */
618 rte->selectedCols = bms_add_member(rte->selectedCols,
619 col - FirstLowInvalidHeapAttributeNumber);
621 else if (rte->rtekind == RTE_JOIN)
623 if (col == InvalidAttrNumber)
626 * A whole-row reference to a join has to be treated as whole-row
627 * references to the two inputs.
629 JoinExpr *j;
631 if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
632 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
633 else
634 j = NULL;
635 if (j == NULL)
636 elog(ERROR, "could not find JoinExpr for whole-row reference");
637 Assert(IsA(j, JoinExpr));
639 /* Note: we can't see FromExpr here */
640 if (IsA(j->larg, RangeTblRef))
642 int varno = ((RangeTblRef *) j->larg)->rtindex;
644 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
646 else if (IsA(j->larg, JoinExpr))
648 int varno = ((JoinExpr *) j->larg)->rtindex;
650 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
652 else
653 elog(ERROR, "unrecognized node type: %d",
654 (int) nodeTag(j->larg));
655 if (IsA(j->rarg, RangeTblRef))
657 int varno = ((RangeTblRef *) j->rarg)->rtindex;
659 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
661 else if (IsA(j->rarg, JoinExpr))
663 int varno = ((JoinExpr *) j->rarg)->rtindex;
665 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
667 else
668 elog(ERROR, "unrecognized node type: %d",
669 (int) nodeTag(j->rarg));
671 else
674 * Regular join attribute, look at the alias-variable list.
676 * The aliasvar could be either a Var or a COALESCE expression,
677 * but in the latter case we should already have marked the two
678 * referent variables as being selected, due to their use in the
679 * JOIN clause. So we need only be concerned with the simple Var
680 * case.
682 Var *aliasvar;
684 Assert(col > 0 && col <= list_length(rte->joinaliasvars));
685 aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
686 if (IsA(aliasvar, Var))
687 markVarForSelectPriv(pstate, aliasvar, NULL);
690 /* other RTE types don't require privilege marking */
694 * markVarForSelectPriv
695 * Mark the RTE referenced by a Var as requiring SELECT privilege
697 * The caller should pass the Var's referenced RTE if it has it handy
698 * (nearly all do); otherwise pass NULL.
700 void
701 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
703 Index lv;
705 Assert(IsA(var, Var));
706 /* Find the appropriate pstate if it's an uplevel Var */
707 for (lv = 0; lv < var->varlevelsup; lv++)
708 pstate = pstate->parentParseState;
709 markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
713 * buildRelationAliases
714 * Construct the eref column name list for a relation RTE.
715 * This code is also used for the case of a function RTE returning
716 * a named composite type.
718 * tupdesc: the physical column information
719 * alias: the user-supplied alias, or NULL if none
720 * eref: the eref Alias to store column names in
722 * eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
723 * empty strings for any dropped columns, so that it will be one-to-one with
724 * physical column numbers.
726 static void
727 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
729 int maxattrs = tupdesc->natts;
730 ListCell *aliaslc;
731 int numaliases;
732 int varattno;
733 int numdropped = 0;
735 Assert(eref->colnames == NIL);
737 if (alias)
739 aliaslc = list_head(alias->colnames);
740 numaliases = list_length(alias->colnames);
741 /* We'll rebuild the alias colname list */
742 alias->colnames = NIL;
744 else
746 aliaslc = NULL;
747 numaliases = 0;
750 for (varattno = 0; varattno < maxattrs; varattno++)
752 Form_pg_attribute attr = tupdesc->attrs[varattno];
753 Value *attrname;
755 if (attr->attisdropped)
757 /* Always insert an empty string for a dropped column */
758 attrname = makeString(pstrdup(""));
759 if (aliaslc)
760 alias->colnames = lappend(alias->colnames, attrname);
761 numdropped++;
763 else if (aliaslc)
765 /* Use the next user-supplied alias */
766 attrname = (Value *) lfirst(aliaslc);
767 aliaslc = lnext(aliaslc);
768 alias->colnames = lappend(alias->colnames, attrname);
770 else
772 attrname = makeString(pstrdup(NameStr(attr->attname)));
773 /* we're done with the alias if any */
776 eref->colnames = lappend(eref->colnames, attrname);
779 /* Too many user-supplied aliases? */
780 if (aliaslc)
781 ereport(ERROR,
782 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
783 errmsg("table \"%s\" has %d columns available but %d columns specified",
784 eref->aliasname, maxattrs - numdropped, numaliases)));
788 * buildScalarFunctionAlias
789 * Construct the eref column name list for a function RTE,
790 * when the function returns a scalar type (not composite or RECORD).
792 * funcexpr: transformed expression tree for the function call
793 * funcname: function name (used only for error message)
794 * alias: the user-supplied alias, or NULL if none
795 * eref: the eref Alias to store column names in
797 * eref->colnames is filled in.
799 static void
800 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
801 Alias *alias, Alias *eref)
803 char *pname;
805 Assert(eref->colnames == NIL);
807 /* Use user-specified column alias if there is one. */
808 if (alias && alias->colnames != NIL)
810 if (list_length(alias->colnames) != 1)
811 ereport(ERROR,
812 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
813 errmsg("too many column aliases specified for function %s",
814 funcname)));
815 eref->colnames = copyObject(alias->colnames);
816 return;
820 * If the expression is a simple function call, and the function has a
821 * single OUT parameter that is named, use the parameter's name.
823 if (funcexpr && IsA(funcexpr, FuncExpr))
825 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
826 if (pname)
828 eref->colnames = list_make1(makeString(pname));
829 return;
834 * Otherwise use the previously-determined alias (not necessarily the
835 * function name!)
837 eref->colnames = list_make1(makeString(eref->aliasname));
841 * Open a table during parse analysis
843 * This is essentially just the same as heap_openrv(), except that it caters
844 * to some parser-specific error reporting needs, notably that it arranges
845 * to include the RangeVar's parse location in any resulting error.
847 * Note: properly, lockmode should be declared LOCKMODE not int, but that
848 * would require importing storage/lock.h into parse_relation.h. Since
849 * LOCKMODE is typedef'd as int anyway, that seems like overkill.
851 Relation
852 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
854 Relation rel;
855 ParseCallbackState pcbstate;
857 setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
858 rel = try_heap_openrv(relation, lockmode);
859 if (rel == NULL)
861 if (relation->schemaname)
862 ereport(ERROR,
863 (errcode(ERRCODE_UNDEFINED_TABLE),
864 errmsg("relation \"%s.%s\" does not exist",
865 relation->schemaname, relation->relname)));
866 else
869 * An unqualified name might have been meant as a reference to
870 * some not-yet-in-scope CTE. The bare "does not exist" message
871 * has proven remarkably unhelpful for figuring out such problems,
872 * so we take pains to offer a specific hint.
874 if (isFutureCTE(pstate, relation->relname))
875 ereport(ERROR,
876 (errcode(ERRCODE_UNDEFINED_TABLE),
877 errmsg("relation \"%s\" does not exist",
878 relation->relname),
879 errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
880 relation->relname),
881 errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
882 else
883 ereport(ERROR,
884 (errcode(ERRCODE_UNDEFINED_TABLE),
885 errmsg("relation \"%s\" does not exist",
886 relation->relname)));
889 cancel_parser_errposition_callback(&pcbstate);
890 return rel;
894 * Add an entry for a relation to the pstate's range table (p_rtable).
896 * If pstate is NULL, we just build an RTE and return it without adding it
897 * to an rtable list.
899 * Note: formerly this checked for refname conflicts, but that's wrong.
900 * Caller is responsible for checking for conflicts in the appropriate scope.
902 RangeTblEntry *
903 addRangeTableEntry(ParseState *pstate,
904 RangeVar *relation,
905 Alias *alias,
906 bool inh,
907 bool inFromCl)
909 RangeTblEntry *rte = makeNode(RangeTblEntry);
910 char *refname = alias ? alias->aliasname : relation->relname;
911 LOCKMODE lockmode;
912 Relation rel;
914 rte->rtekind = RTE_RELATION;
915 rte->alias = alias;
918 * Get the rel's OID. This access also ensures that we have an up-to-date
919 * relcache entry for the rel. Since this is typically the first access
920 * to a rel in a statement, be careful to get the right access level
921 * depending on whether we're doing SELECT FOR UPDATE/SHARE.
923 lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
924 rel = parserOpenTable(pstate, relation, lockmode);
925 rte->relid = RelationGetRelid(rel);
928 * Build the list of effective column names using user-supplied aliases
929 * and/or actual column names.
931 rte->eref = makeAlias(refname, NIL);
932 buildRelationAliases(rel->rd_att, alias, rte->eref);
935 * Drop the rel refcount, but keep the access lock till end of transaction
936 * so that the table can't be deleted or have its schema modified
937 * underneath us.
939 heap_close(rel, NoLock);
941 /*----------
942 * Flags:
943 * - this RTE should be expanded to include descendant tables,
944 * - this RTE is in the FROM clause,
945 * - this RTE should be checked for appropriate access rights.
947 * The initial default on access checks is always check-for-READ-access,
948 * which is the right thing for all except target tables.
949 *----------
951 rte->inh = inh;
952 rte->inFromCl = inFromCl;
954 rte->requiredPerms = ACL_SELECT;
955 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
956 rte->selectedCols = NULL;
957 rte->modifiedCols = NULL;
960 * Add completed RTE to pstate's range table list, but not to join list
961 * nor namespace --- caller must do that if appropriate.
963 if (pstate != NULL)
964 pstate->p_rtable = lappend(pstate->p_rtable, rte);
966 return rte;
970 * Add an entry for a relation to the pstate's range table (p_rtable).
972 * This is just like addRangeTableEntry() except that it makes an RTE
973 * given an already-open relation instead of a RangeVar reference.
975 RangeTblEntry *
976 addRangeTableEntryForRelation(ParseState *pstate,
977 Relation rel,
978 Alias *alias,
979 bool inh,
980 bool inFromCl)
982 RangeTblEntry *rte = makeNode(RangeTblEntry);
983 char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
985 rte->rtekind = RTE_RELATION;
986 rte->alias = alias;
987 rte->relid = RelationGetRelid(rel);
990 * Build the list of effective column names using user-supplied aliases
991 * and/or actual column names.
993 rte->eref = makeAlias(refname, NIL);
994 buildRelationAliases(rel->rd_att, alias, rte->eref);
996 /*----------
997 * Flags:
998 * - this RTE should be expanded to include descendant tables,
999 * - this RTE is in the FROM clause,
1000 * - this RTE should be checked for appropriate access rights.
1002 * The initial default on access checks is always check-for-READ-access,
1003 * which is the right thing for all except target tables.
1004 *----------
1006 rte->inh = inh;
1007 rte->inFromCl = inFromCl;
1009 rte->requiredPerms = ACL_SELECT;
1010 rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
1011 rte->selectedCols = NULL;
1012 rte->modifiedCols = NULL;
1015 * Add completed RTE to pstate's range table list, but not to join list
1016 * nor namespace --- caller must do that if appropriate.
1018 if (pstate != NULL)
1019 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1021 return rte;
1025 * Add an entry for a subquery to the pstate's range table (p_rtable).
1027 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1028 * Note that an alias clause *must* be supplied.
1030 RangeTblEntry *
1031 addRangeTableEntryForSubquery(ParseState *pstate,
1032 Query *subquery,
1033 Alias *alias,
1034 bool inFromCl)
1036 RangeTblEntry *rte = makeNode(RangeTblEntry);
1037 char *refname = alias->aliasname;
1038 Alias *eref;
1039 int numaliases;
1040 int varattno;
1041 ListCell *tlistitem;
1043 rte->rtekind = RTE_SUBQUERY;
1044 rte->relid = InvalidOid;
1045 rte->subquery = subquery;
1046 rte->alias = alias;
1048 eref = copyObject(alias);
1049 numaliases = list_length(eref->colnames);
1051 /* fill in any unspecified alias columns */
1052 varattno = 0;
1053 foreach(tlistitem, subquery->targetList)
1055 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1057 if (te->resjunk)
1058 continue;
1059 varattno++;
1060 Assert(varattno == te->resno);
1061 if (varattno > numaliases)
1063 char *attrname;
1065 attrname = pstrdup(te->resname);
1066 eref->colnames = lappend(eref->colnames, makeString(attrname));
1069 if (varattno < numaliases)
1070 ereport(ERROR,
1071 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1072 errmsg("table \"%s\" has %d columns available but %d columns specified",
1073 refname, varattno, numaliases)));
1075 rte->eref = eref;
1077 /*----------
1078 * Flags:
1079 * - this RTE should be expanded to include descendant tables,
1080 * - this RTE is in the FROM clause,
1081 * - this RTE should be checked for appropriate access rights.
1083 * Subqueries are never checked for access rights.
1084 *----------
1086 rte->inh = false; /* never true for subqueries */
1087 rte->inFromCl = inFromCl;
1089 rte->requiredPerms = 0;
1090 rte->checkAsUser = InvalidOid;
1091 rte->selectedCols = NULL;
1092 rte->modifiedCols = NULL;
1095 * Add completed RTE to pstate's range table list, but not to join list
1096 * nor namespace --- caller must do that if appropriate.
1098 if (pstate != NULL)
1099 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1101 return rte;
1105 * Add an entry for a function to the pstate's range table (p_rtable).
1107 * This is just like addRangeTableEntry() except that it makes a function RTE.
1109 RangeTblEntry *
1110 addRangeTableEntryForFunction(ParseState *pstate,
1111 char *funcname,
1112 Node *funcexpr,
1113 RangeFunction *rangefunc,
1114 bool inFromCl)
1116 RangeTblEntry *rte = makeNode(RangeTblEntry);
1117 TypeFuncClass functypclass;
1118 Oid funcrettype;
1119 TupleDesc tupdesc;
1120 Alias *alias = rangefunc->alias;
1121 List *coldeflist = rangefunc->coldeflist;
1122 Alias *eref;
1124 rte->rtekind = RTE_FUNCTION;
1125 rte->relid = InvalidOid;
1126 rte->subquery = NULL;
1127 rte->funcexpr = funcexpr;
1128 rte->funccoltypes = NIL;
1129 rte->funccoltypmods = NIL;
1130 rte->alias = alias;
1132 eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1133 rte->eref = eref;
1136 * Now determine if the function returns a simple or composite type.
1138 functypclass = get_expr_result_type(funcexpr,
1139 &funcrettype,
1140 &tupdesc);
1143 * A coldeflist is required if the function returns RECORD and hasn't got
1144 * a predetermined record type, and is prohibited otherwise.
1146 if (coldeflist != NIL)
1148 if (functypclass != TYPEFUNC_RECORD)
1149 ereport(ERROR,
1150 (errcode(ERRCODE_SYNTAX_ERROR),
1151 errmsg("a column definition list is only allowed for functions returning \"record\""),
1152 parser_errposition(pstate, exprLocation(funcexpr))));
1154 else
1156 if (functypclass == TYPEFUNC_RECORD)
1157 ereport(ERROR,
1158 (errcode(ERRCODE_SYNTAX_ERROR),
1159 errmsg("a column definition list is required for functions returning \"record\""),
1160 parser_errposition(pstate, exprLocation(funcexpr))));
1163 if (functypclass == TYPEFUNC_COMPOSITE)
1165 /* Composite data type, e.g. a table's row type */
1166 Assert(tupdesc);
1167 /* Build the column alias list */
1168 buildRelationAliases(tupdesc, alias, eref);
1170 else if (functypclass == TYPEFUNC_SCALAR)
1172 /* Base data type, i.e. scalar */
1173 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1175 else if (functypclass == TYPEFUNC_RECORD)
1177 ListCell *col;
1180 * Use the column definition list to form the alias list and
1181 * funccoltypes/funccoltypmods lists.
1183 foreach(col, coldeflist)
1185 ColumnDef *n = (ColumnDef *) lfirst(col);
1186 char *attrname;
1187 Oid attrtype;
1188 int32 attrtypmod;
1190 attrname = pstrdup(n->colname);
1191 if (n->typename->setof)
1192 ereport(ERROR,
1193 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1194 errmsg("column \"%s\" cannot be declared SETOF",
1195 attrname),
1196 parser_errposition(pstate, n->typename->location)));
1197 attrtype = typenameTypeId(pstate, n->typename, &attrtypmod);
1198 eref->colnames = lappend(eref->colnames, makeString(attrname));
1199 rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1200 rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1203 else
1204 ereport(ERROR,
1205 (errcode(ERRCODE_DATATYPE_MISMATCH),
1206 errmsg("function \"%s\" in FROM has unsupported return type %s",
1207 funcname, format_type_be(funcrettype)),
1208 parser_errposition(pstate, exprLocation(funcexpr))));
1210 /*----------
1211 * Flags:
1212 * - this RTE should be expanded to include descendant tables,
1213 * - this RTE is in the FROM clause,
1214 * - this RTE should be checked for appropriate access rights.
1216 * Functions are never checked for access rights (at least, not by
1217 * the RTE permissions mechanism).
1218 *----------
1220 rte->inh = false; /* never true for functions */
1221 rte->inFromCl = inFromCl;
1223 rte->requiredPerms = 0;
1224 rte->checkAsUser = InvalidOid;
1225 rte->selectedCols = NULL;
1226 rte->modifiedCols = NULL;
1229 * Add completed RTE to pstate's range table list, but not to join list
1230 * nor namespace --- caller must do that if appropriate.
1232 if (pstate != NULL)
1233 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1235 return rte;
1239 * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1241 * This is much like addRangeTableEntry() except that it makes a values RTE.
1243 RangeTblEntry *
1244 addRangeTableEntryForValues(ParseState *pstate,
1245 List *exprs,
1246 Alias *alias,
1247 bool inFromCl)
1249 RangeTblEntry *rte = makeNode(RangeTblEntry);
1250 char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1251 Alias *eref;
1252 int numaliases;
1253 int numcolumns;
1255 rte->rtekind = RTE_VALUES;
1256 rte->relid = InvalidOid;
1257 rte->subquery = NULL;
1258 rte->values_lists = exprs;
1259 rte->alias = alias;
1261 eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1263 /* fill in any unspecified alias columns */
1264 numcolumns = list_length((List *) linitial(exprs));
1265 numaliases = list_length(eref->colnames);
1266 while (numaliases < numcolumns)
1268 char attrname[64];
1270 numaliases++;
1271 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1272 eref->colnames = lappend(eref->colnames,
1273 makeString(pstrdup(attrname)));
1275 if (numcolumns < numaliases)
1276 ereport(ERROR,
1277 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1278 errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1279 refname, numcolumns, numaliases)));
1281 rte->eref = eref;
1283 /*----------
1284 * Flags:
1285 * - this RTE should be expanded to include descendant tables,
1286 * - this RTE is in the FROM clause,
1287 * - this RTE should be checked for appropriate access rights.
1289 * Subqueries are never checked for access rights.
1290 *----------
1292 rte->inh = false; /* never true for values RTEs */
1293 rte->inFromCl = inFromCl;
1295 rte->requiredPerms = 0;
1296 rte->checkAsUser = InvalidOid;
1297 rte->selectedCols = NULL;
1298 rte->modifiedCols = NULL;
1301 * Add completed RTE to pstate's range table list, but not to join list
1302 * nor namespace --- caller must do that if appropriate.
1304 if (pstate != NULL)
1305 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1307 return rte;
1311 * Add an entry for a join to the pstate's range table (p_rtable).
1313 * This is much like addRangeTableEntry() except that it makes a join RTE.
1315 RangeTblEntry *
1316 addRangeTableEntryForJoin(ParseState *pstate,
1317 List *colnames,
1318 JoinType jointype,
1319 List *aliasvars,
1320 Alias *alias,
1321 bool inFromCl)
1323 RangeTblEntry *rte = makeNode(RangeTblEntry);
1324 Alias *eref;
1325 int numaliases;
1328 * Fail if join has too many columns --- we must be able to reference any
1329 * of the columns with an AttrNumber.
1331 if (list_length(aliasvars) > MaxAttrNumber)
1332 ereport(ERROR,
1333 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1334 errmsg("joins can have at most %d columns",
1335 MaxAttrNumber)));
1337 rte->rtekind = RTE_JOIN;
1338 rte->relid = InvalidOid;
1339 rte->subquery = NULL;
1340 rte->jointype = jointype;
1341 rte->joinaliasvars = aliasvars;
1342 rte->alias = alias;
1344 eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1345 numaliases = list_length(eref->colnames);
1347 /* fill in any unspecified alias columns */
1348 if (numaliases < list_length(colnames))
1349 eref->colnames = list_concat(eref->colnames,
1350 list_copy_tail(colnames, numaliases));
1352 rte->eref = eref;
1354 /*----------
1355 * Flags:
1356 * - this RTE should be expanded to include descendant tables,
1357 * - this RTE is in the FROM clause,
1358 * - this RTE should be checked for appropriate access rights.
1360 * Joins are never checked for access rights.
1361 *----------
1363 rte->inh = false; /* never true for joins */
1364 rte->inFromCl = inFromCl;
1366 rte->requiredPerms = 0;
1367 rte->checkAsUser = InvalidOid;
1368 rte->selectedCols = NULL;
1369 rte->modifiedCols = NULL;
1372 * Add completed RTE to pstate's range table list, but not to join list
1373 * nor namespace --- caller must do that if appropriate.
1375 if (pstate != NULL)
1376 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1378 return rte;
1382 * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1384 * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1386 RangeTblEntry *
1387 addRangeTableEntryForCTE(ParseState *pstate,
1388 CommonTableExpr *cte,
1389 Index levelsup,
1390 Alias *alias,
1391 bool inFromCl)
1393 RangeTblEntry *rte = makeNode(RangeTblEntry);
1394 char *refname = alias ? alias->aliasname : cte->ctename;
1395 Alias *eref;
1396 int numaliases;
1397 int varattno;
1398 ListCell *lc;
1400 rte->rtekind = RTE_CTE;
1401 rte->ctename = cte->ctename;
1402 rte->ctelevelsup = levelsup;
1404 /* Self-reference if and only if CTE's parse analysis isn't completed */
1405 rte->self_reference = !IsA(cte->ctequery, Query);
1406 Assert(cte->cterecursive || !rte->self_reference);
1407 /* Bump the CTE's refcount if this isn't a self-reference */
1408 if (!rte->self_reference)
1409 cte->cterefcount++;
1411 rte->ctecoltypes = cte->ctecoltypes;
1412 rte->ctecoltypmods = cte->ctecoltypmods;
1414 rte->alias = alias;
1415 if (alias)
1416 eref = copyObject(alias);
1417 else
1418 eref = makeAlias(refname, NIL);
1419 numaliases = list_length(eref->colnames);
1421 /* fill in any unspecified alias columns */
1422 varattno = 0;
1423 foreach(lc, cte->ctecolnames)
1425 varattno++;
1426 if (varattno > numaliases)
1427 eref->colnames = lappend(eref->colnames, lfirst(lc));
1429 if (varattno < numaliases)
1430 ereport(ERROR,
1431 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1432 errmsg("table \"%s\" has %d columns available but %d columns specified",
1433 refname, varattno, numaliases)));
1435 rte->eref = eref;
1437 /*----------
1438 * Flags:
1439 * - this RTE should be expanded to include descendant tables,
1440 * - this RTE is in the FROM clause,
1441 * - this RTE should be checked for appropriate access rights.
1443 * Subqueries are never checked for access rights.
1444 *----------
1446 rte->inh = false; /* never true for subqueries */
1447 rte->inFromCl = inFromCl;
1449 rte->requiredPerms = 0;
1450 rte->checkAsUser = InvalidOid;
1451 rte->selectedCols = NULL;
1452 rte->modifiedCols = NULL;
1455 * Add completed RTE to pstate's range table list, but not to join list
1456 * nor namespace --- caller must do that if appropriate.
1458 if (pstate != NULL)
1459 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1461 return rte;
1466 * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1468 * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1470 static bool
1471 isLockedRel(ParseState *pstate, char *refname)
1473 /* Outer loop to check parent query levels as well as this one */
1474 while (pstate != NULL)
1476 ListCell *l;
1478 foreach(l, pstate->p_locking_clause)
1480 LockingClause *lc = (LockingClause *) lfirst(l);
1482 if (lc->lockedRels == NIL)
1484 /* all tables used in query */
1485 return true;
1487 else
1489 /* just the named tables */
1490 ListCell *l2;
1492 foreach(l2, lc->lockedRels)
1494 RangeVar *thisrel = (RangeVar *) lfirst(l2);
1496 if (strcmp(refname, thisrel->relname) == 0)
1497 return true;
1501 pstate = pstate->parentParseState;
1503 return false;
1507 * Add the given RTE as a top-level entry in the pstate's join list
1508 * and/or name space lists. (We assume caller has checked for any
1509 * namespace conflicts.)
1511 void
1512 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1513 bool addToJoinList,
1514 bool addToRelNameSpace, bool addToVarNameSpace)
1516 if (addToJoinList)
1518 int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1519 RangeTblRef *rtr = makeNode(RangeTblRef);
1521 rtr->rtindex = rtindex;
1522 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1524 if (addToRelNameSpace)
1525 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1526 if (addToVarNameSpace)
1527 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1531 * Add a POSTQUEL-style implicit RTE.
1533 * We assume caller has already checked that there is no RTE or join with
1534 * a conflicting name.
1536 RangeTblEntry *
1537 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1539 CommonTableExpr *cte = NULL;
1540 Index levelsup = 0;
1541 RangeTblEntry *rte;
1543 /* issue warning or error as needed */
1544 warnAutoRange(pstate, relation);
1546 /* if it is an unqualified name, it might be a CTE reference */
1547 if (!relation->schemaname)
1548 cte = scanNameSpaceForCTE(pstate, relation->relname, &levelsup);
1551 * Note that we set inFromCl true, so that the RTE will be listed
1552 * explicitly if the parsetree is ever decompiled by ruleutils.c. This
1553 * provides a migration path for views/rules that were originally written
1554 * with implicit-RTE syntax.
1556 if (cte)
1557 rte = addRangeTableEntryForCTE(pstate, cte, levelsup, NULL, true);
1558 else
1559 rte = addRangeTableEntry(pstate, relation, NULL, false, true);
1560 /* Add to joinlist and relnamespace, but not varnamespace */
1561 addRTEtoQuery(pstate, rte, true, true, false);
1563 return rte;
1567 * expandRTE -- expand the columns of a rangetable entry
1569 * This creates lists of an RTE's column names (aliases if provided, else
1570 * real names) and Vars for each column. Only user columns are considered.
1571 * If include_dropped is FALSE then dropped columns are omitted from the
1572 * results. If include_dropped is TRUE then empty strings and NULL constants
1573 * (not Vars!) are returned for dropped columns.
1575 * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1576 * values to use in the created Vars. Ordinarily rtindex should match the
1577 * actual position of the RTE in its rangetable.
1579 * The output lists go into *colnames and *colvars.
1580 * If only one of the two kinds of output list is needed, pass NULL for the
1581 * output pointer for the unwanted one.
1583 void
1584 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1585 int location, bool include_dropped,
1586 List **colnames, List **colvars)
1588 int varattno;
1590 if (colnames)
1591 *colnames = NIL;
1592 if (colvars)
1593 *colvars = NIL;
1595 switch (rte->rtekind)
1597 case RTE_RELATION:
1598 /* Ordinary relation RTE */
1599 expandRelation(rte->relid, rte->eref,
1600 rtindex, sublevels_up, location,
1601 include_dropped, colnames, colvars);
1602 break;
1603 case RTE_SUBQUERY:
1605 /* Subquery RTE */
1606 ListCell *aliasp_item = list_head(rte->eref->colnames);
1607 ListCell *tlistitem;
1609 varattno = 0;
1610 foreach(tlistitem, rte->subquery->targetList)
1612 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1614 if (te->resjunk)
1615 continue;
1616 varattno++;
1617 Assert(varattno == te->resno);
1619 if (colnames)
1621 /* Assume there is one alias per target item */
1622 char *label = strVal(lfirst(aliasp_item));
1624 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1625 aliasp_item = lnext(aliasp_item);
1628 if (colvars)
1630 Var *varnode;
1632 varnode = makeVar(rtindex, varattno,
1633 exprType((Node *) te->expr),
1634 exprTypmod((Node *) te->expr),
1635 sublevels_up);
1636 varnode->location = location;
1638 *colvars = lappend(*colvars, varnode);
1642 break;
1643 case RTE_FUNCTION:
1645 /* Function RTE */
1646 TypeFuncClass functypclass;
1647 Oid funcrettype;
1648 TupleDesc tupdesc;
1650 functypclass = get_expr_result_type(rte->funcexpr,
1651 &funcrettype,
1652 &tupdesc);
1653 if (functypclass == TYPEFUNC_COMPOSITE)
1655 /* Composite data type, e.g. a table's row type */
1656 Assert(tupdesc);
1657 expandTupleDesc(tupdesc, rte->eref,
1658 rtindex, sublevels_up, location,
1659 include_dropped, colnames, colvars);
1661 else if (functypclass == TYPEFUNC_SCALAR)
1663 /* Base data type, i.e. scalar */
1664 if (colnames)
1665 *colnames = lappend(*colnames,
1666 linitial(rte->eref->colnames));
1668 if (colvars)
1670 Var *varnode;
1672 varnode = makeVar(rtindex, 1,
1673 funcrettype, -1,
1674 sublevels_up);
1675 varnode->location = location;
1677 *colvars = lappend(*colvars, varnode);
1680 else if (functypclass == TYPEFUNC_RECORD)
1682 if (colnames)
1683 *colnames = copyObject(rte->eref->colnames);
1684 if (colvars)
1686 ListCell *l1;
1687 ListCell *l2;
1688 int attnum = 0;
1690 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1692 Oid attrtype = lfirst_oid(l1);
1693 int32 attrtypmod = lfirst_int(l2);
1694 Var *varnode;
1696 attnum++;
1697 varnode = makeVar(rtindex,
1698 attnum,
1699 attrtype,
1700 attrtypmod,
1701 sublevels_up);
1702 varnode->location = location;
1703 *colvars = lappend(*colvars, varnode);
1707 else
1709 /* addRangeTableEntryForFunction should've caught this */
1710 elog(ERROR, "function in FROM has unsupported return type");
1713 break;
1714 case RTE_VALUES:
1716 /* Values RTE */
1717 ListCell *aliasp_item = list_head(rte->eref->colnames);
1718 ListCell *lc;
1720 varattno = 0;
1721 foreach(lc, (List *) linitial(rte->values_lists))
1723 Node *col = (Node *) lfirst(lc);
1725 varattno++;
1726 if (colnames)
1728 /* Assume there is one alias per column */
1729 char *label = strVal(lfirst(aliasp_item));
1731 *colnames = lappend(*colnames,
1732 makeString(pstrdup(label)));
1733 aliasp_item = lnext(aliasp_item);
1736 if (colvars)
1738 Var *varnode;
1740 varnode = makeVar(rtindex, varattno,
1741 exprType(col),
1742 exprTypmod(col),
1743 sublevels_up);
1744 varnode->location = location;
1745 *colvars = lappend(*colvars, varnode);
1749 break;
1750 case RTE_JOIN:
1752 /* Join RTE */
1753 ListCell *colname;
1754 ListCell *aliasvar;
1756 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1758 varattno = 0;
1759 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1761 Node *avar = (Node *) lfirst(aliasvar);
1763 varattno++;
1766 * During ordinary parsing, there will never be any
1767 * deleted columns in the join; but we have to check since
1768 * this routine is also used by the rewriter, and joins
1769 * found in stored rules might have join columns for
1770 * since-deleted columns. This will be signaled by a NULL
1771 * Const in the alias-vars list.
1773 if (IsA(avar, Const))
1775 if (include_dropped)
1777 if (colnames)
1778 *colnames = lappend(*colnames,
1779 makeString(pstrdup("")));
1780 if (colvars)
1781 *colvars = lappend(*colvars,
1782 copyObject(avar));
1784 continue;
1787 if (colnames)
1789 char *label = strVal(lfirst(colname));
1791 *colnames = lappend(*colnames,
1792 makeString(pstrdup(label)));
1795 if (colvars)
1797 Var *varnode;
1799 varnode = makeVar(rtindex, varattno,
1800 exprType(avar),
1801 exprTypmod(avar),
1802 sublevels_up);
1803 varnode->location = location;
1805 *colvars = lappend(*colvars, varnode);
1809 break;
1810 case RTE_CTE:
1812 ListCell *aliasp_item = list_head(rte->eref->colnames);
1813 ListCell *lct;
1814 ListCell *lcm;
1816 varattno = 0;
1817 forboth(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods)
1819 Oid coltype = lfirst_oid(lct);
1820 int32 coltypmod = lfirst_int(lcm);
1822 varattno++;
1824 if (colnames)
1826 /* Assume there is one alias per output column */
1827 char *label = strVal(lfirst(aliasp_item));
1829 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1830 aliasp_item = lnext(aliasp_item);
1833 if (colvars)
1835 Var *varnode;
1837 varnode = makeVar(rtindex, varattno,
1838 coltype, coltypmod,
1839 sublevels_up);
1840 *colvars = lappend(*colvars, varnode);
1844 break;
1845 default:
1846 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1851 * expandRelation -- expandRTE subroutine
1853 static void
1854 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1855 int location, bool include_dropped,
1856 List **colnames, List **colvars)
1858 Relation rel;
1860 /* Get the tupledesc and turn it over to expandTupleDesc */
1861 rel = relation_open(relid, AccessShareLock);
1862 expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1863 location, include_dropped,
1864 colnames, colvars);
1865 relation_close(rel, AccessShareLock);
1869 * expandTupleDesc -- expandRTE subroutine
1871 static void
1872 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1873 int rtindex, int sublevels_up,
1874 int location, bool include_dropped,
1875 List **colnames, List **colvars)
1877 int maxattrs = tupdesc->natts;
1878 int numaliases = list_length(eref->colnames);
1879 int varattno;
1881 for (varattno = 0; varattno < maxattrs; varattno++)
1883 Form_pg_attribute attr = tupdesc->attrs[varattno];
1885 if (attr->attisdropped)
1887 if (include_dropped)
1889 if (colnames)
1890 *colnames = lappend(*colnames, makeString(pstrdup("")));
1891 if (colvars)
1894 * can't use atttypid here, but it doesn't really matter
1895 * what type the Const claims to be.
1897 *colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1900 continue;
1903 if (colnames)
1905 char *label;
1907 if (varattno < numaliases)
1908 label = strVal(list_nth(eref->colnames, varattno));
1909 else
1910 label = NameStr(attr->attname);
1911 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1914 if (colvars)
1916 Var *varnode;
1918 varnode = makeVar(rtindex, attr->attnum,
1919 attr->atttypid, attr->atttypmod,
1920 sublevels_up);
1921 varnode->location = location;
1923 *colvars = lappend(*colvars, varnode);
1929 * expandRelAttrs -
1930 * Workhorse for "*" expansion: produce a list of targetentries
1931 * for the attributes of the RTE
1933 * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1934 * fields of the Vars produced, and location sets their location.
1935 * pstate->p_next_resno determines the resnos assigned to the TLEs.
1936 * The referenced columns are marked as requiring SELECT access.
1938 List *
1939 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1940 int rtindex, int sublevels_up, int location)
1942 List *names,
1943 *vars;
1944 ListCell *name,
1945 *var;
1946 List *te_list = NIL;
1948 expandRTE(rte, rtindex, sublevels_up, location, false,
1949 &names, &vars);
1952 * Require read access to the table. This is normally redundant with the
1953 * markVarForSelectPriv calls below, but not if the table has zero
1954 * columns.
1956 rte->requiredPerms |= ACL_SELECT;
1958 forboth(name, names, var, vars)
1960 char *label = strVal(lfirst(name));
1961 Var *varnode = (Var *) lfirst(var);
1962 TargetEntry *te;
1964 te = makeTargetEntry((Expr *) varnode,
1965 (AttrNumber) pstate->p_next_resno++,
1966 label,
1967 false);
1968 te_list = lappend(te_list, te);
1970 /* Require read access to each column */
1971 markVarForSelectPriv(pstate, varnode, rte);
1974 Assert(name == NULL && var == NULL); /* lists not the same length? */
1976 return te_list;
1980 * get_rte_attribute_name
1981 * Get an attribute name from a RangeTblEntry
1983 * This is unlike get_attname() because we use aliases if available.
1984 * In particular, it will work on an RTE for a subselect or join, whereas
1985 * get_attname() only works on real relations.
1987 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1988 * occurs when a Var represents a whole tuple of a relation.
1990 char *
1991 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1993 if (attnum == InvalidAttrNumber)
1994 return "*";
1997 * If there is a user-written column alias, use it.
1999 if (rte->alias &&
2000 attnum > 0 && attnum <= list_length(rte->alias->colnames))
2001 return strVal(list_nth(rte->alias->colnames, attnum - 1));
2004 * If the RTE is a relation, go to the system catalogs not the
2005 * eref->colnames list. This is a little slower but it will give the
2006 * right answer if the column has been renamed since the eref list was
2007 * built (which can easily happen for rules).
2009 if (rte->rtekind == RTE_RELATION)
2010 return get_relid_attribute_name(rte->relid, attnum);
2013 * Otherwise use the column name from eref. There should always be one.
2015 if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2016 return strVal(list_nth(rte->eref->colnames, attnum - 1));
2018 /* else caller gave us a bogus attnum */
2019 elog(ERROR, "invalid attnum %d for rangetable entry %s",
2020 attnum, rte->eref->aliasname);
2021 return NULL; /* keep compiler quiet */
2025 * get_rte_attribute_type
2026 * Get attribute type information from a RangeTblEntry
2028 void
2029 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2030 Oid *vartype, int32 *vartypmod)
2032 switch (rte->rtekind)
2034 case RTE_RELATION:
2036 /* Plain relation RTE --- get the attribute's type info */
2037 HeapTuple tp;
2038 Form_pg_attribute att_tup;
2040 tp = SearchSysCache(ATTNUM,
2041 ObjectIdGetDatum(rte->relid),
2042 Int16GetDatum(attnum),
2043 0, 0);
2044 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2045 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2046 attnum, rte->relid);
2047 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2050 * If dropped column, pretend it ain't there. See notes in
2051 * scanRTEForColumn.
2053 if (att_tup->attisdropped)
2054 ereport(ERROR,
2055 (errcode(ERRCODE_UNDEFINED_COLUMN),
2056 errmsg("column \"%s\" of relation \"%s\" does not exist",
2057 NameStr(att_tup->attname),
2058 get_rel_name(rte->relid))));
2059 *vartype = att_tup->atttypid;
2060 *vartypmod = att_tup->atttypmod;
2061 ReleaseSysCache(tp);
2063 break;
2064 case RTE_SUBQUERY:
2066 /* Subselect RTE --- get type info from subselect's tlist */
2067 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2068 attnum);
2070 if (te == NULL || te->resjunk)
2071 elog(ERROR, "subquery %s does not have attribute %d",
2072 rte->eref->aliasname, attnum);
2073 *vartype = exprType((Node *) te->expr);
2074 *vartypmod = exprTypmod((Node *) te->expr);
2076 break;
2077 case RTE_FUNCTION:
2079 /* Function RTE */
2080 TypeFuncClass functypclass;
2081 Oid funcrettype;
2082 TupleDesc tupdesc;
2084 functypclass = get_expr_result_type(rte->funcexpr,
2085 &funcrettype,
2086 &tupdesc);
2088 if (functypclass == TYPEFUNC_COMPOSITE)
2090 /* Composite data type, e.g. a table's row type */
2091 Form_pg_attribute att_tup;
2093 Assert(tupdesc);
2094 /* this is probably a can't-happen case */
2095 if (attnum < 1 || attnum > tupdesc->natts)
2096 ereport(ERROR,
2097 (errcode(ERRCODE_UNDEFINED_COLUMN),
2098 errmsg("column %d of relation \"%s\" does not exist",
2099 attnum,
2100 rte->eref->aliasname)));
2102 att_tup = tupdesc->attrs[attnum - 1];
2105 * If dropped column, pretend it ain't there. See notes
2106 * in scanRTEForColumn.
2108 if (att_tup->attisdropped)
2109 ereport(ERROR,
2110 (errcode(ERRCODE_UNDEFINED_COLUMN),
2111 errmsg("column \"%s\" of relation \"%s\" does not exist",
2112 NameStr(att_tup->attname),
2113 rte->eref->aliasname)));
2114 *vartype = att_tup->atttypid;
2115 *vartypmod = att_tup->atttypmod;
2117 else if (functypclass == TYPEFUNC_SCALAR)
2119 /* Base data type, i.e. scalar */
2120 *vartype = funcrettype;
2121 *vartypmod = -1;
2123 else if (functypclass == TYPEFUNC_RECORD)
2125 *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2126 *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2128 else
2130 /* addRangeTableEntryForFunction should've caught this */
2131 elog(ERROR, "function in FROM has unsupported return type");
2134 break;
2135 case RTE_VALUES:
2137 /* Values RTE --- get type info from first sublist */
2138 List *collist = (List *) linitial(rte->values_lists);
2139 Node *col;
2141 if (attnum < 1 || attnum > list_length(collist))
2142 elog(ERROR, "values list %s does not have attribute %d",
2143 rte->eref->aliasname, attnum);
2144 col = (Node *) list_nth(collist, attnum - 1);
2145 *vartype = exprType(col);
2146 *vartypmod = exprTypmod(col);
2148 break;
2149 case RTE_JOIN:
2152 * Join RTE --- get type info from join RTE's alias variable
2154 Node *aliasvar;
2156 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2157 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2158 *vartype = exprType(aliasvar);
2159 *vartypmod = exprTypmod(aliasvar);
2161 break;
2162 case RTE_CTE:
2164 /* CTE RTE --- get type info from lists in the RTE */
2165 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2166 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2167 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2169 break;
2170 default:
2171 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2176 * get_rte_attribute_is_dropped
2177 * Check whether attempted attribute ref is to a dropped column
2179 bool
2180 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2182 bool result;
2184 switch (rte->rtekind)
2186 case RTE_RELATION:
2189 * Plain relation RTE --- get the attribute's catalog entry
2191 HeapTuple tp;
2192 Form_pg_attribute att_tup;
2194 tp = SearchSysCache(ATTNUM,
2195 ObjectIdGetDatum(rte->relid),
2196 Int16GetDatum(attnum),
2197 0, 0);
2198 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2199 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2200 attnum, rte->relid);
2201 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2202 result = att_tup->attisdropped;
2203 ReleaseSysCache(tp);
2205 break;
2206 case RTE_SUBQUERY:
2207 case RTE_VALUES:
2208 case RTE_CTE:
2209 /* Subselect, Values, CTE RTEs never have dropped columns */
2210 result = false;
2211 break;
2212 case RTE_JOIN:
2215 * A join RTE would not have dropped columns when constructed,
2216 * but one in a stored rule might contain columns that were
2217 * dropped from the underlying tables, if said columns are
2218 * nowhere explicitly referenced in the rule. This will be
2219 * signaled to us by a NULL Const in the joinaliasvars list.
2221 Var *aliasvar;
2223 if (attnum <= 0 ||
2224 attnum > list_length(rte->joinaliasvars))
2225 elog(ERROR, "invalid varattno %d", attnum);
2226 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2228 result = IsA(aliasvar, Const);
2230 break;
2231 case RTE_FUNCTION:
2233 /* Function RTE */
2234 Oid funcrettype = exprType(rte->funcexpr);
2235 Oid funcrelid = typeidTypeRelid(funcrettype);
2237 if (OidIsValid(funcrelid))
2240 * Composite data type, i.e. a table's row type
2242 * Same as ordinary relation RTE
2244 HeapTuple tp;
2245 Form_pg_attribute att_tup;
2247 tp = SearchSysCache(ATTNUM,
2248 ObjectIdGetDatum(funcrelid),
2249 Int16GetDatum(attnum),
2250 0, 0);
2251 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2252 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2253 attnum, funcrelid);
2254 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2255 result = att_tup->attisdropped;
2256 ReleaseSysCache(tp);
2258 else
2261 * Must be a base data type, i.e. scalar
2263 result = false;
2266 break;
2267 default:
2268 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2269 result = false; /* keep compiler quiet */
2272 return result;
2276 * Given a targetlist and a resno, return the matching TargetEntry
2278 * Returns NULL if resno is not present in list.
2280 * Note: we need to search, rather than just indexing with list_nth(),
2281 * because not all tlists are sorted by resno.
2283 TargetEntry *
2284 get_tle_by_resno(List *tlist, AttrNumber resno)
2286 ListCell *l;
2288 foreach(l, tlist)
2290 TargetEntry *tle = (TargetEntry *) lfirst(l);
2292 if (tle->resno == resno)
2293 return tle;
2295 return NULL;
2299 * Given a Query and rangetable index, return relation's RowMarkClause if any
2301 * Returns NULL if relation is not selected FOR UPDATE/SHARE
2303 RowMarkClause *
2304 get_rowmark(Query *qry, Index rtindex)
2306 ListCell *l;
2308 foreach(l, qry->rowMarks)
2310 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2312 if (rc->rti == rtindex)
2313 return rc;
2315 return NULL;
2319 * given relation and att name, return attnum of variable
2321 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2323 * This should only be used if the relation is already
2324 * heap_open()'ed. Use the cache version get_attnum()
2325 * for access to non-opened relations.
2328 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2330 int i;
2332 for (i = 0; i < rd->rd_rel->relnatts; i++)
2334 Form_pg_attribute att = rd->rd_att->attrs[i];
2336 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2337 return i + 1;
2340 if (sysColOK)
2342 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2344 if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2345 return i;
2349 /* on failure */
2350 return InvalidAttrNumber;
2353 /* specialAttNum()
2355 * Check attribute name to see if it is "special", e.g. "oid".
2356 * - thomas 2000-02-07
2358 * Note: this only discovers whether the name could be a system attribute.
2359 * Caller needs to verify that it really is an attribute of the rel,
2360 * at least in the case of "oid", which is now optional.
2362 static int
2363 specialAttNum(const char *attname)
2365 Form_pg_attribute sysatt;
2367 sysatt = SystemAttributeByName(attname,
2368 true /* "oid" will be accepted */ );
2369 if (sysatt != NULL)
2370 return sysatt->attnum;
2371 return InvalidAttrNumber;
2376 * given attribute id, return name of that attribute
2378 * This should only be used if the relation is already
2379 * heap_open()'ed. Use the cache version get_atttype()
2380 * for access to non-opened relations.
2382 Name
2383 attnumAttName(Relation rd, int attid)
2385 if (attid <= 0)
2387 Form_pg_attribute sysatt;
2389 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2390 return &sysatt->attname;
2392 if (attid > rd->rd_att->natts)
2393 elog(ERROR, "invalid attribute number %d", attid);
2394 return &rd->rd_att->attrs[attid - 1]->attname;
2398 * given attribute id, return type of that attribute
2400 * This should only be used if the relation is already
2401 * heap_open()'ed. Use the cache version get_atttype()
2402 * for access to non-opened relations.
2405 attnumTypeId(Relation rd, int attid)
2407 if (attid <= 0)
2409 Form_pg_attribute sysatt;
2411 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2412 return sysatt->atttypid;
2414 if (attid > rd->rd_att->natts)
2415 elog(ERROR, "invalid attribute number %d", attid);
2416 return rd->rd_att->attrs[attid - 1]->atttypid;
2420 * Generate a warning or error about an implicit RTE, if appropriate.
2422 * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
2423 * a warning.
2425 static void
2426 warnAutoRange(ParseState *pstate, RangeVar *relation)
2428 RangeTblEntry *rte;
2429 int sublevels_up;
2430 const char *badAlias = NULL;
2433 * Check to see if there are any potential matches in the query's
2434 * rangetable. This affects the message we provide.
2436 rte = searchRangeTable(pstate, relation);
2439 * If we found a match that has an alias and the alias is visible in the
2440 * namespace, then the problem is probably use of the relation's real name
2441 * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2442 * common enough to justify a specific hint.
2444 * If we found a match that doesn't meet those criteria, assume the
2445 * problem is illegal use of a relation outside its scope, as in the
2446 * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2448 if (rte && rte->alias &&
2449 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2450 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2451 relation->location,
2452 &sublevels_up) == rte)
2453 badAlias = rte->eref->aliasname;
2455 if (!add_missing_from)
2457 if (rte)
2458 ereport(ERROR,
2459 (errcode(ERRCODE_UNDEFINED_TABLE),
2460 errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2461 relation->relname),
2462 (badAlias ?
2463 errhint("Perhaps you meant to reference the table alias \"%s\".",
2464 badAlias) :
2465 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2466 rte->eref->aliasname)),
2467 parser_errposition(pstate, relation->location)));
2468 else
2469 ereport(ERROR,
2470 (errcode(ERRCODE_UNDEFINED_TABLE),
2471 errmsg("missing FROM-clause entry for table \"%s\"",
2472 relation->relname),
2473 parser_errposition(pstate, relation->location)));
2475 else
2477 /* just issue a warning */
2478 ereport(NOTICE,
2479 (errcode(ERRCODE_UNDEFINED_TABLE),
2480 errmsg("adding missing FROM-clause entry for table \"%s\"",
2481 relation->relname),
2482 (badAlias ?
2483 errhint("Perhaps you meant to reference the table alias \"%s\".",
2484 badAlias) :
2485 (rte ?
2486 errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2487 rte->eref->aliasname) : 0)),
2488 parser_errposition(pstate, relation->location)));