]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
Teach the planner to remove SubqueryScan nodes from the plan if they
[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-2005, 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.107 2005/04/28 21:47:14 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <ctype.h>
18
19 #include "access/heapam.h"
20 #include "catalog/heap.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_type.h"
23 #include "funcapi.h"
24 #include "nodes/makefuncs.h"
25 #include "parser/parsetree.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32
33
34 /* GUC parameter */
35 bool            add_missing_from;
36
37 static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
38                                                 const char *refname);
39 static Node *scanNameSpaceForRelid(ParseState *pstate, Node *nsnode,
40                                           Oid relid);
41 static void scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
42                                                  RangeTblEntry *rte1, const char *aliasname1);
43 static bool isLockedRel(ParseState *pstate, char *refname);
44 static void expandRelation(Oid relid, Alias *eref,
45                            int rtindex, int sublevels_up,
46                            bool include_dropped,
47                            List **colnames, List **colvars);
48 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
49                                                         int rtindex, int sublevels_up,
50                                                         bool include_dropped,
51                                                         List **colnames, List **colvars);
52 static int      specialAttNum(const char *attname);
53 static void warnAutoRange(ParseState *pstate, RangeVar *relation);
54
55
56 /*
57  * refnameRangeTblEntry
58  *        Given a possibly-qualified refname, look to see if it matches any RTE.
59  *        If so, return a pointer to the RangeTblEntry; else return NULL.
60  *
61  *        Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
62  *        If sublevels_up is NULL, only consider items at the current nesting
63  *        level.
64  *
65  * An unqualified refname (schemaname == NULL) can match any RTE with matching
66  * alias, or matching unqualified relname in the case of alias-less relation
67  * RTEs.  It is possible that such a refname matches multiple RTEs in the
68  * nearest nesting level that has a match; if so, we report an error via
69  * ereport().
70  *
71  * A qualified refname (schemaname != NULL) can only match a relation RTE
72  * that (a) has no alias and (b) is for the same relation identified by
73  * schemaname.refname.  In this case we convert schemaname.refname to a
74  * relation OID and search by relid, rather than by alias name.  This is
75  * peculiar, but it's what SQL92 says to do.
76  */
77 RangeTblEntry *
78 refnameRangeTblEntry(ParseState *pstate,
79                                          const char *schemaname,
80                                          const char *refname,
81                                          int *sublevels_up)
82 {
83         Oid                     relId = InvalidOid;
84
85         if (sublevels_up)
86                 *sublevels_up = 0;
87
88         if (schemaname != NULL)
89         {
90                 Oid                     namespaceId;
91
92                 namespaceId = LookupExplicitNamespace(schemaname);
93                 relId = get_relname_relid(refname, namespaceId);
94                 if (!OidIsValid(relId))
95                         return NULL;
96         }
97
98         while (pstate != NULL)
99         {
100                 Node       *nsnode;
101
102                 if (OidIsValid(relId))
103                         nsnode = scanNameSpaceForRelid(pstate,
104                                                                                    (Node *) pstate->p_namespace,
105                                                                                    relId);
106                 else
107                         nsnode = scanNameSpaceForRefname(pstate,
108                                                                                          (Node *) pstate->p_namespace,
109                                                                                          refname);
110
111                 if (nsnode)
112                 {
113                         /* should get an RTE or JoinExpr */
114                         if (IsA(nsnode, RangeTblEntry))
115                                 return (RangeTblEntry *) nsnode;
116                         Assert(IsA(nsnode, JoinExpr));
117                         return rt_fetch(((JoinExpr *) nsnode)->rtindex, pstate->p_rtable);
118                 }
119
120                 pstate = pstate->parentParseState;
121                 if (sublevels_up)
122                         (*sublevels_up)++;
123                 else
124                         break;
125         }
126         return NULL;
127 }
128
129 /*
130  * Recursively search a namespace for an RTE or joinexpr matching the
131  * given unqualified refname.  Return the node if a unique match, or NULL
132  * if no match.  Raise error if multiple matches.
133  *
134  * The top level of p_namespace is a list, and we recurse into any joins
135  * that are not subqueries.
136  */
137 static Node *
138 scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
139                                                 const char *refname)
140 {
141         Node       *result = NULL;
142         Node       *newresult;
143
144         if (nsnode == NULL)
145                 return NULL;
146         if (IsA(nsnode, RangeTblRef))
147         {
148                 int                     varno = ((RangeTblRef *) nsnode)->rtindex;
149                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
150
151                 if (strcmp(rte->eref->aliasname, refname) == 0)
152                         result = (Node *) rte;
153         }
154         else if (IsA(nsnode, JoinExpr))
155         {
156                 JoinExpr   *j = (JoinExpr *) nsnode;
157
158                 if (j->alias)
159                 {
160                         if (strcmp(j->alias->aliasname, refname) == 0)
161                                 return (Node *) j;              /* matched a join alias */
162
163                         /*
164                          * Tables within an aliased join are invisible from outside
165                          * the join, according to the scope rules of SQL92 (the join
166                          * is considered a subquery).  So, stop here.
167                          */
168                         return NULL;
169                 }
170                 result = scanNameSpaceForRefname(pstate, j->larg, refname);
171                 newresult = scanNameSpaceForRefname(pstate, j->rarg, refname);
172                 if (!result)
173                         result = newresult;
174                 else if (newresult)
175                         ereport(ERROR,
176                                         (errcode(ERRCODE_AMBIGUOUS_ALIAS),
177                                          errmsg("table reference \"%s\" is ambiguous",
178                                                         refname)));
179         }
180         else if (IsA(nsnode, List))
181         {
182                 ListCell   *l;
183
184                 foreach(l, (List *) nsnode)
185                 {
186                         newresult = scanNameSpaceForRefname(pstate, lfirst(l), refname);
187                         if (!result)
188                                 result = newresult;
189                         else if (newresult)
190                                 ereport(ERROR,
191                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
192                                                  errmsg("table reference \"%s\" is ambiguous",
193                                                                 refname)));
194                 }
195         }
196         else
197                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
198         return result;
199 }
200
201 /*
202  * Recursively search a namespace for a relation RTE matching the
203  * given relation OID.  Return the node if a unique match, or NULL
204  * if no match.  Raise error if multiple matches (which shouldn't
205  * happen if the namespace was checked correctly when it was created).
206  *
207  * The top level of p_namespace is a list, and we recurse into any joins
208  * that are not subqueries.
209  *
210  * See the comments for refnameRangeTblEntry to understand why this
211  * acts the way it does.
212  */
213 static Node *
214 scanNameSpaceForRelid(ParseState *pstate, Node *nsnode, Oid relid)
215 {
216         Node       *result = NULL;
217         Node       *newresult;
218
219         if (nsnode == NULL)
220                 return NULL;
221         if (IsA(nsnode, RangeTblRef))
222         {
223                 int                     varno = ((RangeTblRef *) nsnode)->rtindex;
224                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
225
226                 /* yes, the test for alias==NULL should be there... */
227                 if (rte->rtekind == RTE_RELATION &&
228                         rte->relid == relid &&
229                         rte->alias == NULL)
230                         result = (Node *) rte;
231         }
232         else if (IsA(nsnode, JoinExpr))
233         {
234                 JoinExpr   *j = (JoinExpr *) nsnode;
235
236                 if (j->alias)
237                 {
238                         /*
239                          * Tables within an aliased join are invisible from outside
240                          * the join, according to the scope rules of SQL92 (the join
241                          * is considered a subquery).  So, stop here.
242                          */
243                         return NULL;
244                 }
245                 result = scanNameSpaceForRelid(pstate, j->larg, relid);
246                 newresult = scanNameSpaceForRelid(pstate, j->rarg, relid);
247                 if (!result)
248                         result = newresult;
249                 else if (newresult)
250                         ereport(ERROR,
251                                         (errcode(ERRCODE_AMBIGUOUS_ALIAS),
252                                          errmsg("table reference %u is ambiguous",
253                                                         relid)));
254         }
255         else if (IsA(nsnode, List))
256         {
257                 ListCell   *l;
258
259                 foreach(l, (List *) nsnode)
260                 {
261                         newresult = scanNameSpaceForRelid(pstate, lfirst(l), relid);
262                         if (!result)
263                                 result = newresult;
264                         else if (newresult)
265                                 ereport(ERROR,
266                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
267                                                  errmsg("table reference %u is ambiguous",
268                                                                 relid)));
269                 }
270         }
271         else
272                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
273         return result;
274 }
275
276 /*
277  * Recursively check for name conflicts between two namespaces or
278  * namespace subtrees.  Raise an error if any is found.
279  *
280  * Works by recursively scanning namespace1 for RTEs and join nodes,
281  * and for each one recursively scanning namespace2 for a match.
282  *
283  * Note: we assume that each given argument does not contain conflicts
284  * itself; we just want to know if the two can be merged together.
285  *
286  * Per SQL92, two alias-less plain relation RTEs do not conflict even if
287  * they have the same eref->aliasname (ie, same relation name), if they
288  * are for different relation OIDs (implying they are in different schemas).
289  */
290 void
291 checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
292                                                 Node *namespace2)
293 {
294         if (namespace1 == NULL)
295                 return;
296         if (IsA(namespace1, RangeTblRef))
297         {
298                 int                     varno = ((RangeTblRef *) namespace1)->rtindex;
299                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
300
301                 if (rte->rtekind == RTE_RELATION && rte->alias == NULL)
302                         scanNameSpaceForConflict(pstate, namespace2,
303                                                                          rte, rte->eref->aliasname);
304                 else
305                         scanNameSpaceForConflict(pstate, namespace2,
306                                                                          NULL, rte->eref->aliasname);
307         }
308         else if (IsA(namespace1, JoinExpr))
309         {
310                 JoinExpr   *j = (JoinExpr *) namespace1;
311
312                 if (j->alias)
313                 {
314                         scanNameSpaceForConflict(pstate, namespace2,
315                                                                          NULL, j->alias->aliasname);
316
317                         /*
318                          * Tables within an aliased join are invisible from outside
319                          * the join, according to the scope rules of SQL92 (the join
320                          * is considered a subquery).  So, stop here.
321                          */
322                         return;
323                 }
324                 checkNameSpaceConflicts(pstate, j->larg, namespace2);
325                 checkNameSpaceConflicts(pstate, j->rarg, namespace2);
326         }
327         else if (IsA(namespace1, List))
328         {
329                 ListCell   *l;
330
331                 foreach(l, (List *) namespace1)
332                         checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
333         }
334         else
335                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(namespace1));
336 }
337
338 /*
339  * Subroutine for checkNameSpaceConflicts: scan namespace2
340  */
341 static void
342 scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
343                                                  RangeTblEntry *rte1, const char *aliasname1)
344 {
345         if (nsnode == NULL)
346                 return;
347         if (IsA(nsnode, RangeTblRef))
348         {
349                 int                     varno = ((RangeTblRef *) nsnode)->rtindex;
350                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
351
352                 if (strcmp(rte->eref->aliasname, aliasname1) != 0)
353                         return;                         /* definitely no conflict */
354                 if (rte->rtekind == RTE_RELATION && rte->alias == NULL &&
355                         rte1 != NULL && rte->relid != rte1->relid)
356                         return;                         /* no conflict per SQL92 rule */
357                 ereport(ERROR,
358                                 (errcode(ERRCODE_DUPLICATE_ALIAS),
359                                  errmsg("table name \"%s\" specified more than once",
360                                                 aliasname1)));
361         }
362         else if (IsA(nsnode, JoinExpr))
363         {
364                 JoinExpr   *j = (JoinExpr *) nsnode;
365
366                 if (j->alias)
367                 {
368                         if (strcmp(j->alias->aliasname, aliasname1) == 0)
369                                 ereport(ERROR,
370                                                 (errcode(ERRCODE_DUPLICATE_ALIAS),
371                                          errmsg("table name \"%s\" specified more than once",
372                                                         aliasname1)));
373
374                         /*
375                          * Tables within an aliased join are invisible from outside
376                          * the join, according to the scope rules of SQL92 (the join
377                          * is considered a subquery).  So, stop here.
378                          */
379                         return;
380                 }
381                 scanNameSpaceForConflict(pstate, j->larg, rte1, aliasname1);
382                 scanNameSpaceForConflict(pstate, j->rarg, rte1, aliasname1);
383         }
384         else if (IsA(nsnode, List))
385         {
386                 ListCell   *l;
387
388                 foreach(l, (List *) nsnode)
389                         scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1);
390         }
391         else
392                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(nsnode));
393 }
394
395 /*
396  * given an RTE, return RT index (starting with 1) of the entry,
397  * and optionally get its nesting depth (0 = current).  If sublevels_up
398  * is NULL, only consider rels at the current nesting level.
399  * Raises error if RTE not found.
400  */
401 int
402 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
403 {
404         int                     index;
405         ListCell   *l;
406
407         if (sublevels_up)
408                 *sublevels_up = 0;
409
410         while (pstate != NULL)
411         {
412                 index = 1;
413                 foreach(l, pstate->p_rtable)
414                 {
415                         if (rte == (RangeTblEntry *) lfirst(l))
416                                 return index;
417                         index++;
418                 }
419                 pstate = pstate->parentParseState;
420                 if (sublevels_up)
421                         (*sublevels_up)++;
422                 else
423                         break;
424         }
425
426         elog(ERROR, "RTE not found (internal error)");
427         return 0;                                       /* keep compiler quiet */
428 }
429
430 /*
431  * Given an RT index and nesting depth, find the corresponding RTE.
432  * This is the inverse of RTERangeTablePosn.
433  */
434 RangeTblEntry *
435 GetRTEByRangeTablePosn(ParseState *pstate,
436                                            int varno,
437                                            int sublevels_up)
438 {
439         while (sublevels_up-- > 0)
440         {
441                 pstate = pstate->parentParseState;
442                 Assert(pstate != NULL);
443         }
444         Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
445         return rt_fetch(varno, pstate->p_rtable);
446 }
447
448 /*
449  * GetLevelNRangeTable
450  *        Get the rangetable list for the N'th query level up from current.
451  */
452 List *
453 GetLevelNRangeTable(ParseState *pstate, int sublevels_up)
454 {
455         int                     index = 0;
456
457         while (pstate != NULL)
458         {
459                 if (index == sublevels_up)
460                         return pstate->p_rtable;
461                 index++;
462                 pstate = pstate->parentParseState;
463         }
464
465         elog(ERROR, "rangetable not found (internal error)");
466         return NIL;                                     /* keep compiler quiet */
467 }
468
469 /*
470  * scanRTEForColumn
471  *        Search the column names of a single RTE for the given name.
472  *        If found, return an appropriate Var node, else return NULL.
473  *        If the name proves ambiguous within this RTE, raise error.
474  *
475  * Side effect: if we find a match, mark the RTE as requiring read access.
476  * See comments in setTargetTable().
477  *
478  * NOTE: if the RTE is for a join, marking it as requiring read access does
479  * nothing.  It might seem that we need to propagate the mark to all the
480  * contained RTEs, but that is not necessary.  This is so because a join
481  * expression can only appear in a FROM clause, and any table named in
482  * FROM will be marked as requiring read access from the beginning.
483  */
484 Node *
485 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
486 {
487         Node       *result = NULL;
488         int                     attnum = 0;
489         ListCell   *c;
490
491         /*
492          * Scan the user column names (or aliases) for a match. Complain if
493          * multiple matches.
494          *
495          * Note: eref->colnames may include entries for dropped columns, but
496          * those will be empty strings that cannot match any legal SQL
497          * identifier, so we don't bother to test for that case here.
498          *
499          * Should this somehow go wrong and we try to access a dropped column,
500          * we'll still catch it by virtue of the checks in
501          * get_rte_attribute_type(), which is called by make_var().  That
502          * routine has to do a cache lookup anyway, so the check there is
503          * cheap.
504          */
505         foreach(c, rte->eref->colnames)
506         {
507                 attnum++;
508                 if (strcmp(strVal(lfirst(c)), colname) == 0)
509                 {
510                         if (result)
511                                 ereport(ERROR,
512                                                 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
513                                                  errmsg("column reference \"%s\" is ambiguous",
514                                                                 colname)));
515                         result = (Node *) make_var(pstate, rte, attnum);
516                         /* Require read access */
517                         rte->requiredPerms |= ACL_SELECT;
518                 }
519         }
520
521         /*
522          * If we have a unique match, return it.  Note that this allows a user
523          * alias to override a system column name (such as OID) without error.
524          */
525         if (result)
526                 return result;
527
528         /*
529          * If the RTE represents a real table, consider system column names.
530          */
531         if (rte->rtekind == RTE_RELATION)
532         {
533                 /* quick check to see if name could be a system column */
534                 attnum = specialAttNum(colname);
535                 if (attnum != InvalidAttrNumber)
536                 {
537                         /* now check to see if column actually is defined */
538                         if (SearchSysCacheExists(ATTNUM,
539                                                                          ObjectIdGetDatum(rte->relid),
540                                                                          Int16GetDatum(attnum),
541                                                                          0, 0))
542                         {
543                                 result = (Node *) make_var(pstate, rte, attnum);
544                                 /* Require read access */
545                                 rte->requiredPerms |= ACL_SELECT;
546                         }
547                 }
548         }
549
550         return result;
551 }
552
553 /*
554  * colNameToVar
555  *        Search for an unqualified column name.
556  *        If found, return the appropriate Var node (or expression).
557  *        If not found, return NULL.  If the name proves ambiguous, raise error.
558  *        If localonly is true, only names in the innermost query are considered.
559  */
560 Node *
561 colNameToVar(ParseState *pstate, char *colname, bool localonly)
562 {
563         Node       *result = NULL;
564         ParseState *orig_pstate = pstate;
565         int                     levels_up = 0;
566
567         while (pstate != NULL)
568         {
569                 ListCell   *ns;
570
571                 /*
572                  * We need to look only at top-level namespace items, and even for
573                  * those, ignore RTEs that are marked as not inFromCl and not the
574                  * query's target relation.
575                  */
576                 foreach(ns, pstate->p_namespace)
577                 {
578                         Node       *nsnode = (Node *) lfirst(ns);
579                         Node       *newresult = NULL;
580
581                         if (IsA(nsnode, RangeTblRef))
582                         {
583                                 int                     varno = ((RangeTblRef *) nsnode)->rtindex;
584                                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
585
586                                 if (!rte->inFromCl &&
587                                         rte != pstate->p_target_rangetblentry)
588                                         continue;
589
590                                 /* use orig_pstate here to get the right sublevels_up */
591                                 newresult = scanRTEForColumn(orig_pstate, rte, colname);
592                         }
593                         else if (IsA(nsnode, JoinExpr))
594                         {
595                                 int                     varno = ((JoinExpr *) nsnode)->rtindex;
596                                 RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
597
598                                 /* joins are always inFromCl, so no need to check */
599                                 Assert(rte->inFromCl);
600
601                                 /* use orig_pstate here to get the right sublevels_up */
602                                 newresult = scanRTEForColumn(orig_pstate, rte, colname);
603                         }
604                         else
605                                 elog(ERROR, "unrecognized node type: %d",
606                                          (int) nodeTag(nsnode));
607
608                         if (newresult)
609                         {
610                                 if (result)
611                                         ereport(ERROR,
612                                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
613                                                    errmsg("column reference \"%s\" is ambiguous",
614                                                                   colname)));
615                                 result = newresult;
616                         }
617                 }
618
619                 if (result != NULL || localonly)
620                         break;                          /* found, or don't want to look at parent */
621
622                 pstate = pstate->parentParseState;
623                 levels_up++;
624         }
625
626         return result;
627 }
628
629 /*
630  * qualifiedNameToVar
631  *        Search for a qualified column name: either refname.colname or
632  *        schemaname.relname.colname.
633  *
634  *        If found, return the appropriate Var node.
635  *        If not found, return NULL.  If the name proves ambiguous, raise error.
636  */
637 Node *
638 qualifiedNameToVar(ParseState *pstate,
639                                    char *schemaname,
640                                    char *refname,
641                                    char *colname,
642                                    bool implicitRTEOK)
643 {
644         RangeTblEntry *rte;
645         int                     sublevels_up;
646
647         rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
648
649         if (rte == NULL)
650         {
651                 if (!implicitRTEOK)
652                         return NULL;
653                 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
654         }
655
656         return scanRTEForColumn(pstate, rte, colname);
657 }
658
659 /*
660  * buildRelationAliases
661  *              Construct the eref column name list for a relation RTE.
662  *              This code is also used for the case of a function RTE returning
663  *              a named composite type.
664  *
665  * tupdesc: the physical column information
666  * alias: the user-supplied alias, or NULL if none
667  * eref: the eref Alias to store column names in
668  *
669  * eref->colnames is filled in.  Also, alias->colnames is rebuilt to insert
670  * empty strings for any dropped columns, so that it will be one-to-one with
671  * physical column numbers.
672  */
673 static void
674 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
675 {
676         int                     maxattrs = tupdesc->natts;
677         ListCell   *aliaslc;
678         int                     numaliases;
679         int                     varattno;
680         int                     numdropped = 0;
681
682         Assert(eref->colnames == NIL);
683
684         if (alias)
685         {
686                 aliaslc = list_head(alias->colnames);
687                 numaliases = list_length(alias->colnames);
688                 /* We'll rebuild the alias colname list */
689                 alias->colnames = NIL;
690         }
691         else
692         {
693                 aliaslc = NULL;
694                 numaliases = 0;
695         }
696
697         for (varattno = 0; varattno < maxattrs; varattno++)
698         {
699                 Form_pg_attribute attr = tupdesc->attrs[varattno];
700                 Value      *attrname;
701
702                 if (attr->attisdropped)
703                 {
704                         /* Always insert an empty string for a dropped column */
705                         attrname = makeString(pstrdup(""));
706                         if (aliaslc)
707                                 alias->colnames = lappend(alias->colnames, attrname);
708                         numdropped++;
709                 }
710                 else if (aliaslc)
711                 {
712                         /* Use the next user-supplied alias */
713                         attrname = (Value *) lfirst(aliaslc);
714                         aliaslc = lnext(aliaslc);
715                         alias->colnames = lappend(alias->colnames, attrname);
716                 }
717                 else
718                 {
719                         attrname = makeString(pstrdup(NameStr(attr->attname)));
720                         /* we're done with the alias if any */
721                 }
722
723                 eref->colnames = lappend(eref->colnames, attrname);
724         }
725
726         /* Too many user-supplied aliases? */
727         if (aliaslc)
728                 ereport(ERROR,
729                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
730                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
731                                    eref->aliasname, maxattrs - numdropped, numaliases)));
732 }
733
734 /*
735  * Add an entry for a relation to the pstate's range table (p_rtable).
736  *
737  * If pstate is NULL, we just build an RTE and return it without adding it
738  * to an rtable list.
739  *
740  * Note: formerly this checked for refname conflicts, but that's wrong.
741  * Caller is responsible for checking for conflicts in the appropriate scope.
742  */
743 RangeTblEntry *
744 addRangeTableEntry(ParseState *pstate,
745                                    RangeVar *relation,
746                                    Alias *alias,
747                                    bool inh,
748                                    bool inFromCl)
749 {
750         RangeTblEntry *rte = makeNode(RangeTblEntry);
751         char       *refname = alias ? alias->aliasname : relation->relname;
752         LOCKMODE        lockmode;
753         Relation        rel;
754
755         rte->rtekind = RTE_RELATION;
756         rte->alias = alias;
757
758         /*
759          * Get the rel's OID.  This access also ensures that we have an
760          * up-to-date relcache entry for the rel.  Since this is typically the
761          * first access to a rel in a statement, be careful to get the right
762          * access level depending on whether we're doing SELECT FOR UPDATE/SHARE.
763          */
764         lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
765         rel = heap_openrv(relation, lockmode);
766         rte->relid = RelationGetRelid(rel);
767
768         /*
769          * Build the list of effective column names using user-supplied
770          * aliases and/or actual column names.
771          */
772         rte->eref = makeAlias(refname, NIL);
773         buildRelationAliases(rel->rd_att, alias, rte->eref);
774
775         /*
776          * Drop the rel refcount, but keep the access lock till end of
777          * transaction so that the table can't be deleted or have its schema
778          * modified underneath us.
779          */
780         heap_close(rel, NoLock);
781
782         /*----------
783          * Flags:
784          * - this RTE should be expanded to include descendant tables,
785          * - this RTE is in the FROM clause,
786          * - this RTE should be checked for appropriate access rights.
787          *
788          * The initial default on access checks is always check-for-READ-access,
789          * which is the right thing for all except target tables.
790          *----------
791          */
792         rte->inh = inh;
793         rte->inFromCl = inFromCl;
794
795         rte->requiredPerms = ACL_SELECT;
796         rte->checkAsUser = 0;           /* not set-uid by default, either */
797
798         /*
799          * Add completed RTE to pstate's range table list, but not to join
800          * list nor namespace --- caller must do that if appropriate.
801          */
802         if (pstate != NULL)
803                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
804
805         return rte;
806 }
807
808 /*
809  * Add an entry for a relation to the pstate's range table (p_rtable).
810  *
811  * This is just like addRangeTableEntry() except that it makes an RTE
812  * given an already-open relation instead of a RangeVar reference.
813  */
814 RangeTblEntry *
815 addRangeTableEntryForRelation(ParseState *pstate,
816                                                           Relation rel,
817                                                           Alias *alias,
818                                                           bool inh,
819                                                           bool inFromCl)
820 {
821         RangeTblEntry *rte = makeNode(RangeTblEntry);
822         char       *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
823
824         rte->rtekind = RTE_RELATION;
825         rte->alias = alias;
826         rte->relid = RelationGetRelid(rel);
827
828         /*
829          * Build the list of effective column names using user-supplied
830          * aliases and/or actual column names.
831          */
832         rte->eref = makeAlias(refname, NIL);
833         buildRelationAliases(rel->rd_att, alias, rte->eref);
834
835         /*----------
836          * Flags:
837          * - this RTE should be expanded to include descendant tables,
838          * - this RTE is in the FROM clause,
839          * - this RTE should be checked for appropriate access rights.
840          *
841          * The initial default on access checks is always check-for-READ-access,
842          * which is the right thing for all except target tables.
843          *----------
844          */
845         rte->inh = inh;
846         rte->inFromCl = inFromCl;
847
848         rte->requiredPerms = ACL_SELECT;
849         rte->checkAsUser = 0;           /* not set-uid by default, either */
850
851         /*
852          * Add completed RTE to pstate's range table list, but not to join
853          * list nor namespace --- caller must do that if appropriate.
854          */
855         if (pstate != NULL)
856                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
857
858         return rte;
859 }
860
861 /*
862  * Add an entry for a subquery to the pstate's range table (p_rtable).
863  *
864  * This is just like addRangeTableEntry() except that it makes a subquery RTE.
865  * Note that an alias clause *must* be supplied.
866  */
867 RangeTblEntry *
868 addRangeTableEntryForSubquery(ParseState *pstate,
869                                                           Query *subquery,
870                                                           Alias *alias,
871                                                           bool inFromCl)
872 {
873         RangeTblEntry *rte = makeNode(RangeTblEntry);
874         char       *refname = alias->aliasname;
875         Alias      *eref;
876         int                     numaliases;
877         int                     varattno;
878         ListCell   *tlistitem;
879
880         rte->rtekind = RTE_SUBQUERY;
881         rte->relid = InvalidOid;
882         rte->subquery = subquery;
883         rte->alias = alias;
884
885         eref = copyObject(alias);
886         numaliases = list_length(eref->colnames);
887
888         /* fill in any unspecified alias columns */
889         varattno = 0;
890         foreach(tlistitem, subquery->targetList)
891         {
892                 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
893
894                 if (te->resjunk)
895                         continue;
896                 varattno++;
897                 Assert(varattno == te->resno);
898                 if (varattno > numaliases)
899                 {
900                         char       *attrname;
901
902                         attrname = pstrdup(te->resname);
903                         eref->colnames = lappend(eref->colnames, makeString(attrname));
904                 }
905         }
906         if (varattno < numaliases)
907                 ereport(ERROR,
908                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
909                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
910                                                 refname, varattno, numaliases)));
911
912         rte->eref = eref;
913
914         /*----------
915          * Flags:
916          * - this RTE should be expanded to include descendant tables,
917          * - this RTE is in the FROM clause,
918          * - this RTE should be checked for appropriate access rights.
919          *
920          * Subqueries are never checked for access rights.
921          *----------
922          */
923         rte->inh = false;                       /* never true for subqueries */
924         rte->inFromCl = inFromCl;
925
926         rte->requiredPerms = 0;
927         rte->checkAsUser = 0;
928
929         /*
930          * Add completed RTE to pstate's range table list, but not to join
931          * list nor namespace --- caller must do that if appropriate.
932          */
933         if (pstate != NULL)
934                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
935
936         return rte;
937 }
938
939 /*
940  * Add an entry for a function to the pstate's range table (p_rtable).
941  *
942  * This is just like addRangeTableEntry() except that it makes a function RTE.
943  */
944 RangeTblEntry *
945 addRangeTableEntryForFunction(ParseState *pstate,
946                                                           char *funcname,
947                                                           Node *funcexpr,
948                                                           RangeFunction *rangefunc,
949                                                           bool inFromCl)
950 {
951         RangeTblEntry *rte = makeNode(RangeTblEntry);
952         TypeFuncClass functypclass;
953         Oid                     funcrettype;
954         TupleDesc       tupdesc;
955         Alias      *alias = rangefunc->alias;
956         List       *coldeflist = rangefunc->coldeflist;
957         Alias      *eref;
958
959         rte->rtekind = RTE_FUNCTION;
960         rte->relid = InvalidOid;
961         rte->subquery = NULL;
962         rte->funcexpr = funcexpr;
963         rte->coldeflist = coldeflist;
964         rte->alias = alias;
965
966         eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
967         rte->eref = eref;
968
969         /*
970          * Now determine if the function returns a simple or composite type.
971          */
972         functypclass = get_expr_result_type(funcexpr,
973                                                                                 &funcrettype,
974                                                                                 &tupdesc);
975
976         /*
977          * A coldeflist is required if the function returns RECORD and hasn't
978          * got a predetermined record type, and is prohibited otherwise.
979          */
980         if (coldeflist != NIL)
981         {
982                 if (functypclass != TYPEFUNC_RECORD)
983                         ereport(ERROR,
984                                         (errcode(ERRCODE_SYNTAX_ERROR),
985                                          errmsg("a column definition list is only allowed for functions returning \"record\"")));
986         }
987         else
988         {
989                 if (functypclass == TYPEFUNC_RECORD)
990                         ereport(ERROR,
991                                         (errcode(ERRCODE_SYNTAX_ERROR),
992                                          errmsg("a column definition list is required for functions returning \"record\"")));
993         }
994
995         if (functypclass == TYPEFUNC_COMPOSITE)
996         {
997                 /* Composite data type, e.g. a table's row type */
998                 Assert(tupdesc);
999                 /* Build the column alias list */
1000                 buildRelationAliases(tupdesc, alias, eref);
1001         }
1002         else if (functypclass == TYPEFUNC_SCALAR)
1003         {
1004                 /* Base data type, i.e. scalar */
1005                 /* Just add one alias column named for the function. */
1006                 if (alias && alias->colnames != NIL)
1007                 {
1008                         if (list_length(alias->colnames) != 1)
1009                                 ereport(ERROR,
1010                                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1011                                                  errmsg("too many column aliases specified for function %s",
1012                                                                 funcname)));
1013                         eref->colnames = copyObject(alias->colnames);
1014                 }
1015                 else
1016                         eref->colnames = list_make1(makeString(eref->aliasname));
1017         }
1018         else if (functypclass == TYPEFUNC_RECORD)
1019         {
1020                 ListCell   *col;
1021
1022                 /* Use the column definition list to form the alias list */
1023                 foreach(col, coldeflist)
1024                 {
1025                         ColumnDef  *n = lfirst(col);
1026                         char       *attrname;
1027
1028                         attrname = pstrdup(n->colname);
1029                         eref->colnames = lappend(eref->colnames, makeString(attrname));
1030                 }
1031         }
1032         else
1033                 ereport(ERROR,
1034                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1035                         errmsg("function \"%s\" in FROM has unsupported return type %s",
1036                                    funcname, format_type_be(funcrettype))));
1037
1038         /*----------
1039          * Flags:
1040          * - this RTE should be expanded to include descendant tables,
1041          * - this RTE is in the FROM clause,
1042          * - this RTE should be checked for appropriate access rights.
1043          *
1044          * Functions are never checked for access rights (at least, not by
1045          * the RTE permissions mechanism).
1046          *----------
1047          */
1048         rte->inh = false;                       /* never true for functions */
1049         rte->inFromCl = inFromCl;
1050
1051         rte->requiredPerms = 0;
1052         rte->checkAsUser = 0;
1053
1054         /*
1055          * Add completed RTE to pstate's range table list, but not to join
1056          * list nor namespace --- caller must do that if appropriate.
1057          */
1058         if (pstate != NULL)
1059                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1060
1061         return rte;
1062 }
1063
1064 /*
1065  * Add an entry for a join to the pstate's range table (p_rtable).
1066  *
1067  * This is much like addRangeTableEntry() except that it makes a join RTE.
1068  */
1069 RangeTblEntry *
1070 addRangeTableEntryForJoin(ParseState *pstate,
1071                                                   List *colnames,
1072                                                   JoinType jointype,
1073                                                   List *aliasvars,
1074                                                   Alias *alias,
1075                                                   bool inFromCl)
1076 {
1077         RangeTblEntry *rte = makeNode(RangeTblEntry);
1078         Alias      *eref;
1079         int                     numaliases;
1080
1081         rte->rtekind = RTE_JOIN;
1082         rte->relid = InvalidOid;
1083         rte->subquery = NULL;
1084         rte->jointype = jointype;
1085         rte->joinaliasvars = aliasvars;
1086         rte->alias = alias;
1087
1088         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1089         numaliases = list_length(eref->colnames);
1090
1091         /* fill in any unspecified alias columns */
1092         if (numaliases < list_length(colnames))
1093                 eref->colnames = list_concat(eref->colnames,
1094                                                                    list_copy_tail(colnames, numaliases));
1095
1096         rte->eref = eref;
1097
1098         /*----------
1099          * Flags:
1100          * - this RTE should be expanded to include descendant tables,
1101          * - this RTE is in the FROM clause,
1102          * - this RTE should be checked for appropriate access rights.
1103          *
1104          * Joins are never checked for access rights.
1105          *----------
1106          */
1107         rte->inh = false;                       /* never true for joins */
1108         rte->inFromCl = inFromCl;
1109
1110         rte->requiredPerms = 0;
1111         rte->checkAsUser = 0;
1112
1113         /*
1114          * Add completed RTE to pstate's range table list, but not to join
1115          * list nor namespace --- caller must do that if appropriate.
1116          */
1117         if (pstate != NULL)
1118                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1119
1120         return rte;
1121 }
1122
1123 /*
1124  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1125  */
1126 static bool
1127 isLockedRel(ParseState *pstate, char *refname)
1128 {
1129         /* Outer loop to check parent query levels as well as this one */
1130         while (pstate != NULL)
1131         {
1132                 if (pstate->p_lockedRels != NIL)
1133                 {
1134                         if (linitial(pstate->p_lockedRels) == NULL)
1135                         {
1136                                 /* all tables used in query */
1137                                 return true;
1138                         }
1139                         else
1140                         {
1141                                 /* just the named tables */
1142                                 ListCell   *l;
1143
1144                                 foreach(l, pstate->p_lockedRels)
1145                                 {
1146                                         char       *rname = strVal(lfirst(l));
1147
1148                                         if (strcmp(refname, rname) == 0)
1149                                                 return true;
1150                                 }
1151                         }
1152                 }
1153                 pstate = pstate->parentParseState;
1154         }
1155         return false;
1156 }
1157
1158 /*
1159  * Add the given RTE as a top-level entry in the pstate's join list
1160  * and/or name space list.      (We assume caller has checked for any
1161  * namespace conflict.)
1162  */
1163 void
1164 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1165                           bool addToJoinList, bool addToNameSpace)
1166 {
1167         int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1168         RangeTblRef *rtr = makeNode(RangeTblRef);
1169
1170         rtr->rtindex = rtindex;
1171
1172         if (addToJoinList)
1173                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1174         if (addToNameSpace)
1175                 pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1176 }
1177
1178 /*
1179  * Add a POSTQUEL-style implicit RTE.
1180  *
1181  * We assume caller has already checked that there is no RTE or join with
1182  * a conflicting name.
1183  */
1184 RangeTblEntry *
1185 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1186 {
1187         RangeTblEntry *rte;
1188
1189         rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1190         addRTEtoQuery(pstate, rte, true, true);
1191         warnAutoRange(pstate, relation);
1192
1193         return rte;
1194 }
1195
1196 /*
1197  * expandRTE -- expand the columns of a rangetable entry
1198  *
1199  * This creates lists of an RTE's column names (aliases if provided, else
1200  * real names) and Vars for each column.  Only user columns are considered.
1201  * If include_dropped is FALSE then dropped columns are omitted from the
1202  * results.  If include_dropped is TRUE then empty strings and NULL constants
1203  * (not Vars!) are returned for dropped columns.
1204  *
1205  * The target RTE is the rtindex'th entry of rtable.  (The whole rangetable
1206  * must be passed since we need it to determine dropped-ness for JOIN columns.)
1207  * sublevels_up is the varlevelsup value to use in the created Vars.
1208  *
1209  * The output lists go into *colnames and *colvars.
1210  * If only one of the two kinds of output list is needed, pass NULL for the
1211  * output pointer for the unwanted one.
1212  */
1213 void
1214 expandRTE(List *rtable, int rtindex, int sublevels_up,
1215                   bool include_dropped,
1216                   List **colnames, List **colvars)
1217 {
1218         RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1219         int                     varattno;
1220
1221         if (colnames)
1222                 *colnames = NIL;
1223         if (colvars)
1224                 *colvars = NIL;
1225
1226         switch (rte->rtekind)
1227         {
1228                 case RTE_RELATION:
1229                         /* Ordinary relation RTE */
1230                         expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1231                                                    include_dropped, colnames, colvars);
1232                         break;
1233                 case RTE_SUBQUERY:
1234                         {
1235                                 /* Subquery RTE */
1236                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1237                                 ListCell   *tlistitem;
1238
1239                                 varattno = 0;
1240                                 foreach(tlistitem, rte->subquery->targetList)
1241                                 {
1242                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1243
1244                                         if (te->resjunk)
1245                                                 continue;
1246                                         varattno++;
1247                                         Assert(varattno == te->resno);
1248
1249                                         if (colnames)
1250                                         {
1251                                                 /* Assume there is one alias per target item */
1252                                                 char       *label = strVal(lfirst(aliasp_item));
1253
1254                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1255                                                 aliasp_item = lnext(aliasp_item);
1256                                         }
1257
1258                                         if (colvars)
1259                                         {
1260                                                 Var                *varnode;
1261
1262                                                 varnode = makeVar(rtindex, varattno,
1263                                                                                   exprType((Node *) te->expr),
1264                                                                                   exprTypmod((Node *) te->expr),
1265                                                                                   sublevels_up);
1266
1267                                                 *colvars = lappend(*colvars, varnode);
1268                                         }
1269                                 }
1270                         }
1271                         break;
1272                 case RTE_FUNCTION:
1273                         {
1274                                 /* Function RTE */
1275                                 TypeFuncClass functypclass;
1276                                 Oid                     funcrettype;
1277                                 TupleDesc       tupdesc;
1278
1279                                 functypclass = get_expr_result_type(rte->funcexpr,
1280                                                                                                         &funcrettype,
1281                                                                                                         &tupdesc);
1282                                 if (functypclass == TYPEFUNC_COMPOSITE)
1283                                 {
1284                                         /* Composite data type, e.g. a table's row type */
1285                                         Assert(tupdesc);
1286                                         expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1287                                                                         include_dropped, colnames, colvars);
1288                                 }
1289                                 else if (functypclass == TYPEFUNC_SCALAR)
1290                                 {
1291                                         /* Base data type, i.e. scalar */
1292                                         if (colnames)
1293                                                 *colnames = lappend(*colnames,
1294                                                                                   linitial(rte->eref->colnames));
1295
1296                                         if (colvars)
1297                                         {
1298                                                 Var                *varnode;
1299
1300                                                 varnode = makeVar(rtindex, 1,
1301                                                                                   funcrettype, -1,
1302                                                                                   sublevels_up);
1303
1304                                                 *colvars = lappend(*colvars, varnode);
1305                                         }
1306                                 }
1307                                 else if (functypclass == TYPEFUNC_RECORD)
1308                                 {
1309                                         List       *coldeflist = rte->coldeflist;
1310                                         ListCell   *col;
1311                                         int                     attnum = 0;
1312
1313                                         foreach(col, coldeflist)
1314                                         {
1315                                                 ColumnDef  *colDef = lfirst(col);
1316
1317                                                 attnum++;
1318                                                 if (colnames)
1319                                                 {
1320                                                         char       *attrname;
1321
1322                                                         attrname = pstrdup(colDef->colname);
1323                                                         *colnames = lappend(*colnames, makeString(attrname));
1324                                                 }
1325
1326                                                 if (colvars)
1327                                                 {
1328                                                         Var                *varnode;
1329                                                         Oid                     atttypid;
1330
1331                                                         atttypid = typenameTypeId(colDef->typename);
1332
1333                                                         varnode = makeVar(rtindex,
1334                                                                                           attnum,
1335                                                                                           atttypid,
1336                                                                                           -1,
1337                                                                                           sublevels_up);
1338
1339                                                         *colvars = lappend(*colvars, varnode);
1340                                                 }
1341                                         }
1342                                 }
1343                                 else
1344                                 {
1345                                         /* addRangeTableEntryForFunction should've caught this */
1346                                         elog(ERROR, "function in FROM has unsupported return type");
1347                                 }
1348                         }
1349                         break;
1350                 case RTE_JOIN:
1351                         {
1352                                 /* Join RTE */
1353                                 ListCell   *colname;
1354                                 ListCell   *aliasvar;
1355
1356                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1357
1358                                 varattno = 0;
1359                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1360                                 {
1361                                         varattno++;
1362
1363                                         /*
1364                                          * During ordinary parsing, there will never be any
1365                                          * deleted columns in the join; but we have to check
1366                                          * since this routine is also used by the rewriter,
1367                                          * and joins found in stored rules might have join
1368                                          * columns for since-deleted columns.
1369                                          */
1370                                         if (get_rte_attribute_is_dropped(rtable, rtindex,
1371                                                                                                          varattno))
1372                                         {
1373                                                 if (include_dropped)
1374                                                 {
1375                                                         if (colnames)
1376                                                                 *colnames = lappend(*colnames,
1377                                                                                                 makeString(pstrdup("")));
1378                                                         if (colvars)
1379                                                         {
1380                                                                 /*
1381                                                                  * can't use atttypid here, but it doesn't
1382                                                                  * really matter what type the Const
1383                                                                  * claims to be.
1384                                                                  */
1385                                                                 *colvars = lappend(*colvars,
1386                                                                                                  makeNullConst(INT4OID));
1387                                                         }
1388                                                 }
1389                                                 continue;
1390                                         }
1391
1392                                         if (colnames)
1393                                         {
1394                                                 char       *label = strVal(lfirst(colname));
1395
1396                                                 *colnames = lappend(*colnames,
1397                                                                                         makeString(pstrdup(label)));
1398                                         }
1399
1400                                         if (colvars)
1401                                         {
1402                                                 Node       *avar = (Node *) lfirst(aliasvar);
1403                                                 Var                *varnode;
1404
1405                                                 varnode = makeVar(rtindex, varattno,
1406                                                                                   exprType(avar),
1407                                                                                   exprTypmod(avar),
1408                                                                                   sublevels_up);
1409
1410                                                 *colvars = lappend(*colvars, varnode);
1411                                         }
1412                                 }
1413                         }
1414                         break;
1415                 default:
1416                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1417         }
1418 }
1419
1420 /*
1421  * expandRelation -- expandRTE subroutine
1422  */
1423 static void
1424 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1425                            bool include_dropped,
1426                            List **colnames, List **colvars)
1427 {
1428         Relation        rel;
1429
1430         /* Get the tupledesc and turn it over to expandTupleDesc */
1431         rel = relation_open(relid, AccessShareLock);
1432         expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1433                                         colnames, colvars);
1434         relation_close(rel, AccessShareLock);
1435 }
1436
1437 /*
1438  * expandTupleDesc -- expandRTE subroutine
1439  */
1440 static void
1441 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1442                                 int rtindex, int sublevels_up,
1443                                 bool include_dropped,
1444                                 List **colnames, List **colvars)
1445 {
1446         int                     maxattrs = tupdesc->natts;
1447         int                     numaliases = list_length(eref->colnames);
1448         int                     varattno;
1449
1450         for (varattno = 0; varattno < maxattrs; varattno++)
1451         {
1452                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1453
1454                 if (attr->attisdropped)
1455                 {
1456                         if (include_dropped)
1457                         {
1458                                 if (colnames)
1459                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1460                                 if (colvars)
1461                                 {
1462                                         /*
1463                                          * can't use atttypid here, but it doesn't really
1464                                          * matter what type the Const claims to be.
1465                                          */
1466                                         *colvars = lappend(*colvars, makeNullConst(INT4OID));
1467                                 }
1468                         }
1469                         continue;
1470                 }
1471
1472                 if (colnames)
1473                 {
1474                         char       *label;
1475
1476                         if (varattno < numaliases)
1477                                 label = strVal(list_nth(eref->colnames, varattno));
1478                         else
1479                                 label = NameStr(attr->attname);
1480                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
1481                 }
1482
1483                 if (colvars)
1484                 {
1485                         Var                *varnode;
1486
1487                         varnode = makeVar(rtindex, attr->attnum,
1488                                                           attr->atttypid, attr->atttypmod,
1489                                                           sublevels_up);
1490
1491                         *colvars = lappend(*colvars, varnode);
1492                 }
1493         }
1494 }
1495
1496 /*
1497  * expandRelAttrs -
1498  *        Workhorse for "*" expansion: produce a list of targetentries
1499  *        for the attributes of the rte
1500  */
1501 List *
1502 expandRelAttrs(ParseState *pstate, List *rtable, int rtindex, int sublevels_up)
1503 {
1504         List       *names,
1505                            *vars;
1506         ListCell   *name,
1507                            *var;
1508         List       *te_list = NIL;
1509
1510         expandRTE(rtable, rtindex, sublevels_up, false, &names, &vars);
1511
1512         forboth(name, names, var, vars)
1513         {
1514                 char       *label = strVal(lfirst(name));
1515                 Node       *varnode = (Node *) lfirst(var);
1516                 TargetEntry *te;
1517
1518                 te = makeTargetEntry((Expr *) varnode,
1519                                                          (AttrNumber) pstate->p_next_resno++,
1520                                                          label,
1521                                                          false);
1522                 te_list = lappend(te_list, te);
1523         }
1524
1525         Assert(name == NULL && var == NULL);            /* lists not the same
1526                                                                                                  * length? */
1527
1528         return te_list;
1529 }
1530
1531 /*
1532  * get_rte_attribute_name
1533  *              Get an attribute name from a RangeTblEntry
1534  *
1535  * This is unlike get_attname() because we use aliases if available.
1536  * In particular, it will work on an RTE for a subselect or join, whereas
1537  * get_attname() only works on real relations.
1538  *
1539  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1540  * occurs when a Var represents a whole tuple of a relation.
1541  */
1542 char *
1543 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1544 {
1545         if (attnum == InvalidAttrNumber)
1546                 return "*";
1547
1548         /*
1549          * If there is a user-written column alias, use it.
1550          */
1551         if (rte->alias &&
1552                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1553                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1554
1555         /*
1556          * If the RTE is a relation, go to the system catalogs not the
1557          * eref->colnames list.  This is a little slower but it will give the
1558          * right answer if the column has been renamed since the eref list was
1559          * built (which can easily happen for rules).
1560          */
1561         if (rte->rtekind == RTE_RELATION)
1562                 return get_relid_attribute_name(rte->relid, attnum);
1563
1564         /*
1565          * Otherwise use the column name from eref.  There should always be
1566          * one.
1567          */
1568         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1569                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1570
1571         /* else caller gave us a bogus attnum */
1572         elog(ERROR, "invalid attnum %d for rangetable entry %s",
1573                  attnum, rte->eref->aliasname);
1574         return NULL;                            /* keep compiler quiet */
1575 }
1576
1577 /*
1578  * get_rte_attribute_type
1579  *              Get attribute type information from a RangeTblEntry
1580  */
1581 void
1582 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1583                                            Oid *vartype, int32 *vartypmod)
1584 {
1585         switch (rte->rtekind)
1586         {
1587                 case RTE_RELATION:
1588                         {
1589                                 /* Plain relation RTE --- get the attribute's type info */
1590                                 HeapTuple       tp;
1591                                 Form_pg_attribute att_tup;
1592
1593                                 tp = SearchSysCache(ATTNUM,
1594                                                                         ObjectIdGetDatum(rte->relid),
1595                                                                         Int16GetDatum(attnum),
1596                                                                         0, 0);
1597                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1598                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1599                                                  attnum, rte->relid);
1600                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1601
1602                                 /*
1603                                  * If dropped column, pretend it ain't there.  See notes
1604                                  * in scanRTEForColumn.
1605                                  */
1606                                 if (att_tup->attisdropped)
1607                                         ereport(ERROR,
1608                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1609                                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
1610                                                                         NameStr(att_tup->attname),
1611                                                                         get_rel_name(rte->relid))));
1612                                 *vartype = att_tup->atttypid;
1613                                 *vartypmod = att_tup->atttypmod;
1614                                 ReleaseSysCache(tp);
1615                         }
1616                         break;
1617                 case RTE_SUBQUERY:
1618                         {
1619                                 /* Subselect RTE --- get type info from subselect's tlist */
1620                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1621                                                                                                    attnum);
1622
1623                                 if (te == NULL || te->resjunk)
1624                                         elog(ERROR, "subquery %s does not have attribute %d",
1625                                                  rte->eref->aliasname, attnum);
1626                                 *vartype = exprType((Node *) te->expr);
1627                                 *vartypmod = exprTypmod((Node *) te->expr);
1628                         }
1629                         break;
1630                 case RTE_FUNCTION:
1631                         {
1632                                 /* Function RTE */
1633                                 TypeFuncClass functypclass;
1634                                 Oid                     funcrettype;
1635                                 TupleDesc       tupdesc;
1636
1637                                 functypclass = get_expr_result_type(rte->funcexpr,
1638                                                                                                         &funcrettype,
1639                                                                                                         &tupdesc);
1640
1641                                 if (functypclass == TYPEFUNC_COMPOSITE)
1642                                 {
1643                                         /* Composite data type, e.g. a table's row type */
1644                                         Form_pg_attribute att_tup;
1645
1646                                         Assert(tupdesc);
1647                                         /* this is probably a can't-happen case */
1648                                         if (attnum < 1 || attnum > tupdesc->natts)
1649                                                 ereport(ERROR,
1650                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1651                                                                  errmsg("column %d of relation \"%s\" does not exist",
1652                                                                                 attnum,
1653                                                                                 rte->eref->aliasname)));
1654
1655                                         att_tup = tupdesc->attrs[attnum - 1];
1656
1657                                         /*
1658                                          * If dropped column, pretend it ain't there.  See
1659                                          * notes in scanRTEForColumn.
1660                                          */
1661                                         if (att_tup->attisdropped)
1662                                                 ereport(ERROR,
1663                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1664                                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
1665                                                                                 NameStr(att_tup->attname),
1666                                                                                 rte->eref->aliasname)));
1667                                         *vartype = att_tup->atttypid;
1668                                         *vartypmod = att_tup->atttypmod;
1669                                 }
1670                                 else if (functypclass == TYPEFUNC_SCALAR)
1671                                 {
1672                                         /* Base data type, i.e. scalar */
1673                                         *vartype = funcrettype;
1674                                         *vartypmod = -1;
1675                                 }
1676                                 else if (functypclass == TYPEFUNC_RECORD)
1677                                 {
1678                                         ColumnDef  *colDef = list_nth(rte->coldeflist, attnum - 1);
1679
1680                                         *vartype = typenameTypeId(colDef->typename);
1681                                         *vartypmod = -1;
1682                                 }
1683                                 else
1684                                 {
1685                                         /* addRangeTableEntryForFunction should've caught this */
1686                                         elog(ERROR, "function in FROM has unsupported return type");
1687                                 }
1688                         }
1689                         break;
1690                 case RTE_JOIN:
1691                         {
1692                                 /*
1693                                  * Join RTE --- get type info from join RTE's alias
1694                                  * variable
1695                                  */
1696                                 Node       *aliasvar;
1697
1698                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1699                                 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1700                                 *vartype = exprType(aliasvar);
1701                                 *vartypmod = exprTypmod(aliasvar);
1702                         }
1703                         break;
1704                 default:
1705                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1706         }
1707 }
1708
1709 /*
1710  * get_rte_attribute_is_dropped
1711  *              Check whether attempted attribute ref is to a dropped column
1712  */
1713 bool
1714 get_rte_attribute_is_dropped(List *rtable, int rtindex, AttrNumber attnum)
1715 {
1716         RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1717         bool            result;
1718
1719         switch (rte->rtekind)
1720         {
1721                 case RTE_RELATION:
1722                         {
1723                                 /*
1724                                  * Plain relation RTE --- get the attribute's catalog
1725                                  * entry
1726                                  */
1727                                 HeapTuple       tp;
1728                                 Form_pg_attribute att_tup;
1729
1730                                 tp = SearchSysCache(ATTNUM,
1731                                                                         ObjectIdGetDatum(rte->relid),
1732                                                                         Int16GetDatum(attnum),
1733                                                                         0, 0);
1734                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1735                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1736                                                  attnum, rte->relid);
1737                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1738                                 result = att_tup->attisdropped;
1739                                 ReleaseSysCache(tp);
1740                         }
1741                         break;
1742                 case RTE_SUBQUERY:
1743                         /* Subselect RTEs never have dropped columns */
1744                         result = false;
1745                         break;
1746                 case RTE_JOIN:
1747                         {
1748                                 /*
1749                                  * A join RTE would not have dropped columns when
1750                                  * constructed, but one in a stored rule might contain
1751                                  * columns that were dropped from the underlying tables,
1752                                  * if said columns are nowhere explicitly referenced in
1753                                  * the rule.  So we have to recursively look at the
1754                                  * referenced column.
1755                                  */
1756                                 Var                *aliasvar;
1757
1758                                 if (attnum <= 0 ||
1759                                         attnum > list_length(rte->joinaliasvars))
1760                                         elog(ERROR, "invalid varattno %d", attnum);
1761                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1762
1763                                 /*
1764                                  * If the list item isn't a simple Var, then it must
1765                                  * represent a merged column, ie a USING column, and so it
1766                                  * couldn't possibly be dropped (since it's referenced in
1767                                  * the join clause).
1768                                  */
1769                                 if (!IsA(aliasvar, Var))
1770                                         result = false;
1771                                 else
1772                                         result = get_rte_attribute_is_dropped(rtable,
1773                                                                                                                   aliasvar->varno,
1774                                                                                                          aliasvar->varattno);
1775                         }
1776                         break;
1777                 case RTE_FUNCTION:
1778                         {
1779                                 /* Function RTE */
1780                                 Oid                     funcrettype = exprType(rte->funcexpr);
1781                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
1782
1783                                 if (OidIsValid(funcrelid))
1784                                 {
1785                                         /*
1786                                          * Composite data type, i.e. a table's row type
1787                                          *
1788                                          * Same as ordinary relation RTE
1789                                          */
1790                                         HeapTuple       tp;
1791                                         Form_pg_attribute att_tup;
1792
1793                                         tp = SearchSysCache(ATTNUM,
1794                                                                                 ObjectIdGetDatum(funcrelid),
1795                                                                                 Int16GetDatum(attnum),
1796                                                                                 0, 0);
1797                                         if (!HeapTupleIsValid(tp))      /* shouldn't happen */
1798                                                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1799                                                          attnum, funcrelid);
1800                                         att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1801                                         result = att_tup->attisdropped;
1802                                         ReleaseSysCache(tp);
1803                                 }
1804                                 else
1805                                 {
1806                                         /*
1807                                          * Must be a base data type, i.e. scalar
1808                                          */
1809                                         result = false;
1810                                 }
1811                         }
1812                         break;
1813                 default:
1814                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1815                         result = false;         /* keep compiler quiet */
1816         }
1817
1818         return result;
1819 }
1820
1821 /*
1822  * Given a targetlist and a resno, return the matching TargetEntry
1823  *
1824  * Returns NULL if resno is not present in list.
1825  *
1826  * Note: we need to search, rather than just indexing with list_nth(),
1827  * because not all tlists are sorted by resno.
1828  */
1829 TargetEntry *
1830 get_tle_by_resno(List *tlist, AttrNumber resno)
1831 {
1832         ListCell   *l;
1833
1834         foreach(l, tlist)
1835         {
1836                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1837
1838                 if (tle->resno == resno)
1839                         return tle;
1840         }
1841         return NULL;
1842 }
1843
1844 /*
1845  *      given relation and att name, return id of variable
1846  *
1847  *      This should only be used if the relation is already
1848  *      heap_open()'ed.  Use the cache version get_attnum()
1849  *      for access to non-opened relations.
1850  */
1851 int
1852 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1853 {
1854         int                     i;
1855
1856         for (i = 0; i < rd->rd_rel->relnatts; i++)
1857         {
1858                 Form_pg_attribute att = rd->rd_att->attrs[i];
1859
1860                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1861                         return i + 1;
1862         }
1863
1864         if (sysColOK)
1865         {
1866                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1867                 {
1868                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1869                                 return i;
1870                 }
1871         }
1872
1873         /* on failure */
1874         ereport(ERROR,
1875                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1876                          errmsg("column \"%s\" of relation \"%s\" does not exist",
1877                                         attname, RelationGetRelationName(rd))));
1878         return InvalidAttrNumber;       /* keep compiler quiet */
1879 }
1880
1881 /* specialAttNum()
1882  *
1883  * Check attribute name to see if it is "special", e.g. "oid".
1884  * - thomas 2000-02-07
1885  *
1886  * Note: this only discovers whether the name could be a system attribute.
1887  * Caller needs to verify that it really is an attribute of the rel,
1888  * at least in the case of "oid", which is now optional.
1889  */
1890 static int
1891 specialAttNum(const char *attname)
1892 {
1893         Form_pg_attribute sysatt;
1894
1895         sysatt = SystemAttributeByName(attname,
1896                                                                    true /* "oid" will be accepted */ );
1897         if (sysatt != NULL)
1898                 return sysatt->attnum;
1899         return InvalidAttrNumber;
1900 }
1901
1902
1903 /*
1904  * given attribute id, return name of that attribute
1905  *
1906  *      This should only be used if the relation is already
1907  *      heap_open()'ed.  Use the cache version get_atttype()
1908  *      for access to non-opened relations.
1909  */
1910 Name
1911 attnumAttName(Relation rd, int attid)
1912 {
1913         if (attid <= 0)
1914         {
1915                 Form_pg_attribute sysatt;
1916
1917                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1918                 return &sysatt->attname;
1919         }
1920         if (attid > rd->rd_att->natts)
1921                 elog(ERROR, "invalid attribute number %d", attid);
1922         return &rd->rd_att->attrs[attid - 1]->attname;
1923 }
1924
1925 /*
1926  * given attribute id, return type of that attribute
1927  *
1928  *      This should only be used if the relation is already
1929  *      heap_open()'ed.  Use the cache version get_atttype()
1930  *      for access to non-opened relations.
1931  */
1932 Oid
1933 attnumTypeId(Relation rd, int attid)
1934 {
1935         if (attid <= 0)
1936         {
1937                 Form_pg_attribute sysatt;
1938
1939                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1940                 return sysatt->atttypid;
1941         }
1942         if (attid > rd->rd_att->natts)
1943                 elog(ERROR, "invalid attribute number %d", attid);
1944         return rd->rd_att->attrs[attid - 1]->atttypid;
1945 }
1946
1947 /*
1948  * Generate a warning or error about an implicit RTE, if appropriate.
1949  *
1950  * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
1951  * a warning.
1952  */
1953 static void
1954 warnAutoRange(ParseState *pstate, RangeVar *relation)
1955 {
1956         if (!add_missing_from)
1957         {
1958                 if (pstate->parentParseState != NULL)
1959                         ereport(ERROR,
1960                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1961                                          errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1962                                                         relation->relname)));
1963                 else
1964                         ereport(ERROR,
1965                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1966                                          errmsg("missing FROM-clause entry for table \"%s\"",
1967                                                         relation->relname)));
1968         }
1969         else
1970         {
1971                 /* just issue a warning */
1972                 if (pstate->parentParseState != NULL)
1973                         ereport(NOTICE,
1974                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1975                                          errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
1976                                                         relation->relname)));
1977                 else
1978                         ereport(NOTICE,
1979                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1980                           errmsg("adding missing FROM-clause entry for table \"%s\"",
1981                                          relation->relname)));
1982         }
1983 }