]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
Improve the recently-added support for properly pluralized error messages
[postgresql] / src / backend / parser / parse_relation.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_relation.c
4  *        parser support routines dealing with relations
5  *
6  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_relation.c,v 1.141 2009/01/22 20:16:05 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <ctype.h>
18
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"
33
34
35 /* GUC parameter */
36 bool            add_missing_from;
37
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);
55
56
57 /*
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.
61  *
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.
65  *
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().
71  *
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.
77  */
78 RangeTblEntry *
79 refnameRangeTblEntry(ParseState *pstate,
80                                          const char *schemaname,
81                                          const char *refname,
82                                          int location,
83                                          int *sublevels_up)
84 {
85         Oid                     relId = InvalidOid;
86
87         if (sublevels_up)
88                 *sublevels_up = 0;
89
90         if (schemaname != NULL)
91         {
92                 Oid                     namespaceId;
93
94                 namespaceId = LookupExplicitNamespace(schemaname);
95                 relId = get_relname_relid(refname, namespaceId);
96                 if (!OidIsValid(relId))
97                         return NULL;
98         }
99
100         while (pstate != NULL)
101         {
102                 RangeTblEntry *result;
103
104                 if (OidIsValid(relId))
105                         result = scanNameSpaceForRelid(pstate, relId, location);
106                 else
107                         result = scanNameSpaceForRefname(pstate, refname, location);
108
109                 if (result)
110                         return result;
111
112                 if (sublevels_up)
113                         (*sublevels_up)++;
114                 else
115                         break;
116
117                 pstate = pstate->parentParseState;
118         }
119         return NULL;
120 }
121
122 /*
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.
126  */
127 static RangeTblEntry *
128 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
129 {
130         RangeTblEntry *result = NULL;
131         ListCell   *l;
132
133         foreach(l, pstate->p_relnamespace)
134         {
135                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
136
137                 if (strcmp(rte->eref->aliasname, refname) == 0)
138                 {
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;
146                 }
147         }
148         return result;
149 }
150
151 /*
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).
156  *
157  * See the comments for refnameRangeTblEntry to understand why this
158  * acts the way it does.
159  */
160 static RangeTblEntry *
161 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
162 {
163         RangeTblEntry *result = NULL;
164         ListCell   *l;
165
166         foreach(l, pstate->p_relnamespace)
167         {
168                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
169
170                 /* yes, the test for alias == NULL should be there... */
171                 if (rte->rtekind == RTE_RELATION &&
172                         rte->relid == relid &&
173                         rte->alias == NULL)
174                 {
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;
182                 }
183         }
184         return result;
185 }
186
187 /*
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.
192  */
193 CommonTableExpr *
194 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
195                                         Index *ctelevelsup)
196 {
197         Index   levelsup;
198
199         for (levelsup = 0;
200                  pstate != NULL;
201                  pstate = pstate->parentParseState, levelsup++)
202         {
203                 ListCell *lc;
204
205                 foreach(lc, pstate->p_ctenamespace)
206                 {
207                         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
208
209                         if (strcmp(cte->ctename, refname) == 0)
210                         {
211                                 *ctelevelsup = levelsup;
212                                 return cte;
213                         }
214                 }
215         }
216         return NULL;
217 }
218
219 /*
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.
223  */
224 static bool
225 isFutureCTE(ParseState *pstate, const char *refname)
226 {
227         for (; pstate != NULL; pstate = pstate->parentParseState)
228         {
229                 ListCell *lc;
230
231                 foreach(lc, pstate->p_future_ctes)
232                 {
233                         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
234
235                         if (strcmp(cte->ctename, refname) == 0)
236                                 return true;
237                 }
238         }
239         return false;
240 }
241
242 /*
243  * searchRangeTable
244  *        See if any RangeTblEntry could possibly match the RangeVar.
245  *        If so, return a pointer to the RangeTblEntry; else return NULL.
246  *
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.
253  *
254  * Notice that we consider both matches on actual relation (or CTE) name
255  * and matches on alias.
256  */
257 static RangeTblEntry *
258 searchRangeTable(ParseState *pstate, RangeVar *relation)
259 {
260         const char *refname = relation->relname;
261         Oid                     relId = InvalidOid;
262         CommonTableExpr *cte = NULL;
263         Index           ctelevelsup = 0;
264         Index           levelsup;
265
266         /*
267          * If it's an unqualified name, check for possible CTE matches.
268          * A CTE hides any real relation matches.  If no CTE, look for
269          * a matching relation.
270          */
271         if (!relation->schemaname)
272                 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
273         if (!cte)
274                 relId = RangeVarGetRelid(relation, true);
275
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++)
280         {
281                 ListCell   *l;
282
283                 foreach(l, pstate->p_rtable)
284                 {
285                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
286
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;
298                 }
299         }
300         return NULL;
301 }
302
303 /*
304  * Check for relation-name conflicts between two relnamespace lists.
305  * Raise an error if any is found.
306  *
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.
309  *
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).
313  */
314 void
315 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
316                                                 List *namespace2)
317 {
318         ListCell   *l1;
319
320         foreach(l1, namespace1)
321         {
322                 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
323                 const char *aliasname1 = rte1->eref->aliasname;
324                 ListCell   *l2;
325
326                 foreach(l2, namespace2)
327                 {
328                         RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
329
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)));
340                 }
341         }
342 }
343
344 /*
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.
349  */
350 int
351 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
352 {
353         int                     index;
354         ListCell   *l;
355
356         if (sublevels_up)
357                 *sublevels_up = 0;
358
359         while (pstate != NULL)
360         {
361                 index = 1;
362                 foreach(l, pstate->p_rtable)
363                 {
364                         if (rte == (RangeTblEntry *) lfirst(l))
365                                 return index;
366                         index++;
367                 }
368                 pstate = pstate->parentParseState;
369                 if (sublevels_up)
370                         (*sublevels_up)++;
371                 else
372                         break;
373         }
374
375         elog(ERROR, "RTE not found (internal error)");
376         return 0;                                       /* keep compiler quiet */
377 }
378
379 /*
380  * Given an RT index and nesting depth, find the corresponding RTE.
381  * This is the inverse of RTERangeTablePosn.
382  */
383 RangeTblEntry *
384 GetRTEByRangeTablePosn(ParseState *pstate,
385                                            int varno,
386                                            int sublevels_up)
387 {
388         while (sublevels_up-- > 0)
389         {
390                 pstate = pstate->parentParseState;
391                 Assert(pstate != NULL);
392         }
393         Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
394         return rt_fetch(varno, pstate->p_rtable);
395 }
396
397 /*
398  * Fetch the CTE for a CTE-reference RTE.
399  *
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.
403  */
404 CommonTableExpr *
405 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
406 {
407         Index           levelsup;
408         ListCell   *lc;
409
410         /* Determine RTE's levelsup if caller didn't know it */
411         if (rtelevelsup < 0)
412                 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
413
414         Assert(rte->rtekind == RTE_CTE);
415         levelsup = rte->ctelevelsup + rtelevelsup;
416         while (levelsup-- > 0)
417         {
418                 pstate = pstate->parentParseState;
419                 if (!pstate)                    /* shouldn't happen */
420                         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
421         }
422         foreach(lc, pstate->p_ctenamespace)
423         {
424                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
425
426                 if (strcmp(cte->ctename, rte->ctename) == 0)
427                         return cte;
428         }
429         /* shouldn't happen */
430         elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
431         return NULL;                            /* keep compiler quiet */
432 }
433
434 /*
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.
439  *
440  * Side effect: if we find a match, mark the RTE as requiring read access
441  * for the column.
442  */
443 Node *
444 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
445                                  int location)
446 {
447         Node       *result = NULL;
448         int                     attnum = 0;
449         Var                *var;
450         ListCell   *c;
451
452         /*
453          * Scan the user column names (or aliases) for a match. Complain if
454          * multiple matches.
455          *
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.
459          *
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.
464          */
465         foreach(c, rte->eref->colnames)
466         {
467                 attnum++;
468                 if (strcmp(strVal(lfirst(c)), colname) == 0)
469                 {
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;
480                 }
481         }
482
483         /*
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.
486          */
487         if (result)
488                 return result;
489
490         /*
491          * If the RTE represents a real table, consider system column names.
492          */
493         if (rte->rtekind == RTE_RELATION)
494         {
495                 /* quick check to see if name could be a system column */
496                 attnum = specialAttNum(colname);
497                 if (attnum != InvalidAttrNumber)
498                 {
499                         /* now check to see if column actually is defined */
500                         if (SearchSysCacheExists(ATTNUM,
501                                                                          ObjectIdGetDatum(rte->relid),
502                                                                          Int16GetDatum(attnum),
503                                                                          0, 0))
504                         {
505                                 var = make_var(pstate, rte, attnum, location);
506                                 /* Require read access to the column */
507                                 markVarForSelectPriv(pstate, var, rte);
508                                 result = (Node *) var;
509                         }
510                 }
511         }
512
513         return result;
514 }
515
516 /*
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.
522  */
523 Node *
524 colNameToVar(ParseState *pstate, char *colname, bool localonly,
525                          int location)
526 {
527         Node       *result = NULL;
528         ParseState *orig_pstate = pstate;
529
530         while (pstate != NULL)
531         {
532                 ListCell   *l;
533
534                 foreach(l, pstate->p_varnamespace)
535                 {
536                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
537                         Node       *newresult;
538
539                         /* use orig_pstate here to get the right sublevels_up */
540                         newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
541
542                         if (newresult)
543                         {
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;
551                         }
552                 }
553
554                 if (result != NULL || localonly)
555                         break;                          /* found, or don't want to look at parent */
556
557                 pstate = pstate->parentParseState;
558         }
559
560         return result;
561 }
562
563 /*
564  * qualifiedNameToVar
565  *        Search for a qualified column name: either refname.colname or
566  *        schemaname.relname.colname.
567  *
568  *        If found, return the appropriate Var node.
569  *        If not found, return NULL.  If the name proves ambiguous, raise error.
570  */
571 Node *
572 qualifiedNameToVar(ParseState *pstate,
573                                    char *schemaname,
574                                    char *refname,
575                                    char *colname,
576                                    bool implicitRTEOK,
577                                    int location)
578 {
579         RangeTblEntry *rte;
580         int                     sublevels_up;
581
582         rte = refnameRangeTblEntry(pstate, schemaname, refname, location,
583                                                            &sublevels_up);
584
585         if (rte == NULL)
586         {
587                 if (!implicitRTEOK)
588                         return NULL;
589                 rte = addImplicitRTE(pstate,
590                                                          makeRangeVar(schemaname, refname, location));
591         }
592
593         return scanRTEForColumn(pstate, rte, colname, location);
594 }
595
596 /*
597  * markRTEForSelectPriv
598  *         Mark the specified column of an RTE as requiring SELECT privilege
599  *
600  * col == InvalidAttrNumber means a "whole row" reference
601  *
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.)
605  */
606 static void
607 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
608                                          int rtindex, AttrNumber col)
609 {
610         if (rte == NULL)
611                 rte = rt_fetch(rtindex, pstate->p_rtable);
612
613         if (rte->rtekind == RTE_RELATION)
614         {
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);
620         }
621         else if (rte->rtekind == RTE_JOIN)
622         {
623                 if (col == InvalidAttrNumber)
624                 {
625                         /*
626                          * A whole-row reference to a join has to be treated as
627                          * whole-row references to the two inputs.
628                          */
629                         JoinExpr   *j;
630
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));
638
639                         /* Note: we can't see FromExpr here */
640                         if (IsA(j->larg, RangeTblRef))
641                         {
642                                 int             varno = ((RangeTblRef *) j->larg)->rtindex;
643
644                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
645                         }
646                         else if (IsA(j->larg, JoinExpr))
647                         {
648                                 int             varno = ((JoinExpr *) j->larg)->rtindex;
649
650                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
651                         }
652                         else
653                                 elog(ERROR, "unrecognized node type: %d",
654                                          (int) nodeTag(j->larg));
655                         if (IsA(j->rarg, RangeTblRef))
656                         {
657                                 int             varno = ((RangeTblRef *) j->rarg)->rtindex;
658
659                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
660                         }
661                         else if (IsA(j->rarg, JoinExpr))
662                         {
663                                 int             varno = ((JoinExpr *) j->rarg)->rtindex;
664
665                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
666                         }
667                         else
668                                 elog(ERROR, "unrecognized node type: %d",
669                                          (int) nodeTag(j->rarg));
670                 }
671                 else
672                 {
673                         /*
674                          * Regular join attribute, look at the alias-variable list.
675                          *
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
680                          * Var case.
681                          */
682                         Var        *aliasvar;
683
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);
688                 }
689         }
690         /* other RTE types don't require privilege marking */
691 }
692
693 /*
694  * markVarForSelectPriv
695  *         Mark the RTE referenced by a Var as requiring SELECT privilege
696  *
697  * The caller should pass the Var's referenced RTE if it has it handy
698  * (nearly all do); otherwise pass NULL.
699  */
700 void
701 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
702 {
703         Index   lv;
704
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);
710 }
711
712 /*
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.
717  *
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
721  *
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.
725  */
726 static void
727 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
728 {
729         int                     maxattrs = tupdesc->natts;
730         ListCell   *aliaslc;
731         int                     numaliases;
732         int                     varattno;
733         int                     numdropped = 0;
734
735         Assert(eref->colnames == NIL);
736
737         if (alias)
738         {
739                 aliaslc = list_head(alias->colnames);
740                 numaliases = list_length(alias->colnames);
741                 /* We'll rebuild the alias colname list */
742                 alias->colnames = NIL;
743         }
744         else
745         {
746                 aliaslc = NULL;
747                 numaliases = 0;
748         }
749
750         for (varattno = 0; varattno < maxattrs; varattno++)
751         {
752                 Form_pg_attribute attr = tupdesc->attrs[varattno];
753                 Value      *attrname;
754
755                 if (attr->attisdropped)
756                 {
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++;
762                 }
763                 else if (aliaslc)
764                 {
765                         /* Use the next user-supplied alias */
766                         attrname = (Value *) lfirst(aliaslc);
767                         aliaslc = lnext(aliaslc);
768                         alias->colnames = lappend(alias->colnames, attrname);
769                 }
770                 else
771                 {
772                         attrname = makeString(pstrdup(NameStr(attr->attname)));
773                         /* we're done with the alias if any */
774                 }
775
776                 eref->colnames = lappend(eref->colnames, attrname);
777         }
778
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)));
785 }
786
787 /*
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).
791  *
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
796  *
797  * eref->colnames is filled in.
798  */
799 static void
800 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
801                                                  Alias *alias, Alias *eref)
802 {
803         char       *pname;
804
805         Assert(eref->colnames == NIL);
806
807         /* Use user-specified column alias if there is one. */
808         if (alias && alias->colnames != NIL)
809         {
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;
817         }
818
819         /*
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.
822          */
823         if (funcexpr && IsA(funcexpr, FuncExpr))
824         {
825                 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
826                 if (pname)
827                 {
828                         eref->colnames = list_make1(makeString(pname));
829                         return;
830                 }
831         }
832
833         /*
834          * Otherwise use the previously-determined alias (not necessarily the
835          * function name!)
836          */
837         eref->colnames = list_make1(makeString(eref->aliasname));
838 }
839
840 /*
841  * Open a table during parse analysis
842  *
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.
846  *
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.
850  */
851 Relation
852 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
853 {
854         Relation        rel;
855         ParseCallbackState pcbstate;
856
857         setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
858         rel = try_heap_openrv(relation, lockmode);
859         if (rel == NULL)
860         {
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
867                 {
868                         /*
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.
873                          */
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)));
887                 }
888         }
889         cancel_parser_errposition_callback(&pcbstate);
890         return rel;
891 }
892
893 /*
894  * Add an entry for a relation to the pstate's range table (p_rtable).
895  *
896  * If pstate is NULL, we just build an RTE and return it without adding it
897  * to an rtable list.
898  *
899  * Note: formerly this checked for refname conflicts, but that's wrong.
900  * Caller is responsible for checking for conflicts in the appropriate scope.
901  */
902 RangeTblEntry *
903 addRangeTableEntry(ParseState *pstate,
904                                    RangeVar *relation,
905                                    Alias *alias,
906                                    bool inh,
907                                    bool inFromCl)
908 {
909         RangeTblEntry *rte = makeNode(RangeTblEntry);
910         char       *refname = alias ? alias->aliasname : relation->relname;
911         LOCKMODE        lockmode;
912         Relation        rel;
913
914         rte->rtekind = RTE_RELATION;
915         rte->alias = alias;
916
917         /*
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.
922          */
923         lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
924         rel = parserOpenTable(pstate, relation, lockmode);
925         rte->relid = RelationGetRelid(rel);
926
927         /*
928          * Build the list of effective column names using user-supplied aliases
929          * and/or actual column names.
930          */
931         rte->eref = makeAlias(refname, NIL);
932         buildRelationAliases(rel->rd_att, alias, rte->eref);
933
934         /*
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.
938          */
939         heap_close(rel, NoLock);
940
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.
946          *
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          *----------
950          */
951         rte->inh = inh;
952         rte->inFromCl = inFromCl;
953
954         rte->requiredPerms = ACL_SELECT;
955         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
956         rte->selectedCols = NULL;
957         rte->modifiedCols = NULL;
958
959         /*
960          * Add completed RTE to pstate's range table list, but not to join list
961          * nor namespace --- caller must do that if appropriate.
962          */
963         if (pstate != NULL)
964                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
965
966         return rte;
967 }
968
969 /*
970  * Add an entry for a relation to the pstate's range table (p_rtable).
971  *
972  * This is just like addRangeTableEntry() except that it makes an RTE
973  * given an already-open relation instead of a RangeVar reference.
974  */
975 RangeTblEntry *
976 addRangeTableEntryForRelation(ParseState *pstate,
977                                                           Relation rel,
978                                                           Alias *alias,
979                                                           bool inh,
980                                                           bool inFromCl)
981 {
982         RangeTblEntry *rte = makeNode(RangeTblEntry);
983         char       *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
984
985         rte->rtekind = RTE_RELATION;
986         rte->alias = alias;
987         rte->relid = RelationGetRelid(rel);
988
989         /*
990          * Build the list of effective column names using user-supplied aliases
991          * and/or actual column names.
992          */
993         rte->eref = makeAlias(refname, NIL);
994         buildRelationAliases(rel->rd_att, alias, rte->eref);
995
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.
1001          *
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          *----------
1005          */
1006         rte->inh = inh;
1007         rte->inFromCl = inFromCl;
1008
1009         rte->requiredPerms = ACL_SELECT;
1010         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
1011         rte->selectedCols = NULL;
1012         rte->modifiedCols = NULL;
1013
1014         /*
1015          * Add completed RTE to pstate's range table list, but not to join list
1016          * nor namespace --- caller must do that if appropriate.
1017          */
1018         if (pstate != NULL)
1019                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1020
1021         return rte;
1022 }
1023
1024 /*
1025  * Add an entry for a subquery to the pstate's range table (p_rtable).
1026  *
1027  * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1028  * Note that an alias clause *must* be supplied.
1029  */
1030 RangeTblEntry *
1031 addRangeTableEntryForSubquery(ParseState *pstate,
1032                                                           Query *subquery,
1033                                                           Alias *alias,
1034                                                           bool inFromCl)
1035 {
1036         RangeTblEntry *rte = makeNode(RangeTblEntry);
1037         char       *refname = alias->aliasname;
1038         Alias      *eref;
1039         int                     numaliases;
1040         int                     varattno;
1041         ListCell   *tlistitem;
1042
1043         rte->rtekind = RTE_SUBQUERY;
1044         rte->relid = InvalidOid;
1045         rte->subquery = subquery;
1046         rte->alias = alias;
1047
1048         eref = copyObject(alias);
1049         numaliases = list_length(eref->colnames);
1050
1051         /* fill in any unspecified alias columns */
1052         varattno = 0;
1053         foreach(tlistitem, subquery->targetList)
1054         {
1055                 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1056
1057                 if (te->resjunk)
1058                         continue;
1059                 varattno++;
1060                 Assert(varattno == te->resno);
1061                 if (varattno > numaliases)
1062                 {
1063                         char       *attrname;
1064
1065                         attrname = pstrdup(te->resname);
1066                         eref->colnames = lappend(eref->colnames, makeString(attrname));
1067                 }
1068         }
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)));
1074
1075         rte->eref = eref;
1076
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.
1082          *
1083          * Subqueries are never checked for access rights.
1084          *----------
1085          */
1086         rte->inh = false;                       /* never true for subqueries */
1087         rte->inFromCl = inFromCl;
1088
1089         rte->requiredPerms = 0;
1090         rte->checkAsUser = InvalidOid;
1091         rte->selectedCols = NULL;
1092         rte->modifiedCols = NULL;
1093
1094         /*
1095          * Add completed RTE to pstate's range table list, but not to join list
1096          * nor namespace --- caller must do that if appropriate.
1097          */
1098         if (pstate != NULL)
1099                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1100
1101         return rte;
1102 }
1103
1104 /*
1105  * Add an entry for a function to the pstate's range table (p_rtable).
1106  *
1107  * This is just like addRangeTableEntry() except that it makes a function RTE.
1108  */
1109 RangeTblEntry *
1110 addRangeTableEntryForFunction(ParseState *pstate,
1111                                                           char *funcname,
1112                                                           Node *funcexpr,
1113                                                           RangeFunction *rangefunc,
1114                                                           bool inFromCl)
1115 {
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;
1123
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;
1131
1132         eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1133         rte->eref = eref;
1134
1135         /*
1136          * Now determine if the function returns a simple or composite type.
1137          */
1138         functypclass = get_expr_result_type(funcexpr,
1139                                                                                 &funcrettype,
1140                                                                                 &tupdesc);
1141
1142         /*
1143          * A coldeflist is required if the function returns RECORD and hasn't got
1144          * a predetermined record type, and is prohibited otherwise.
1145          */
1146         if (coldeflist != NIL)
1147         {
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))));
1153         }
1154         else
1155         {
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))));
1161         }
1162
1163         if (functypclass == TYPEFUNC_COMPOSITE)
1164         {
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);
1169         }
1170         else if (functypclass == TYPEFUNC_SCALAR)
1171         {
1172                 /* Base data type, i.e. scalar */
1173                 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1174         }
1175         else if (functypclass == TYPEFUNC_RECORD)
1176         {
1177                 ListCell   *col;
1178
1179                 /*
1180                  * Use the column definition list to form the alias list and
1181                  * funccoltypes/funccoltypmods lists.
1182                  */
1183                 foreach(col, coldeflist)
1184                 {
1185                         ColumnDef  *n = (ColumnDef *) lfirst(col);
1186                         char       *attrname;
1187                         Oid                     attrtype;
1188                         int32           attrtypmod;
1189
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);
1201                 }
1202         }
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))));
1209
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.
1215          *
1216          * Functions are never checked for access rights (at least, not by
1217          * the RTE permissions mechanism).
1218          *----------
1219          */
1220         rte->inh = false;                       /* never true for functions */
1221         rte->inFromCl = inFromCl;
1222
1223         rte->requiredPerms = 0;
1224         rte->checkAsUser = InvalidOid;
1225         rte->selectedCols = NULL;
1226         rte->modifiedCols = NULL;
1227
1228         /*
1229          * Add completed RTE to pstate's range table list, but not to join list
1230          * nor namespace --- caller must do that if appropriate.
1231          */
1232         if (pstate != NULL)
1233                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1234
1235         return rte;
1236 }
1237
1238 /*
1239  * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1240  *
1241  * This is much like addRangeTableEntry() except that it makes a values RTE.
1242  */
1243 RangeTblEntry *
1244 addRangeTableEntryForValues(ParseState *pstate,
1245                                                         List *exprs,
1246                                                         Alias *alias,
1247                                                         bool inFromCl)
1248 {
1249         RangeTblEntry *rte = makeNode(RangeTblEntry);
1250         char       *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1251         Alias      *eref;
1252         int                     numaliases;
1253         int                     numcolumns;
1254
1255         rte->rtekind = RTE_VALUES;
1256         rte->relid = InvalidOid;
1257         rte->subquery = NULL;
1258         rte->values_lists = exprs;
1259         rte->alias = alias;
1260
1261         eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1262
1263         /* fill in any unspecified alias columns */
1264         numcolumns = list_length((List *) linitial(exprs));
1265         numaliases = list_length(eref->colnames);
1266         while (numaliases < numcolumns)
1267         {
1268                 char            attrname[64];
1269
1270                 numaliases++;
1271                 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1272                 eref->colnames = lappend(eref->colnames,
1273                                                                  makeString(pstrdup(attrname)));
1274         }
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)));
1280
1281         rte->eref = eref;
1282
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.
1288          *
1289          * Subqueries are never checked for access rights.
1290          *----------
1291          */
1292         rte->inh = false;                       /* never true for values RTEs */
1293         rte->inFromCl = inFromCl;
1294
1295         rte->requiredPerms = 0;
1296         rte->checkAsUser = InvalidOid;
1297         rte->selectedCols = NULL;
1298         rte->modifiedCols = NULL;
1299
1300         /*
1301          * Add completed RTE to pstate's range table list, but not to join list
1302          * nor namespace --- caller must do that if appropriate.
1303          */
1304         if (pstate != NULL)
1305                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1306
1307         return rte;
1308 }
1309
1310 /*
1311  * Add an entry for a join to the pstate's range table (p_rtable).
1312  *
1313  * This is much like addRangeTableEntry() except that it makes a join RTE.
1314  */
1315 RangeTblEntry *
1316 addRangeTableEntryForJoin(ParseState *pstate,
1317                                                   List *colnames,
1318                                                   JoinType jointype,
1319                                                   List *aliasvars,
1320                                                   Alias *alias,
1321                                                   bool inFromCl)
1322 {
1323         RangeTblEntry *rte = makeNode(RangeTblEntry);
1324         Alias      *eref;
1325         int                     numaliases;
1326
1327         /*
1328          * Fail if join has too many columns --- we must be able to reference
1329          * any of the columns with an AttrNumber.
1330          */
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)));
1336
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;
1343
1344         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1345         numaliases = list_length(eref->colnames);
1346
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));
1351
1352         rte->eref = eref;
1353
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.
1359          *
1360          * Joins are never checked for access rights.
1361          *----------
1362          */
1363         rte->inh = false;                       /* never true for joins */
1364         rte->inFromCl = inFromCl;
1365
1366         rte->requiredPerms = 0;
1367         rte->checkAsUser = InvalidOid;
1368         rte->selectedCols = NULL;
1369         rte->modifiedCols = NULL;
1370
1371         /*
1372          * Add completed RTE to pstate's range table list, but not to join list
1373          * nor namespace --- caller must do that if appropriate.
1374          */
1375         if (pstate != NULL)
1376                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1377
1378         return rte;
1379 }
1380
1381 /*
1382  * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1383  *
1384  * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1385  */
1386 RangeTblEntry *
1387 addRangeTableEntryForCTE(ParseState *pstate,
1388                                                  CommonTableExpr *cte,
1389                                                  Index levelsup,
1390                                                  Alias *alias,
1391                                                  bool inFromCl)
1392 {
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;
1399
1400         rte->rtekind = RTE_CTE;
1401         rte->ctename = cte->ctename;
1402         rte->ctelevelsup = levelsup;
1403
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++;
1410
1411         rte->ctecoltypes = cte->ctecoltypes;
1412         rte->ctecoltypmods = cte->ctecoltypmods;
1413
1414         rte->alias = alias;
1415         if (alias)
1416                 eref = copyObject(alias);
1417         else
1418                 eref = makeAlias(refname, NIL);
1419         numaliases = list_length(eref->colnames);
1420
1421         /* fill in any unspecified alias columns */
1422         varattno = 0;
1423         foreach(lc, cte->ctecolnames)
1424         {
1425                 varattno++;
1426                 if (varattno > numaliases)
1427                         eref->colnames = lappend(eref->colnames, lfirst(lc));
1428         }
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)));
1434
1435         rte->eref = eref;
1436
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.
1442          *
1443          * Subqueries are never checked for access rights.
1444          *----------
1445          */
1446         rte->inh = false;                       /* never true for subqueries */
1447         rte->inFromCl = inFromCl;
1448
1449         rte->requiredPerms = 0;
1450         rte->checkAsUser = InvalidOid;
1451         rte->selectedCols = NULL;
1452         rte->modifiedCols = NULL;
1453
1454         /*
1455          * Add completed RTE to pstate's range table list, but not to join list
1456          * nor namespace --- caller must do that if appropriate.
1457          */
1458         if (pstate != NULL)
1459                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1460
1461         return rte;
1462 }
1463
1464
1465 /*
1466  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1467  *
1468  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1469  */
1470 static bool
1471 isLockedRel(ParseState *pstate, char *refname)
1472 {
1473         /* Outer loop to check parent query levels as well as this one */
1474         while (pstate != NULL)
1475         {
1476                 ListCell   *l;
1477
1478                 foreach(l, pstate->p_locking_clause)
1479                 {
1480                         LockingClause *lc = (LockingClause *) lfirst(l);
1481
1482                         if (lc->lockedRels == NIL)
1483                         {
1484                                 /* all tables used in query */
1485                                 return true;
1486                         }
1487                         else
1488                         {
1489                                 /* just the named tables */
1490                                 ListCell   *l2;
1491
1492                                 foreach(l2, lc->lockedRels)
1493                                 {
1494                                         RangeVar   *thisrel = (RangeVar *) lfirst(l2);
1495
1496                                         if (strcmp(refname, thisrel->relname) == 0)
1497                                                 return true;
1498                                 }
1499                         }
1500                 }
1501                 pstate = pstate->parentParseState;
1502         }
1503         return false;
1504 }
1505
1506 /*
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.)
1510  */
1511 void
1512 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1513                           bool addToJoinList,
1514                           bool addToRelNameSpace, bool addToVarNameSpace)
1515 {
1516         if (addToJoinList)
1517         {
1518                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1519                 RangeTblRef *rtr = makeNode(RangeTblRef);
1520
1521                 rtr->rtindex = rtindex;
1522                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1523         }
1524         if (addToRelNameSpace)
1525                 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1526         if (addToVarNameSpace)
1527                 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1528 }
1529
1530 /*
1531  * Add a POSTQUEL-style implicit RTE.
1532  *
1533  * We assume caller has already checked that there is no RTE or join with
1534  * a conflicting name.
1535  */
1536 RangeTblEntry *
1537 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1538 {
1539         CommonTableExpr *cte = NULL;
1540         Index           levelsup = 0;
1541         RangeTblEntry *rte;
1542
1543         /* issue warning or error as needed */
1544         warnAutoRange(pstate, relation);
1545
1546         /* if it is an unqualified name, it might be a CTE reference */
1547         if (!relation->schemaname)
1548                 cte = scanNameSpaceForCTE(pstate, relation->relname, &levelsup);
1549
1550         /*
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.
1555          */
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);
1562
1563         return rte;
1564 }
1565
1566 /*
1567  * expandRTE -- expand the columns of a rangetable entry
1568  *
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.
1574  *
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.
1578  *
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.
1582  */
1583 void
1584 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1585                   int location, bool include_dropped,
1586                   List **colnames, List **colvars)
1587 {
1588         int                     varattno;
1589
1590         if (colnames)
1591                 *colnames = NIL;
1592         if (colvars)
1593                 *colvars = NIL;
1594
1595         switch (rte->rtekind)
1596         {
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:
1604                         {
1605                                 /* Subquery RTE */
1606                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1607                                 ListCell   *tlistitem;
1608
1609                                 varattno = 0;
1610                                 foreach(tlistitem, rte->subquery->targetList)
1611                                 {
1612                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1613
1614                                         if (te->resjunk)
1615                                                 continue;
1616                                         varattno++;
1617                                         Assert(varattno == te->resno);
1618
1619                                         if (colnames)
1620                                         {
1621                                                 /* Assume there is one alias per target item */
1622                                                 char       *label = strVal(lfirst(aliasp_item));
1623
1624                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1625                                                 aliasp_item = lnext(aliasp_item);
1626                                         }
1627
1628                                         if (colvars)
1629                                         {
1630                                                 Var                *varnode;
1631
1632                                                 varnode = makeVar(rtindex, varattno,
1633                                                                                   exprType((Node *) te->expr),
1634                                                                                   exprTypmod((Node *) te->expr),
1635                                                                                   sublevels_up);
1636                                                 varnode->location = location;
1637
1638                                                 *colvars = lappend(*colvars, varnode);
1639                                         }
1640                                 }
1641                         }
1642                         break;
1643                 case RTE_FUNCTION:
1644                         {
1645                                 /* Function RTE */
1646                                 TypeFuncClass functypclass;
1647                                 Oid                     funcrettype;
1648                                 TupleDesc       tupdesc;
1649
1650                                 functypclass = get_expr_result_type(rte->funcexpr,
1651                                                                                                         &funcrettype,
1652                                                                                                         &tupdesc);
1653                                 if (functypclass == TYPEFUNC_COMPOSITE)
1654                                 {
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);
1660                                 }
1661                                 else if (functypclass == TYPEFUNC_SCALAR)
1662                                 {
1663                                         /* Base data type, i.e. scalar */
1664                                         if (colnames)
1665                                                 *colnames = lappend(*colnames,
1666                                                                                         linitial(rte->eref->colnames));
1667
1668                                         if (colvars)
1669                                         {
1670                                                 Var                *varnode;
1671
1672                                                 varnode = makeVar(rtindex, 1,
1673                                                                                   funcrettype, -1,
1674                                                                                   sublevels_up);
1675                                                 varnode->location = location;
1676
1677                                                 *colvars = lappend(*colvars, varnode);
1678                                         }
1679                                 }
1680                                 else if (functypclass == TYPEFUNC_RECORD)
1681                                 {
1682                                         if (colnames)
1683                                                 *colnames = copyObject(rte->eref->colnames);
1684                                         if (colvars)
1685                                         {
1686                                                 ListCell   *l1;
1687                                                 ListCell   *l2;
1688                                                 int                     attnum = 0;
1689
1690                                                 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1691                                                 {
1692                                                         Oid                     attrtype = lfirst_oid(l1);
1693                                                         int32           attrtypmod = lfirst_int(l2);
1694                                                         Var                *varnode;
1695
1696                                                         attnum++;
1697                                                         varnode = makeVar(rtindex,
1698                                                                                           attnum,
1699                                                                                           attrtype,
1700                                                                                           attrtypmod,
1701                                                                                           sublevels_up);
1702                                                         varnode->location = location;
1703                                                         *colvars = lappend(*colvars, varnode);
1704                                                 }
1705                                         }
1706                                 }
1707                                 else
1708                                 {
1709                                         /* addRangeTableEntryForFunction should've caught this */
1710                                         elog(ERROR, "function in FROM has unsupported return type");
1711                                 }
1712                         }
1713                         break;
1714                 case RTE_VALUES:
1715                         {
1716                                 /* Values RTE */
1717                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1718                                 ListCell   *lc;
1719
1720                                 varattno = 0;
1721                                 foreach(lc, (List *) linitial(rte->values_lists))
1722                                 {
1723                                         Node       *col = (Node *) lfirst(lc);
1724
1725                                         varattno++;
1726                                         if (colnames)
1727                                         {
1728                                                 /* Assume there is one alias per column */
1729                                                 char       *label = strVal(lfirst(aliasp_item));
1730
1731                                                 *colnames = lappend(*colnames,
1732                                                                                         makeString(pstrdup(label)));
1733                                                 aliasp_item = lnext(aliasp_item);
1734                                         }
1735
1736                                         if (colvars)
1737                                         {
1738                                                 Var                *varnode;
1739
1740                                                 varnode = makeVar(rtindex, varattno,
1741                                                                                   exprType(col),
1742                                                                                   exprTypmod(col),
1743                                                                                   sublevels_up);
1744                                                 varnode->location = location;
1745                                                 *colvars = lappend(*colvars, varnode);
1746                                         }
1747                                 }
1748                         }
1749                         break;
1750                 case RTE_JOIN:
1751                         {
1752                                 /* Join RTE */
1753                                 ListCell   *colname;
1754                                 ListCell   *aliasvar;
1755
1756                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1757
1758                                 varattno = 0;
1759                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1760                                 {
1761                                         Node       *avar = (Node *) lfirst(aliasvar);
1762
1763                                         varattno++;
1764
1765                                         /*
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.
1772                                          */
1773                                         if (IsA(avar, Const))
1774                                         {
1775                                                 if (include_dropped)
1776                                                 {
1777                                                         if (colnames)
1778                                                                 *colnames = lappend(*colnames,
1779                                                                                                         makeString(pstrdup("")));
1780                                                         if (colvars)
1781                                                                 *colvars = lappend(*colvars,
1782                                                                                                    copyObject(avar));
1783                                                 }
1784                                                 continue;
1785                                         }
1786
1787                                         if (colnames)
1788                                         {
1789                                                 char       *label = strVal(lfirst(colname));
1790
1791                                                 *colnames = lappend(*colnames,
1792                                                                                         makeString(pstrdup(label)));
1793                                         }
1794
1795                                         if (colvars)
1796                                         {
1797                                                 Var                *varnode;
1798
1799                                                 varnode = makeVar(rtindex, varattno,
1800                                                                                   exprType(avar),
1801                                                                                   exprTypmod(avar),
1802                                                                                   sublevels_up);
1803                                                 varnode->location = location;
1804
1805                                                 *colvars = lappend(*colvars, varnode);
1806                                         }
1807                                 }
1808                         }
1809                         break;
1810                 case RTE_CTE:
1811                         {
1812                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1813                                 ListCell   *lct;
1814                                 ListCell   *lcm;
1815
1816                                 varattno = 0;
1817                                 forboth(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods)
1818                                 {
1819                                         Oid             coltype = lfirst_oid(lct);
1820                                         int32   coltypmod = lfirst_int(lcm);
1821
1822                                         varattno++;
1823
1824                                         if (colnames)
1825                                         {
1826                                                 /* Assume there is one alias per output column */
1827                                                 char       *label = strVal(lfirst(aliasp_item));
1828
1829                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1830                                                 aliasp_item = lnext(aliasp_item);
1831                                         }
1832
1833                                         if (colvars)
1834                                         {
1835                                                 Var                *varnode;
1836
1837                                                 varnode = makeVar(rtindex, varattno,
1838                                                                                   coltype, coltypmod,
1839                                                                                   sublevels_up);
1840                                                 *colvars = lappend(*colvars, varnode);
1841                                         }
1842                                 }
1843                         }
1844                         break;
1845                 default:
1846                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1847         }
1848 }
1849
1850 /*
1851  * expandRelation -- expandRTE subroutine
1852  */
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)
1857 {
1858         Relation        rel;
1859
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);
1866 }
1867
1868 /*
1869  * expandTupleDesc -- expandRTE subroutine
1870  */
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)
1876 {
1877         int                     maxattrs = tupdesc->natts;
1878         int                     numaliases = list_length(eref->colnames);
1879         int                     varattno;
1880
1881         for (varattno = 0; varattno < maxattrs; varattno++)
1882         {
1883                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1884
1885                 if (attr->attisdropped)
1886                 {
1887                         if (include_dropped)
1888                         {
1889                                 if (colnames)
1890                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1891                                 if (colvars)
1892                                 {
1893                                         /*
1894                                          * can't use atttypid here, but it doesn't really matter
1895                                          * what type the Const claims to be.
1896                                          */
1897                                         *colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1898                                 }
1899                         }
1900                         continue;
1901                 }
1902
1903                 if (colnames)
1904                 {
1905                         char       *label;
1906
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)));
1912                 }
1913
1914                 if (colvars)
1915                 {
1916                         Var                *varnode;
1917
1918                         varnode = makeVar(rtindex, attr->attnum,
1919                                                           attr->atttypid, attr->atttypmod,
1920                                                           sublevels_up);
1921                         varnode->location = location;
1922
1923                         *colvars = lappend(*colvars, varnode);
1924                 }
1925         }
1926 }
1927
1928 /*
1929  * expandRelAttrs -
1930  *        Workhorse for "*" expansion: produce a list of targetentries
1931  *        for the attributes of the RTE
1932  *
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.
1937  */
1938 List *
1939 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1940                            int rtindex, int sublevels_up, int location)
1941 {
1942         List       *names,
1943                            *vars;
1944         ListCell   *name,
1945                            *var;
1946         List       *te_list = NIL;
1947
1948         expandRTE(rte, rtindex, sublevels_up, location, false,
1949                           &names, &vars);
1950
1951         /*
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.
1955          */
1956         rte->requiredPerms |= ACL_SELECT;
1957
1958         forboth(name, names, var, vars)
1959         {
1960                 char       *label = strVal(lfirst(name));
1961                 Var                *varnode = (Var *) lfirst(var);
1962                 TargetEntry *te;
1963
1964                 te = makeTargetEntry((Expr *) varnode,
1965                                                          (AttrNumber) pstate->p_next_resno++,
1966                                                          label,
1967                                                          false);
1968                 te_list = lappend(te_list, te);
1969
1970                 /* Require read access to each column */
1971                 markVarForSelectPriv(pstate, varnode, rte);
1972         }
1973
1974         Assert(name == NULL && var == NULL);    /* lists not the same length? */
1975
1976         return te_list;
1977 }
1978
1979 /*
1980  * get_rte_attribute_name
1981  *              Get an attribute name from a RangeTblEntry
1982  *
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.
1986  *
1987  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1988  * occurs when a Var represents a whole tuple of a relation.
1989  */
1990 char *
1991 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1992 {
1993         if (attnum == InvalidAttrNumber)
1994                 return "*";
1995
1996         /*
1997          * If there is a user-written column alias, use it.
1998          */
1999         if (rte->alias &&
2000                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
2001                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
2002
2003         /*
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).
2008          */
2009         if (rte->rtekind == RTE_RELATION)
2010                 return get_relid_attribute_name(rte->relid, attnum);
2011
2012         /*
2013          * Otherwise use the column name from eref.  There should always be one.
2014          */
2015         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2016                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
2017
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 */
2022 }
2023
2024 /*
2025  * get_rte_attribute_type
2026  *              Get attribute type information from a RangeTblEntry
2027  */
2028 void
2029 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2030                                            Oid *vartype, int32 *vartypmod)
2031 {
2032         switch (rte->rtekind)
2033         {
2034                 case RTE_RELATION:
2035                         {
2036                                 /* Plain relation RTE --- get the attribute's type info */
2037                                 HeapTuple       tp;
2038                                 Form_pg_attribute att_tup;
2039
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);
2048
2049                                 /*
2050                                  * If dropped column, pretend it ain't there.  See notes in
2051                                  * scanRTEForColumn.
2052                                  */
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);
2062                         }
2063                         break;
2064                 case RTE_SUBQUERY:
2065                         {
2066                                 /* Subselect RTE --- get type info from subselect's tlist */
2067                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2068                                                                                                    attnum);
2069
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);
2075                         }
2076                         break;
2077                 case RTE_FUNCTION:
2078                         {
2079                                 /* Function RTE */
2080                                 TypeFuncClass functypclass;
2081                                 Oid                     funcrettype;
2082                                 TupleDesc       tupdesc;
2083
2084                                 functypclass = get_expr_result_type(rte->funcexpr,
2085                                                                                                         &funcrettype,
2086                                                                                                         &tupdesc);
2087
2088                                 if (functypclass == TYPEFUNC_COMPOSITE)
2089                                 {
2090                                         /* Composite data type, e.g. a table's row type */
2091                                         Form_pg_attribute att_tup;
2092
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)));
2101
2102                                         att_tup = tupdesc->attrs[attnum - 1];
2103
2104                                         /*
2105                                          * If dropped column, pretend it ain't there.  See notes
2106                                          * in scanRTEForColumn.
2107                                          */
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;
2116                                 }
2117                                 else if (functypclass == TYPEFUNC_SCALAR)
2118                                 {
2119                                         /* Base data type, i.e. scalar */
2120                                         *vartype = funcrettype;
2121                                         *vartypmod = -1;
2122                                 }
2123                                 else if (functypclass == TYPEFUNC_RECORD)
2124                                 {
2125                                         *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2126                                         *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2127                                 }
2128                                 else
2129                                 {
2130                                         /* addRangeTableEntryForFunction should've caught this */
2131                                         elog(ERROR, "function in FROM has unsupported return type");
2132                                 }
2133                         }
2134                         break;
2135                 case RTE_VALUES:
2136                         {
2137                                 /* Values RTE --- get type info from first sublist */
2138                                 List       *collist = (List *) linitial(rte->values_lists);
2139                                 Node       *col;
2140
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);
2147                         }
2148                         break;
2149                 case RTE_JOIN:
2150                         {
2151                                 /*
2152                                  * Join RTE --- get type info from join RTE's alias variable
2153                                  */
2154                                 Node       *aliasvar;
2155
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);
2160                         }
2161                         break;
2162                 case RTE_CTE:
2163                         {
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);
2168                         }
2169                         break;
2170                 default:
2171                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2172         }
2173 }
2174
2175 /*
2176  * get_rte_attribute_is_dropped
2177  *              Check whether attempted attribute ref is to a dropped column
2178  */
2179 bool
2180 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2181 {
2182         bool            result;
2183
2184         switch (rte->rtekind)
2185         {
2186                 case RTE_RELATION:
2187                         {
2188                                 /*
2189                                  * Plain relation RTE --- get the attribute's catalog entry
2190                                  */
2191                                 HeapTuple       tp;
2192                                 Form_pg_attribute att_tup;
2193
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);
2204                         }
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:
2213                         {
2214                                 /*
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.
2220                                  */
2221                                 Var                *aliasvar;
2222
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);
2227
2228                                 result = IsA(aliasvar, Const);
2229                         }
2230                         break;
2231                 case RTE_FUNCTION:
2232                         {
2233                                 /* Function RTE */
2234                                 Oid                     funcrettype = exprType(rte->funcexpr);
2235                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
2236
2237                                 if (OidIsValid(funcrelid))
2238                                 {
2239                                         /*
2240                                          * Composite data type, i.e. a table's row type
2241                                          *
2242                                          * Same as ordinary relation RTE
2243                                          */
2244                                         HeapTuple       tp;
2245                                         Form_pg_attribute att_tup;
2246
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);
2257                                 }
2258                                 else
2259                                 {
2260                                         /*
2261                                          * Must be a base data type, i.e. scalar
2262                                          */
2263                                         result = false;
2264                                 }
2265                         }
2266                         break;
2267                 default:
2268                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2269                         result = false;         /* keep compiler quiet */
2270         }
2271
2272         return result;
2273 }
2274
2275 /*
2276  * Given a targetlist and a resno, return the matching TargetEntry
2277  *
2278  * Returns NULL if resno is not present in list.
2279  *
2280  * Note: we need to search, rather than just indexing with list_nth(),
2281  * because not all tlists are sorted by resno.
2282  */
2283 TargetEntry *
2284 get_tle_by_resno(List *tlist, AttrNumber resno)
2285 {
2286         ListCell   *l;
2287
2288         foreach(l, tlist)
2289         {
2290                 TargetEntry *tle = (TargetEntry *) lfirst(l);
2291
2292                 if (tle->resno == resno)
2293                         return tle;
2294         }
2295         return NULL;
2296 }
2297
2298 /*
2299  * Given a Query and rangetable index, return relation's RowMarkClause if any
2300  *
2301  * Returns NULL if relation is not selected FOR UPDATE/SHARE
2302  */
2303 RowMarkClause *
2304 get_rowmark(Query *qry, Index rtindex)
2305 {
2306         ListCell   *l;
2307
2308         foreach(l, qry->rowMarks)
2309         {
2310                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2311
2312                 if (rc->rti == rtindex)
2313                         return rc;
2314         }
2315         return NULL;
2316 }
2317
2318 /*
2319  *      given relation and att name, return attnum of variable
2320  *
2321  *      Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2322  *
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.
2326  */
2327 int
2328 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2329 {
2330         int                     i;
2331
2332         for (i = 0; i < rd->rd_rel->relnatts; i++)
2333         {
2334                 Form_pg_attribute att = rd->rd_att->attrs[i];
2335
2336                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2337                         return i + 1;
2338         }
2339
2340         if (sysColOK)
2341         {
2342                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2343                 {
2344                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2345                                 return i;
2346                 }
2347         }
2348
2349         /* on failure */
2350         return InvalidAttrNumber;
2351 }
2352
2353 /* specialAttNum()
2354  *
2355  * Check attribute name to see if it is "special", e.g. "oid".
2356  * - thomas 2000-02-07
2357  *
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.
2361  */
2362 static int
2363 specialAttNum(const char *attname)
2364 {
2365         Form_pg_attribute sysatt;
2366
2367         sysatt = SystemAttributeByName(attname,
2368                                                                    true /* "oid" will be accepted */ );
2369         if (sysatt != NULL)
2370                 return sysatt->attnum;
2371         return InvalidAttrNumber;
2372 }
2373
2374
2375 /*
2376  * given attribute id, return name of that attribute
2377  *
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.
2381  */
2382 Name
2383 attnumAttName(Relation rd, int attid)
2384 {
2385         if (attid <= 0)
2386         {
2387                 Form_pg_attribute sysatt;
2388
2389                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2390                 return &sysatt->attname;
2391         }
2392         if (attid > rd->rd_att->natts)
2393                 elog(ERROR, "invalid attribute number %d", attid);
2394         return &rd->rd_att->attrs[attid - 1]->attname;
2395 }
2396
2397 /*
2398  * given attribute id, return type of that attribute
2399  *
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.
2403  */
2404 Oid
2405 attnumTypeId(Relation rd, int attid)
2406 {
2407         if (attid <= 0)
2408         {
2409                 Form_pg_attribute sysatt;
2410
2411                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2412                 return sysatt->atttypid;
2413         }
2414         if (attid > rd->rd_att->natts)
2415                 elog(ERROR, "invalid attribute number %d", attid);
2416         return rd->rd_att->attrs[attid - 1]->atttypid;
2417 }
2418
2419 /*
2420  * Generate a warning or error about an implicit RTE, if appropriate.
2421  *
2422  * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
2423  * a warning.
2424  */
2425 static void
2426 warnAutoRange(ParseState *pstate, RangeVar *relation)
2427 {
2428         RangeTblEntry *rte;
2429         int                     sublevels_up;
2430         const char *badAlias = NULL;
2431
2432         /*
2433          * Check to see if there are any potential matches in the query's
2434          * rangetable.  This affects the message we provide.
2435          */
2436         rte = searchRangeTable(pstate, relation);
2437
2438         /*
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.
2443          *
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)".
2447          */
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;
2454
2455         if (!add_missing_from)
2456         {
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)));
2474         }
2475         else
2476         {
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)));
2489         }
2490 }