]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
When a GUC string variable is not set, print the empty string (in SHOW etc.),
[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-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_relation.c,v 1.123 2006/04/30 18:30:39 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <ctype.h>
18
19 #include "access/heapam.h"
20 #include "catalog/heap.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_type.h"
23 #include "funcapi.h"
24 #include "nodes/makefuncs.h"
25 #include "parser/parsetree.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_type.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32
33
34 /* GUC parameter */
35 bool            add_missing_from;
36
37 static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
38                                                 const char *refname);
39 static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid);
40 static bool isLockedRel(ParseState *pstate, char *refname);
41 static void expandRelation(Oid relid, Alias *eref,
42                            int rtindex, int sublevels_up,
43                            bool include_dropped,
44                            List **colnames, List **colvars);
45 static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
46                                 int rtindex, int sublevels_up,
47                                 bool include_dropped,
48                                 List **colnames, List **colvars);
49 static int      specialAttNum(const char *attname);
50 static void warnAutoRange(ParseState *pstate, RangeVar *relation,
51                                                   int location);
52
53
54 /*
55  * refnameRangeTblEntry
56  *        Given a possibly-qualified refname, look to see if it matches any RTE.
57  *        If so, return a pointer to the RangeTblEntry; else return NULL.
58  *
59  *        Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
60  *        If sublevels_up is NULL, only consider items at the current nesting
61  *        level.
62  *
63  * An unqualified refname (schemaname == NULL) can match any RTE with matching
64  * alias, or matching unqualified relname in the case of alias-less relation
65  * RTEs.  It is possible that such a refname matches multiple RTEs in the
66  * nearest nesting level that has a match; if so, we report an error via
67  * ereport().
68  *
69  * A qualified refname (schemaname != NULL) can only match a relation RTE
70  * that (a) has no alias and (b) is for the same relation identified by
71  * schemaname.refname.  In this case we convert schemaname.refname to a
72  * relation OID and search by relid, rather than by alias name.  This is
73  * peculiar, but it's what SQL92 says to do.
74  */
75 RangeTblEntry *
76 refnameRangeTblEntry(ParseState *pstate,
77                                          const char *schemaname,
78                                          const char *refname,
79                                          int *sublevels_up)
80 {
81         Oid                     relId = InvalidOid;
82
83         if (sublevels_up)
84                 *sublevels_up = 0;
85
86         if (schemaname != NULL)
87         {
88                 Oid                     namespaceId;
89
90                 namespaceId = LookupExplicitNamespace(schemaname);
91                 relId = get_relname_relid(refname, namespaceId);
92                 if (!OidIsValid(relId))
93                         return NULL;
94         }
95
96         while (pstate != NULL)
97         {
98                 RangeTblEntry *result;
99
100                 if (OidIsValid(relId))
101                         result = scanNameSpaceForRelid(pstate, relId);
102                 else
103                         result = scanNameSpaceForRefname(pstate, refname);
104
105                 if (result)
106                         return result;
107
108                 if (sublevels_up)
109                         (*sublevels_up)++;
110                 else
111                         break;
112
113                 pstate = pstate->parentParseState;
114         }
115         return NULL;
116 }
117
118 /*
119  * Search the query's table namespace for an RTE matching the
120  * given unqualified refname.  Return the RTE if a unique match, or NULL
121  * if no match.  Raise error if multiple matches.
122  */
123 static RangeTblEntry *
124 scanNameSpaceForRefname(ParseState *pstate, const char *refname)
125 {
126         RangeTblEntry *result = NULL;
127         ListCell   *l;
128
129         foreach(l, pstate->p_relnamespace)
130         {
131                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
132
133                 if (strcmp(rte->eref->aliasname, refname) == 0)
134                 {
135                         if (result)
136                                 ereport(ERROR,
137                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
138                                                  errmsg("table reference \"%s\" is ambiguous",
139                                                                 refname)));
140                         result = rte;
141                 }
142         }
143         return result;
144 }
145
146 /*
147  * Search the query's table namespace for a relation RTE matching the
148  * given relation OID.  Return the RTE if a unique match, or NULL
149  * if no match.  Raise error if multiple matches (which shouldn't
150  * happen if the namespace was checked correctly when it was created).
151  *
152  * See the comments for refnameRangeTblEntry to understand why this
153  * acts the way it does.
154  */
155 static RangeTblEntry *
156 scanNameSpaceForRelid(ParseState *pstate, Oid relid)
157 {
158         RangeTblEntry *result = NULL;
159         ListCell   *l;
160
161         foreach(l, pstate->p_relnamespace)
162         {
163                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
164
165                 /* yes, the test for alias == NULL should be there... */
166                 if (rte->rtekind == RTE_RELATION &&
167                         rte->relid == relid &&
168                         rte->alias == NULL)
169                 {
170                         if (result)
171                                 ereport(ERROR,
172                                                 (errcode(ERRCODE_AMBIGUOUS_ALIAS),
173                                                  errmsg("table reference %u is ambiguous",
174                                                                 relid)));
175                         result = rte;
176                 }
177         }
178         return result;
179 }
180
181 /*
182  * searchRangeTable
183  *        See if any RangeTblEntry could possibly match the RangeVar.
184  *        If so, return a pointer to the RangeTblEntry; else return NULL.
185  *
186  * This is different from refnameRangeTblEntry in that it considers every
187  * entry in the ParseState's rangetable(s), not only those that are currently
188  * visible in the p_relnamespace lists.  This behavior is invalid per the SQL
189  * spec, and it may give ambiguous results (there might be multiple equally
190  * valid matches, but only one will be returned).  This must be used ONLY
191  * as a heuristic in giving suitable error messages.  See warnAutoRange.
192  *
193  * Notice that we consider both matches on actual relation name and matches
194  * on alias.
195  */
196 static RangeTblEntry *
197 searchRangeTable(ParseState *pstate, RangeVar *relation)
198 {
199         Oid                     relId = RangeVarGetRelid(relation, true);
200         char       *refname = relation->relname;
201
202         while (pstate != NULL)
203         {
204                 ListCell   *l;
205
206                 foreach(l, pstate->p_rtable)
207                 {
208                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
209
210                         if (OidIsValid(relId) &&
211                                 rte->rtekind == RTE_RELATION &&
212                                 rte->relid == relId)
213                                 return rte;
214                         if (strcmp(rte->eref->aliasname, refname) == 0)
215                                 return rte;
216                 }
217
218                 pstate = pstate->parentParseState;
219         }
220         return NULL;
221 }
222
223 /*
224  * Check for relation-name conflicts between two relnamespace lists.
225  * Raise an error if any is found.
226  *
227  * Note: we assume that each given argument does not contain conflicts
228  * itself; we just want to know if the two can be merged together.
229  *
230  * Per SQL92, two alias-less plain relation RTEs do not conflict even if
231  * they have the same eref->aliasname (ie, same relation name), if they
232  * are for different relation OIDs (implying they are in different schemas).
233  */
234 void
235 checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
236                                                 List *namespace2)
237 {
238         ListCell   *l1;
239
240         foreach(l1, namespace1)
241         {
242                 RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
243                 const char *aliasname1 = rte1->eref->aliasname;
244                 ListCell   *l2;
245
246                 foreach(l2, namespace2)
247                 {
248                         RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
249
250                         if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
251                                 continue;               /* definitely no conflict */
252                         if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
253                                 rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
254                                 rte1->relid != rte2->relid)
255                                 continue;               /* no conflict per SQL92 rule */
256                         ereport(ERROR,
257                                         (errcode(ERRCODE_DUPLICATE_ALIAS),
258                                          errmsg("table name \"%s\" specified more than once",
259                                                         aliasname1)));
260                 }
261         }
262 }
263
264 /*
265  * given an RTE, return RT index (starting with 1) of the entry,
266  * and optionally get its nesting depth (0 = current).  If sublevels_up
267  * is NULL, only consider rels at the current nesting level.
268  * Raises error if RTE not found.
269  */
270 int
271 RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
272 {
273         int                     index;
274         ListCell   *l;
275
276         if (sublevels_up)
277                 *sublevels_up = 0;
278
279         while (pstate != NULL)
280         {
281                 index = 1;
282                 foreach(l, pstate->p_rtable)
283                 {
284                         if (rte == (RangeTblEntry *) lfirst(l))
285                                 return index;
286                         index++;
287                 }
288                 pstate = pstate->parentParseState;
289                 if (sublevels_up)
290                         (*sublevels_up)++;
291                 else
292                         break;
293         }
294
295         elog(ERROR, "RTE not found (internal error)");
296         return 0;                                       /* keep compiler quiet */
297 }
298
299 /*
300  * Given an RT index and nesting depth, find the corresponding RTE.
301  * This is the inverse of RTERangeTablePosn.
302  */
303 RangeTblEntry *
304 GetRTEByRangeTablePosn(ParseState *pstate,
305                                            int varno,
306                                            int sublevels_up)
307 {
308         while (sublevels_up-- > 0)
309         {
310                 pstate = pstate->parentParseState;
311                 Assert(pstate != NULL);
312         }
313         Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
314         return rt_fetch(varno, pstate->p_rtable);
315 }
316
317 /*
318  * scanRTEForColumn
319  *        Search the column names of a single RTE for the given name.
320  *        If found, return an appropriate Var node, else return NULL.
321  *        If the name proves ambiguous within this RTE, raise error.
322  *
323  * Side effect: if we find a match, mark the RTE as requiring read access.
324  * See comments in setTargetTable().
325  *
326  * NOTE: if the RTE is for a join, marking it as requiring read access does
327  * nothing.  It might seem that we need to propagate the mark to all the
328  * contained RTEs, but that is not necessary.  This is so because a join
329  * expression can only appear in a FROM clause, and any table named in
330  * FROM will be marked as requiring read access from the beginning.
331  */
332 Node *
333 scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
334                                  int location)
335 {
336         Node       *result = NULL;
337         int                     attnum = 0;
338         ListCell   *c;
339
340         /*
341          * Scan the user column names (or aliases) for a match. Complain if
342          * multiple matches.
343          *
344          * Note: eref->colnames may include entries for dropped columns, but those
345          * will be empty strings that cannot match any legal SQL identifier, so we
346          * don't bother to test for that case here.
347          *
348          * Should this somehow go wrong and we try to access a dropped column,
349          * we'll still catch it by virtue of the checks in
350          * get_rte_attribute_type(), which is called by make_var().  That routine
351          * has to do a cache lookup anyway, so the check there is cheap.
352          */
353         foreach(c, rte->eref->colnames)
354         {
355                 attnum++;
356                 if (strcmp(strVal(lfirst(c)), colname) == 0)
357                 {
358                         if (result)
359                                 ereport(ERROR,
360                                                 (errcode(ERRCODE_AMBIGUOUS_COLUMN),
361                                                  errmsg("column reference \"%s\" is ambiguous",
362                                                                 colname),
363                                                  parser_errposition(pstate, location)));
364                         result = (Node *) make_var(pstate, rte, attnum);
365                         /* Require read access */
366                         rte->requiredPerms |= ACL_SELECT;
367                 }
368         }
369
370         /*
371          * If we have a unique match, return it.  Note that this allows a user
372          * alias to override a system column name (such as OID) without error.
373          */
374         if (result)
375                 return result;
376
377         /*
378          * If the RTE represents a real table, consider system column names.
379          */
380         if (rte->rtekind == RTE_RELATION)
381         {
382                 /* quick check to see if name could be a system column */
383                 attnum = specialAttNum(colname);
384                 if (attnum != InvalidAttrNumber)
385                 {
386                         /* now check to see if column actually is defined */
387                         if (SearchSysCacheExists(ATTNUM,
388                                                                          ObjectIdGetDatum(rte->relid),
389                                                                          Int16GetDatum(attnum),
390                                                                          0, 0))
391                         {
392                                 result = (Node *) make_var(pstate, rte, attnum);
393                                 /* Require read access */
394                                 rte->requiredPerms |= ACL_SELECT;
395                         }
396                 }
397         }
398
399         return result;
400 }
401
402 /*
403  * colNameToVar
404  *        Search for an unqualified column name.
405  *        If found, return the appropriate Var node (or expression).
406  *        If not found, return NULL.  If the name proves ambiguous, raise error.
407  *        If localonly is true, only names in the innermost query are considered.
408  */
409 Node *
410 colNameToVar(ParseState *pstate, char *colname, bool localonly,
411                          int location)
412 {
413         Node       *result = NULL;
414         ParseState *orig_pstate = pstate;
415
416         while (pstate != NULL)
417         {
418                 ListCell   *l;
419
420                 foreach(l, pstate->p_varnamespace)
421                 {
422                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
423                         Node       *newresult;
424
425                         /* use orig_pstate here to get the right sublevels_up */
426                         newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
427
428                         if (newresult)
429                         {
430                                 if (result)
431                                         ereport(ERROR,
432                                                         (errcode(ERRCODE_AMBIGUOUS_COLUMN),
433                                                          errmsg("column reference \"%s\" is ambiguous",
434                                                                         colname),
435                                                          parser_errposition(orig_pstate, location)));
436                                 result = newresult;
437                         }
438                 }
439
440                 if (result != NULL || localonly)
441                         break;                          /* found, or don't want to look at parent */
442
443                 pstate = pstate->parentParseState;
444         }
445
446         return result;
447 }
448
449 /*
450  * qualifiedNameToVar
451  *        Search for a qualified column name: either refname.colname or
452  *        schemaname.relname.colname.
453  *
454  *        If found, return the appropriate Var node.
455  *        If not found, return NULL.  If the name proves ambiguous, raise error.
456  */
457 Node *
458 qualifiedNameToVar(ParseState *pstate,
459                                    char *schemaname,
460                                    char *refname,
461                                    char *colname,
462                                    bool implicitRTEOK,
463                                    int location)
464 {
465         RangeTblEntry *rte;
466         int                     sublevels_up;
467
468         rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
469
470         if (rte == NULL)
471         {
472                 if (!implicitRTEOK)
473                         return NULL;
474                 rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname),
475                                                          location);
476         }
477
478         return scanRTEForColumn(pstate, rte, colname, location);
479 }
480
481 /*
482  * buildRelationAliases
483  *              Construct the eref column name list for a relation RTE.
484  *              This code is also used for the case of a function RTE returning
485  *              a named composite type.
486  *
487  * tupdesc: the physical column information
488  * alias: the user-supplied alias, or NULL if none
489  * eref: the eref Alias to store column names in
490  *
491  * eref->colnames is filled in.  Also, alias->colnames is rebuilt to insert
492  * empty strings for any dropped columns, so that it will be one-to-one with
493  * physical column numbers.
494  */
495 static void
496 buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
497 {
498         int                     maxattrs = tupdesc->natts;
499         ListCell   *aliaslc;
500         int                     numaliases;
501         int                     varattno;
502         int                     numdropped = 0;
503
504         Assert(eref->colnames == NIL);
505
506         if (alias)
507         {
508                 aliaslc = list_head(alias->colnames);
509                 numaliases = list_length(alias->colnames);
510                 /* We'll rebuild the alias colname list */
511                 alias->colnames = NIL;
512         }
513         else
514         {
515                 aliaslc = NULL;
516                 numaliases = 0;
517         }
518
519         for (varattno = 0; varattno < maxattrs; varattno++)
520         {
521                 Form_pg_attribute attr = tupdesc->attrs[varattno];
522                 Value      *attrname;
523
524                 if (attr->attisdropped)
525                 {
526                         /* Always insert an empty string for a dropped column */
527                         attrname = makeString(pstrdup(""));
528                         if (aliaslc)
529                                 alias->colnames = lappend(alias->colnames, attrname);
530                         numdropped++;
531                 }
532                 else if (aliaslc)
533                 {
534                         /* Use the next user-supplied alias */
535                         attrname = (Value *) lfirst(aliaslc);
536                         aliaslc = lnext(aliaslc);
537                         alias->colnames = lappend(alias->colnames, attrname);
538                 }
539                 else
540                 {
541                         attrname = makeString(pstrdup(NameStr(attr->attname)));
542                         /* we're done with the alias if any */
543                 }
544
545                 eref->colnames = lappend(eref->colnames, attrname);
546         }
547
548         /* Too many user-supplied aliases? */
549         if (aliaslc)
550                 ereport(ERROR,
551                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
552                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
553                                                 eref->aliasname, maxattrs - numdropped, numaliases)));
554 }
555
556 /*
557  * buildScalarFunctionAlias
558  *              Construct the eref column name list for a function RTE,
559  *              when the function returns a scalar type (not composite or RECORD).
560  *
561  * funcexpr: transformed expression tree for the function call
562  * funcname: function name (used only for error message)
563  * alias: the user-supplied alias, or NULL if none
564  * eref: the eref Alias to store column names in
565  *
566  * eref->colnames is filled in.
567  */
568 static void
569 buildScalarFunctionAlias(Node *funcexpr, char *funcname,
570                                                  Alias *alias, Alias *eref)
571 {
572         char       *pname;
573
574         Assert(eref->colnames == NIL);
575
576         /* Use user-specified column alias if there is one. */
577         if (alias && alias->colnames != NIL)
578         {
579                 if (list_length(alias->colnames) != 1)
580                         ereport(ERROR,
581                                         (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
582                                   errmsg("too many column aliases specified for function %s",
583                                                  funcname)));
584                 eref->colnames = copyObject(alias->colnames);
585                 return;
586         }
587
588         /*
589          * If the expression is a simple function call, and the function has a
590          * single OUT parameter that is named, use the parameter's name.
591          */
592         if (funcexpr && IsA(funcexpr, FuncExpr))
593         {
594                 pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
595                 if (pname)
596                 {
597                         eref->colnames = list_make1(makeString(pname));
598                         return;
599                 }
600         }
601
602         /*
603          * Otherwise use the previously-determined alias (not necessarily the
604          * function name!)
605          */
606         eref->colnames = list_make1(makeString(eref->aliasname));
607 }
608
609 /*
610  * Add an entry for a relation to the pstate's range table (p_rtable).
611  *
612  * If pstate is NULL, we just build an RTE and return it without adding it
613  * to an rtable list.
614  *
615  * Note: formerly this checked for refname conflicts, but that's wrong.
616  * Caller is responsible for checking for conflicts in the appropriate scope.
617  */
618 RangeTblEntry *
619 addRangeTableEntry(ParseState *pstate,
620                                    RangeVar *relation,
621                                    Alias *alias,
622                                    bool inh,
623                                    bool inFromCl)
624 {
625         RangeTblEntry *rte = makeNode(RangeTblEntry);
626         char       *refname = alias ? alias->aliasname : relation->relname;
627         LOCKMODE        lockmode;
628         Relation        rel;
629
630         rte->rtekind = RTE_RELATION;
631         rte->alias = alias;
632
633         /*
634          * Get the rel's OID.  This access also ensures that we have an up-to-date
635          * relcache entry for the rel.  Since this is typically the first access
636          * to a rel in a statement, be careful to get the right access level
637          * depending on whether we're doing SELECT FOR UPDATE/SHARE.
638          */
639         lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
640         rel = heap_openrv(relation, lockmode);
641         rte->relid = RelationGetRelid(rel);
642
643         /*
644          * Build the list of effective column names using user-supplied aliases
645          * and/or actual column names.
646          */
647         rte->eref = makeAlias(refname, NIL);
648         buildRelationAliases(rel->rd_att, alias, rte->eref);
649
650         /*
651          * Drop the rel refcount, but keep the access lock till end of transaction
652          * so that the table can't be deleted or have its schema modified
653          * underneath us.
654          */
655         heap_close(rel, NoLock);
656
657         /*----------
658          * Flags:
659          * - this RTE should be expanded to include descendant tables,
660          * - this RTE is in the FROM clause,
661          * - this RTE should be checked for appropriate access rights.
662          *
663          * The initial default on access checks is always check-for-READ-access,
664          * which is the right thing for all except target tables.
665          *----------
666          */
667         rte->inh = inh;
668         rte->inFromCl = inFromCl;
669
670         rte->requiredPerms = ACL_SELECT;
671         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
672
673         /*
674          * Add completed RTE to pstate's range table list, but not to join list
675          * nor namespace --- caller must do that if appropriate.
676          */
677         if (pstate != NULL)
678                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
679
680         return rte;
681 }
682
683 /*
684  * Add an entry for a relation to the pstate's range table (p_rtable).
685  *
686  * This is just like addRangeTableEntry() except that it makes an RTE
687  * given an already-open relation instead of a RangeVar reference.
688  */
689 RangeTblEntry *
690 addRangeTableEntryForRelation(ParseState *pstate,
691                                                           Relation rel,
692                                                           Alias *alias,
693                                                           bool inh,
694                                                           bool inFromCl)
695 {
696         RangeTblEntry *rte = makeNode(RangeTblEntry);
697         char       *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
698
699         rte->rtekind = RTE_RELATION;
700         rte->alias = alias;
701         rte->relid = RelationGetRelid(rel);
702
703         /*
704          * Build the list of effective column names using user-supplied aliases
705          * and/or actual column names.
706          */
707         rte->eref = makeAlias(refname, NIL);
708         buildRelationAliases(rel->rd_att, alias, rte->eref);
709
710         /*----------
711          * Flags:
712          * - this RTE should be expanded to include descendant tables,
713          * - this RTE is in the FROM clause,
714          * - this RTE should be checked for appropriate access rights.
715          *
716          * The initial default on access checks is always check-for-READ-access,
717          * which is the right thing for all except target tables.
718          *----------
719          */
720         rte->inh = inh;
721         rte->inFromCl = inFromCl;
722
723         rte->requiredPerms = ACL_SELECT;
724         rte->checkAsUser = InvalidOid;          /* not set-uid by default, either */
725
726         /*
727          * Add completed RTE to pstate's range table list, but not to join list
728          * nor namespace --- caller must do that if appropriate.
729          */
730         if (pstate != NULL)
731                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
732
733         return rte;
734 }
735
736 /*
737  * Add an entry for a subquery to the pstate's range table (p_rtable).
738  *
739  * This is just like addRangeTableEntry() except that it makes a subquery RTE.
740  * Note that an alias clause *must* be supplied.
741  */
742 RangeTblEntry *
743 addRangeTableEntryForSubquery(ParseState *pstate,
744                                                           Query *subquery,
745                                                           Alias *alias,
746                                                           bool inFromCl)
747 {
748         RangeTblEntry *rte = makeNode(RangeTblEntry);
749         char       *refname = alias->aliasname;
750         Alias      *eref;
751         int                     numaliases;
752         int                     varattno;
753         ListCell   *tlistitem;
754
755         rte->rtekind = RTE_SUBQUERY;
756         rte->relid = InvalidOid;
757         rte->subquery = subquery;
758         rte->alias = alias;
759
760         eref = copyObject(alias);
761         numaliases = list_length(eref->colnames);
762
763         /* fill in any unspecified alias columns */
764         varattno = 0;
765         foreach(tlistitem, subquery->targetList)
766         {
767                 TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
768
769                 if (te->resjunk)
770                         continue;
771                 varattno++;
772                 Assert(varattno == te->resno);
773                 if (varattno > numaliases)
774                 {
775                         char       *attrname;
776
777                         attrname = pstrdup(te->resname);
778                         eref->colnames = lappend(eref->colnames, makeString(attrname));
779                 }
780         }
781         if (varattno < numaliases)
782                 ereport(ERROR,
783                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
784                                  errmsg("table \"%s\" has %d columns available but %d columns specified",
785                                                 refname, varattno, numaliases)));
786
787         rte->eref = eref;
788
789         /*----------
790          * Flags:
791          * - this RTE should be expanded to include descendant tables,
792          * - this RTE is in the FROM clause,
793          * - this RTE should be checked for appropriate access rights.
794          *
795          * Subqueries are never checked for access rights.
796          *----------
797          */
798         rte->inh = false;                       /* never true for subqueries */
799         rte->inFromCl = inFromCl;
800
801         rte->requiredPerms = 0;
802         rte->checkAsUser = InvalidOid;
803
804         /*
805          * Add completed RTE to pstate's range table list, but not to join list
806          * nor namespace --- caller must do that if appropriate.
807          */
808         if (pstate != NULL)
809                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
810
811         return rte;
812 }
813
814 /*
815  * Add an entry for a function to the pstate's range table (p_rtable).
816  *
817  * This is just like addRangeTableEntry() except that it makes a function RTE.
818  */
819 RangeTblEntry *
820 addRangeTableEntryForFunction(ParseState *pstate,
821                                                           char *funcname,
822                                                           Node *funcexpr,
823                                                           RangeFunction *rangefunc,
824                                                           bool inFromCl)
825 {
826         RangeTblEntry *rte = makeNode(RangeTblEntry);
827         TypeFuncClass functypclass;
828         Oid                     funcrettype;
829         TupleDesc       tupdesc;
830         Alias      *alias = rangefunc->alias;
831         List       *coldeflist = rangefunc->coldeflist;
832         Alias      *eref;
833
834         rte->rtekind = RTE_FUNCTION;
835         rte->relid = InvalidOid;
836         rte->subquery = NULL;
837         rte->funcexpr = funcexpr;
838         rte->funccoltypes = NIL;
839         rte->funccoltypmods = NIL;
840         rte->alias = alias;
841
842         eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
843         rte->eref = eref;
844
845         /*
846          * Now determine if the function returns a simple or composite type.
847          */
848         functypclass = get_expr_result_type(funcexpr,
849                                                                                 &funcrettype,
850                                                                                 &tupdesc);
851
852         /*
853          * A coldeflist is required if the function returns RECORD and hasn't got
854          * a predetermined record type, and is prohibited otherwise.
855          */
856         if (coldeflist != NIL)
857         {
858                 if (functypclass != TYPEFUNC_RECORD)
859                         ereport(ERROR,
860                                         (errcode(ERRCODE_SYNTAX_ERROR),
861                                          errmsg("a column definition list is only allowed for functions returning \"record\"")));
862         }
863         else
864         {
865                 if (functypclass == TYPEFUNC_RECORD)
866                         ereport(ERROR,
867                                         (errcode(ERRCODE_SYNTAX_ERROR),
868                                          errmsg("a column definition list is required for functions returning \"record\"")));
869         }
870
871         if (functypclass == TYPEFUNC_COMPOSITE)
872         {
873                 /* Composite data type, e.g. a table's row type */
874                 Assert(tupdesc);
875                 /* Build the column alias list */
876                 buildRelationAliases(tupdesc, alias, eref);
877         }
878         else if (functypclass == TYPEFUNC_SCALAR)
879         {
880                 /* Base data type, i.e. scalar */
881                 buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
882         }
883         else if (functypclass == TYPEFUNC_RECORD)
884         {
885                 ListCell   *col;
886
887                 /*
888                  * Use the column definition list to form the alias list and
889                  * funccoltypes/funccoltypmods lists.
890                  */
891                 foreach(col, coldeflist)
892                 {
893                         ColumnDef  *n = (ColumnDef *) lfirst(col);
894                         char       *attrname;
895                         Oid                     attrtype;
896                         int32           attrtypmod;
897
898                         attrname = pstrdup(n->colname);
899                         if (n->typename->setof)
900                                 ereport(ERROR,
901                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
902                                                  errmsg("column \"%s\" cannot be declared SETOF",
903                                                                 attrname)));
904                         eref->colnames = lappend(eref->colnames, makeString(attrname));
905                         attrtype = typenameTypeId(pstate, n->typename);
906                         attrtypmod = n->typename->typmod;
907                         rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
908                         rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
909                 }
910         }
911         else
912                 ereport(ERROR,
913                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
914                          errmsg("function \"%s\" in FROM has unsupported return type %s",
915                                         funcname, format_type_be(funcrettype))));
916
917         /*----------
918          * Flags:
919          * - this RTE should be expanded to include descendant tables,
920          * - this RTE is in the FROM clause,
921          * - this RTE should be checked for appropriate access rights.
922          *
923          * Functions are never checked for access rights (at least, not by
924          * the RTE permissions mechanism).
925          *----------
926          */
927         rte->inh = false;                       /* never true for functions */
928         rte->inFromCl = inFromCl;
929
930         rte->requiredPerms = 0;
931         rte->checkAsUser = InvalidOid;
932
933         /*
934          * Add completed RTE to pstate's range table list, but not to join list
935          * nor namespace --- caller must do that if appropriate.
936          */
937         if (pstate != NULL)
938                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
939
940         return rte;
941 }
942
943 /*
944  * Add an entry for a join to the pstate's range table (p_rtable).
945  *
946  * This is much like addRangeTableEntry() except that it makes a join RTE.
947  */
948 RangeTblEntry *
949 addRangeTableEntryForJoin(ParseState *pstate,
950                                                   List *colnames,
951                                                   JoinType jointype,
952                                                   List *aliasvars,
953                                                   Alias *alias,
954                                                   bool inFromCl)
955 {
956         RangeTblEntry *rte = makeNode(RangeTblEntry);
957         Alias      *eref;
958         int                     numaliases;
959
960         rte->rtekind = RTE_JOIN;
961         rte->relid = InvalidOid;
962         rte->subquery = NULL;
963         rte->jointype = jointype;
964         rte->joinaliasvars = aliasvars;
965         rte->alias = alias;
966
967         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
968         numaliases = list_length(eref->colnames);
969
970         /* fill in any unspecified alias columns */
971         if (numaliases < list_length(colnames))
972                 eref->colnames = list_concat(eref->colnames,
973                                                                          list_copy_tail(colnames, numaliases));
974
975         rte->eref = eref;
976
977         /*----------
978          * Flags:
979          * - this RTE should be expanded to include descendant tables,
980          * - this RTE is in the FROM clause,
981          * - this RTE should be checked for appropriate access rights.
982          *
983          * Joins are never checked for access rights.
984          *----------
985          */
986         rte->inh = false;                       /* never true for joins */
987         rte->inFromCl = inFromCl;
988
989         rte->requiredPerms = 0;
990         rte->checkAsUser = InvalidOid;
991
992         /*
993          * Add completed RTE to pstate's range table list, but not to join list
994          * nor namespace --- caller must do that if appropriate.
995          */
996         if (pstate != NULL)
997                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
998
999         return rte;
1000 }
1001
1002 /*
1003  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1004  *
1005  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1006  */
1007 static bool
1008 isLockedRel(ParseState *pstate, char *refname)
1009 {
1010         /* Outer loop to check parent query levels as well as this one */
1011         while (pstate != NULL)
1012         {
1013                 ListCell   *l;
1014
1015                 foreach(l, pstate->p_locking_clause)
1016                 {
1017                         LockingClause *lc = (LockingClause *) lfirst(l);
1018
1019                         if (lc->lockedRels == NIL)
1020                         {
1021                                 /* all tables used in query */
1022                                 return true;
1023                         }
1024                         else
1025                         {
1026                                 /* just the named tables */
1027                                 ListCell   *l2;
1028
1029                                 foreach(l2, lc->lockedRels)
1030                                 {
1031                                         char       *rname = strVal(lfirst(l2));
1032
1033                                         if (strcmp(refname, rname) == 0)
1034                                                 return true;
1035                                 }
1036                         }
1037                 }
1038                 pstate = pstate->parentParseState;
1039         }
1040         return false;
1041 }
1042
1043 /*
1044  * Add the given RTE as a top-level entry in the pstate's join list
1045  * and/or name space lists.  (We assume caller has checked for any
1046  * namespace conflicts.)
1047  */
1048 void
1049 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1050                           bool addToJoinList,
1051                           bool addToRelNameSpace, bool addToVarNameSpace)
1052 {
1053         if (addToJoinList)
1054         {
1055                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1056                 RangeTblRef *rtr = makeNode(RangeTblRef);
1057
1058                 rtr->rtindex = rtindex;
1059                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1060         }
1061         if (addToRelNameSpace)
1062                 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1063         if (addToVarNameSpace)
1064                 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1065 }
1066
1067 /*
1068  * Add a POSTQUEL-style implicit RTE.
1069  *
1070  * We assume caller has already checked that there is no RTE or join with
1071  * a conflicting name.
1072  */
1073 RangeTblEntry *
1074 addImplicitRTE(ParseState *pstate, RangeVar *relation, int location)
1075 {
1076         RangeTblEntry *rte;
1077
1078         /* issue warning or error as needed */
1079         warnAutoRange(pstate, relation, location);
1080         /*
1081          * Note that we set inFromCl true, so that the RTE will be listed
1082          * explicitly if the parsetree is ever decompiled by ruleutils.c. This
1083          * provides a migration path for views/rules that were originally written
1084          * with implicit-RTE syntax.
1085          */
1086         rte = addRangeTableEntry(pstate, relation, NULL, false, true);
1087         /* Add to joinlist and relnamespace, but not varnamespace */
1088         addRTEtoQuery(pstate, rte, true, true, false);
1089
1090         return rte;
1091 }
1092
1093 /*
1094  * expandRTE -- expand the columns of a rangetable entry
1095  *
1096  * This creates lists of an RTE's column names (aliases if provided, else
1097  * real names) and Vars for each column.  Only user columns are considered.
1098  * If include_dropped is FALSE then dropped columns are omitted from the
1099  * results.  If include_dropped is TRUE then empty strings and NULL constants
1100  * (not Vars!) are returned for dropped columns.
1101  *
1102  * rtindex and sublevels_up are the varno and varlevelsup values to use
1103  * in the created Vars.  Ordinarily rtindex should match the actual position
1104  * of the RTE in its rangetable.
1105  *
1106  * The output lists go into *colnames and *colvars.
1107  * If only one of the two kinds of output list is needed, pass NULL for the
1108  * output pointer for the unwanted one.
1109  */
1110 void
1111 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1112                   bool include_dropped,
1113                   List **colnames, List **colvars)
1114 {
1115         int                     varattno;
1116
1117         if (colnames)
1118                 *colnames = NIL;
1119         if (colvars)
1120                 *colvars = NIL;
1121
1122         switch (rte->rtekind)
1123         {
1124                 case RTE_RELATION:
1125                         /* Ordinary relation RTE */
1126                         expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1127                                                    include_dropped, colnames, colvars);
1128                         break;
1129                 case RTE_SUBQUERY:
1130                         {
1131                                 /* Subquery RTE */
1132                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1133                                 ListCell   *tlistitem;
1134
1135                                 varattno = 0;
1136                                 foreach(tlistitem, rte->subquery->targetList)
1137                                 {
1138                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1139
1140                                         if (te->resjunk)
1141                                                 continue;
1142                                         varattno++;
1143                                         Assert(varattno == te->resno);
1144
1145                                         if (colnames)
1146                                         {
1147                                                 /* Assume there is one alias per target item */
1148                                                 char       *label = strVal(lfirst(aliasp_item));
1149
1150                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1151                                                 aliasp_item = lnext(aliasp_item);
1152                                         }
1153
1154                                         if (colvars)
1155                                         {
1156                                                 Var                *varnode;
1157
1158                                                 varnode = makeVar(rtindex, varattno,
1159                                                                                   exprType((Node *) te->expr),
1160                                                                                   exprTypmod((Node *) te->expr),
1161                                                                                   sublevels_up);
1162
1163                                                 *colvars = lappend(*colvars, varnode);
1164                                         }
1165                                 }
1166                         }
1167                         break;
1168                 case RTE_FUNCTION:
1169                         {
1170                                 /* Function RTE */
1171                                 TypeFuncClass functypclass;
1172                                 Oid                     funcrettype;
1173                                 TupleDesc       tupdesc;
1174
1175                                 functypclass = get_expr_result_type(rte->funcexpr,
1176                                                                                                         &funcrettype,
1177                                                                                                         &tupdesc);
1178                                 if (functypclass == TYPEFUNC_COMPOSITE)
1179                                 {
1180                                         /* Composite data type, e.g. a table's row type */
1181                                         Assert(tupdesc);
1182                                         expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1183                                                                         include_dropped, colnames, colvars);
1184                                 }
1185                                 else if (functypclass == TYPEFUNC_SCALAR)
1186                                 {
1187                                         /* Base data type, i.e. scalar */
1188                                         if (colnames)
1189                                                 *colnames = lappend(*colnames,
1190                                                                                         linitial(rte->eref->colnames));
1191
1192                                         if (colvars)
1193                                         {
1194                                                 Var                *varnode;
1195
1196                                                 varnode = makeVar(rtindex, 1,
1197                                                                                   funcrettype, -1,
1198                                                                                   sublevels_up);
1199
1200                                                 *colvars = lappend(*colvars, varnode);
1201                                         }
1202                                 }
1203                                 else if (functypclass == TYPEFUNC_RECORD)
1204                                 {
1205                                         if (colnames)
1206                                                 *colnames = copyObject(rte->eref->colnames);
1207                                         if (colvars)
1208                                         {
1209                                                 ListCell   *l1;
1210                                                 ListCell   *l2;
1211                                                 int                     attnum = 0;
1212
1213                                                 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1214                                                 {
1215                                                         Oid                     attrtype = lfirst_oid(l1);
1216                                                         int32           attrtypmod = lfirst_int(l2);
1217                                                         Var                *varnode;
1218
1219                                                         attnum++;
1220                                                         varnode = makeVar(rtindex,
1221                                                                                           attnum,
1222                                                                                           attrtype,
1223                                                                                           attrtypmod,
1224                                                                                           sublevels_up);
1225                                                         *colvars = lappend(*colvars, varnode);
1226                                                 }
1227                                         }
1228                                 }
1229                                 else
1230                                 {
1231                                         /* addRangeTableEntryForFunction should've caught this */
1232                                         elog(ERROR, "function in FROM has unsupported return type");
1233                                 }
1234                         }
1235                         break;
1236                 case RTE_JOIN:
1237                         {
1238                                 /* Join RTE */
1239                                 ListCell   *colname;
1240                                 ListCell   *aliasvar;
1241
1242                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1243
1244                                 varattno = 0;
1245                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1246                                 {
1247                                         Node       *avar = (Node *) lfirst(aliasvar);
1248
1249                                         varattno++;
1250
1251                                         /*
1252                                          * During ordinary parsing, there will never be any
1253                                          * deleted columns in the join; but we have to check since
1254                                          * this routine is also used by the rewriter, and joins
1255                                          * found in stored rules might have join columns for
1256                                          * since-deleted columns.  This will be signaled by a NULL
1257                                          * Const in the alias-vars list.
1258                                          */
1259                                         if (IsA(avar, Const))
1260                                         {
1261                                                 if (include_dropped)
1262                                                 {
1263                                                         if (colnames)
1264                                                                 *colnames = lappend(*colnames,
1265                                                                                                         makeString(pstrdup("")));
1266                                                         if (colvars)
1267                                                                 *colvars = lappend(*colvars,
1268                                                                                                    copyObject(avar));
1269                                                 }
1270                                                 continue;
1271                                         }
1272
1273                                         if (colnames)
1274                                         {
1275                                                 char       *label = strVal(lfirst(colname));
1276
1277                                                 *colnames = lappend(*colnames,
1278                                                                                         makeString(pstrdup(label)));
1279                                         }
1280
1281                                         if (colvars)
1282                                         {
1283                                                 Var                *varnode;
1284
1285                                                 varnode = makeVar(rtindex, varattno,
1286                                                                                   exprType(avar),
1287                                                                                   exprTypmod(avar),
1288                                                                                   sublevels_up);
1289
1290                                                 *colvars = lappend(*colvars, varnode);
1291                                         }
1292                                 }
1293                         }
1294                         break;
1295                 default:
1296                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1297         }
1298 }
1299
1300 /*
1301  * expandRelation -- expandRTE subroutine
1302  */
1303 static void
1304 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1305                            bool include_dropped,
1306                            List **colnames, List **colvars)
1307 {
1308         Relation        rel;
1309
1310         /* Get the tupledesc and turn it over to expandTupleDesc */
1311         rel = relation_open(relid, AccessShareLock);
1312         expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1313                                         colnames, colvars);
1314         relation_close(rel, AccessShareLock);
1315 }
1316
1317 /*
1318  * expandTupleDesc -- expandRTE subroutine
1319  */
1320 static void
1321 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1322                                 int rtindex, int sublevels_up,
1323                                 bool include_dropped,
1324                                 List **colnames, List **colvars)
1325 {
1326         int                     maxattrs = tupdesc->natts;
1327         int                     numaliases = list_length(eref->colnames);
1328         int                     varattno;
1329
1330         for (varattno = 0; varattno < maxattrs; varattno++)
1331         {
1332                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1333
1334                 if (attr->attisdropped)
1335                 {
1336                         if (include_dropped)
1337                         {
1338                                 if (colnames)
1339                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1340                                 if (colvars)
1341                                 {
1342                                         /*
1343                                          * can't use atttypid here, but it doesn't really matter
1344                                          * what type the Const claims to be.
1345                                          */
1346                                         *colvars = lappend(*colvars, makeNullConst(INT4OID));
1347                                 }
1348                         }
1349                         continue;
1350                 }
1351
1352                 if (colnames)
1353                 {
1354                         char       *label;
1355
1356                         if (varattno < numaliases)
1357                                 label = strVal(list_nth(eref->colnames, varattno));
1358                         else
1359                                 label = NameStr(attr->attname);
1360                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
1361                 }
1362
1363                 if (colvars)
1364                 {
1365                         Var                *varnode;
1366
1367                         varnode = makeVar(rtindex, attr->attnum,
1368                                                           attr->atttypid, attr->atttypmod,
1369                                                           sublevels_up);
1370
1371                         *colvars = lappend(*colvars, varnode);
1372                 }
1373         }
1374 }
1375
1376 /*
1377  * expandRelAttrs -
1378  *        Workhorse for "*" expansion: produce a list of targetentries
1379  *        for the attributes of the rte
1380  *
1381  * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1382  * fields of the Vars produced.  pstate->p_next_resno determines the resnos
1383  * assigned to the TLEs.
1384  */
1385 List *
1386 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1387                            int rtindex, int sublevels_up)
1388 {
1389         List       *names,
1390                            *vars;
1391         ListCell   *name,
1392                            *var;
1393         List       *te_list = NIL;
1394
1395         expandRTE(rte, rtindex, sublevels_up, false,
1396                           &names, &vars);
1397
1398         forboth(name, names, var, vars)
1399         {
1400                 char       *label = strVal(lfirst(name));
1401                 Node       *varnode = (Node *) lfirst(var);
1402                 TargetEntry *te;
1403
1404                 te = makeTargetEntry((Expr *) varnode,
1405                                                          (AttrNumber) pstate->p_next_resno++,
1406                                                          label,
1407                                                          false);
1408                 te_list = lappend(te_list, te);
1409         }
1410
1411         Assert(name == NULL && var == NULL);            /* lists not the same length? */
1412
1413         return te_list;
1414 }
1415
1416 /*
1417  * get_rte_attribute_name
1418  *              Get an attribute name from a RangeTblEntry
1419  *
1420  * This is unlike get_attname() because we use aliases if available.
1421  * In particular, it will work on an RTE for a subselect or join, whereas
1422  * get_attname() only works on real relations.
1423  *
1424  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1425  * occurs when a Var represents a whole tuple of a relation.
1426  */
1427 char *
1428 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1429 {
1430         if (attnum == InvalidAttrNumber)
1431                 return "*";
1432
1433         /*
1434          * If there is a user-written column alias, use it.
1435          */
1436         if (rte->alias &&
1437                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1438                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1439
1440         /*
1441          * If the RTE is a relation, go to the system catalogs not the
1442          * eref->colnames list.  This is a little slower but it will give the
1443          * right answer if the column has been renamed since the eref list was
1444          * built (which can easily happen for rules).
1445          */
1446         if (rte->rtekind == RTE_RELATION)
1447                 return get_relid_attribute_name(rte->relid, attnum);
1448
1449         /*
1450          * Otherwise use the column name from eref.  There should always be one.
1451          */
1452         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1453                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1454
1455         /* else caller gave us a bogus attnum */
1456         elog(ERROR, "invalid attnum %d for rangetable entry %s",
1457                  attnum, rte->eref->aliasname);
1458         return NULL;                            /* keep compiler quiet */
1459 }
1460
1461 /*
1462  * get_rte_attribute_type
1463  *              Get attribute type information from a RangeTblEntry
1464  */
1465 void
1466 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1467                                            Oid *vartype, int32 *vartypmod)
1468 {
1469         switch (rte->rtekind)
1470         {
1471                 case RTE_RELATION:
1472                         {
1473                                 /* Plain relation RTE --- get the attribute's type info */
1474                                 HeapTuple       tp;
1475                                 Form_pg_attribute att_tup;
1476
1477                                 tp = SearchSysCache(ATTNUM,
1478                                                                         ObjectIdGetDatum(rte->relid),
1479                                                                         Int16GetDatum(attnum),
1480                                                                         0, 0);
1481                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1482                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1483                                                  attnum, rte->relid);
1484                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1485
1486                                 /*
1487                                  * If dropped column, pretend it ain't there.  See notes in
1488                                  * scanRTEForColumn.
1489                                  */
1490                                 if (att_tup->attisdropped)
1491                                         ereport(ERROR,
1492                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1493                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
1494                                                    NameStr(att_tup->attname),
1495                                                    get_rel_name(rte->relid))));
1496                                 *vartype = att_tup->atttypid;
1497                                 *vartypmod = att_tup->atttypmod;
1498                                 ReleaseSysCache(tp);
1499                         }
1500                         break;
1501                 case RTE_SUBQUERY:
1502                         {
1503                                 /* Subselect RTE --- get type info from subselect's tlist */
1504                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1505                                                                                                    attnum);
1506
1507                                 if (te == NULL || te->resjunk)
1508                                         elog(ERROR, "subquery %s does not have attribute %d",
1509                                                  rte->eref->aliasname, attnum);
1510                                 *vartype = exprType((Node *) te->expr);
1511                                 *vartypmod = exprTypmod((Node *) te->expr);
1512                         }
1513                         break;
1514                 case RTE_FUNCTION:
1515                         {
1516                                 /* Function RTE */
1517                                 TypeFuncClass functypclass;
1518                                 Oid                     funcrettype;
1519                                 TupleDesc       tupdesc;
1520
1521                                 functypclass = get_expr_result_type(rte->funcexpr,
1522                                                                                                         &funcrettype,
1523                                                                                                         &tupdesc);
1524
1525                                 if (functypclass == TYPEFUNC_COMPOSITE)
1526                                 {
1527                                         /* Composite data type, e.g. a table's row type */
1528                                         Form_pg_attribute att_tup;
1529
1530                                         Assert(tupdesc);
1531                                         /* this is probably a can't-happen case */
1532                                         if (attnum < 1 || attnum > tupdesc->natts)
1533                                                 ereport(ERROR,
1534                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1535                                                 errmsg("column %d of relation \"%s\" does not exist",
1536                                                            attnum,
1537                                                            rte->eref->aliasname)));
1538
1539                                         att_tup = tupdesc->attrs[attnum - 1];
1540
1541                                         /*
1542                                          * If dropped column, pretend it ain't there.  See notes
1543                                          * in scanRTEForColumn.
1544                                          */
1545                                         if (att_tup->attisdropped)
1546                                                 ereport(ERROR,
1547                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1548                                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
1549                                                                                 NameStr(att_tup->attname),
1550                                                                                 rte->eref->aliasname)));
1551                                         *vartype = att_tup->atttypid;
1552                                         *vartypmod = att_tup->atttypmod;
1553                                 }
1554                                 else if (functypclass == TYPEFUNC_SCALAR)
1555                                 {
1556                                         /* Base data type, i.e. scalar */
1557                                         *vartype = funcrettype;
1558                                         *vartypmod = -1;
1559                                 }
1560                                 else if (functypclass == TYPEFUNC_RECORD)
1561                                 {
1562                                         *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
1563                                         *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
1564                                 }
1565                                 else
1566                                 {
1567                                         /* addRangeTableEntryForFunction should've caught this */
1568                                         elog(ERROR, "function in FROM has unsupported return type");
1569                                 }
1570                         }
1571                         break;
1572                 case RTE_JOIN:
1573                         {
1574                                 /*
1575                                  * Join RTE --- get type info from join RTE's alias variable
1576                                  */
1577                                 Node       *aliasvar;
1578
1579                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1580                                 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1581                                 *vartype = exprType(aliasvar);
1582                                 *vartypmod = exprTypmod(aliasvar);
1583                         }
1584                         break;
1585                 default:
1586                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1587         }
1588 }
1589
1590 /*
1591  * get_rte_attribute_is_dropped
1592  *              Check whether attempted attribute ref is to a dropped column
1593  */
1594 bool
1595 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
1596 {
1597         bool            result;
1598
1599         switch (rte->rtekind)
1600         {
1601                 case RTE_RELATION:
1602                         {
1603                                 /*
1604                                  * Plain relation RTE --- get the attribute's catalog entry
1605                                  */
1606                                 HeapTuple       tp;
1607                                 Form_pg_attribute att_tup;
1608
1609                                 tp = SearchSysCache(ATTNUM,
1610                                                                         ObjectIdGetDatum(rte->relid),
1611                                                                         Int16GetDatum(attnum),
1612                                                                         0, 0);
1613                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1614                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1615                                                  attnum, rte->relid);
1616                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1617                                 result = att_tup->attisdropped;
1618                                 ReleaseSysCache(tp);
1619                         }
1620                         break;
1621                 case RTE_SUBQUERY:
1622                         /* Subselect RTEs never have dropped columns */
1623                         result = false;
1624                         break;
1625                 case RTE_JOIN:
1626                         {
1627                                 /*
1628                                  * A join RTE would not have dropped columns when constructed,
1629                                  * but one in a stored rule might contain columns that were
1630                                  * dropped from the underlying tables, if said columns are
1631                                  * nowhere explicitly referenced in the rule.  This will be
1632                                  * signaled to us by a NULL Const in the joinaliasvars list.
1633                                  */
1634                                 Var                *aliasvar;
1635
1636                                 if (attnum <= 0 ||
1637                                         attnum > list_length(rte->joinaliasvars))
1638                                         elog(ERROR, "invalid varattno %d", attnum);
1639                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1640
1641                                 result = IsA(aliasvar, Const);
1642                         }
1643                         break;
1644                 case RTE_FUNCTION:
1645                         {
1646                                 /* Function RTE */
1647                                 Oid                     funcrettype = exprType(rte->funcexpr);
1648                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
1649
1650                                 if (OidIsValid(funcrelid))
1651                                 {
1652                                         /*
1653                                          * Composite data type, i.e. a table's row type
1654                                          *
1655                                          * Same as ordinary relation RTE
1656                                          */
1657                                         HeapTuple       tp;
1658                                         Form_pg_attribute att_tup;
1659
1660                                         tp = SearchSysCache(ATTNUM,
1661                                                                                 ObjectIdGetDatum(funcrelid),
1662                                                                                 Int16GetDatum(attnum),
1663                                                                                 0, 0);
1664                                         if (!HeapTupleIsValid(tp))      /* shouldn't happen */
1665                                                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1666                                                          attnum, funcrelid);
1667                                         att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1668                                         result = att_tup->attisdropped;
1669                                         ReleaseSysCache(tp);
1670                                 }
1671                                 else
1672                                 {
1673                                         /*
1674                                          * Must be a base data type, i.e. scalar
1675                                          */
1676                                         result = false;
1677                                 }
1678                         }
1679                         break;
1680                 default:
1681                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1682                         result = false;         /* keep compiler quiet */
1683         }
1684
1685         return result;
1686 }
1687
1688 /*
1689  * Given a targetlist and a resno, return the matching TargetEntry
1690  *
1691  * Returns NULL if resno is not present in list.
1692  *
1693  * Note: we need to search, rather than just indexing with list_nth(),
1694  * because not all tlists are sorted by resno.
1695  */
1696 TargetEntry *
1697 get_tle_by_resno(List *tlist, AttrNumber resno)
1698 {
1699         ListCell   *l;
1700
1701         foreach(l, tlist)
1702         {
1703                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1704
1705                 if (tle->resno == resno)
1706                         return tle;
1707         }
1708         return NULL;
1709 }
1710
1711 /*
1712  * Given a Query and rangetable index, return relation's RowMarkClause if any
1713  *
1714  * Returns NULL if relation is not selected FOR UPDATE/SHARE
1715  */
1716 RowMarkClause *
1717 get_rowmark(Query *qry, Index rtindex)
1718 {
1719         ListCell   *l;
1720
1721         foreach(l, qry->rowMarks)
1722         {
1723                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1724
1725                 if (rc->rti == rtindex)
1726                         return rc;
1727         }
1728         return NULL;
1729 }
1730
1731 /*
1732  *      given relation and att name, return attnum of variable
1733  *
1734  *      Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
1735  *
1736  *      This should only be used if the relation is already
1737  *      heap_open()'ed.  Use the cache version get_attnum()
1738  *      for access to non-opened relations.
1739  */
1740 int
1741 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1742 {
1743         int                     i;
1744
1745         for (i = 0; i < rd->rd_rel->relnatts; i++)
1746         {
1747                 Form_pg_attribute att = rd->rd_att->attrs[i];
1748
1749                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1750                         return i + 1;
1751         }
1752
1753         if (sysColOK)
1754         {
1755                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1756                 {
1757                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1758                                 return i;
1759                 }
1760         }
1761
1762         /* on failure */
1763         return InvalidAttrNumber;
1764 }
1765
1766 /* specialAttNum()
1767  *
1768  * Check attribute name to see if it is "special", e.g. "oid".
1769  * - thomas 2000-02-07
1770  *
1771  * Note: this only discovers whether the name could be a system attribute.
1772  * Caller needs to verify that it really is an attribute of the rel,
1773  * at least in the case of "oid", which is now optional.
1774  */
1775 static int
1776 specialAttNum(const char *attname)
1777 {
1778         Form_pg_attribute sysatt;
1779
1780         sysatt = SystemAttributeByName(attname,
1781                                                                    true /* "oid" will be accepted */ );
1782         if (sysatt != NULL)
1783                 return sysatt->attnum;
1784         return InvalidAttrNumber;
1785 }
1786
1787
1788 /*
1789  * given attribute id, return name of that attribute
1790  *
1791  *      This should only be used if the relation is already
1792  *      heap_open()'ed.  Use the cache version get_atttype()
1793  *      for access to non-opened relations.
1794  */
1795 Name
1796 attnumAttName(Relation rd, int attid)
1797 {
1798         if (attid <= 0)
1799         {
1800                 Form_pg_attribute sysatt;
1801
1802                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1803                 return &sysatt->attname;
1804         }
1805         if (attid > rd->rd_att->natts)
1806                 elog(ERROR, "invalid attribute number %d", attid);
1807         return &rd->rd_att->attrs[attid - 1]->attname;
1808 }
1809
1810 /*
1811  * given attribute id, return type of that attribute
1812  *
1813  *      This should only be used if the relation is already
1814  *      heap_open()'ed.  Use the cache version get_atttype()
1815  *      for access to non-opened relations.
1816  */
1817 Oid
1818 attnumTypeId(Relation rd, int attid)
1819 {
1820         if (attid <= 0)
1821         {
1822                 Form_pg_attribute sysatt;
1823
1824                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1825                 return sysatt->atttypid;
1826         }
1827         if (attid > rd->rd_att->natts)
1828                 elog(ERROR, "invalid attribute number %d", attid);
1829         return rd->rd_att->attrs[attid - 1]->atttypid;
1830 }
1831
1832 /*
1833  * Generate a warning or error about an implicit RTE, if appropriate.
1834  *
1835  * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
1836  * a warning.
1837  */
1838 static void
1839 warnAutoRange(ParseState *pstate, RangeVar *relation, int location)
1840 {
1841         RangeTblEntry *rte;
1842         int                     sublevels_up;
1843         const char *badAlias = NULL;
1844
1845         /*
1846          * Check to see if there are any potential matches in the query's
1847          * rangetable.  This affects the message we provide.
1848          */
1849         rte = searchRangeTable(pstate, relation);
1850
1851         /*
1852          * If we found a match that has an alias and the alias is visible in
1853          * the namespace, then the problem is probably use of the relation's
1854          * real name instead of its alias, ie "SELECT foo.* FROM foo f".
1855          * This mistake is common enough to justify a specific hint.
1856          *
1857          * If we found a match that doesn't meet those criteria, assume the
1858          * problem is illegal use of a relation outside its scope, as in the
1859          * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
1860          */
1861         if (rte && rte->alias &&
1862                 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
1863                 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
1864                                                          &sublevels_up) == rte)
1865                 badAlias = rte->eref->aliasname;
1866
1867         if (!add_missing_from)
1868         {
1869                 if (rte)
1870                         ereport(ERROR,
1871                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1872                                          errmsg("invalid reference to FROM-clause entry for table \"%s\"",
1873                                                         relation->relname),
1874                                          (badAlias ?
1875                                           errhint("Perhaps you meant to reference the table alias \"%s\".",
1876                                                           badAlias) :
1877                                           errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
1878                                                           rte->eref->aliasname)),
1879                                          parser_errposition(pstate, location)));
1880                 else
1881                         ereport(ERROR,
1882                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1883                                          (pstate->parentParseState ?
1884                                           errmsg("missing FROM-clause entry in subquery for table \"%s\"",
1885                                                          relation->relname) :
1886                                           errmsg("missing FROM-clause entry for table \"%s\"",
1887                                                          relation->relname)),
1888                                          parser_errposition(pstate, location)));
1889         }
1890         else
1891         {
1892                 /* just issue a warning */
1893                 ereport(NOTICE,
1894                                 (errcode(ERRCODE_UNDEFINED_TABLE),
1895                                  (pstate->parentParseState ?
1896                                   errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
1897                                                  relation->relname) :
1898                                   errmsg("adding missing FROM-clause entry for table \"%s\"",
1899                                                  relation->relname)),
1900                                  (badAlias ?
1901                                   errhint("Perhaps you meant to reference the table alias \"%s\".",
1902                                                   badAlias) :
1903                                   (rte ?
1904                                    errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
1905                                                    rte->eref->aliasname) : 0)),
1906                                  parser_errposition(pstate, location)));
1907         }
1908 }