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