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