]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
Update copyright for the year 2010.
[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-2010, 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.148 2010/01/02 16:57:50 momjian 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 static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
36                                                 const char *refname, int location);
37 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
38                                           int location);
39 static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
40                                          int rtindex, AttrNumber col);
41 static void expandRelation(Oid relid, Alias *eref,
42                            int rtindex, int sublevels_up,
43                            int location, bool include_dropped,
44                            List **colnames, List **colvars);
45 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
46                                 int rtindex, int sublevels_up,
47                                 int location, bool include_dropped,
48                                 List **colnames, List **colvars);
49 static int      specialAttNum(const char *attname);
50
51
52 /*
53  * refnameRangeTblEntry
54  *        Given a possibly-qualified refname, look to see if it matches any RTE.
55  *        If so, return a pointer to the RangeTblEntry; else return NULL.
56  *
57  *        Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
58  *        If sublevels_up is NULL, only consider items at the current nesting
59  *        level.
60  *
61  * An unqualified refname (schemaname == NULL) can match any RTE with matching
62  * alias, or matching unqualified relname in the case of alias-less relation
63  * RTEs.  It is possible that such a refname matches multiple RTEs in the
64  * nearest nesting level that has a match; if so, we report an error via
65  * ereport().
66  *
67  * A qualified refname (schemaname != NULL) can only match a relation RTE
68  * that (a) has no alias and (b) is for the same relation identified by
69  * schemaname.refname.  In this case we convert schemaname.refname to a
70  * relation OID and search by relid, rather than by alias name.  This is
71  * peculiar, but it's what SQL92 says to do.
72  */
73 RangeTblEntry *
74 refnameRangeTblEntry(ParseState *pstate,
75                                          const char *schemaname,
76                                          const char *refname,
77                                          int location,
78                                          int *sublevels_up)
79 {
80         Oid                     relId = InvalidOid;
81
82         if (sublevels_up)
83                 *sublevels_up = 0;
84
85         if (schemaname != NULL)
86         {
87                 Oid                     namespaceId;
88
89                 /*
90                  * We can use LookupNamespaceNoError() here because we are only
91                  * interested in finding existing RTEs.  Checking USAGE permission
92                  * on the schema is unnecessary since it would have already been
93                  * checked when the RTE was made.  Furthermore, we want to report
94                  * "RTE not found", not "no permissions for schema", if the name
95                  * happens to match a schema name the user hasn't got access to.
96                  */
97                 namespaceId = LookupNamespaceNoError(schemaname);
98                 if (!OidIsValid(relId))
99                         return NULL;
100                 relId = get_relname_relid(refname, namespaceId);
101                 if (!OidIsValid(relId))
102                         return NULL;
103         }
104
105         while (pstate != NULL)
106         {
107                 RangeTblEntry *result;
108
109                 if (OidIsValid(relId))
110                         result = scanNameSpaceForRelid(pstate, relId, location);
111                 else
112                         result = scanNameSpaceForRefname(pstate, refname, location);
113
114                 if (result)
115                         return result;
116
117                 if (sublevels_up)
118                         (*sublevels_up)++;
119                 else
120                         break;
121
122                 pstate = pstate->parentParseState;
123         }
124         return NULL;
125 }
126
127 /*
128  * Search the query's table namespace for an RTE matching the
129  * given unqualified refname.  Return the RTE if a unique match, or NULL
130  * if no match.  Raise error if multiple matches.
131  */
132 static RangeTblEntry *
133 scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
134 {
135         RangeTblEntry *result = NULL;
136         ListCell   *l;
137
138         foreach(l, pstate->p_relnamespace)
139         {
140                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
141
142                 if (strcmp(rte->eref->aliasname, refname) == 0)
143                 {
144                         if (result)
145                                 ereport(ERROR,
146                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
147                                                  errmsg("table reference \"%s\" is ambiguous",
148                                                                 refname),
149                                                  parser_errposition(pstate, location)));
150                         result = rte;
151                 }
152         }
153         return result;
154 }
155
156 /*
157  * Search the query's table namespace for a relation RTE matching the
158  * given relation OID.  Return the RTE if a unique match, or NULL
159  * if no match.  Raise error if multiple matches (which shouldn't
160  * happen if the namespace was checked correctly when it was created).
161  *
162  * See the comments for refnameRangeTblEntry to understand why this
163  * acts the way it does.
164  */
165 static RangeTblEntry *
166 scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
167 {
168         RangeTblEntry *result = NULL;
169         ListCell   *l;
170
171         foreach(l, pstate->p_relnamespace)
172         {
173                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
174
175                 /* yes, the test for alias == NULL should be there... */
176                 if (rte->rtekind == RTE_RELATION &&
177                         rte->relid == relid &&
178                         rte->alias == NULL)
179                 {
180                         if (result)
181                                 ereport(ERROR,
182                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
183                                                  errmsg("table reference %u is ambiguous",
184                                                                 relid),
185                                                  parser_errposition(pstate, location)));
186                         result = rte;
187                 }
188         }
189         return result;
190 }
191
192 /*
193  * Search the query's CTE namespace for a CTE matching the given unqualified
194  * refname.  Return the CTE (and its levelsup count) if a match, or NULL
195  * if no match.  We need not worry about multiple matches, since parse_cte.c
196  * rejects WITH lists containing duplicate CTE names.
197  */
198 CommonTableExpr *
199 scanNameSpaceForCTE(ParseState *pstate, const char *refname,
200                                         Index *ctelevelsup)
201 {
202         Index           levelsup;
203
204         for (levelsup = 0;
205                  pstate != NULL;
206                  pstate = pstate->parentParseState, levelsup++)
207         {
208                 ListCell   *lc;
209
210                 foreach(lc, pstate->p_ctenamespace)
211                 {
212                         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
213
214                         if (strcmp(cte->ctename, refname) == 0)
215                         {
216                                 *ctelevelsup = levelsup;
217                                 return cte;
218                         }
219                 }
220         }
221         return NULL;
222 }
223
224 /*
225  * Search for a possible "future CTE", that is one that is not yet in scope
226  * according to the WITH scoping rules.  This has nothing to do with valid
227  * SQL semantics, but it's important for error reporting purposes.
228  */
229 static bool
230 isFutureCTE(ParseState *pstate, const char *refname)
231 {
232         for (; pstate != NULL; pstate = pstate->parentParseState)
233         {
234                 ListCell   *lc;
235
236                 foreach(lc, pstate->p_future_ctes)
237                 {
238                         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
239
240                         if (strcmp(cte->ctename, refname) == 0)
241                                 return true;
242                 }
243         }
244         return false;
245 }
246
247 /*
248  * searchRangeTable
249  *        See if any RangeTblEntry could possibly match the RangeVar.
250  *        If so, return a pointer to the RangeTblEntry; else return NULL.
251  *
252  * This is different from refnameRangeTblEntry in that it considers every
253  * entry in the ParseState's rangetable(s), not only those that are currently
254  * visible in the p_relnamespace lists.  This behavior is invalid per the SQL
255  * spec, and it may give ambiguous results (there might be multiple equally
256  * valid matches, but only one will be returned).  This must be used ONLY
257  * as a heuristic in giving suitable error messages.  See errorMissingRTE.
258  *
259  * Notice that we consider both matches on actual relation (or CTE) name
260  * and matches on alias.
261  */
262 static RangeTblEntry *
263 searchRangeTable(ParseState *pstate, RangeVar *relation)
264 {
265         const char *refname = relation->relname;
266         Oid                     relId = InvalidOid;
267         CommonTableExpr *cte = NULL;
268         Index           ctelevelsup = 0;
269         Index           levelsup;
270
271         /*
272          * If it's an unqualified name, check for possible CTE matches. A CTE
273          * hides any real relation matches.  If no CTE, look for a matching
274          * relation.
275          */
276         if (!relation->schemaname)
277                 cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
278         if (!cte)
279                 relId = RangeVarGetRelid(relation, true);
280
281         /* Now look for RTEs matching either the relation/CTE or the alias */
282         for (levelsup = 0;
283                  pstate != NULL;
284                  pstate = pstate->parentParseState, levelsup++)
285         {
286                 ListCell   *l;
287
288                 foreach(l, pstate->p_rtable)
289                 {
290                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
291
292                         if (rte->rtekind == RTE_RELATION &&
293                                 OidIsValid(relId) &&
294                                 rte->relid == relId)
295                                 return rte;
296                         if (rte->rtekind == RTE_CTE &&
297                                 cte != NULL &&
298                                 rte->ctelevelsup + levelsup == ctelevelsup &&
299                                 strcmp(rte->ctename, refname) == 0)
300                                 return rte;
301                         if (strcmp(rte->eref->aliasname, refname) == 0)
302                                 return rte;
303                 }
304         }
305         return NULL;
306 }
307
308 /*
309  * Check for relation-name conflicts between two relnamespace lists.
310  * Raise an error if any is found.
311  *
312  * Note: we assume that each given argument does not contain conflicts
313  * itself; we just want to know if the two can be merged together.
314  *
315  * Per SQL92, two alias-less plain relation RTEs do not conflict even if
316  * they have the same eref->aliasname (ie, same relation name), if they
317  * are for different relation OIDs (implying they are in different schemas).
318  */
319 void
320 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
321                                                 List *namespace2)
322 {
323         ListCell   *l1;
324
325         foreach(l1, namespace1)
326         {
327                 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
328                 const char *aliasname1 = rte1->eref->aliasname;
329                 ListCell   *l2;
330
331                 foreach(l2, namespace2)
332                 {
333                         RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
334
335                         if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
336                                 continue;               /* definitely no conflict */
337                         if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
338                                 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
339                                 rte1->relid != rte2->relid)
340                                 continue;               /* no conflict per SQL92 rule */
341                         ereport(ERROR,
342                                         (errcode(ERRCODE_DUPLICATE_ALIAS),
343                                          errmsg("table name \"%s\" specified more than once",
344                                                         aliasname1)));
345                 }
346         }
347 }
348
349 /*
350  * given an RTE, return RT index (starting with 1) of the entry,
351  * and optionally get its nesting depth (0 = current).  If sublevels_up
352  * is NULL, only consider rels at the current nesting level.
353  * Raises error if RTE not found.
354  */
355 int
356 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
357 {
358         int                     index;
359         ListCell   *l;
360
361         if (sublevels_up)
362                 *sublevels_up = 0;
363
364         while (pstate != NULL)
365         {
366                 index = 1;
367                 foreach(l, pstate->p_rtable)
368                 {
369                         if (rte == (RangeTblEntry *) lfirst(l))
370                                 return index;
371                         index++;
372                 }
373                 pstate = pstate->parentParseState;
374                 if (sublevels_up)
375                         (*sublevels_up)++;
376                 else
377                         break;
378         }
379
380         elog(ERROR, "RTE not found (internal error)");
381         return 0;                                       /* keep compiler quiet */
382 }
383
384 /*
385  * Given an RT index and nesting depth, find the corresponding RTE.
386  * This is the inverse of RTERangeTablePosn.
387  */
388 RangeTblEntry *
389 GetRTEByRangeTablePosn(ParseState *pstate,
390                                            int varno,
391                                            int sublevels_up)
392 {
393         while (sublevels_up-- > 0)
394         {
395                 pstate = pstate->parentParseState;
396                 Assert(pstate != NULL);
397         }
398         Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
399         return rt_fetch(varno, pstate->p_rtable);
400 }
401
402 /*
403  * Fetch the CTE for a CTE-reference RTE.
404  *
405  * rtelevelsup is the number of query levels above the given pstate that the
406  * RTE came from.  Callers that don't have this information readily available
407  * may pass -1 instead.
408  */
409 CommonTableExpr *
410 GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
411 {
412         Index           levelsup;
413         ListCell   *lc;
414
415         /* Determine RTE's levelsup if caller didn't know it */
416         if (rtelevelsup < 0)
417                 (void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
418
419         Assert(rte->rtekind == RTE_CTE);
420         levelsup = rte->ctelevelsup + rtelevelsup;
421         while (levelsup-- > 0)
422         {
423                 pstate = pstate->parentParseState;
424                 if (!pstate)                    /* shouldn't happen */
425                         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
426         }
427         foreach(lc, pstate->p_ctenamespace)
428         {
429                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
430
431                 if (strcmp(cte->ctename, rte->ctename) == 0)
432                         return cte;
433         }
434         /* shouldn't happen */
435         elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
436         return NULL;                            /* keep compiler quiet */
437 }
438
439 /*
440  * scanRTEForColumn
441  *        Search the column names of a single RTE for the given name.
442  *        If found, return an appropriate Var node, else return NULL.
443  *        If the name proves ambiguous within this RTE, raise error.
444  *
445  * Side effect: if we find a match, mark the RTE as requiring read access
446  * for the column.
447  */
448 Node *
449 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
450                                  int location)
451 {
452         Node       *result = NULL;
453         int                     attnum = 0;
454         Var                *var;
455         ListCell   *c;
456
457         /*
458          * Scan the user column names (or aliases) for a match. Complain if
459          * multiple matches.
460          *
461          * Note: eref->colnames may include entries for dropped columns, but those
462          * will be empty strings that cannot match any legal SQL identifier, so we
463          * don't bother to test for that case here.
464          *
465          * Should this somehow go wrong and we try to access a dropped column,
466          * we'll still catch it by virtue of the checks in
467          * get_rte_attribute_type(), which is called by make_var().  That routine
468          * has to do a cache lookup anyway, so the check there is cheap.
469          */
470         foreach(c, rte->eref->colnames)
471         {
472                 attnum++;
473                 if (strcmp(strVal(lfirst(c)), colname) == 0)
474                 {
475                         if (result)
476                                 ereport(ERROR,
477                                                 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
478                                                  errmsg("column reference \"%s\" is ambiguous",
479                                                                 colname),
480                                                  parser_errposition(pstate, location)));
481                         var = make_var(pstate, rte, attnum, location);
482                         /* Require read access to the column */
483                         markVarForSelectPriv(pstate, var, rte);
484                         result = (Node *) var;
485                 }
486         }
487
488         /*
489          * If we have a unique match, return it.  Note that this allows a user
490          * alias to override a system column name (such as OID) without error.
491          */
492         if (result)
493                 return result;
494
495         /*
496          * If the RTE represents a real table, consider system column names.
497          */
498         if (rte->rtekind == RTE_RELATION)
499         {
500                 /* quick check to see if name could be a system column */
501                 attnum = specialAttNum(colname);
502                 if (attnum != InvalidAttrNumber)
503                 {
504                         /* now check to see if column actually is defined */
505                         if (SearchSysCacheExists(ATTNUM,
506                                                                          ObjectIdGetDatum(rte->relid),
507                                                                          Int16GetDatum(attnum),
508                                                                          0, 0))
509                         {
510                                 var = make_var(pstate, rte, attnum, location);
511                                 /* Require read access to the column */
512                                 markVarForSelectPriv(pstate, var, rte);
513                                 result = (Node *) var;
514                         }
515                 }
516         }
517
518         return result;
519 }
520
521 /*
522  * colNameToVar
523  *        Search for an unqualified column name.
524  *        If found, return the appropriate Var node (or expression).
525  *        If not found, return NULL.  If the name proves ambiguous, raise error.
526  *        If localonly is true, only names in the innermost query are considered.
527  */
528 Node *
529 colNameToVar(ParseState *pstate, char *colname, bool localonly,
530                          int location)
531 {
532         Node       *result = NULL;
533         ParseState *orig_pstate = pstate;
534
535         while (pstate != NULL)
536         {
537                 ListCell   *l;
538
539                 foreach(l, pstate->p_varnamespace)
540                 {
541                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
542                         Node       *newresult;
543
544                         /* use orig_pstate here to get the right sublevels_up */
545                         newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
546
547                         if (newresult)
548                         {
549                                 if (result)
550                                         ereport(ERROR,
551                                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
552                                                          errmsg("column reference \"%s\" is ambiguous",
553                                                                         colname),
554                                                          parser_errposition(orig_pstate, location)));
555                                 result = newresult;
556                         }
557                 }
558
559                 if (result != NULL || localonly)
560                         break;                          /* found, or don't want to look at parent */
561
562                 pstate = pstate->parentParseState;
563         }
564
565         return result;
566 }
567
568 /*
569  * markRTEForSelectPriv
570  *         Mark the specified column of an RTE as requiring SELECT privilege
571  *
572  * col == InvalidAttrNumber means a "whole row" reference
573  *
574  * The caller should pass the actual RTE if it has it handy; otherwise pass
575  * NULL, and we'll look it up here.  (This uglification of the API is
576  * worthwhile because nearly all external callers have the RTE at hand.)
577  */
578 static void
579 markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
580                                          int rtindex, AttrNumber col)
581 {
582         if (rte == NULL)
583                 rte = rt_fetch(rtindex, pstate->p_rtable);
584
585         if (rte->rtekind == RTE_RELATION)
586         {
587                 /* Make sure the rel as a whole is marked for SELECT access */
588                 rte->requiredPerms |= ACL_SELECT;
589                 /* Must offset the attnum to fit in a bitmapset */
590                 rte->selectedCols = bms_add_member(rte->selectedCols,
591                                                                    col - FirstLowInvalidHeapAttributeNumber);
592         }
593         else if (rte->rtekind == RTE_JOIN)
594         {
595                 if (col == InvalidAttrNumber)
596                 {
597                         /*
598                          * A whole-row reference to a join has to be treated as whole-row
599                          * references to the two inputs.
600                          */
601                         JoinExpr   *j;
602
603                         if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
604                                 j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
605                         else
606                                 j = NULL;
607                         if (j == NULL)
608                                 elog(ERROR, "could not find JoinExpr for whole-row reference");
609                         Assert(IsA(j, JoinExpr));
610
611                         /* Note: we can't see FromExpr here */
612                         if (IsA(j->larg, RangeTblRef))
613                         {
614                                 int                     varno = ((RangeTblRef *) j->larg)->rtindex;
615
616                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
617                         }
618                         else if (IsA(j->larg, JoinExpr))
619                         {
620                                 int                     varno = ((JoinExpr *) j->larg)->rtindex;
621
622                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
623                         }
624                         else
625                                 elog(ERROR, "unrecognized node type: %d",
626                                          (int) nodeTag(j->larg));
627                         if (IsA(j->rarg, RangeTblRef))
628                         {
629                                 int                     varno = ((RangeTblRef *) j->rarg)->rtindex;
630
631                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
632                         }
633                         else if (IsA(j->rarg, JoinExpr))
634                         {
635                                 int                     varno = ((JoinExpr *) j->rarg)->rtindex;
636
637                                 markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
638                         }
639                         else
640                                 elog(ERROR, "unrecognized node type: %d",
641                                          (int) nodeTag(j->rarg));
642                 }
643                 else
644                 {
645                         /*
646                          * Regular join attribute, look at the alias-variable list.
647                          *
648                          * The aliasvar could be either a Var or a COALESCE expression,
649                          * but in the latter case we should already have marked the two
650                          * referent variables as being selected, due to their use in the
651                          * JOIN clause.  So we need only be concerned with the simple Var
652                          * case.
653                          */
654                         Var                *aliasvar;
655
656                         Assert(col > 0 && col <= list_length(rte->joinaliasvars));
657                         aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
658                         if (IsA(aliasvar, Var))
659                                 markVarForSelectPriv(pstate, aliasvar, NULL);
660                 }
661         }
662         /* other RTE types don't require privilege marking */
663 }
664
665 /*
666  * markVarForSelectPriv
667  *         Mark the RTE referenced by a Var as requiring SELECT privilege
668  *
669  * The caller should pass the Var's referenced RTE if it has it handy
670  * (nearly all do); otherwise pass NULL.
671  */
672 void
673 markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
674 {
675         Index           lv;
676
677         Assert(IsA(var, Var));
678         /* Find the appropriate pstate if it's an uplevel Var */
679         for (lv = 0; lv < var->varlevelsup; lv++)
680                 pstate = pstate->parentParseState;
681         markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
682 }
683
684 /*
685  * buildRelationAliases
686  *              Construct the eref column name list for a relation RTE.
687  *              This code is also used for the case of a function RTE returning
688  *              a named composite type.
689  *
690  * tupdesc: the physical column information
691  * alias: the user-supplied alias, or NULL if none
692  * eref: the eref Alias to store column names in
693  *
694  * eref->colnames is filled in.  Also, alias->colnames is rebuilt to insert
695  * empty strings for any dropped columns, so that it will be one-to-one with
696  * physical column numbers.
697  */
698 static void
699 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
700 {
701         int                     maxattrs = tupdesc->natts;
702         ListCell   *aliaslc;
703         int                     numaliases;
704         int                     varattno;
705         int                     numdropped = 0;
706
707         Assert(eref->colnames == NIL);
708
709         if (alias)
710         {
711                 aliaslc = list_head(alias->colnames);
712                 numaliases = list_length(alias->colnames);
713                 /* We'll rebuild the alias colname list */
714                 alias->colnames = NIL;
715         }
716         else
717         {
718                 aliaslc = NULL;
719                 numaliases = 0;
720         }
721
722         for (varattno = 0; varattno < maxattrs; varattno++)
723         {
724                 Form_pg_attribute attr = tupdesc->attrs[varattno];
725                 Value      *attrname;
726
727                 if (attr->attisdropped)
728                 {
729                         /* Always insert an empty string for a dropped column */
730                         attrname = makeString(pstrdup(""));
731                         if (aliaslc)
732                                 alias->colnames = lappend(alias->colnames, attrname);
733                         numdropped++;
734                 }
735                 else if (aliaslc)
736                 {
737                         /* Use the next user-supplied alias */
738                         attrname = (Value *) lfirst(aliaslc);
739                         aliaslc = lnext(aliaslc);
740                         alias->colnames = lappend(alias->colnames, attrname);
741                 }
742                 else
743                 {
744                         attrname = makeString(pstrdup(NameStr(attr->attname)));
745                         /* we're done with the alias if any */
746                 }
747
748                 eref->colnames = lappend(eref->colnames, attrname);
749         }
750
751         /* Too many user-supplied aliases? */
752         if (aliaslc)
753                 ereport(ERROR,
754                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
755                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
756                                                 eref->aliasname, maxattrs - numdropped, numaliases)));
757 }
758
759 /*
760  * buildScalarFunctionAlias
761  *              Construct the eref column name list for a function RTE,
762  *              when the function returns a scalar type (not composite or RECORD).
763  *
764  * funcexpr: transformed expression tree for the function call
765  * funcname: function name (used only for error message)
766  * alias: the user-supplied alias, or NULL if none
767  * eref: the eref Alias to store column names in
768  *
769  * eref->colnames is filled in.
770  */
771 static void
772 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
773                                                  Alias *alias, Alias *eref)
774 {
775         char       *pname;
776
777         Assert(eref->colnames == NIL);
778
779         /* Use user-specified column alias if there is one. */
780         if (alias && alias->colnames != NIL)
781         {
782                 if (list_length(alias->colnames) != 1)
783                         ereport(ERROR,
784                                         (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
785                                   errmsg("too many column aliases specified for function %s",
786                                                  funcname)));
787                 eref->colnames = copyObject(alias->colnames);
788                 return;
789         }
790
791         /*
792          * If the expression is a simple function call, and the function has a
793          * single OUT parameter that is named, use the parameter's name.
794          */
795         if (funcexpr && IsA(funcexpr, FuncExpr))
796         {
797                 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
798                 if (pname)
799                 {
800                         eref->colnames = list_make1(makeString(pname));
801                         return;
802                 }
803         }
804
805         /*
806          * Otherwise use the previously-determined alias (not necessarily the
807          * function name!)
808          */
809         eref->colnames = list_make1(makeString(eref->aliasname));
810 }
811
812 /*
813  * Open a table during parse analysis
814  *
815  * This is essentially just the same as heap_openrv(), except that it caters
816  * to some parser-specific error reporting needs, notably that it arranges
817  * to include the RangeVar's parse location in any resulting error.
818  *
819  * Note: properly, lockmode should be declared LOCKMODE not int, but that
820  * would require importing storage/lock.h into parse_relation.h.  Since
821  * LOCKMODE is typedef'd as int anyway, that seems like overkill.
822  */
823 Relation
824 parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
825 {
826         Relation        rel;
827         ParseCallbackState pcbstate;
828
829         setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
830         rel = try_heap_openrv(relation, lockmode);
831         if (rel == NULL)
832         {
833                 if (relation->schemaname)
834                         ereport(ERROR,
835                                         (errcode(ERRCODE_UNDEFINED_TABLE),
836                                          errmsg("relation \"%s.%s\" does not exist",
837                                                         relation->schemaname, relation->relname)));
838                 else
839                 {
840                         /*
841                          * An unqualified name might have been meant as a reference to
842                          * some not-yet-in-scope CTE.  The bare "does not exist" message
843                          * has proven remarkably unhelpful for figuring out such problems,
844                          * so we take pains to offer a specific hint.
845                          */
846                         if (isFutureCTE(pstate, relation->relname))
847                                 ereport(ERROR,
848                                                 (errcode(ERRCODE_UNDEFINED_TABLE),
849                                                  errmsg("relation \"%s\" does not exist",
850                                                                 relation->relname),
851                                                  errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
852                                                                    relation->relname),
853                                                  errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
854                         else
855                                 ereport(ERROR,
856                                                 (errcode(ERRCODE_UNDEFINED_TABLE),
857                                                  errmsg("relation \"%s\" does not exist",
858                                                                 relation->relname)));
859                 }
860         }
861         cancel_parser_errposition_callback(&pcbstate);
862         return rel;
863 }
864
865 /*
866  * Add an entry for a relation to the pstate's range table (p_rtable).
867  *
868  * If pstate is NULL, we just build an RTE and return it without adding it
869  * to an rtable list.
870  *
871  * Note: formerly this checked for refname conflicts, but that's wrong.
872  * Caller is responsible for checking for conflicts in the appropriate scope.
873  */
874 RangeTblEntry *
875 addRangeTableEntry(ParseState *pstate,
876                                    RangeVar *relation,
877                                    Alias *alias,
878                                    bool inh,
879                                    bool inFromCl)
880 {
881         RangeTblEntry *rte = makeNode(RangeTblEntry);
882         char       *refname = alias ? alias->aliasname : relation->relname;
883         LOCKMODE        lockmode;
884         Relation        rel;
885
886         rte->rtekind = RTE_RELATION;
887         rte->alias = alias;
888
889         /*
890          * Get the rel's OID.  This access also ensures that we have an up-to-date
891          * relcache entry for the rel.  Since this is typically the first access
892          * to a rel in a statement, be careful to get the right access level
893          * depending on whether we're doing SELECT FOR UPDATE/SHARE.
894          */
895         lockmode = isLockedRefname(pstate, refname) ? RowShareLock : AccessShareLock;
896         rel = parserOpenTable(pstate, relation, lockmode);
897         rte->relid = RelationGetRelid(rel);
898
899         /*
900          * Build the list of effective column names using user-supplied aliases
901          * and/or actual column names.
902          */
903         rte->eref = makeAlias(refname, NIL);
904         buildRelationAliases(rel->rd_att, alias, rte->eref);
905
906         /*
907          * Drop the rel refcount, but keep the access lock till end of transaction
908          * so that the table can't be deleted or have its schema modified
909          * underneath us.
910          */
911         heap_close(rel, NoLock);
912
913         /*----------
914          * Flags:
915          * - this RTE should be expanded to include descendant tables,
916          * - this RTE is in the FROM clause,
917          * - this RTE should be checked for appropriate access rights.
918          *
919          * The initial default on access checks is always check-for-READ-access,
920          * which is the right thing for all except target tables.
921          *----------
922          */
923         rte->inh = inh;
924         rte->inFromCl = inFromCl;
925
926         rte->requiredPerms = ACL_SELECT;
927         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
928         rte->selectedCols = NULL;
929         rte->modifiedCols = NULL;
930
931         /*
932          * Add completed RTE to pstate's range table list, but not to join list
933          * nor namespace --- caller must do that if appropriate.
934          */
935         if (pstate != NULL)
936                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
937
938         return rte;
939 }
940
941 /*
942  * Add an entry for a relation to the pstate's range table (p_rtable).
943  *
944  * This is just like addRangeTableEntry() except that it makes an RTE
945  * given an already-open relation instead of a RangeVar reference.
946  */
947 RangeTblEntry *
948 addRangeTableEntryForRelation(ParseState *pstate,
949                                                           Relation rel,
950                                                           Alias *alias,
951                                                           bool inh,
952                                                           bool inFromCl)
953 {
954         RangeTblEntry *rte = makeNode(RangeTblEntry);
955         char       *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
956
957         rte->rtekind = RTE_RELATION;
958         rte->alias = alias;
959         rte->relid = RelationGetRelid(rel);
960
961         /*
962          * Build the list of effective column names using user-supplied aliases
963          * and/or actual column names.
964          */
965         rte->eref = makeAlias(refname, NIL);
966         buildRelationAliases(rel->rd_att, alias, rte->eref);
967
968         /*----------
969          * Flags:
970          * - this RTE should be expanded to include descendant tables,
971          * - this RTE is in the FROM clause,
972          * - this RTE should be checked for appropriate access rights.
973          *
974          * The initial default on access checks is always check-for-READ-access,
975          * which is the right thing for all except target tables.
976          *----------
977          */
978         rte->inh = inh;
979         rte->inFromCl = inFromCl;
980
981         rte->requiredPerms = ACL_SELECT;
982         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
983         rte->selectedCols = NULL;
984         rte->modifiedCols = NULL;
985
986         /*
987          * Add completed RTE to pstate's range table list, but not to join list
988          * nor namespace --- caller must do that if appropriate.
989          */
990         if (pstate != NULL)
991                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
992
993         return rte;
994 }
995
996 /*
997  * Add an entry for a subquery to the pstate's range table (p_rtable).
998  *
999  * This is just like addRangeTableEntry() except that it makes a subquery RTE.
1000  * Note that an alias clause *must* be supplied.
1001  */
1002 RangeTblEntry *
1003 addRangeTableEntryForSubquery(ParseState *pstate,
1004                                                           Query *subquery,
1005                                                           Alias *alias,
1006                                                           bool inFromCl)
1007 {
1008         RangeTblEntry *rte = makeNode(RangeTblEntry);
1009         char       *refname = alias->aliasname;
1010         Alias      *eref;
1011         int                     numaliases;
1012         int                     varattno;
1013         ListCell   *tlistitem;
1014
1015         rte->rtekind = RTE_SUBQUERY;
1016         rte->relid = InvalidOid;
1017         rte->subquery = subquery;
1018         rte->alias = alias;
1019
1020         eref = copyObject(alias);
1021         numaliases = list_length(eref->colnames);
1022
1023         /* fill in any unspecified alias columns */
1024         varattno = 0;
1025         foreach(tlistitem, subquery->targetList)
1026         {
1027                 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1028
1029                 if (te->resjunk)
1030                         continue;
1031                 varattno++;
1032                 Assert(varattno == te->resno);
1033                 if (varattno > numaliases)
1034                 {
1035                         char       *attrname;
1036
1037                         attrname = pstrdup(te->resname);
1038                         eref->colnames = lappend(eref->colnames, makeString(attrname));
1039                 }
1040         }
1041         if (varattno < numaliases)
1042                 ereport(ERROR,
1043                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1044                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
1045                                                 refname, varattno, numaliases)));
1046
1047         rte->eref = eref;
1048
1049         /*----------
1050          * Flags:
1051          * - this RTE should be expanded to include descendant tables,
1052          * - this RTE is in the FROM clause,
1053          * - this RTE should be checked for appropriate access rights.
1054          *
1055          * Subqueries are never checked for access rights.
1056          *----------
1057          */
1058         rte->inh = false;                       /* never true for subqueries */
1059         rte->inFromCl = inFromCl;
1060
1061         rte->requiredPerms = 0;
1062         rte->checkAsUser = InvalidOid;
1063         rte->selectedCols = NULL;
1064         rte->modifiedCols = NULL;
1065
1066         /*
1067          * Add completed RTE to pstate's range table list, but not to join list
1068          * nor namespace --- caller must do that if appropriate.
1069          */
1070         if (pstate != NULL)
1071                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1072
1073         return rte;
1074 }
1075
1076 /*
1077  * Add an entry for a function to the pstate's range table (p_rtable).
1078  *
1079  * This is just like addRangeTableEntry() except that it makes a function RTE.
1080  */
1081 RangeTblEntry *
1082 addRangeTableEntryForFunction(ParseState *pstate,
1083                                                           char *funcname,
1084                                                           Node *funcexpr,
1085                                                           RangeFunction *rangefunc,
1086                                                           bool inFromCl)
1087 {
1088         RangeTblEntry *rte = makeNode(RangeTblEntry);
1089         TypeFuncClass functypclass;
1090         Oid                     funcrettype;
1091         TupleDesc       tupdesc;
1092         Alias      *alias = rangefunc->alias;
1093         List       *coldeflist = rangefunc->coldeflist;
1094         Alias      *eref;
1095
1096         rte->rtekind = RTE_FUNCTION;
1097         rte->relid = InvalidOid;
1098         rte->subquery = NULL;
1099         rte->funcexpr = funcexpr;
1100         rte->funccoltypes = NIL;
1101         rte->funccoltypmods = NIL;
1102         rte->alias = alias;
1103
1104         eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1105         rte->eref = eref;
1106
1107         /*
1108          * Now determine if the function returns a simple or composite type.
1109          */
1110         functypclass = get_expr_result_type(funcexpr,
1111                                                                                 &funcrettype,
1112                                                                                 &tupdesc);
1113
1114         /*
1115          * A coldeflist is required if the function returns RECORD and hasn't got
1116          * a predetermined record type, and is prohibited otherwise.
1117          */
1118         if (coldeflist != NIL)
1119         {
1120                 if (functypclass != TYPEFUNC_RECORD)
1121                         ereport(ERROR,
1122                                         (errcode(ERRCODE_SYNTAX_ERROR),
1123                                          errmsg("a column definition list is only allowed for functions returning \"record\""),
1124                                          parser_errposition(pstate, exprLocation(funcexpr))));
1125         }
1126         else
1127         {
1128                 if (functypclass == TYPEFUNC_RECORD)
1129                         ereport(ERROR,
1130                                         (errcode(ERRCODE_SYNTAX_ERROR),
1131                                          errmsg("a column definition list is required for functions returning \"record\""),
1132                                          parser_errposition(pstate, exprLocation(funcexpr))));
1133         }
1134
1135         if (functypclass == TYPEFUNC_COMPOSITE)
1136         {
1137                 /* Composite data type, e.g. a table's row type */
1138                 Assert(tupdesc);
1139                 /* Build the column alias list */
1140                 buildRelationAliases(tupdesc, alias, eref);
1141         }
1142         else if (functypclass == TYPEFUNC_SCALAR)
1143         {
1144                 /* Base data type, i.e. scalar */
1145                 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1146         }
1147         else if (functypclass == TYPEFUNC_RECORD)
1148         {
1149                 ListCell   *col;
1150
1151                 /*
1152                  * Use the column definition list to form the alias list and
1153                  * funccoltypes/funccoltypmods lists.
1154                  */
1155                 foreach(col, coldeflist)
1156                 {
1157                         ColumnDef  *n = (ColumnDef *) lfirst(col);
1158                         char       *attrname;
1159                         Oid                     attrtype;
1160                         int32           attrtypmod;
1161
1162                         attrname = pstrdup(n->colname);
1163                         if (n->typeName->setof)
1164                                 ereport(ERROR,
1165                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1166                                                  errmsg("column \"%s\" cannot be declared SETOF",
1167                                                                 attrname),
1168                                                  parser_errposition(pstate, n->typeName->location)));
1169                         attrtype = typenameTypeId(pstate, n->typeName, &attrtypmod);
1170                         eref->colnames = lappend(eref->colnames, makeString(attrname));
1171                         rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1172                         rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1173                 }
1174         }
1175         else
1176                 ereport(ERROR,
1177                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1178                          errmsg("function \"%s\" in FROM has unsupported return type %s",
1179                                         funcname, format_type_be(funcrettype)),
1180                                  parser_errposition(pstate, exprLocation(funcexpr))));
1181
1182         /*----------
1183          * Flags:
1184          * - this RTE should be expanded to include descendant tables,
1185          * - this RTE is in the FROM clause,
1186          * - this RTE should be checked for appropriate access rights.
1187          *
1188          * Functions are never checked for access rights (at least, not by
1189          * the RTE permissions mechanism).
1190          *----------
1191          */
1192         rte->inh = false;                       /* never true for functions */
1193         rte->inFromCl = inFromCl;
1194
1195         rte->requiredPerms = 0;
1196         rte->checkAsUser = InvalidOid;
1197         rte->selectedCols = NULL;
1198         rte->modifiedCols = NULL;
1199
1200         /*
1201          * Add completed RTE to pstate's range table list, but not to join list
1202          * nor namespace --- caller must do that if appropriate.
1203          */
1204         if (pstate != NULL)
1205                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1206
1207         return rte;
1208 }
1209
1210 /*
1211  * Add an entry for a VALUES list to the pstate's range table (p_rtable).
1212  *
1213  * This is much like addRangeTableEntry() except that it makes a values RTE.
1214  */
1215 RangeTblEntry *
1216 addRangeTableEntryForValues(ParseState *pstate,
1217                                                         List *exprs,
1218                                                         Alias *alias,
1219                                                         bool inFromCl)
1220 {
1221         RangeTblEntry *rte = makeNode(RangeTblEntry);
1222         char       *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1223         Alias      *eref;
1224         int                     numaliases;
1225         int                     numcolumns;
1226
1227         rte->rtekind = RTE_VALUES;
1228         rte->relid = InvalidOid;
1229         rte->subquery = NULL;
1230         rte->values_lists = exprs;
1231         rte->alias = alias;
1232
1233         eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1234
1235         /* fill in any unspecified alias columns */
1236         numcolumns = list_length((List *) linitial(exprs));
1237         numaliases = list_length(eref->colnames);
1238         while (numaliases < numcolumns)
1239         {
1240                 char            attrname[64];
1241
1242                 numaliases++;
1243                 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1244                 eref->colnames = lappend(eref->colnames,
1245                                                                  makeString(pstrdup(attrname)));
1246         }
1247         if (numcolumns < numaliases)
1248                 ereport(ERROR,
1249                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1250                                  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1251                                                 refname, numcolumns, numaliases)));
1252
1253         rte->eref = eref;
1254
1255         /*----------
1256          * Flags:
1257          * - this RTE should be expanded to include descendant tables,
1258          * - this RTE is in the FROM clause,
1259          * - this RTE should be checked for appropriate access rights.
1260          *
1261          * Subqueries are never checked for access rights.
1262          *----------
1263          */
1264         rte->inh = false;                       /* never true for values RTEs */
1265         rte->inFromCl = inFromCl;
1266
1267         rte->requiredPerms = 0;
1268         rte->checkAsUser = InvalidOid;
1269         rte->selectedCols = NULL;
1270         rte->modifiedCols = NULL;
1271
1272         /*
1273          * Add completed RTE to pstate's range table list, but not to join list
1274          * nor namespace --- caller must do that if appropriate.
1275          */
1276         if (pstate != NULL)
1277                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1278
1279         return rte;
1280 }
1281
1282 /*
1283  * Add an entry for a join to the pstate's range table (p_rtable).
1284  *
1285  * This is much like addRangeTableEntry() except that it makes a join RTE.
1286  */
1287 RangeTblEntry *
1288 addRangeTableEntryForJoin(ParseState *pstate,
1289                                                   List *colnames,
1290                                                   JoinType jointype,
1291                                                   List *aliasvars,
1292                                                   Alias *alias,
1293                                                   bool inFromCl)
1294 {
1295         RangeTblEntry *rte = makeNode(RangeTblEntry);
1296         Alias      *eref;
1297         int                     numaliases;
1298
1299         /*
1300          * Fail if join has too many columns --- we must be able to reference any
1301          * of the columns with an AttrNumber.
1302          */
1303         if (list_length(aliasvars) > MaxAttrNumber)
1304                 ereport(ERROR,
1305                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1306                                  errmsg("joins can have at most %d columns",
1307                                                 MaxAttrNumber)));
1308
1309         rte->rtekind = RTE_JOIN;
1310         rte->relid = InvalidOid;
1311         rte->subquery = NULL;
1312         rte->jointype = jointype;
1313         rte->joinaliasvars = aliasvars;
1314         rte->alias = alias;
1315
1316         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1317         numaliases = list_length(eref->colnames);
1318
1319         /* fill in any unspecified alias columns */
1320         if (numaliases < list_length(colnames))
1321                 eref->colnames = list_concat(eref->colnames,
1322                                                                          list_copy_tail(colnames, numaliases));
1323
1324         rte->eref = eref;
1325
1326         /*----------
1327          * Flags:
1328          * - this RTE should be expanded to include descendant tables,
1329          * - this RTE is in the FROM clause,
1330          * - this RTE should be checked for appropriate access rights.
1331          *
1332          * Joins are never checked for access rights.
1333          *----------
1334          */
1335         rte->inh = false;                       /* never true for joins */
1336         rte->inFromCl = inFromCl;
1337
1338         rte->requiredPerms = 0;
1339         rte->checkAsUser = InvalidOid;
1340         rte->selectedCols = NULL;
1341         rte->modifiedCols = NULL;
1342
1343         /*
1344          * Add completed RTE to pstate's range table list, but not to join list
1345          * nor namespace --- caller must do that if appropriate.
1346          */
1347         if (pstate != NULL)
1348                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1349
1350         return rte;
1351 }
1352
1353 /*
1354  * Add an entry for a CTE reference to the pstate's range table (p_rtable).
1355  *
1356  * This is much like addRangeTableEntry() except that it makes a CTE RTE.
1357  */
1358 RangeTblEntry *
1359 addRangeTableEntryForCTE(ParseState *pstate,
1360                                                  CommonTableExpr *cte,
1361                                                  Index levelsup,
1362                                                  Alias *alias,
1363                                                  bool inFromCl)
1364 {
1365         RangeTblEntry *rte = makeNode(RangeTblEntry);
1366         char       *refname = alias ? alias->aliasname : cte->ctename;
1367         Alias      *eref;
1368         int                     numaliases;
1369         int                     varattno;
1370         ListCell   *lc;
1371
1372         rte->rtekind = RTE_CTE;
1373         rte->ctename = cte->ctename;
1374         rte->ctelevelsup = levelsup;
1375
1376         /* Self-reference if and only if CTE's parse analysis isn't completed */
1377         rte->self_reference = !IsA(cte->ctequery, Query);
1378         Assert(cte->cterecursive || !rte->self_reference);
1379         /* Bump the CTE's refcount if this isn't a self-reference */
1380         if (!rte->self_reference)
1381                 cte->cterefcount++;
1382
1383         rte->ctecoltypes = cte->ctecoltypes;
1384         rte->ctecoltypmods = cte->ctecoltypmods;
1385
1386         rte->alias = alias;
1387         if (alias)
1388                 eref = copyObject(alias);
1389         else
1390                 eref = makeAlias(refname, NIL);
1391         numaliases = list_length(eref->colnames);
1392
1393         /* fill in any unspecified alias columns */
1394         varattno = 0;
1395         foreach(lc, cte->ctecolnames)
1396         {
1397                 varattno++;
1398                 if (varattno > numaliases)
1399                         eref->colnames = lappend(eref->colnames, lfirst(lc));
1400         }
1401         if (varattno < numaliases)
1402                 ereport(ERROR,
1403                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1404                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
1405                                                 refname, varattno, numaliases)));
1406
1407         rte->eref = eref;
1408
1409         /*----------
1410          * Flags:
1411          * - this RTE should be expanded to include descendant tables,
1412          * - this RTE is in the FROM clause,
1413          * - this RTE should be checked for appropriate access rights.
1414          *
1415          * Subqueries are never checked for access rights.
1416          *----------
1417          */
1418         rte->inh = false;                       /* never true for subqueries */
1419         rte->inFromCl = inFromCl;
1420
1421         rte->requiredPerms = 0;
1422         rte->checkAsUser = InvalidOid;
1423         rte->selectedCols = NULL;
1424         rte->modifiedCols = NULL;
1425
1426         /*
1427          * Add completed RTE to pstate's range table list, but not to join list
1428          * nor namespace --- caller must do that if appropriate.
1429          */
1430         if (pstate != NULL)
1431                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1432
1433         return rte;
1434 }
1435
1436
1437 /*
1438  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1439  *
1440  * This is used when we have not yet done transformLockingClause, but need
1441  * to know the correct lock to take during initial opening of relations.
1442  *
1443  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE,
1444  * since the table-level lock is the same either way.
1445  */
1446 bool
1447 isLockedRefname(ParseState *pstate, const char *refname)
1448 {
1449         ListCell   *l;
1450
1451         /*
1452          * If we are in a subquery specified as locked FOR UPDATE/SHARE from
1453          * parent level, then act as though there's a generic FOR UPDATE here.
1454          */
1455         if (pstate->p_locked_from_parent)
1456                 return true;
1457
1458         foreach(l, pstate->p_locking_clause)
1459         {
1460                 LockingClause *lc = (LockingClause *) lfirst(l);
1461
1462                 if (lc->lockedRels == NIL)
1463                 {
1464                         /* all tables used in query */
1465                         return true;
1466                 }
1467                 else
1468                 {
1469                         /* just the named tables */
1470                         ListCell   *l2;
1471
1472                         foreach(l2, lc->lockedRels)
1473                         {
1474                                 RangeVar   *thisrel = (RangeVar *) lfirst(l2);
1475
1476                                 if (strcmp(refname, thisrel->relname) == 0)
1477                                         return true;
1478                         }
1479                 }
1480         }
1481         return false;
1482 }
1483
1484 /*
1485  * Add the given RTE as a top-level entry in the pstate's join list
1486  * and/or name space lists.  (We assume caller has checked for any
1487  * namespace conflicts.)
1488  */
1489 void
1490 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1491                           bool addToJoinList,
1492                           bool addToRelNameSpace, bool addToVarNameSpace)
1493 {
1494         if (addToJoinList)
1495         {
1496                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1497                 RangeTblRef *rtr = makeNode(RangeTblRef);
1498
1499                 rtr->rtindex = rtindex;
1500                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1501         }
1502         if (addToRelNameSpace)
1503                 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1504         if (addToVarNameSpace)
1505                 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1506 }
1507
1508 /*
1509  * expandRTE -- expand the columns of a rangetable entry
1510  *
1511  * This creates lists of an RTE's column names (aliases if provided, else
1512  * real names) and Vars for each column.  Only user columns are considered.
1513  * If include_dropped is FALSE then dropped columns are omitted from the
1514  * results.  If include_dropped is TRUE then empty strings and NULL constants
1515  * (not Vars!) are returned for dropped columns.
1516  *
1517  * rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1518  * values to use in the created Vars.  Ordinarily rtindex should match the
1519  * actual position of the RTE in its rangetable.
1520  *
1521  * The output lists go into *colnames and *colvars.
1522  * If only one of the two kinds of output list is needed, pass NULL for the
1523  * output pointer for the unwanted one.
1524  */
1525 void
1526 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1527                   int location, bool include_dropped,
1528                   List **colnames, List **colvars)
1529 {
1530         int                     varattno;
1531
1532         if (colnames)
1533                 *colnames = NIL;
1534         if (colvars)
1535                 *colvars = NIL;
1536
1537         switch (rte->rtekind)
1538         {
1539                 case RTE_RELATION:
1540                         /* Ordinary relation RTE */
1541                         expandRelation(rte->relid, rte->eref,
1542                                                    rtindex, sublevels_up, location,
1543                                                    include_dropped, colnames, colvars);
1544                         break;
1545                 case RTE_SUBQUERY:
1546                         {
1547                                 /* Subquery RTE */
1548                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1549                                 ListCell   *tlistitem;
1550
1551                                 varattno = 0;
1552                                 foreach(tlistitem, rte->subquery->targetList)
1553                                 {
1554                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1555
1556                                         if (te->resjunk)
1557                                                 continue;
1558                                         varattno++;
1559                                         Assert(varattno == te->resno);
1560
1561                                         if (colnames)
1562                                         {
1563                                                 /* Assume there is one alias per target item */
1564                                                 char       *label = strVal(lfirst(aliasp_item));
1565
1566                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1567                                                 aliasp_item = lnext(aliasp_item);
1568                                         }
1569
1570                                         if (colvars)
1571                                         {
1572                                                 Var                *varnode;
1573
1574                                                 varnode = makeVar(rtindex, varattno,
1575                                                                                   exprType((Node *) te->expr),
1576                                                                                   exprTypmod((Node *) te->expr),
1577                                                                                   sublevels_up);
1578                                                 varnode->location = location;
1579
1580                                                 *colvars = lappend(*colvars, varnode);
1581                                         }
1582                                 }
1583                         }
1584                         break;
1585                 case RTE_FUNCTION:
1586                         {
1587                                 /* Function RTE */
1588                                 TypeFuncClass functypclass;
1589                                 Oid                     funcrettype;
1590                                 TupleDesc       tupdesc;
1591
1592                                 functypclass = get_expr_result_type(rte->funcexpr,
1593                                                                                                         &funcrettype,
1594                                                                                                         &tupdesc);
1595                                 if (functypclass == TYPEFUNC_COMPOSITE)
1596                                 {
1597                                         /* Composite data type, e.g. a table's row type */
1598                                         Assert(tupdesc);
1599                                         expandTupleDesc(tupdesc, rte->eref,
1600                                                                         rtindex, sublevels_up, location,
1601                                                                         include_dropped, colnames, colvars);
1602                                 }
1603                                 else if (functypclass == TYPEFUNC_SCALAR)
1604                                 {
1605                                         /* Base data type, i.e. scalar */
1606                                         if (colnames)
1607                                                 *colnames = lappend(*colnames,
1608                                                                                         linitial(rte->eref->colnames));
1609
1610                                         if (colvars)
1611                                         {
1612                                                 Var                *varnode;
1613
1614                                                 varnode = makeVar(rtindex, 1,
1615                                                                                   funcrettype, -1,
1616                                                                                   sublevels_up);
1617                                                 varnode->location = location;
1618
1619                                                 *colvars = lappend(*colvars, varnode);
1620                                         }
1621                                 }
1622                                 else if (functypclass == TYPEFUNC_RECORD)
1623                                 {
1624                                         if (colnames)
1625                                                 *colnames = copyObject(rte->eref->colnames);
1626                                         if (colvars)
1627                                         {
1628                                                 ListCell   *l1;
1629                                                 ListCell   *l2;
1630                                                 int                     attnum = 0;
1631
1632                                                 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1633                                                 {
1634                                                         Oid                     attrtype = lfirst_oid(l1);
1635                                                         int32           attrtypmod = lfirst_int(l2);
1636                                                         Var                *varnode;
1637
1638                                                         attnum++;
1639                                                         varnode = makeVar(rtindex,
1640                                                                                           attnum,
1641                                                                                           attrtype,
1642                                                                                           attrtypmod,
1643                                                                                           sublevels_up);
1644                                                         varnode->location = location;
1645                                                         *colvars = lappend(*colvars, varnode);
1646                                                 }
1647                                         }
1648                                 }
1649                                 else
1650                                 {
1651                                         /* addRangeTableEntryForFunction should've caught this */
1652                                         elog(ERROR, "function in FROM has unsupported return type");
1653                                 }
1654                         }
1655                         break;
1656                 case RTE_VALUES:
1657                         {
1658                                 /* Values RTE */
1659                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1660                                 ListCell   *lc;
1661
1662                                 varattno = 0;
1663                                 foreach(lc, (List *) linitial(rte->values_lists))
1664                                 {
1665                                         Node       *col = (Node *) lfirst(lc);
1666
1667                                         varattno++;
1668                                         if (colnames)
1669                                         {
1670                                                 /* Assume there is one alias per column */
1671                                                 char       *label = strVal(lfirst(aliasp_item));
1672
1673                                                 *colnames = lappend(*colnames,
1674                                                                                         makeString(pstrdup(label)));
1675                                                 aliasp_item = lnext(aliasp_item);
1676                                         }
1677
1678                                         if (colvars)
1679                                         {
1680                                                 Var                *varnode;
1681
1682                                                 varnode = makeVar(rtindex, varattno,
1683                                                                                   exprType(col),
1684                                                                                   exprTypmod(col),
1685                                                                                   sublevels_up);
1686                                                 varnode->location = location;
1687                                                 *colvars = lappend(*colvars, varnode);
1688                                         }
1689                                 }
1690                         }
1691                         break;
1692                 case RTE_JOIN:
1693                         {
1694                                 /* Join RTE */
1695                                 ListCell   *colname;
1696                                 ListCell   *aliasvar;
1697
1698                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1699
1700                                 varattno = 0;
1701                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1702                                 {
1703                                         Node       *avar = (Node *) lfirst(aliasvar);
1704
1705                                         varattno++;
1706
1707                                         /*
1708                                          * During ordinary parsing, there will never be any
1709                                          * deleted columns in the join; but we have to check since
1710                                          * this routine is also used by the rewriter, and joins
1711                                          * found in stored rules might have join columns for
1712                                          * since-deleted columns.  This will be signaled by a NULL
1713                                          * Const in the alias-vars list.
1714                                          */
1715                                         if (IsA(avar, Const))
1716                                         {
1717                                                 if (include_dropped)
1718                                                 {
1719                                                         if (colnames)
1720                                                                 *colnames = lappend(*colnames,
1721                                                                                                         makeString(pstrdup("")));
1722                                                         if (colvars)
1723                                                                 *colvars = lappend(*colvars,
1724                                                                                                    copyObject(avar));
1725                                                 }
1726                                                 continue;
1727                                         }
1728
1729                                         if (colnames)
1730                                         {
1731                                                 char       *label = strVal(lfirst(colname));
1732
1733                                                 *colnames = lappend(*colnames,
1734                                                                                         makeString(pstrdup(label)));
1735                                         }
1736
1737                                         if (colvars)
1738                                         {
1739                                                 Var                *varnode;
1740
1741                                                 varnode = makeVar(rtindex, varattno,
1742                                                                                   exprType(avar),
1743                                                                                   exprTypmod(avar),
1744                                                                                   sublevels_up);
1745                                                 varnode->location = location;
1746
1747                                                 *colvars = lappend(*colvars, varnode);
1748                                         }
1749                                 }
1750                         }
1751                         break;
1752                 case RTE_CTE:
1753                         {
1754                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1755                                 ListCell   *lct;
1756                                 ListCell   *lcm;
1757
1758                                 varattno = 0;
1759                                 forboth(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods)
1760                                 {
1761                                         Oid                     coltype = lfirst_oid(lct);
1762                                         int32           coltypmod = lfirst_int(lcm);
1763
1764                                         varattno++;
1765
1766                                         if (colnames)
1767                                         {
1768                                                 /* Assume there is one alias per output column */
1769                                                 char       *label = strVal(lfirst(aliasp_item));
1770
1771                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1772                                                 aliasp_item = lnext(aliasp_item);
1773                                         }
1774
1775                                         if (colvars)
1776                                         {
1777                                                 Var                *varnode;
1778
1779                                                 varnode = makeVar(rtindex, varattno,
1780                                                                                   coltype, coltypmod,
1781                                                                                   sublevels_up);
1782                                                 *colvars = lappend(*colvars, varnode);
1783                                         }
1784                                 }
1785                         }
1786                         break;
1787                 default:
1788                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1789         }
1790 }
1791
1792 /*
1793  * expandRelation -- expandRTE subroutine
1794  */
1795 static void
1796 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1797                            int location, bool include_dropped,
1798                            List **colnames, List **colvars)
1799 {
1800         Relation        rel;
1801
1802         /* Get the tupledesc and turn it over to expandTupleDesc */
1803         rel = relation_open(relid, AccessShareLock);
1804         expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1805                                         location, include_dropped,
1806                                         colnames, colvars);
1807         relation_close(rel, AccessShareLock);
1808 }
1809
1810 /*
1811  * expandTupleDesc -- expandRTE subroutine
1812  */
1813 static void
1814 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1815                                 int rtindex, int sublevels_up,
1816                                 int location, bool include_dropped,
1817                                 List **colnames, List **colvars)
1818 {
1819         int                     maxattrs = tupdesc->natts;
1820         int                     numaliases = list_length(eref->colnames);
1821         int                     varattno;
1822
1823         for (varattno = 0; varattno < maxattrs; varattno++)
1824         {
1825                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1826
1827                 if (attr->attisdropped)
1828                 {
1829                         if (include_dropped)
1830                         {
1831                                 if (colnames)
1832                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1833                                 if (colvars)
1834                                 {
1835                                         /*
1836                                          * can't use atttypid here, but it doesn't really matter
1837                                          * what type the Const claims to be.
1838                                          */
1839                                         *colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1840                                 }
1841                         }
1842                         continue;
1843                 }
1844
1845                 if (colnames)
1846                 {
1847                         char       *label;
1848
1849                         if (varattno < numaliases)
1850                                 label = strVal(list_nth(eref->colnames, varattno));
1851                         else
1852                                 label = NameStr(attr->attname);
1853                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
1854                 }
1855
1856                 if (colvars)
1857                 {
1858                         Var                *varnode;
1859
1860                         varnode = makeVar(rtindex, attr->attnum,
1861                                                           attr->atttypid, attr->atttypmod,
1862                                                           sublevels_up);
1863                         varnode->location = location;
1864
1865                         *colvars = lappend(*colvars, varnode);
1866                 }
1867         }
1868 }
1869
1870 /*
1871  * expandRelAttrs -
1872  *        Workhorse for "*" expansion: produce a list of targetentries
1873  *        for the attributes of the RTE
1874  *
1875  * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1876  * fields of the Vars produced, and location sets their location.
1877  * pstate->p_next_resno determines the resnos assigned to the TLEs.
1878  * The referenced columns are marked as requiring SELECT access.
1879  */
1880 List *
1881 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1882                            int rtindex, int sublevels_up, int location)
1883 {
1884         List       *names,
1885                            *vars;
1886         ListCell   *name,
1887                            *var;
1888         List       *te_list = NIL;
1889
1890         expandRTE(rte, rtindex, sublevels_up, location, false,
1891                           &names, &vars);
1892
1893         /*
1894          * Require read access to the table.  This is normally redundant with the
1895          * markVarForSelectPriv calls below, but not if the table has zero
1896          * columns.
1897          */
1898         rte->requiredPerms |= ACL_SELECT;
1899
1900         forboth(name, names, var, vars)
1901         {
1902                 char       *label = strVal(lfirst(name));
1903                 Var                *varnode = (Var *) lfirst(var);
1904                 TargetEntry *te;
1905
1906                 te = makeTargetEntry((Expr *) varnode,
1907                                                          (AttrNumber) pstate->p_next_resno++,
1908                                                          label,
1909                                                          false);
1910                 te_list = lappend(te_list, te);
1911
1912                 /* Require read access to each column */
1913                 markVarForSelectPriv(pstate, varnode, rte);
1914         }
1915
1916         Assert(name == NULL && var == NULL);            /* lists not the same length? */
1917
1918         return te_list;
1919 }
1920
1921 /*
1922  * get_rte_attribute_name
1923  *              Get an attribute name from a RangeTblEntry
1924  *
1925  * This is unlike get_attname() because we use aliases if available.
1926  * In particular, it will work on an RTE for a subselect or join, whereas
1927  * get_attname() only works on real relations.
1928  *
1929  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1930  * occurs when a Var represents a whole tuple of a relation.
1931  */
1932 char *
1933 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1934 {
1935         if (attnum == InvalidAttrNumber)
1936                 return "*";
1937
1938         /*
1939          * If there is a user-written column alias, use it.
1940          */
1941         if (rte->alias &&
1942                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1943                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1944
1945         /*
1946          * If the RTE is a relation, go to the system catalogs not the
1947          * eref->colnames list.  This is a little slower but it will give the
1948          * right answer if the column has been renamed since the eref list was
1949          * built (which can easily happen for rules).
1950          */
1951         if (rte->rtekind == RTE_RELATION)
1952                 return get_relid_attribute_name(rte->relid, attnum);
1953
1954         /*
1955          * Otherwise use the column name from eref.  There should always be one.
1956          */
1957         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1958                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1959
1960         /* else caller gave us a bogus attnum */
1961         elog(ERROR, "invalid attnum %d for rangetable entry %s",
1962                  attnum, rte->eref->aliasname);
1963         return NULL;                            /* keep compiler quiet */
1964 }
1965
1966 /*
1967  * get_rte_attribute_type
1968  *              Get attribute type information from a RangeTblEntry
1969  */
1970 void
1971 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1972                                            Oid *vartype, int32 *vartypmod)
1973 {
1974         switch (rte->rtekind)
1975         {
1976                 case RTE_RELATION:
1977                         {
1978                                 /* Plain relation RTE --- get the attribute's type info */
1979                                 HeapTuple       tp;
1980                                 Form_pg_attribute att_tup;
1981
1982                                 tp = SearchSysCache(ATTNUM,
1983                                                                         ObjectIdGetDatum(rte->relid),
1984                                                                         Int16GetDatum(attnum),
1985                                                                         0, 0);
1986                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1987                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1988                                                  attnum, rte->relid);
1989                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1990
1991                                 /*
1992                                  * If dropped column, pretend it ain't there.  See notes in
1993                                  * scanRTEForColumn.
1994                                  */
1995                                 if (att_tup->attisdropped)
1996                                         ereport(ERROR,
1997                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1998                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
1999                                                    NameStr(att_tup->attname),
2000                                                    get_rel_name(rte->relid))));
2001                                 *vartype = att_tup->atttypid;
2002                                 *vartypmod = att_tup->atttypmod;
2003                                 ReleaseSysCache(tp);
2004                         }
2005                         break;
2006                 case RTE_SUBQUERY:
2007                         {
2008                                 /* Subselect RTE --- get type info from subselect's tlist */
2009                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2010                                                                                                    attnum);
2011
2012                                 if (te == NULL || te->resjunk)
2013                                         elog(ERROR, "subquery %s does not have attribute %d",
2014                                                  rte->eref->aliasname, attnum);
2015                                 *vartype = exprType((Node *) te->expr);
2016                                 *vartypmod = exprTypmod((Node *) te->expr);
2017                         }
2018                         break;
2019                 case RTE_FUNCTION:
2020                         {
2021                                 /* Function RTE */
2022                                 TypeFuncClass functypclass;
2023                                 Oid                     funcrettype;
2024                                 TupleDesc       tupdesc;
2025
2026                                 functypclass = get_expr_result_type(rte->funcexpr,
2027                                                                                                         &funcrettype,
2028                                                                                                         &tupdesc);
2029
2030                                 if (functypclass == TYPEFUNC_COMPOSITE)
2031                                 {
2032                                         /* Composite data type, e.g. a table's row type */
2033                                         Form_pg_attribute att_tup;
2034
2035                                         Assert(tupdesc);
2036                                         /* this is probably a can't-happen case */
2037                                         if (attnum < 1 || attnum > tupdesc->natts)
2038                                                 ereport(ERROR,
2039                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
2040                                                 errmsg("column %d of relation \"%s\" does not exist",
2041                                                            attnum,
2042                                                            rte->eref->aliasname)));
2043
2044                                         att_tup = tupdesc->attrs[attnum - 1];
2045
2046                                         /*
2047                                          * If dropped column, pretend it ain't there.  See notes
2048                                          * in scanRTEForColumn.
2049                                          */
2050                                         if (att_tup->attisdropped)
2051                                                 ereport(ERROR,
2052                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
2053                                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
2054                                                                                 NameStr(att_tup->attname),
2055                                                                                 rte->eref->aliasname)));
2056                                         *vartype = att_tup->atttypid;
2057                                         *vartypmod = att_tup->atttypmod;
2058                                 }
2059                                 else if (functypclass == TYPEFUNC_SCALAR)
2060                                 {
2061                                         /* Base data type, i.e. scalar */
2062                                         *vartype = funcrettype;
2063                                         *vartypmod = -1;
2064                                 }
2065                                 else if (functypclass == TYPEFUNC_RECORD)
2066                                 {
2067                                         *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2068                                         *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2069                                 }
2070                                 else
2071                                 {
2072                                         /* addRangeTableEntryForFunction should've caught this */
2073                                         elog(ERROR, "function in FROM has unsupported return type");
2074                                 }
2075                         }
2076                         break;
2077                 case RTE_VALUES:
2078                         {
2079                                 /* Values RTE --- get type info from first sublist */
2080                                 List       *collist = (List *) linitial(rte->values_lists);
2081                                 Node       *col;
2082
2083                                 if (attnum < 1 || attnum > list_length(collist))
2084                                         elog(ERROR, "values list %s does not have attribute %d",
2085                                                  rte->eref->aliasname, attnum);
2086                                 col = (Node *) list_nth(collist, attnum - 1);
2087                                 *vartype = exprType(col);
2088                                 *vartypmod = exprTypmod(col);
2089                         }
2090                         break;
2091                 case RTE_JOIN:
2092                         {
2093                                 /*
2094                                  * Join RTE --- get type info from join RTE's alias variable
2095                                  */
2096                                 Node       *aliasvar;
2097
2098                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2099                                 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2100                                 *vartype = exprType(aliasvar);
2101                                 *vartypmod = exprTypmod(aliasvar);
2102                         }
2103                         break;
2104                 case RTE_CTE:
2105                         {
2106                                 /* CTE RTE --- get type info from lists in the RTE */
2107                                 Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2108                                 *vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2109                                 *vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2110                         }
2111                         break;
2112                 default:
2113                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2114         }
2115 }
2116
2117 /*
2118  * get_rte_attribute_is_dropped
2119  *              Check whether attempted attribute ref is to a dropped column
2120  */
2121 bool
2122 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2123 {
2124         bool            result;
2125
2126         switch (rte->rtekind)
2127         {
2128                 case RTE_RELATION:
2129                         {
2130                                 /*
2131                                  * Plain relation RTE --- get the attribute's catalog entry
2132                                  */
2133                                 HeapTuple       tp;
2134                                 Form_pg_attribute att_tup;
2135
2136                                 tp = SearchSysCache(ATTNUM,
2137                                                                         ObjectIdGetDatum(rte->relid),
2138                                                                         Int16GetDatum(attnum),
2139                                                                         0, 0);
2140                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
2141                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2142                                                  attnum, rte->relid);
2143                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2144                                 result = att_tup->attisdropped;
2145                                 ReleaseSysCache(tp);
2146                         }
2147                         break;
2148                 case RTE_SUBQUERY:
2149                 case RTE_VALUES:
2150                 case RTE_CTE:
2151                         /* Subselect, Values, CTE RTEs never have dropped columns */
2152                         result = false;
2153                         break;
2154                 case RTE_JOIN:
2155                         {
2156                                 /*
2157                                  * A join RTE would not have dropped columns when constructed,
2158                                  * but one in a stored rule might contain columns that were
2159                                  * dropped from the underlying tables, if said columns are
2160                                  * nowhere explicitly referenced in the rule.  This will be
2161                                  * signaled to us by a NULL Const in the joinaliasvars list.
2162                                  */
2163                                 Var                *aliasvar;
2164
2165                                 if (attnum <= 0 ||
2166                                         attnum > list_length(rte->joinaliasvars))
2167                                         elog(ERROR, "invalid varattno %d", attnum);
2168                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2169
2170                                 result = IsA(aliasvar, Const);
2171                         }
2172                         break;
2173                 case RTE_FUNCTION:
2174                         {
2175                                 /* Function RTE */
2176                                 Oid                     funcrettype = exprType(rte->funcexpr);
2177                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
2178
2179                                 if (OidIsValid(funcrelid))
2180                                 {
2181                                         /*
2182                                          * Composite data type, i.e. a table's row type
2183                                          *
2184                                          * Same as ordinary relation RTE
2185                                          */
2186                                         HeapTuple       tp;
2187                                         Form_pg_attribute att_tup;
2188
2189                                         tp = SearchSysCache(ATTNUM,
2190                                                                                 ObjectIdGetDatum(funcrelid),
2191                                                                                 Int16GetDatum(attnum),
2192                                                                                 0, 0);
2193                                         if (!HeapTupleIsValid(tp))      /* shouldn't happen */
2194                                                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2195                                                          attnum, funcrelid);
2196                                         att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2197                                         result = att_tup->attisdropped;
2198                                         ReleaseSysCache(tp);
2199                                 }
2200                                 else
2201                                 {
2202                                         /*
2203                                          * Must be a base data type, i.e. scalar
2204                                          */
2205                                         result = false;
2206                                 }
2207                         }
2208                         break;
2209                 default:
2210                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2211                         result = false;         /* keep compiler quiet */
2212         }
2213
2214         return result;
2215 }
2216
2217 /*
2218  * Given a targetlist and a resno, return the matching TargetEntry
2219  *
2220  * Returns NULL if resno is not present in list.
2221  *
2222  * Note: we need to search, rather than just indexing with list_nth(),
2223  * because not all tlists are sorted by resno.
2224  */
2225 TargetEntry *
2226 get_tle_by_resno(List *tlist, AttrNumber resno)
2227 {
2228         ListCell   *l;
2229
2230         foreach(l, tlist)
2231         {
2232                 TargetEntry *tle = (TargetEntry *) lfirst(l);
2233
2234                 if (tle->resno == resno)
2235                         return tle;
2236         }
2237         return NULL;
2238 }
2239
2240 /*
2241  * Given a Query and rangetable index, return relation's RowMarkClause if any
2242  *
2243  * Returns NULL if relation is not selected FOR UPDATE/SHARE
2244  */
2245 RowMarkClause *
2246 get_parse_rowmark(Query *qry, Index rtindex)
2247 {
2248         ListCell   *l;
2249
2250         foreach(l, qry->rowMarks)
2251         {
2252                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2253
2254                 if (rc->rti == rtindex)
2255                         return rc;
2256         }
2257         return NULL;
2258 }
2259
2260 /*
2261  *      given relation and att name, return attnum of variable
2262  *
2263  *      Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2264  *
2265  *      This should only be used if the relation is already
2266  *      heap_open()'ed.  Use the cache version get_attnum()
2267  *      for access to non-opened relations.
2268  */
2269 int
2270 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2271 {
2272         int                     i;
2273
2274         for (i = 0; i < rd->rd_rel->relnatts; i++)
2275         {
2276                 Form_pg_attribute att = rd->rd_att->attrs[i];
2277
2278                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2279                         return i + 1;
2280         }
2281
2282         if (sysColOK)
2283         {
2284                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2285                 {
2286                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2287                                 return i;
2288                 }
2289         }
2290
2291         /* on failure */
2292         return InvalidAttrNumber;
2293 }
2294
2295 /* specialAttNum()
2296  *
2297  * Check attribute name to see if it is "special", e.g. "oid".
2298  * - thomas 2000-02-07
2299  *
2300  * Note: this only discovers whether the name could be a system attribute.
2301  * Caller needs to verify that it really is an attribute of the rel,
2302  * at least in the case of "oid", which is now optional.
2303  */
2304 static int
2305 specialAttNum(const char *attname)
2306 {
2307         Form_pg_attribute sysatt;
2308
2309         sysatt = SystemAttributeByName(attname,
2310                                                                    true /* "oid" will be accepted */ );
2311         if (sysatt != NULL)
2312                 return sysatt->attnum;
2313         return InvalidAttrNumber;
2314 }
2315
2316
2317 /*
2318  * given attribute id, return name of that attribute
2319  *
2320  *      This should only be used if the relation is already
2321  *      heap_open()'ed.  Use the cache version get_atttype()
2322  *      for access to non-opened relations.
2323  */
2324 Name
2325 attnumAttName(Relation rd, int attid)
2326 {
2327         if (attid <= 0)
2328         {
2329                 Form_pg_attribute sysatt;
2330
2331                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2332                 return &sysatt->attname;
2333         }
2334         if (attid > rd->rd_att->natts)
2335                 elog(ERROR, "invalid attribute number %d", attid);
2336         return &rd->rd_att->attrs[attid - 1]->attname;
2337 }
2338
2339 /*
2340  * given attribute id, return type of that attribute
2341  *
2342  *      This should only be used if the relation is already
2343  *      heap_open()'ed.  Use the cache version get_atttype()
2344  *      for access to non-opened relations.
2345  */
2346 Oid
2347 attnumTypeId(Relation rd, int attid)
2348 {
2349         if (attid <= 0)
2350         {
2351                 Form_pg_attribute sysatt;
2352
2353                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2354                 return sysatt->atttypid;
2355         }
2356         if (attid > rd->rd_att->natts)
2357                 elog(ERROR, "invalid attribute number %d", attid);
2358         return rd->rd_att->attrs[attid - 1]->atttypid;
2359 }
2360
2361 /*
2362  * Generate a suitable error about a missing RTE.
2363  *
2364  * Since this is a very common type of error, we work rather hard to
2365  * produce a helpful message.
2366  */
2367 void
2368 errorMissingRTE(ParseState *pstate, RangeVar *relation)
2369 {
2370         RangeTblEntry *rte;
2371         int                     sublevels_up;
2372         const char *badAlias = NULL;
2373
2374         /*
2375          * Check to see if there are any potential matches in the query's
2376          * rangetable.  (Note: cases involving a bad schema name in the
2377          * RangeVar will throw error immediately here.  That seems OK.)
2378          */
2379         rte = searchRangeTable(pstate, relation);
2380
2381         /*
2382          * If we found a match that has an alias and the alias is visible in the
2383          * namespace, then the problem is probably use of the relation's real name
2384          * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2385          * common enough to justify a specific hint.
2386          *
2387          * If we found a match that doesn't meet those criteria, assume the
2388          * problem is illegal use of a relation outside its scope, as in the
2389          * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2390          */
2391         if (rte && rte->alias &&
2392                 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2393                 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2394                                                          relation->location,
2395                                                          &sublevels_up) == rte)
2396                 badAlias = rte->eref->aliasname;
2397
2398         if (rte)
2399                 ereport(ERROR,
2400                                 (errcode(ERRCODE_UNDEFINED_TABLE),
2401                                  errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2402                                                 relation->relname),
2403                                  (badAlias ?
2404                                   errhint("Perhaps you meant to reference the table alias \"%s\".",
2405                                                   badAlias) :
2406                                   errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2407                                                   rte->eref->aliasname)),
2408                                  parser_errposition(pstate, relation->location)));
2409         else
2410                 ereport(ERROR,
2411                                 (errcode(ERRCODE_UNDEFINED_TABLE),
2412                                  errmsg("missing FROM-clause entry for table \"%s\"",
2413                                                 relation->relname),
2414                                  parser_errposition(pstate, relation->location)));
2415 }