]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
First phase of OUT-parameters project. We can now define and use SQL
[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.103 2005/03/31 22:46:13 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 isForUpdate(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
600                                 /* use orig_pstate here to get the right sublevels_up */
601                                 newresult = scanRTEForColumn(orig_pstate, rte, colname);
602                         }
603                         else
604                                 elog(ERROR, "unrecognized node type: %d",
605                                          (int) nodeTag(nsnode));
606
607                         if (newresult)
608                         {
609                                 if (result)
610                                         ereport(ERROR,
611                                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
612                                                    errmsg("column reference \"%s\" is ambiguous",
613                                                                   colname)));
614                                 result = newresult;
615                         }
616                 }
617
618                 if (result != NULL || localonly)
619                         break;                          /* found, or don't want to look at parent */
620
621                 pstate = pstate->parentParseState;
622                 levels_up++;
623         }
624
625         return result;
626 }
627
628 /*
629  * qualifiedNameToVar
630  *        Search for a qualified column name: either refname.colname or
631  *        schemaname.relname.colname.
632  *
633  *        If found, return the appropriate Var node.
634  *        If not found, return NULL.  If the name proves ambiguous, raise error.
635  */
636 Node *
637 qualifiedNameToVar(ParseState *pstate,
638                                    char *schemaname,
639                                    char *refname,
640                                    char *colname,
641                                    bool implicitRTEOK)
642 {
643         RangeTblEntry *rte;
644         int                     sublevels_up;
645
646         rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
647
648         if (rte == NULL)
649         {
650                 if (!implicitRTEOK)
651                         return NULL;
652                 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
653         }
654
655         return scanRTEForColumn(pstate, rte, colname);
656 }
657
658 /*
659  * buildRelationAliases
660  *              Construct the eref column name list for a relation RTE.
661  *              This code is also used for the case of a function RTE returning
662  *              a named composite type.
663  *
664  * tupdesc: the physical column information
665  * alias: the user-supplied alias, or NULL if none
666  * eref: the eref Alias to store column names in
667  *
668  * eref->colnames is filled in.  Also, alias->colnames is rebuilt to insert
669  * empty strings for any dropped columns, so that it will be one-to-one with
670  * physical column numbers.
671  */
672 static void
673 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
674 {
675         int                     maxattrs = tupdesc->natts;
676         ListCell   *aliaslc;
677         int                     numaliases;
678         int                     varattno;
679         int                     numdropped = 0;
680
681         Assert(eref->colnames == NIL);
682
683         if (alias)
684         {
685                 aliaslc = list_head(alias->colnames);
686                 numaliases = list_length(alias->colnames);
687                 /* We'll rebuild the alias colname list */
688                 alias->colnames = NIL;
689         }
690         else
691         {
692                 aliaslc = NULL;
693                 numaliases = 0;
694         }
695
696         for (varattno = 0; varattno < maxattrs; varattno++)
697         {
698                 Form_pg_attribute attr = tupdesc->attrs[varattno];
699                 Value      *attrname;
700
701                 if (attr->attisdropped)
702                 {
703                         /* Always insert an empty string for a dropped column */
704                         attrname = makeString(pstrdup(""));
705                         if (aliaslc)
706                                 alias->colnames = lappend(alias->colnames, attrname);
707                         numdropped++;
708                 }
709                 else if (aliaslc)
710                 {
711                         /* Use the next user-supplied alias */
712                         attrname = (Value *) lfirst(aliaslc);
713                         aliaslc = lnext(aliaslc);
714                         alias->colnames = lappend(alias->colnames, attrname);
715                 }
716                 else
717                 {
718                         attrname = makeString(pstrdup(NameStr(attr->attname)));
719                         /* we're done with the alias if any */
720                 }
721
722                 eref->colnames = lappend(eref->colnames, attrname);
723         }
724
725         /* Too many user-supplied aliases? */
726         if (aliaslc)
727                 ereport(ERROR,
728                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
729                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
730                                    eref->aliasname, maxattrs - numdropped, numaliases)));
731 }
732
733 /*
734  * Add an entry for a relation to the pstate's range table (p_rtable).
735  *
736  * If pstate is NULL, we just build an RTE and return it without adding it
737  * to an rtable list.
738  *
739  * Note: formerly this checked for refname conflicts, but that's wrong.
740  * Caller is responsible for checking for conflicts in the appropriate scope.
741  */
742 RangeTblEntry *
743 addRangeTableEntry(ParseState *pstate,
744                                    RangeVar *relation,
745                                    Alias *alias,
746                                    bool inh,
747                                    bool inFromCl)
748 {
749         RangeTblEntry *rte = makeNode(RangeTblEntry);
750         char       *refname = alias ? alias->aliasname : relation->relname;
751         LOCKMODE        lockmode;
752         Relation        rel;
753
754         rte->rtekind = RTE_RELATION;
755         rte->alias = alias;
756
757         /*
758          * Get the rel's OID.  This access also ensures that we have an
759          * up-to-date relcache entry for the rel.  Since this is typically the
760          * first access to a rel in a statement, be careful to get the right
761          * access level depending on whether we're doing SELECT FOR UPDATE.
762          */
763         lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
764         rel = heap_openrv(relation, lockmode);
765         rte->relid = RelationGetRelid(rel);
766
767         /*
768          * Build the list of effective column names using user-supplied
769          * aliases and/or actual column names.
770          */
771         rte->eref = makeAlias(refname, NIL);
772         buildRelationAliases(rel->rd_att, alias, rte->eref);
773
774         /*
775          * Drop the rel refcount, but keep the access lock till end of
776          * transaction so that the table can't be deleted or have its schema
777          * modified underneath us.
778          */
779         heap_close(rel, NoLock);
780
781         /*----------
782          * Flags:
783          * - this RTE should be expanded to include descendant tables,
784          * - this RTE is in the FROM clause,
785          * - this RTE should be checked for appropriate access rights.
786          *
787          * The initial default on access checks is always check-for-READ-access,
788          * which is the right thing for all except target tables.
789          *----------
790          */
791         rte->inh = inh;
792         rte->inFromCl = inFromCl;
793
794         rte->requiredPerms = ACL_SELECT;
795         rte->checkAsUser = 0;           /* not set-uid by default, either */
796
797         /*
798          * Add completed RTE to pstate's range table list, but not to join
799          * list nor namespace --- caller must do that if appropriate.
800          */
801         if (pstate != NULL)
802                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
803
804         return rte;
805 }
806
807 /*
808  * Add an entry for a relation to the pstate's range table (p_rtable).
809  *
810  * This is just like addRangeTableEntry() except that it makes an RTE
811  * given a relation OID instead of a RangeVar reference.
812  *
813  * Note that an alias clause *must* be supplied.
814  */
815 RangeTblEntry *
816 addRangeTableEntryForRelation(ParseState *pstate,
817                                                           Oid relid,
818                                                           Alias *alias,
819                                                           bool inh,
820                                                           bool inFromCl)
821 {
822         RangeTblEntry *rte = makeNode(RangeTblEntry);
823         char       *refname = alias->aliasname;
824         LOCKMODE        lockmode;
825         Relation        rel;
826
827         rte->rtekind = RTE_RELATION;
828         rte->alias = alias;
829
830         /*
831          * Get the rel's relcache entry.  This access ensures that we have an
832          * up-to-date relcache entry for the rel.  Since this is typically the
833          * first access to a rel in a statement, be careful to get the right
834          * access level depending on whether we're doing SELECT FOR UPDATE.
835          */
836         lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
837         rel = heap_open(relid, lockmode);
838         rte->relid = relid;
839
840         /*
841          * Build the list of effective column names using user-supplied
842          * aliases and/or actual column names.
843          */
844         rte->eref = makeAlias(refname, NIL);
845         buildRelationAliases(rel->rd_att, alias, rte->eref);
846
847         /*
848          * Drop the rel refcount, but keep the access lock till end of
849          * transaction so that the table can't be deleted or have its schema
850          * modified underneath us.
851          */
852         heap_close(rel, NoLock);
853
854         /*----------
855          * Flags:
856          * - this RTE should be expanded to include descendant tables,
857          * - this RTE is in the FROM clause,
858          * - this RTE should be checked for appropriate access rights.
859          *
860          * The initial default on access checks is always check-for-READ-access,
861          * which is the right thing for all except target tables.
862          *----------
863          */
864         rte->inh = inh;
865         rte->inFromCl = inFromCl;
866
867         rte->requiredPerms = ACL_SELECT;
868         rte->checkAsUser = 0;           /* not set-uid by default, either */
869
870         /*
871          * Add completed RTE to pstate's range table list, but not to join
872          * list nor namespace --- caller must do that if appropriate.
873          */
874         if (pstate != NULL)
875                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
876
877         return rte;
878 }
879
880 /*
881  * Add an entry for a subquery to the pstate's range table (p_rtable).
882  *
883  * This is just like addRangeTableEntry() except that it makes a subquery RTE.
884  * Note that an alias clause *must* be supplied.
885  */
886 RangeTblEntry *
887 addRangeTableEntryForSubquery(ParseState *pstate,
888                                                           Query *subquery,
889                                                           Alias *alias,
890                                                           bool inFromCl)
891 {
892         RangeTblEntry *rte = makeNode(RangeTblEntry);
893         char       *refname = alias->aliasname;
894         Alias      *eref;
895         int                     numaliases;
896         int                     varattno;
897         ListCell   *tlistitem;
898
899         rte->rtekind = RTE_SUBQUERY;
900         rte->relid = InvalidOid;
901         rte->subquery = subquery;
902         rte->alias = alias;
903
904         eref = copyObject(alias);
905         numaliases = list_length(eref->colnames);
906
907         /* fill in any unspecified alias columns */
908         varattno = 0;
909         foreach(tlistitem, subquery->targetList)
910         {
911                 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
912
913                 if (te->resdom->resjunk)
914                         continue;
915                 varattno++;
916                 Assert(varattno == te->resdom->resno);
917                 if (varattno > numaliases)
918                 {
919                         char       *attrname;
920
921                         attrname = pstrdup(te->resdom->resname);
922                         eref->colnames = lappend(eref->colnames, makeString(attrname));
923                 }
924         }
925         if (varattno < numaliases)
926                 ereport(ERROR,
927                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
928                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
929                                                 refname, varattno, numaliases)));
930
931         rte->eref = eref;
932
933         /*----------
934          * Flags:
935          * - this RTE should be expanded to include descendant tables,
936          * - this RTE is in the FROM clause,
937          * - this RTE should be checked for appropriate access rights.
938          *
939          * Subqueries are never checked for access rights.
940          *----------
941          */
942         rte->inh = false;                       /* never true for subqueries */
943         rte->inFromCl = inFromCl;
944
945         rte->requiredPerms = 0;
946         rte->checkAsUser = 0;
947
948         /*
949          * Add completed RTE to pstate's range table list, but not to join
950          * list nor namespace --- caller must do that if appropriate.
951          */
952         if (pstate != NULL)
953                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
954
955         return rte;
956 }
957
958 /*
959  * Add an entry for a function to the pstate's range table (p_rtable).
960  *
961  * This is just like addRangeTableEntry() except that it makes a function RTE.
962  */
963 RangeTblEntry *
964 addRangeTableEntryForFunction(ParseState *pstate,
965                                                           char *funcname,
966                                                           Node *funcexpr,
967                                                           RangeFunction *rangefunc,
968                                                           bool inFromCl)
969 {
970         RangeTblEntry *rte = makeNode(RangeTblEntry);
971         TypeFuncClass functypclass;
972         Oid                     funcrettype;
973         TupleDesc       tupdesc;
974         Alias      *alias = rangefunc->alias;
975         List       *coldeflist = rangefunc->coldeflist;
976         Alias      *eref;
977
978         rte->rtekind = RTE_FUNCTION;
979         rte->relid = InvalidOid;
980         rte->subquery = NULL;
981         rte->funcexpr = funcexpr;
982         rte->coldeflist = coldeflist;
983         rte->alias = alias;
984
985         eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
986         rte->eref = eref;
987
988         /*
989          * Now determine if the function returns a simple or composite type.
990          */
991         functypclass = get_expr_result_type(funcexpr,
992                                                                                 &funcrettype,
993                                                                                 &tupdesc);
994
995         /*
996          * A coldeflist is required if the function returns RECORD and hasn't
997          * got a predetermined record type, and is prohibited otherwise.
998          */
999         if (coldeflist != NIL)
1000         {
1001                 if (functypclass != TYPEFUNC_RECORD)
1002                         ereport(ERROR,
1003                                         (errcode(ERRCODE_SYNTAX_ERROR),
1004                                          errmsg("a column definition list is only allowed for functions returning \"record\"")));
1005         }
1006         else
1007         {
1008                 if (functypclass == TYPEFUNC_RECORD)
1009                         ereport(ERROR,
1010                                         (errcode(ERRCODE_SYNTAX_ERROR),
1011                                          errmsg("a column definition list is required for functions returning \"record\"")));
1012         }
1013
1014         if (functypclass == TYPEFUNC_COMPOSITE)
1015         {
1016                 /* Composite data type, e.g. a table's row type */
1017                 Assert(tupdesc);
1018                 /* Build the column alias list */
1019                 buildRelationAliases(tupdesc, alias, eref);
1020         }
1021         else if (functypclass == TYPEFUNC_SCALAR)
1022         {
1023                 /* Base data type, i.e. scalar */
1024                 /* Just add one alias column named for the function. */
1025                 if (alias && alias->colnames != NIL)
1026                 {
1027                         if (list_length(alias->colnames) != 1)
1028                                 ereport(ERROR,
1029                                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1030                                                  errmsg("too many column aliases specified for function %s",
1031                                                                 funcname)));
1032                         eref->colnames = copyObject(alias->colnames);
1033                 }
1034                 else
1035                         eref->colnames = list_make1(makeString(eref->aliasname));
1036         }
1037         else if (functypclass == TYPEFUNC_RECORD)
1038         {
1039                 ListCell   *col;
1040
1041                 /* Use the column definition list to form the alias list */
1042                 foreach(col, coldeflist)
1043                 {
1044                         ColumnDef  *n = lfirst(col);
1045                         char       *attrname;
1046
1047                         attrname = pstrdup(n->colname);
1048                         eref->colnames = lappend(eref->colnames, makeString(attrname));
1049                 }
1050         }
1051         else
1052                 ereport(ERROR,
1053                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1054                         errmsg("function \"%s\" in FROM has unsupported return type %s",
1055                                    funcname, format_type_be(funcrettype))));
1056
1057         /*----------
1058          * Flags:
1059          * - this RTE should be expanded to include descendant tables,
1060          * - this RTE is in the FROM clause,
1061          * - this RTE should be checked for appropriate access rights.
1062          *
1063          * Functions are never checked for access rights (at least, not by
1064          * the RTE permissions mechanism).
1065          *----------
1066          */
1067         rte->inh = false;                       /* never true for functions */
1068         rte->inFromCl = inFromCl;
1069
1070         rte->requiredPerms = 0;
1071         rte->checkAsUser = 0;
1072
1073         /*
1074          * Add completed RTE to pstate's range table list, but not to join
1075          * list nor namespace --- caller must do that if appropriate.
1076          */
1077         if (pstate != NULL)
1078                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1079
1080         return rte;
1081 }
1082
1083 /*
1084  * Add an entry for a join to the pstate's range table (p_rtable).
1085  *
1086  * This is much like addRangeTableEntry() except that it makes a join RTE.
1087  */
1088 RangeTblEntry *
1089 addRangeTableEntryForJoin(ParseState *pstate,
1090                                                   List *colnames,
1091                                                   JoinType jointype,
1092                                                   List *aliasvars,
1093                                                   Alias *alias,
1094                                                   bool inFromCl)
1095 {
1096         RangeTblEntry *rte = makeNode(RangeTblEntry);
1097         Alias      *eref;
1098         int                     numaliases;
1099
1100         rte->rtekind = RTE_JOIN;
1101         rte->relid = InvalidOid;
1102         rte->subquery = NULL;
1103         rte->jointype = jointype;
1104         rte->joinaliasvars = aliasvars;
1105         rte->alias = alias;
1106
1107         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1108         numaliases = list_length(eref->colnames);
1109
1110         /* fill in any unspecified alias columns */
1111         if (numaliases < list_length(colnames))
1112                 eref->colnames = list_concat(eref->colnames,
1113                                                                    list_copy_tail(colnames, numaliases));
1114
1115         rte->eref = eref;
1116
1117         /*----------
1118          * Flags:
1119          * - this RTE should be expanded to include descendant tables,
1120          * - this RTE is in the FROM clause,
1121          * - this RTE should be checked for appropriate access rights.
1122          *
1123          * Joins are never checked for access rights.
1124          *----------
1125          */
1126         rte->inh = false;                       /* never true for joins */
1127         rte->inFromCl = inFromCl;
1128
1129         rte->requiredPerms = 0;
1130         rte->checkAsUser = 0;
1131
1132         /*
1133          * Add completed RTE to pstate's range table list, but not to join
1134          * list nor namespace --- caller must do that if appropriate.
1135          */
1136         if (pstate != NULL)
1137                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1138
1139         return rte;
1140 }
1141
1142 /*
1143  * Has the specified refname been selected FOR UPDATE?
1144  */
1145 static bool
1146 isForUpdate(ParseState *pstate, char *refname)
1147 {
1148         /* Outer loop to check parent query levels as well as this one */
1149         while (pstate != NULL)
1150         {
1151                 if (pstate->p_forUpdate != NIL)
1152                 {
1153                         if (linitial(pstate->p_forUpdate) == NULL)
1154                         {
1155                                 /* all tables used in query */
1156                                 return true;
1157                         }
1158                         else
1159                         {
1160                                 /* just the named tables */
1161                                 ListCell   *l;
1162
1163                                 foreach(l, pstate->p_forUpdate)
1164                                 {
1165                                         char       *rname = strVal(lfirst(l));
1166
1167                                         if (strcmp(refname, rname) == 0)
1168                                                 return true;
1169                                 }
1170                         }
1171                 }
1172                 pstate = pstate->parentParseState;
1173         }
1174         return false;
1175 }
1176
1177 /*
1178  * Add the given RTE as a top-level entry in the pstate's join list
1179  * and/or name space list.      (We assume caller has checked for any
1180  * namespace conflict.)
1181  */
1182 void
1183 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1184                           bool addToJoinList, bool addToNameSpace)
1185 {
1186         int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1187         RangeTblRef *rtr = makeNode(RangeTblRef);
1188
1189         rtr->rtindex = rtindex;
1190
1191         if (addToJoinList)
1192                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1193         if (addToNameSpace)
1194                 pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1195 }
1196
1197 /*
1198  * Add a POSTQUEL-style implicit RTE.
1199  *
1200  * We assume caller has already checked that there is no RTE or join with
1201  * a conflicting name.
1202  */
1203 RangeTblEntry *
1204 addImplicitRTE(ParseState *pstate, RangeVar *relation)
1205 {
1206         RangeTblEntry *rte;
1207
1208         rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1209         addRTEtoQuery(pstate, rte, true, true);
1210         warnAutoRange(pstate, relation);
1211
1212         return rte;
1213 }
1214
1215 /*
1216  * expandRTE -- expand the columns of a rangetable entry
1217  *
1218  * This creates lists of an RTE's column names (aliases if provided, else
1219  * real names) and Vars for each column.  Only user columns are considered.
1220  * If include_dropped is FALSE then dropped columns are omitted from the
1221  * results.  If include_dropped is TRUE then empty strings and NULL constants
1222  * (not Vars!) are returned for dropped columns.
1223  *
1224  * The target RTE is the rtindex'th entry of rtable.  (The whole rangetable
1225  * must be passed since we need it to determine dropped-ness for JOIN columns.)
1226  * sublevels_up is the varlevelsup value to use in the created Vars.
1227  *
1228  * The output lists go into *colnames and *colvars.
1229  * If only one of the two kinds of output list is needed, pass NULL for the
1230  * output pointer for the unwanted one.
1231  */
1232 void
1233 expandRTE(List *rtable, int rtindex, int sublevels_up,
1234                   bool include_dropped,
1235                   List **colnames, List **colvars)
1236 {
1237         RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1238         int                     varattno;
1239
1240         if (colnames)
1241                 *colnames = NIL;
1242         if (colvars)
1243                 *colvars = NIL;
1244
1245         switch (rte->rtekind)
1246         {
1247                 case RTE_RELATION:
1248                         /* Ordinary relation RTE */
1249                         expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1250                                                    include_dropped, colnames, colvars);
1251                         break;
1252                 case RTE_SUBQUERY:
1253                         {
1254                                 /* Subquery RTE */
1255                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1256                                 ListCell   *tlistitem;
1257
1258                                 varattno = 0;
1259                                 foreach(tlistitem, rte->subquery->targetList)
1260                                 {
1261                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1262
1263                                         if (te->resdom->resjunk)
1264                                                 continue;
1265                                         varattno++;
1266                                         Assert(varattno == te->resdom->resno);
1267
1268                                         if (colnames)
1269                                         {
1270                                                 /* Assume there is one alias per target item */
1271                                                 char       *label = strVal(lfirst(aliasp_item));
1272
1273                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1274                                                 aliasp_item = lnext(aliasp_item);
1275                                         }
1276
1277                                         if (colvars)
1278                                         {
1279                                                 Var                *varnode;
1280
1281                                                 varnode = makeVar(rtindex, varattno,
1282                                                                                   te->resdom->restype,
1283                                                                                   te->resdom->restypmod,
1284                                                                                   sublevels_up);
1285
1286                                                 *colvars = lappend(*colvars, varnode);
1287                                         }
1288                                 }
1289                         }
1290                         break;
1291                 case RTE_FUNCTION:
1292                         {
1293                                 /* Function RTE */
1294                                 TypeFuncClass functypclass;
1295                                 Oid                     funcrettype;
1296                                 TupleDesc       tupdesc;
1297
1298                                 functypclass = get_expr_result_type(rte->funcexpr,
1299                                                                                                         &funcrettype,
1300                                                                                                         &tupdesc);
1301                                 if (functypclass == TYPEFUNC_COMPOSITE)
1302                                 {
1303                                         /* Composite data type, e.g. a table's row type */
1304                                         Assert(tupdesc);
1305                                         expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1306                                                                         include_dropped, colnames, colvars);
1307                                 }
1308                                 else if (functypclass == TYPEFUNC_SCALAR)
1309                                 {
1310                                         /* Base data type, i.e. scalar */
1311                                         if (colnames)
1312                                                 *colnames = lappend(*colnames,
1313                                                                                   linitial(rte->eref->colnames));
1314
1315                                         if (colvars)
1316                                         {
1317                                                 Var                *varnode;
1318
1319                                                 varnode = makeVar(rtindex, 1,
1320                                                                                   funcrettype, -1,
1321                                                                                   sublevels_up);
1322
1323                                                 *colvars = lappend(*colvars, varnode);
1324                                         }
1325                                 }
1326                                 else if (functypclass == TYPEFUNC_RECORD)
1327                                 {
1328                                         List       *coldeflist = rte->coldeflist;
1329                                         ListCell   *col;
1330                                         int                     attnum = 0;
1331
1332                                         foreach(col, coldeflist)
1333                                         {
1334                                                 ColumnDef  *colDef = lfirst(col);
1335
1336                                                 attnum++;
1337                                                 if (colnames)
1338                                                 {
1339                                                         char       *attrname;
1340
1341                                                         attrname = pstrdup(colDef->colname);
1342                                                         *colnames = lappend(*colnames, makeString(attrname));
1343                                                 }
1344
1345                                                 if (colvars)
1346                                                 {
1347                                                         Var                *varnode;
1348                                                         Oid                     atttypid;
1349
1350                                                         atttypid = typenameTypeId(colDef->typename);
1351
1352                                                         varnode = makeVar(rtindex,
1353                                                                                           attnum,
1354                                                                                           atttypid,
1355                                                                                           -1,
1356                                                                                           sublevels_up);
1357
1358                                                         *colvars = lappend(*colvars, varnode);
1359                                                 }
1360                                         }
1361                                 }
1362                                 else
1363                                 {
1364                                         /* addRangeTableEntryForFunction should've caught this */
1365                                         elog(ERROR, "function in FROM has unsupported return type");
1366                                 }
1367                         }
1368                         break;
1369                 case RTE_JOIN:
1370                         {
1371                                 /* Join RTE */
1372                                 ListCell   *colname;
1373                                 ListCell   *aliasvar;
1374
1375                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1376
1377                                 varattno = 0;
1378                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1379                                 {
1380                                         varattno++;
1381
1382                                         /*
1383                                          * During ordinary parsing, there will never be any
1384                                          * deleted columns in the join; but we have to check
1385                                          * since this routine is also used by the rewriter,
1386                                          * and joins found in stored rules might have join
1387                                          * columns for since-deleted columns.
1388                                          */
1389                                         if (get_rte_attribute_is_dropped(rtable, rtindex,
1390                                                                                                          varattno))
1391                                         {
1392                                                 if (include_dropped)
1393                                                 {
1394                                                         if (colnames)
1395                                                                 *colnames = lappend(*colnames,
1396                                                                                                 makeString(pstrdup("")));
1397                                                         if (colvars)
1398                                                         {
1399                                                                 /*
1400                                                                  * can't use atttypid here, but it doesn't
1401                                                                  * really matter what type the Const
1402                                                                  * claims to be.
1403                                                                  */
1404                                                                 *colvars = lappend(*colvars,
1405                                                                                                  makeNullConst(INT4OID));
1406                                                         }
1407                                                 }
1408                                                 continue;
1409                                         }
1410
1411                                         if (colnames)
1412                                         {
1413                                                 char       *label = strVal(lfirst(colname));
1414
1415                                                 *colnames = lappend(*colnames,
1416                                                                                         makeString(pstrdup(label)));
1417                                         }
1418
1419                                         if (colvars)
1420                                         {
1421                                                 Node       *avar = (Node *) lfirst(aliasvar);
1422                                                 Var                *varnode;
1423
1424                                                 varnode = makeVar(rtindex, varattno,
1425                                                                                   exprType(avar),
1426                                                                                   exprTypmod(avar),
1427                                                                                   sublevels_up);
1428
1429                                                 *colvars = lappend(*colvars, varnode);
1430                                         }
1431                                 }
1432                         }
1433                         break;
1434                 default:
1435                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1436         }
1437 }
1438
1439 /*
1440  * expandRelation -- expandRTE subroutine
1441  */
1442 static void
1443 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1444                            bool include_dropped,
1445                            List **colnames, List **colvars)
1446 {
1447         Relation        rel;
1448
1449         /* Get the tupledesc and turn it over to expandTupleDesc */
1450         rel = relation_open(relid, AccessShareLock);
1451         expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1452                                         colnames, colvars);
1453         relation_close(rel, AccessShareLock);
1454 }
1455
1456 /*
1457  * expandTupleDesc -- expandRTE subroutine
1458  */
1459 static void
1460 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1461                                 int rtindex, int sublevels_up,
1462                                 bool include_dropped,
1463                                 List **colnames, List **colvars)
1464 {
1465         int                     maxattrs = tupdesc->natts;
1466         int                     numaliases = list_length(eref->colnames);
1467         int                     varattno;
1468
1469         for (varattno = 0; varattno < maxattrs; varattno++)
1470         {
1471                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1472
1473                 if (attr->attisdropped)
1474                 {
1475                         if (include_dropped)
1476                         {
1477                                 if (colnames)
1478                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1479                                 if (colvars)
1480                                 {
1481                                         /*
1482                                          * can't use atttypid here, but it doesn't really
1483                                          * matter what type the Const claims to be.
1484                                          */
1485                                         *colvars = lappend(*colvars, makeNullConst(INT4OID));
1486                                 }
1487                         }
1488                         continue;
1489                 }
1490
1491                 if (colnames)
1492                 {
1493                         char       *label;
1494
1495                         if (varattno < numaliases)
1496                                 label = strVal(list_nth(eref->colnames, varattno));
1497                         else
1498                                 label = NameStr(attr->attname);
1499                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
1500                 }
1501
1502                 if (colvars)
1503                 {
1504                         Var                *varnode;
1505
1506                         varnode = makeVar(rtindex, attr->attnum,
1507                                                           attr->atttypid, attr->atttypmod,
1508                                                           sublevels_up);
1509
1510                         *colvars = lappend(*colvars, varnode);
1511                 }
1512         }
1513 }
1514
1515 /*
1516  * expandRelAttrs -
1517  *        Workhorse for "*" expansion: produce a list of targetentries
1518  *        for the attributes of the rte
1519  */
1520 List *
1521 expandRelAttrs(ParseState *pstate, List *rtable, int rtindex, int sublevels_up)
1522 {
1523         List       *names,
1524                            *vars;
1525         ListCell   *name,
1526                            *var;
1527         List       *te_list = NIL;
1528
1529         expandRTE(rtable, rtindex, sublevels_up, false, &names, &vars);
1530
1531         forboth(name, names, var, vars)
1532         {
1533                 char       *label = strVal(lfirst(name));
1534                 Node       *varnode = (Node *) lfirst(var);
1535                 TargetEntry *te = makeNode(TargetEntry);
1536
1537                 te->resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1538                                                                 exprType(varnode),
1539                                                                 exprTypmod(varnode),
1540                                                                 label,
1541                                                                 false);
1542                 te->expr = (Expr *) varnode;
1543                 te_list = lappend(te_list, te);
1544         }
1545
1546         Assert(name == NULL && var == NULL);            /* lists not the same
1547                                                                                                  * length? */
1548
1549         return te_list;
1550 }
1551
1552 /*
1553  * get_rte_attribute_name
1554  *              Get an attribute name from a RangeTblEntry
1555  *
1556  * This is unlike get_attname() because we use aliases if available.
1557  * In particular, it will work on an RTE for a subselect or join, whereas
1558  * get_attname() only works on real relations.
1559  *
1560  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1561  * occurs when a Var represents a whole tuple of a relation.
1562  */
1563 char *
1564 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1565 {
1566         if (attnum == InvalidAttrNumber)
1567                 return "*";
1568
1569         /*
1570          * If there is a user-written column alias, use it.
1571          */
1572         if (rte->alias &&
1573                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1574                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1575
1576         /*
1577          * If the RTE is a relation, go to the system catalogs not the
1578          * eref->colnames list.  This is a little slower but it will give the
1579          * right answer if the column has been renamed since the eref list was
1580          * built (which can easily happen for rules).
1581          */
1582         if (rte->rtekind == RTE_RELATION)
1583                 return get_relid_attribute_name(rte->relid, attnum);
1584
1585         /*
1586          * Otherwise use the column name from eref.  There should always be
1587          * one.
1588          */
1589         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1590                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1591
1592         /* else caller gave us a bogus attnum */
1593         elog(ERROR, "invalid attnum %d for rangetable entry %s",
1594                  attnum, rte->eref->aliasname);
1595         return NULL;                            /* keep compiler quiet */
1596 }
1597
1598 /*
1599  * get_rte_attribute_type
1600  *              Get attribute type information from a RangeTblEntry
1601  */
1602 void
1603 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1604                                            Oid *vartype, int32 *vartypmod)
1605 {
1606         switch (rte->rtekind)
1607         {
1608                 case RTE_RELATION:
1609                         {
1610                                 /* Plain relation RTE --- get the attribute's type info */
1611                                 HeapTuple       tp;
1612                                 Form_pg_attribute att_tup;
1613
1614                                 tp = SearchSysCache(ATTNUM,
1615                                                                         ObjectIdGetDatum(rte->relid),
1616                                                                         Int16GetDatum(attnum),
1617                                                                         0, 0);
1618                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1619                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1620                                                  attnum, rte->relid);
1621                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1622
1623                                 /*
1624                                  * If dropped column, pretend it ain't there.  See notes
1625                                  * in scanRTEForColumn.
1626                                  */
1627                                 if (att_tup->attisdropped)
1628                                         ereport(ERROR,
1629                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1630                                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
1631                                                                         NameStr(att_tup->attname),
1632                                                                         get_rel_name(rte->relid))));
1633                                 *vartype = att_tup->atttypid;
1634                                 *vartypmod = att_tup->atttypmod;
1635                                 ReleaseSysCache(tp);
1636                         }
1637                         break;
1638                 case RTE_SUBQUERY:
1639                         {
1640                                 /* Subselect RTE --- get type info from subselect's tlist */
1641                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1642                                                                                                    attnum);
1643
1644                                 if (te == NULL || te->resdom->resjunk)
1645                                         elog(ERROR, "subquery %s does not have attribute %d",
1646                                                  rte->eref->aliasname, attnum);
1647                                 *vartype = te->resdom->restype;
1648                                 *vartypmod = te->resdom->restypmod;
1649                         }
1650                         break;
1651                 case RTE_FUNCTION:
1652                         {
1653                                 /* Function RTE */
1654                                 TypeFuncClass functypclass;
1655                                 Oid                     funcrettype;
1656                                 TupleDesc       tupdesc;
1657
1658                                 functypclass = get_expr_result_type(rte->funcexpr,
1659                                                                                                         &funcrettype,
1660                                                                                                         &tupdesc);
1661
1662                                 if (functypclass == TYPEFUNC_COMPOSITE)
1663                                 {
1664                                         /* Composite data type, e.g. a table's row type */
1665                                         Form_pg_attribute att_tup;
1666
1667                                         Assert(tupdesc);
1668                                         /* this is probably a can't-happen case */
1669                                         if (attnum < 1 || attnum > tupdesc->natts)
1670                                                 ereport(ERROR,
1671                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1672                                                                  errmsg("column %d of relation \"%s\" does not exist",
1673                                                                                 attnum,
1674                                                                                 rte->eref->aliasname)));
1675
1676                                         att_tup = tupdesc->attrs[attnum - 1];
1677
1678                                         /*
1679                                          * If dropped column, pretend it ain't there.  See
1680                                          * notes in scanRTEForColumn.
1681                                          */
1682                                         if (att_tup->attisdropped)
1683                                                 ereport(ERROR,
1684                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1685                                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
1686                                                                                 NameStr(att_tup->attname),
1687                                                                                 rte->eref->aliasname)));
1688                                         *vartype = att_tup->atttypid;
1689                                         *vartypmod = att_tup->atttypmod;
1690                                 }
1691                                 else if (functypclass == TYPEFUNC_SCALAR)
1692                                 {
1693                                         /* Base data type, i.e. scalar */
1694                                         *vartype = funcrettype;
1695                                         *vartypmod = -1;
1696                                 }
1697                                 else if (functypclass == TYPEFUNC_RECORD)
1698                                 {
1699                                         ColumnDef  *colDef = list_nth(rte->coldeflist, attnum - 1);
1700
1701                                         *vartype = typenameTypeId(colDef->typename);
1702                                         *vartypmod = -1;
1703                                 }
1704                                 else
1705                                 {
1706                                         /* addRangeTableEntryForFunction should've caught this */
1707                                         elog(ERROR, "function in FROM has unsupported return type");
1708                                 }
1709                         }
1710                         break;
1711                 case RTE_JOIN:
1712                         {
1713                                 /*
1714                                  * Join RTE --- get type info from join RTE's alias
1715                                  * variable
1716                                  */
1717                                 Node       *aliasvar;
1718
1719                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1720                                 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1721                                 *vartype = exprType(aliasvar);
1722                                 *vartypmod = exprTypmod(aliasvar);
1723                         }
1724                         break;
1725                 default:
1726                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1727         }
1728 }
1729
1730 /*
1731  * get_rte_attribute_is_dropped
1732  *              Check whether attempted attribute ref is to a dropped column
1733  */
1734 bool
1735 get_rte_attribute_is_dropped(List *rtable, int rtindex, AttrNumber attnum)
1736 {
1737         RangeTblEntry *rte = rt_fetch(rtindex, rtable);
1738         bool            result;
1739
1740         switch (rte->rtekind)
1741         {
1742                 case RTE_RELATION:
1743                         {
1744                                 /*
1745                                  * Plain relation RTE --- get the attribute's catalog
1746                                  * entry
1747                                  */
1748                                 HeapTuple       tp;
1749                                 Form_pg_attribute att_tup;
1750
1751                                 tp = SearchSysCache(ATTNUM,
1752                                                                         ObjectIdGetDatum(rte->relid),
1753                                                                         Int16GetDatum(attnum),
1754                                                                         0, 0);
1755                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1756                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1757                                                  attnum, rte->relid);
1758                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1759                                 result = att_tup->attisdropped;
1760                                 ReleaseSysCache(tp);
1761                         }
1762                         break;
1763                 case RTE_SUBQUERY:
1764                         /* Subselect RTEs never have dropped columns */
1765                         result = false;
1766                         break;
1767                 case RTE_JOIN:
1768                         {
1769                                 /*
1770                                  * A join RTE would not have dropped columns when
1771                                  * constructed, but one in a stored rule might contain
1772                                  * columns that were dropped from the underlying tables,
1773                                  * if said columns are nowhere explicitly referenced in
1774                                  * the rule.  So we have to recursively look at the
1775                                  * referenced column.
1776                                  */
1777                                 Var                *aliasvar;
1778
1779                                 if (attnum <= 0 ||
1780                                         attnum > list_length(rte->joinaliasvars))
1781                                         elog(ERROR, "invalid varattno %d", attnum);
1782                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1783
1784                                 /*
1785                                  * If the list item isn't a simple Var, then it must
1786                                  * represent a merged column, ie a USING column, and so it
1787                                  * couldn't possibly be dropped (since it's referenced in
1788                                  * the join clause).
1789                                  */
1790                                 if (!IsA(aliasvar, Var))
1791                                         result = false;
1792                                 else
1793                                         result = get_rte_attribute_is_dropped(rtable,
1794                                                                                                                   aliasvar->varno,
1795                                                                                                          aliasvar->varattno);
1796                         }
1797                         break;
1798                 case RTE_FUNCTION:
1799                         {
1800                                 /* Function RTE */
1801                                 Oid                     funcrettype = exprType(rte->funcexpr);
1802                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
1803
1804                                 if (OidIsValid(funcrelid))
1805                                 {
1806                                         /*
1807                                          * Composite data type, i.e. a table's row type
1808                                          *
1809                                          * Same as ordinary relation RTE
1810                                          */
1811                                         HeapTuple       tp;
1812                                         Form_pg_attribute att_tup;
1813
1814                                         tp = SearchSysCache(ATTNUM,
1815                                                                                 ObjectIdGetDatum(funcrelid),
1816                                                                                 Int16GetDatum(attnum),
1817                                                                                 0, 0);
1818                                         if (!HeapTupleIsValid(tp))      /* shouldn't happen */
1819                                                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1820                                                          attnum, funcrelid);
1821                                         att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1822                                         result = att_tup->attisdropped;
1823                                         ReleaseSysCache(tp);
1824                                 }
1825                                 else
1826                                 {
1827                                         /*
1828                                          * Must be a base data type, i.e. scalar
1829                                          */
1830                                         result = false;
1831                                 }
1832                         }
1833                         break;
1834                 default:
1835                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1836                         result = false;         /* keep compiler quiet */
1837         }
1838
1839         return result;
1840 }
1841
1842 /*
1843  * Given a targetlist and a resno, return the matching TargetEntry
1844  *
1845  * Returns NULL if resno is not present in list.
1846  *
1847  * Note: we need to search, rather than just indexing with list_nth(),
1848  * because not all tlists are sorted by resno.
1849  */
1850 TargetEntry *
1851 get_tle_by_resno(List *tlist, AttrNumber resno)
1852 {
1853         ListCell   *l;
1854
1855         foreach(l, tlist)
1856         {
1857                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1858
1859                 if (tle->resdom->resno == resno)
1860                         return tle;
1861         }
1862         return NULL;
1863 }
1864
1865 /*
1866  *      given relation and att name, return id of variable
1867  *
1868  *      This should only be used if the relation is already
1869  *      heap_open()'ed.  Use the cache version get_attnum()
1870  *      for access to non-opened relations.
1871  */
1872 int
1873 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1874 {
1875         int                     i;
1876
1877         for (i = 0; i < rd->rd_rel->relnatts; i++)
1878         {
1879                 Form_pg_attribute att = rd->rd_att->attrs[i];
1880
1881                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1882                         return i + 1;
1883         }
1884
1885         if (sysColOK)
1886         {
1887                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1888                 {
1889                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1890                                 return i;
1891                 }
1892         }
1893
1894         /* on failure */
1895         ereport(ERROR,
1896                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1897                          errmsg("column \"%s\" of relation \"%s\" does not exist",
1898                                         attname, RelationGetRelationName(rd))));
1899         return InvalidAttrNumber;       /* keep compiler quiet */
1900 }
1901
1902 /* specialAttNum()
1903  *
1904  * Check attribute name to see if it is "special", e.g. "oid".
1905  * - thomas 2000-02-07
1906  *
1907  * Note: this only discovers whether the name could be a system attribute.
1908  * Caller needs to verify that it really is an attribute of the rel,
1909  * at least in the case of "oid", which is now optional.
1910  */
1911 static int
1912 specialAttNum(const char *attname)
1913 {
1914         Form_pg_attribute sysatt;
1915
1916         sysatt = SystemAttributeByName(attname,
1917                                                                    true /* "oid" will be accepted */ );
1918         if (sysatt != NULL)
1919                 return sysatt->attnum;
1920         return InvalidAttrNumber;
1921 }
1922
1923
1924 /*
1925  * given attribute id, return name of that attribute
1926  *
1927  *      This should only be used if the relation is already
1928  *      heap_open()'ed.  Use the cache version get_atttype()
1929  *      for access to non-opened relations.
1930  */
1931 Name
1932 attnumAttName(Relation rd, int attid)
1933 {
1934         if (attid <= 0)
1935         {
1936                 Form_pg_attribute sysatt;
1937
1938                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1939                 return &sysatt->attname;
1940         }
1941         if (attid > rd->rd_att->natts)
1942                 elog(ERROR, "invalid attribute number %d", attid);
1943         return &rd->rd_att->attrs[attid - 1]->attname;
1944 }
1945
1946 /*
1947  * given attribute id, return type of that attribute
1948  *
1949  *      This should only be used if the relation is already
1950  *      heap_open()'ed.  Use the cache version get_atttype()
1951  *      for access to non-opened relations.
1952  */
1953 Oid
1954 attnumTypeId(Relation rd, int attid)
1955 {
1956         if (attid <= 0)
1957         {
1958                 Form_pg_attribute sysatt;
1959
1960                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1961                 return sysatt->atttypid;
1962         }
1963         if (attid > rd->rd_att->natts)
1964                 elog(ERROR, "invalid attribute number %d", attid);
1965         return rd->rd_att->attrs[attid - 1]->atttypid;
1966 }
1967
1968 /*
1969  * Generate a warning or error about an implicit RTE, if appropriate.
1970  *
1971  * If ADD_MISSING_FROM is not enabled, raise an error.
1972  *
1973  * Our current theory on warnings is that we should allow "SELECT foo.*"
1974  * but warn about a mixture of explicit and implicit RTEs.
1975  */
1976 static void
1977 warnAutoRange(ParseState *pstate, RangeVar *relation)
1978 {
1979         bool            foundInFromCl = false;
1980         ListCell   *temp;
1981
1982         if (!add_missing_from)
1983         {
1984                 if (pstate->parentParseState != NULL)
1985                         ereport(ERROR,
1986                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1987                                          errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1988                                                         relation->relname)));
1989                 else
1990                         ereport(ERROR,
1991                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1992                                          errmsg("missing FROM-clause entry for table \"%s\"",
1993                                                         relation->relname)));
1994         }
1995
1996         foreach(temp, pstate->p_rtable)
1997         {
1998                 RangeTblEntry *rte = lfirst(temp);
1999
2000                 if (rte->inFromCl)
2001                 {
2002                         foundInFromCl = true;
2003                         break;
2004                 }
2005         }
2006         if (foundInFromCl)
2007         {
2008                 if (pstate->parentParseState != NULL)
2009                         ereport(NOTICE,
2010                                         (errcode(ERRCODE_UNDEFINED_TABLE),
2011                                          errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
2012                                                         relation->relname)));
2013                 else
2014                         ereport(NOTICE,
2015                                         (errcode(ERRCODE_UNDEFINED_TABLE),
2016                           errmsg("adding missing FROM-clause entry for table \"%s\"",
2017                                          relation->relname)));
2018         }
2019 }