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