]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_relation.c
f6d4fcae4aa80fce8e4470993ede1dcab50a980b
[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.126 2006/12/30 21:21:54 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                         attrtype = typenameTypeId(pstate, n->typename);
905                         attrtypmod = typenameTypeMod(pstate, n->typename, attrtype);
906                         eref->colnames = lappend(eref->colnames, makeString(attrname));
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 VALUES list to the pstate's range table (p_rtable).
945  *
946  * This is much like addRangeTableEntry() except that it makes a values RTE.
947  */
948 RangeTblEntry *
949 addRangeTableEntryForValues(ParseState *pstate,
950                                                         List *exprs,
951                                                         Alias *alias,
952                                                         bool inFromCl)
953 {
954         RangeTblEntry *rte = makeNode(RangeTblEntry);
955         char       *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
956         Alias      *eref;
957         int                     numaliases;
958         int                     numcolumns;
959
960         rte->rtekind = RTE_VALUES;
961         rte->relid = InvalidOid;
962         rte->subquery = NULL;
963         rte->values_lists = exprs;
964         rte->alias = alias;
965
966         eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
967
968         /* fill in any unspecified alias columns */
969         numcolumns = list_length((List *) linitial(exprs));
970         numaliases = list_length(eref->colnames);
971         while (numaliases < numcolumns)
972         {
973                 char            attrname[64];
974
975                 numaliases++;
976                 snprintf(attrname, sizeof(attrname), "column%d", numaliases);
977                 eref->colnames = lappend(eref->colnames,
978                                                                  makeString(pstrdup(attrname)));
979         }
980         if (numcolumns < numaliases)
981                 ereport(ERROR,
982                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
983                                  errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
984                                                 refname, numcolumns, numaliases)));
985
986         rte->eref = eref;
987
988         /*----------
989          * Flags:
990          * - this RTE should be expanded to include descendant tables,
991          * - this RTE is in the FROM clause,
992          * - this RTE should be checked for appropriate access rights.
993          *
994          * Subqueries are never checked for access rights.
995          *----------
996          */
997         rte->inh = false;                       /* never true for values RTEs */
998         rte->inFromCl = inFromCl;
999         rte->requiredPerms = 0;
1000         rte->checkAsUser = InvalidOid;
1001
1002         /*
1003          * Add completed RTE to pstate's range table list, but not to join list
1004          * nor namespace --- caller must do that if appropriate.
1005          */
1006         if (pstate != NULL)
1007                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1008
1009         return rte;
1010 }
1011
1012 /*
1013  * Add an entry for a join to the pstate's range table (p_rtable).
1014  *
1015  * This is much like addRangeTableEntry() except that it makes a join RTE.
1016  */
1017 RangeTblEntry *
1018 addRangeTableEntryForJoin(ParseState *pstate,
1019                                                   List *colnames,
1020                                                   JoinType jointype,
1021                                                   List *aliasvars,
1022                                                   Alias *alias,
1023                                                   bool inFromCl)
1024 {
1025         RangeTblEntry *rte = makeNode(RangeTblEntry);
1026         Alias      *eref;
1027         int                     numaliases;
1028
1029         rte->rtekind = RTE_JOIN;
1030         rte->relid = InvalidOid;
1031         rte->subquery = NULL;
1032         rte->jointype = jointype;
1033         rte->joinaliasvars = aliasvars;
1034         rte->alias = alias;
1035
1036         eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1037         numaliases = list_length(eref->colnames);
1038
1039         /* fill in any unspecified alias columns */
1040         if (numaliases < list_length(colnames))
1041                 eref->colnames = list_concat(eref->colnames,
1042                                                                          list_copy_tail(colnames, numaliases));
1043
1044         rte->eref = eref;
1045
1046         /*----------
1047          * Flags:
1048          * - this RTE should be expanded to include descendant tables,
1049          * - this RTE is in the FROM clause,
1050          * - this RTE should be checked for appropriate access rights.
1051          *
1052          * Joins are never checked for access rights.
1053          *----------
1054          */
1055         rte->inh = false;                       /* never true for joins */
1056         rte->inFromCl = inFromCl;
1057
1058         rte->requiredPerms = 0;
1059         rte->checkAsUser = InvalidOid;
1060
1061         /*
1062          * Add completed RTE to pstate's range table list, but not to join list
1063          * nor namespace --- caller must do that if appropriate.
1064          */
1065         if (pstate != NULL)
1066                 pstate->p_rtable = lappend(pstate->p_rtable, rte);
1067
1068         return rte;
1069 }
1070
1071 /*
1072  * Has the specified refname been selected FOR UPDATE/FOR SHARE?
1073  *
1074  * Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1075  */
1076 static bool
1077 isLockedRel(ParseState *pstate, char *refname)
1078 {
1079         /* Outer loop to check parent query levels as well as this one */
1080         while (pstate != NULL)
1081         {
1082                 ListCell   *l;
1083
1084                 foreach(l, pstate->p_locking_clause)
1085                 {
1086                         LockingClause *lc = (LockingClause *) lfirst(l);
1087
1088                         if (lc->lockedRels == NIL)
1089                         {
1090                                 /* all tables used in query */
1091                                 return true;
1092                         }
1093                         else
1094                         {
1095                                 /* just the named tables */
1096                                 ListCell   *l2;
1097
1098                                 foreach(l2, lc->lockedRels)
1099                                 {
1100                                         char       *rname = strVal(lfirst(l2));
1101
1102                                         if (strcmp(refname, rname) == 0)
1103                                                 return true;
1104                                 }
1105                         }
1106                 }
1107                 pstate = pstate->parentParseState;
1108         }
1109         return false;
1110 }
1111
1112 /*
1113  * Add the given RTE as a top-level entry in the pstate's join list
1114  * and/or name space lists.  (We assume caller has checked for any
1115  * namespace conflicts.)
1116  */
1117 void
1118 addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1119                           bool addToJoinList,
1120                           bool addToRelNameSpace, bool addToVarNameSpace)
1121 {
1122         if (addToJoinList)
1123         {
1124                 int                     rtindex = RTERangeTablePosn(pstate, rte, NULL);
1125                 RangeTblRef *rtr = makeNode(RangeTblRef);
1126
1127                 rtr->rtindex = rtindex;
1128                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1129         }
1130         if (addToRelNameSpace)
1131                 pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1132         if (addToVarNameSpace)
1133                 pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1134 }
1135
1136 /*
1137  * Add a POSTQUEL-style implicit RTE.
1138  *
1139  * We assume caller has already checked that there is no RTE or join with
1140  * a conflicting name.
1141  */
1142 RangeTblEntry *
1143 addImplicitRTE(ParseState *pstate, RangeVar *relation, int location)
1144 {
1145         RangeTblEntry *rte;
1146
1147         /* issue warning or error as needed */
1148         warnAutoRange(pstate, relation, location);
1149
1150         /*
1151          * Note that we set inFromCl true, so that the RTE will be listed
1152          * explicitly if the parsetree is ever decompiled by ruleutils.c. This
1153          * provides a migration path for views/rules that were originally written
1154          * with implicit-RTE syntax.
1155          */
1156         rte = addRangeTableEntry(pstate, relation, NULL, false, true);
1157         /* Add to joinlist and relnamespace, but not varnamespace */
1158         addRTEtoQuery(pstate, rte, true, true, false);
1159
1160         return rte;
1161 }
1162
1163 /*
1164  * expandRTE -- expand the columns of a rangetable entry
1165  *
1166  * This creates lists of an RTE's column names (aliases if provided, else
1167  * real names) and Vars for each column.  Only user columns are considered.
1168  * If include_dropped is FALSE then dropped columns are omitted from the
1169  * results.  If include_dropped is TRUE then empty strings and NULL constants
1170  * (not Vars!) are returned for dropped columns.
1171  *
1172  * rtindex and sublevels_up are the varno and varlevelsup values to use
1173  * in the created Vars.  Ordinarily rtindex should match the actual position
1174  * of the RTE in its rangetable.
1175  *
1176  * The output lists go into *colnames and *colvars.
1177  * If only one of the two kinds of output list is needed, pass NULL for the
1178  * output pointer for the unwanted one.
1179  */
1180 void
1181 expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1182                   bool include_dropped,
1183                   List **colnames, List **colvars)
1184 {
1185         int                     varattno;
1186
1187         if (colnames)
1188                 *colnames = NIL;
1189         if (colvars)
1190                 *colvars = NIL;
1191
1192         switch (rte->rtekind)
1193         {
1194                 case RTE_RELATION:
1195                         /* Ordinary relation RTE */
1196                         expandRelation(rte->relid, rte->eref, rtindex, sublevels_up,
1197                                                    include_dropped, colnames, colvars);
1198                         break;
1199                 case RTE_SUBQUERY:
1200                         {
1201                                 /* Subquery RTE */
1202                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1203                                 ListCell   *tlistitem;
1204
1205                                 varattno = 0;
1206                                 foreach(tlistitem, rte->subquery->targetList)
1207                                 {
1208                                         TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1209
1210                                         if (te->resjunk)
1211                                                 continue;
1212                                         varattno++;
1213                                         Assert(varattno == te->resno);
1214
1215                                         if (colnames)
1216                                         {
1217                                                 /* Assume there is one alias per target item */
1218                                                 char       *label = strVal(lfirst(aliasp_item));
1219
1220                                                 *colnames = lappend(*colnames, makeString(pstrdup(label)));
1221                                                 aliasp_item = lnext(aliasp_item);
1222                                         }
1223
1224                                         if (colvars)
1225                                         {
1226                                                 Var                *varnode;
1227
1228                                                 varnode = makeVar(rtindex, varattno,
1229                                                                                   exprType((Node *) te->expr),
1230                                                                                   exprTypmod((Node *) te->expr),
1231                                                                                   sublevels_up);
1232
1233                                                 *colvars = lappend(*colvars, varnode);
1234                                         }
1235                                 }
1236                         }
1237                         break;
1238                 case RTE_FUNCTION:
1239                         {
1240                                 /* Function RTE */
1241                                 TypeFuncClass functypclass;
1242                                 Oid                     funcrettype;
1243                                 TupleDesc       tupdesc;
1244
1245                                 functypclass = get_expr_result_type(rte->funcexpr,
1246                                                                                                         &funcrettype,
1247                                                                                                         &tupdesc);
1248                                 if (functypclass == TYPEFUNC_COMPOSITE)
1249                                 {
1250                                         /* Composite data type, e.g. a table's row type */
1251                                         Assert(tupdesc);
1252                                         expandTupleDesc(tupdesc, rte->eref, rtindex, sublevels_up,
1253                                                                         include_dropped, colnames, colvars);
1254                                 }
1255                                 else if (functypclass == TYPEFUNC_SCALAR)
1256                                 {
1257                                         /* Base data type, i.e. scalar */
1258                                         if (colnames)
1259                                                 *colnames = lappend(*colnames,
1260                                                                                         linitial(rte->eref->colnames));
1261
1262                                         if (colvars)
1263                                         {
1264                                                 Var                *varnode;
1265
1266                                                 varnode = makeVar(rtindex, 1,
1267                                                                                   funcrettype, -1,
1268                                                                                   sublevels_up);
1269
1270                                                 *colvars = lappend(*colvars, varnode);
1271                                         }
1272                                 }
1273                                 else if (functypclass == TYPEFUNC_RECORD)
1274                                 {
1275                                         if (colnames)
1276                                                 *colnames = copyObject(rte->eref->colnames);
1277                                         if (colvars)
1278                                         {
1279                                                 ListCell   *l1;
1280                                                 ListCell   *l2;
1281                                                 int                     attnum = 0;
1282
1283                                                 forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1284                                                 {
1285                                                         Oid                     attrtype = lfirst_oid(l1);
1286                                                         int32           attrtypmod = lfirst_int(l2);
1287                                                         Var                *varnode;
1288
1289                                                         attnum++;
1290                                                         varnode = makeVar(rtindex,
1291                                                                                           attnum,
1292                                                                                           attrtype,
1293                                                                                           attrtypmod,
1294                                                                                           sublevels_up);
1295                                                         *colvars = lappend(*colvars, varnode);
1296                                                 }
1297                                         }
1298                                 }
1299                                 else
1300                                 {
1301                                         /* addRangeTableEntryForFunction should've caught this */
1302                                         elog(ERROR, "function in FROM has unsupported return type");
1303                                 }
1304                         }
1305                         break;
1306                 case RTE_VALUES:
1307                         {
1308                                 /* Values RTE */
1309                                 ListCell   *aliasp_item = list_head(rte->eref->colnames);
1310                                 ListCell   *lc;
1311
1312                                 varattno = 0;
1313                                 foreach(lc, (List *) linitial(rte->values_lists))
1314                                 {
1315                                         Node       *col = (Node *) lfirst(lc);
1316
1317                                         varattno++;
1318                                         if (colnames)
1319                                         {
1320                                                 /* Assume there is one alias per column */
1321                                                 char       *label = strVal(lfirst(aliasp_item));
1322
1323                                                 *colnames = lappend(*colnames,
1324                                                                                         makeString(pstrdup(label)));
1325                                                 aliasp_item = lnext(aliasp_item);
1326                                         }
1327
1328                                         if (colvars)
1329                                         {
1330                                                 Var                *varnode;
1331
1332                                                 varnode = makeVar(rtindex, varattno,
1333                                                                                   exprType(col),
1334                                                                                   exprTypmod(col),
1335                                                                                   sublevels_up);
1336                                                 *colvars = lappend(*colvars, varnode);
1337                                         }
1338                                 }
1339                         }
1340                         break;
1341                 case RTE_JOIN:
1342                         {
1343                                 /* Join RTE */
1344                                 ListCell   *colname;
1345                                 ListCell   *aliasvar;
1346
1347                                 Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1348
1349                                 varattno = 0;
1350                                 forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1351                                 {
1352                                         Node       *avar = (Node *) lfirst(aliasvar);
1353
1354                                         varattno++;
1355
1356                                         /*
1357                                          * During ordinary parsing, there will never be any
1358                                          * deleted columns in the join; but we have to check since
1359                                          * this routine is also used by the rewriter, and joins
1360                                          * found in stored rules might have join columns for
1361                                          * since-deleted columns.  This will be signaled by a NULL
1362                                          * Const in the alias-vars list.
1363                                          */
1364                                         if (IsA(avar, Const))
1365                                         {
1366                                                 if (include_dropped)
1367                                                 {
1368                                                         if (colnames)
1369                                                                 *colnames = lappend(*colnames,
1370                                                                                                         makeString(pstrdup("")));
1371                                                         if (colvars)
1372                                                                 *colvars = lappend(*colvars,
1373                                                                                                    copyObject(avar));
1374                                                 }
1375                                                 continue;
1376                                         }
1377
1378                                         if (colnames)
1379                                         {
1380                                                 char       *label = strVal(lfirst(colname));
1381
1382                                                 *colnames = lappend(*colnames,
1383                                                                                         makeString(pstrdup(label)));
1384                                         }
1385
1386                                         if (colvars)
1387                                         {
1388                                                 Var                *varnode;
1389
1390                                                 varnode = makeVar(rtindex, varattno,
1391                                                                                   exprType(avar),
1392                                                                                   exprTypmod(avar),
1393                                                                                   sublevels_up);
1394
1395                                                 *colvars = lappend(*colvars, varnode);
1396                                         }
1397                                 }
1398                         }
1399                         break;
1400                 default:
1401                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1402         }
1403 }
1404
1405 /*
1406  * expandRelation -- expandRTE subroutine
1407  */
1408 static void
1409 expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1410                            bool include_dropped,
1411                            List **colnames, List **colvars)
1412 {
1413         Relation        rel;
1414
1415         /* Get the tupledesc and turn it over to expandTupleDesc */
1416         rel = relation_open(relid, AccessShareLock);
1417         expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up, include_dropped,
1418                                         colnames, colvars);
1419         relation_close(rel, AccessShareLock);
1420 }
1421
1422 /*
1423  * expandTupleDesc -- expandRTE subroutine
1424  */
1425 static void
1426 expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1427                                 int rtindex, int sublevels_up,
1428                                 bool include_dropped,
1429                                 List **colnames, List **colvars)
1430 {
1431         int                     maxattrs = tupdesc->natts;
1432         int                     numaliases = list_length(eref->colnames);
1433         int                     varattno;
1434
1435         for (varattno = 0; varattno < maxattrs; varattno++)
1436         {
1437                 Form_pg_attribute attr = tupdesc->attrs[varattno];
1438
1439                 if (attr->attisdropped)
1440                 {
1441                         if (include_dropped)
1442                         {
1443                                 if (colnames)
1444                                         *colnames = lappend(*colnames, makeString(pstrdup("")));
1445                                 if (colvars)
1446                                 {
1447                                         /*
1448                                          * can't use atttypid here, but it doesn't really matter
1449                                          * what type the Const claims to be.
1450                                          */
1451                                         *colvars = lappend(*colvars, makeNullConst(INT4OID));
1452                                 }
1453                         }
1454                         continue;
1455                 }
1456
1457                 if (colnames)
1458                 {
1459                         char       *label;
1460
1461                         if (varattno < numaliases)
1462                                 label = strVal(list_nth(eref->colnames, varattno));
1463                         else
1464                                 label = NameStr(attr->attname);
1465                         *colnames = lappend(*colnames, makeString(pstrdup(label)));
1466                 }
1467
1468                 if (colvars)
1469                 {
1470                         Var                *varnode;
1471
1472                         varnode = makeVar(rtindex, attr->attnum,
1473                                                           attr->atttypid, attr->atttypmod,
1474                                                           sublevels_up);
1475
1476                         *colvars = lappend(*colvars, varnode);
1477                 }
1478         }
1479 }
1480
1481 /*
1482  * expandRelAttrs -
1483  *        Workhorse for "*" expansion: produce a list of targetentries
1484  *        for the attributes of the rte
1485  *
1486  * As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1487  * fields of the Vars produced.  pstate->p_next_resno determines the resnos
1488  * assigned to the TLEs.
1489  */
1490 List *
1491 expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1492                            int rtindex, int sublevels_up)
1493 {
1494         List       *names,
1495                            *vars;
1496         ListCell   *name,
1497                            *var;
1498         List       *te_list = NIL;
1499
1500         expandRTE(rte, rtindex, sublevels_up, false,
1501                           &names, &vars);
1502
1503         forboth(name, names, var, vars)
1504         {
1505                 char       *label = strVal(lfirst(name));
1506                 Node       *varnode = (Node *) lfirst(var);
1507                 TargetEntry *te;
1508
1509                 te = makeTargetEntry((Expr *) varnode,
1510                                                          (AttrNumber) pstate->p_next_resno++,
1511                                                          label,
1512                                                          false);
1513                 te_list = lappend(te_list, te);
1514         }
1515
1516         Assert(name == NULL && var == NULL);            /* lists not the same length? */
1517
1518         return te_list;
1519 }
1520
1521 /*
1522  * get_rte_attribute_name
1523  *              Get an attribute name from a RangeTblEntry
1524  *
1525  * This is unlike get_attname() because we use aliases if available.
1526  * In particular, it will work on an RTE for a subselect or join, whereas
1527  * get_attname() only works on real relations.
1528  *
1529  * "*" is returned if the given attnum is InvalidAttrNumber --- this case
1530  * occurs when a Var represents a whole tuple of a relation.
1531  */
1532 char *
1533 get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1534 {
1535         if (attnum == InvalidAttrNumber)
1536                 return "*";
1537
1538         /*
1539          * If there is a user-written column alias, use it.
1540          */
1541         if (rte->alias &&
1542                 attnum > 0 && attnum <= list_length(rte->alias->colnames))
1543                 return strVal(list_nth(rte->alias->colnames, attnum - 1));
1544
1545         /*
1546          * If the RTE is a relation, go to the system catalogs not the
1547          * eref->colnames list.  This is a little slower but it will give the
1548          * right answer if the column has been renamed since the eref list was
1549          * built (which can easily happen for rules).
1550          */
1551         if (rte->rtekind == RTE_RELATION)
1552                 return get_relid_attribute_name(rte->relid, attnum);
1553
1554         /*
1555          * Otherwise use the column name from eref.  There should always be one.
1556          */
1557         if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
1558                 return strVal(list_nth(rte->eref->colnames, attnum - 1));
1559
1560         /* else caller gave us a bogus attnum */
1561         elog(ERROR, "invalid attnum %d for rangetable entry %s",
1562                  attnum, rte->eref->aliasname);
1563         return NULL;                            /* keep compiler quiet */
1564 }
1565
1566 /*
1567  * get_rte_attribute_type
1568  *              Get attribute type information from a RangeTblEntry
1569  */
1570 void
1571 get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
1572                                            Oid *vartype, int32 *vartypmod)
1573 {
1574         switch (rte->rtekind)
1575         {
1576                 case RTE_RELATION:
1577                         {
1578                                 /* Plain relation RTE --- get the attribute's type info */
1579                                 HeapTuple       tp;
1580                                 Form_pg_attribute att_tup;
1581
1582                                 tp = SearchSysCache(ATTNUM,
1583                                                                         ObjectIdGetDatum(rte->relid),
1584                                                                         Int16GetDatum(attnum),
1585                                                                         0, 0);
1586                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1587                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1588                                                  attnum, rte->relid);
1589                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1590
1591                                 /*
1592                                  * If dropped column, pretend it ain't there.  See notes in
1593                                  * scanRTEForColumn.
1594                                  */
1595                                 if (att_tup->attisdropped)
1596                                         ereport(ERROR,
1597                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1598                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
1599                                                    NameStr(att_tup->attname),
1600                                                    get_rel_name(rte->relid))));
1601                                 *vartype = att_tup->atttypid;
1602                                 *vartypmod = att_tup->atttypmod;
1603                                 ReleaseSysCache(tp);
1604                         }
1605                         break;
1606                 case RTE_SUBQUERY:
1607                         {
1608                                 /* Subselect RTE --- get type info from subselect's tlist */
1609                                 TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
1610                                                                                                    attnum);
1611
1612                                 if (te == NULL || te->resjunk)
1613                                         elog(ERROR, "subquery %s does not have attribute %d",
1614                                                  rte->eref->aliasname, attnum);
1615                                 *vartype = exprType((Node *) te->expr);
1616                                 *vartypmod = exprTypmod((Node *) te->expr);
1617                         }
1618                         break;
1619                 case RTE_FUNCTION:
1620                         {
1621                                 /* Function RTE */
1622                                 TypeFuncClass functypclass;
1623                                 Oid                     funcrettype;
1624                                 TupleDesc       tupdesc;
1625
1626                                 functypclass = get_expr_result_type(rte->funcexpr,
1627                                                                                                         &funcrettype,
1628                                                                                                         &tupdesc);
1629
1630                                 if (functypclass == TYPEFUNC_COMPOSITE)
1631                                 {
1632                                         /* Composite data type, e.g. a table's row type */
1633                                         Form_pg_attribute att_tup;
1634
1635                                         Assert(tupdesc);
1636                                         /* this is probably a can't-happen case */
1637                                         if (attnum < 1 || attnum > tupdesc->natts)
1638                                                 ereport(ERROR,
1639                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1640                                                 errmsg("column %d of relation \"%s\" does not exist",
1641                                                            attnum,
1642                                                            rte->eref->aliasname)));
1643
1644                                         att_tup = tupdesc->attrs[attnum - 1];
1645
1646                                         /*
1647                                          * If dropped column, pretend it ain't there.  See notes
1648                                          * in scanRTEForColumn.
1649                                          */
1650                                         if (att_tup->attisdropped)
1651                                                 ereport(ERROR,
1652                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1653                                                                  errmsg("column \"%s\" of relation \"%s\" does not exist",
1654                                                                                 NameStr(att_tup->attname),
1655                                                                                 rte->eref->aliasname)));
1656                                         *vartype = att_tup->atttypid;
1657                                         *vartypmod = att_tup->atttypmod;
1658                                 }
1659                                 else if (functypclass == TYPEFUNC_SCALAR)
1660                                 {
1661                                         /* Base data type, i.e. scalar */
1662                                         *vartype = funcrettype;
1663                                         *vartypmod = -1;
1664                                 }
1665                                 else if (functypclass == TYPEFUNC_RECORD)
1666                                 {
1667                                         *vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
1668                                         *vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
1669                                 }
1670                                 else
1671                                 {
1672                                         /* addRangeTableEntryForFunction should've caught this */
1673                                         elog(ERROR, "function in FROM has unsupported return type");
1674                                 }
1675                         }
1676                         break;
1677                 case RTE_VALUES:
1678                         {
1679                                 /* Values RTE --- get type info from first sublist */
1680                                 List       *collist = (List *) linitial(rte->values_lists);
1681                                 Node       *col;
1682
1683                                 if (attnum < 1 || attnum > list_length(collist))
1684                                         elog(ERROR, "values list %s does not have attribute %d",
1685                                                  rte->eref->aliasname, attnum);
1686                                 col = (Node *) list_nth(collist, attnum - 1);
1687                                 *vartype = exprType(col);
1688                                 *vartypmod = exprTypmod(col);
1689                         }
1690                         break;
1691                 case RTE_JOIN:
1692                         {
1693                                 /*
1694                                  * Join RTE --- get type info from join RTE's alias variable
1695                                  */
1696                                 Node       *aliasvar;
1697
1698                                 Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
1699                                 aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
1700                                 *vartype = exprType(aliasvar);
1701                                 *vartypmod = exprTypmod(aliasvar);
1702                         }
1703                         break;
1704                 default:
1705                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1706         }
1707 }
1708
1709 /*
1710  * get_rte_attribute_is_dropped
1711  *              Check whether attempted attribute ref is to a dropped column
1712  */
1713 bool
1714 get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
1715 {
1716         bool            result;
1717
1718         switch (rte->rtekind)
1719         {
1720                 case RTE_RELATION:
1721                         {
1722                                 /*
1723                                  * Plain relation RTE --- get the attribute's catalog entry
1724                                  */
1725                                 HeapTuple       tp;
1726                                 Form_pg_attribute att_tup;
1727
1728                                 tp = SearchSysCache(ATTNUM,
1729                                                                         ObjectIdGetDatum(rte->relid),
1730                                                                         Int16GetDatum(attnum),
1731                                                                         0, 0);
1732                                 if (!HeapTupleIsValid(tp))              /* shouldn't happen */
1733                                         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1734                                                  attnum, rte->relid);
1735                                 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1736                                 result = att_tup->attisdropped;
1737                                 ReleaseSysCache(tp);
1738                         }
1739                         break;
1740                 case RTE_SUBQUERY:
1741                 case RTE_VALUES:
1742                         /* Subselect and Values RTEs never have dropped columns */
1743                         result = false;
1744                         break;
1745                 case RTE_JOIN:
1746                         {
1747                                 /*
1748                                  * A join RTE would not have dropped columns when constructed,
1749                                  * but one in a stored rule might contain columns that were
1750                                  * dropped from the underlying tables, if said columns are
1751                                  * nowhere explicitly referenced in the rule.  This will be
1752                                  * signaled to us by a NULL Const in the joinaliasvars list.
1753                                  */
1754                                 Var                *aliasvar;
1755
1756                                 if (attnum <= 0 ||
1757                                         attnum > list_length(rte->joinaliasvars))
1758                                         elog(ERROR, "invalid varattno %d", attnum);
1759                                 aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
1760
1761                                 result = IsA(aliasvar, Const);
1762                         }
1763                         break;
1764                 case RTE_FUNCTION:
1765                         {
1766                                 /* Function RTE */
1767                                 Oid                     funcrettype = exprType(rte->funcexpr);
1768                                 Oid                     funcrelid = typeidTypeRelid(funcrettype);
1769
1770                                 if (OidIsValid(funcrelid))
1771                                 {
1772                                         /*
1773                                          * Composite data type, i.e. a table's row type
1774                                          *
1775                                          * Same as ordinary relation RTE
1776                                          */
1777                                         HeapTuple       tp;
1778                                         Form_pg_attribute att_tup;
1779
1780                                         tp = SearchSysCache(ATTNUM,
1781                                                                                 ObjectIdGetDatum(funcrelid),
1782                                                                                 Int16GetDatum(attnum),
1783                                                                                 0, 0);
1784                                         if (!HeapTupleIsValid(tp))      /* shouldn't happen */
1785                                                 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1786                                                          attnum, funcrelid);
1787                                         att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1788                                         result = att_tup->attisdropped;
1789                                         ReleaseSysCache(tp);
1790                                 }
1791                                 else
1792                                 {
1793                                         /*
1794                                          * Must be a base data type, i.e. scalar
1795                                          */
1796                                         result = false;
1797                                 }
1798                         }
1799                         break;
1800                 default:
1801                         elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1802                         result = false;         /* keep compiler quiet */
1803         }
1804
1805         return result;
1806 }
1807
1808 /*
1809  * Given a targetlist and a resno, return the matching TargetEntry
1810  *
1811  * Returns NULL if resno is not present in list.
1812  *
1813  * Note: we need to search, rather than just indexing with list_nth(),
1814  * because not all tlists are sorted by resno.
1815  */
1816 TargetEntry *
1817 get_tle_by_resno(List *tlist, AttrNumber resno)
1818 {
1819         ListCell   *l;
1820
1821         foreach(l, tlist)
1822         {
1823                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1824
1825                 if (tle->resno == resno)
1826                         return tle;
1827         }
1828         return NULL;
1829 }
1830
1831 /*
1832  * Given a Query and rangetable index, return relation's RowMarkClause if any
1833  *
1834  * Returns NULL if relation is not selected FOR UPDATE/SHARE
1835  */
1836 RowMarkClause *
1837 get_rowmark(Query *qry, Index rtindex)
1838 {
1839         ListCell   *l;
1840
1841         foreach(l, qry->rowMarks)
1842         {
1843                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1844
1845                 if (rc->rti == rtindex)
1846                         return rc;
1847         }
1848         return NULL;
1849 }
1850
1851 /*
1852  *      given relation and att name, return attnum of variable
1853  *
1854  *      Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
1855  *
1856  *      This should only be used if the relation is already
1857  *      heap_open()'ed.  Use the cache version get_attnum()
1858  *      for access to non-opened relations.
1859  */
1860 int
1861 attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1862 {
1863         int                     i;
1864
1865         for (i = 0; i < rd->rd_rel->relnatts; i++)
1866         {
1867                 Form_pg_attribute att = rd->rd_att->attrs[i];
1868
1869                 if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1870                         return i + 1;
1871         }
1872
1873         if (sysColOK)
1874         {
1875                 if ((i = specialAttNum(attname)) != InvalidAttrNumber)
1876                 {
1877                         if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
1878                                 return i;
1879                 }
1880         }
1881
1882         /* on failure */
1883         return InvalidAttrNumber;
1884 }
1885
1886 /* specialAttNum()
1887  *
1888  * Check attribute name to see if it is "special", e.g. "oid".
1889  * - thomas 2000-02-07
1890  *
1891  * Note: this only discovers whether the name could be a system attribute.
1892  * Caller needs to verify that it really is an attribute of the rel,
1893  * at least in the case of "oid", which is now optional.
1894  */
1895 static int
1896 specialAttNum(const char *attname)
1897 {
1898         Form_pg_attribute sysatt;
1899
1900         sysatt = SystemAttributeByName(attname,
1901                                                                    true /* "oid" will be accepted */ );
1902         if (sysatt != NULL)
1903                 return sysatt->attnum;
1904         return InvalidAttrNumber;
1905 }
1906
1907
1908 /*
1909  * given attribute id, return name of that attribute
1910  *
1911  *      This should only be used if the relation is already
1912  *      heap_open()'ed.  Use the cache version get_atttype()
1913  *      for access to non-opened relations.
1914  */
1915 Name
1916 attnumAttName(Relation rd, int attid)
1917 {
1918         if (attid <= 0)
1919         {
1920                 Form_pg_attribute sysatt;
1921
1922                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1923                 return &sysatt->attname;
1924         }
1925         if (attid > rd->rd_att->natts)
1926                 elog(ERROR, "invalid attribute number %d", attid);
1927         return &rd->rd_att->attrs[attid - 1]->attname;
1928 }
1929
1930 /*
1931  * given attribute id, return type of that attribute
1932  *
1933  *      This should only be used if the relation is already
1934  *      heap_open()'ed.  Use the cache version get_atttype()
1935  *      for access to non-opened relations.
1936  */
1937 Oid
1938 attnumTypeId(Relation rd, int attid)
1939 {
1940         if (attid <= 0)
1941         {
1942                 Form_pg_attribute sysatt;
1943
1944                 sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
1945                 return sysatt->atttypid;
1946         }
1947         if (attid > rd->rd_att->natts)
1948                 elog(ERROR, "invalid attribute number %d", attid);
1949         return rd->rd_att->attrs[attid - 1]->atttypid;
1950 }
1951
1952 /*
1953  * Generate a warning or error about an implicit RTE, if appropriate.
1954  *
1955  * If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
1956  * a warning.
1957  */
1958 static void
1959 warnAutoRange(ParseState *pstate, RangeVar *relation, int location)
1960 {
1961         RangeTblEntry *rte;
1962         int                     sublevels_up;
1963         const char *badAlias = NULL;
1964
1965         /*
1966          * Check to see if there are any potential matches in the query's
1967          * rangetable.  This affects the message we provide.
1968          */
1969         rte = searchRangeTable(pstate, relation);
1970
1971         /*
1972          * If we found a match that has an alias and the alias is visible in the
1973          * namespace, then the problem is probably use of the relation's real name
1974          * instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
1975          * common enough to justify a specific hint.
1976          *
1977          * If we found a match that doesn't meet those criteria, assume the
1978          * problem is illegal use of a relation outside its scope, as in the
1979          * MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
1980          */
1981         if (rte && rte->alias &&
1982                 strcmp(rte->eref->aliasname, relation->relname) != 0 &&
1983                 refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
1984                                                          &sublevels_up) == rte)
1985                 badAlias = rte->eref->aliasname;
1986
1987         if (!add_missing_from)
1988         {
1989                 if (rte)
1990                         ereport(ERROR,
1991                                         (errcode(ERRCODE_UNDEFINED_TABLE),
1992                         errmsg("invalid reference to FROM-clause entry for table \"%s\"",
1993                                    relation->relname),
1994                                          (badAlias ?
1995                         errhint("Perhaps you meant to reference the table alias \"%s\".",
1996                                         badAlias) :
1997                                           errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
1998                                                           rte->eref->aliasname)),
1999                                          parser_errposition(pstate, location)));
2000                 else
2001                         ereport(ERROR,
2002                                         (errcode(ERRCODE_UNDEFINED_TABLE),
2003                                          (pstate->parentParseState ?
2004                          errmsg("missing FROM-clause entry in subquery for table \"%s\"",
2005                                         relation->relname) :
2006                                           errmsg("missing FROM-clause entry for table \"%s\"",
2007                                                          relation->relname)),
2008                                          parser_errposition(pstate, location)));
2009         }
2010         else
2011         {
2012                 /* just issue a warning */
2013                 ereport(NOTICE,
2014                                 (errcode(ERRCODE_UNDEFINED_TABLE),
2015                                  (pstate->parentParseState ?
2016                                   errmsg("adding missing FROM-clause entry in subquery for table \"%s\"",
2017                                                  relation->relname) :
2018                                   errmsg("adding missing FROM-clause entry for table \"%s\"",
2019                                                  relation->relname)),
2020                                  (badAlias ?
2021                         errhint("Perhaps you meant to reference the table alias \"%s\".",
2022                                         badAlias) :
2023                                   (rte ?
2024                                    errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2025                                                    rte->eref->aliasname) : 0)),
2026                                  parser_errposition(pstate, location)));
2027         }
2028 }