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