1
/*-------------------------------------------------------------------------
4
* parser support routines dealing with relations
6
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7
* Portions Copyright (c) 1994, Regents of the University of California
13
*-------------------------------------------------------------------------
19
#include "access/heapam.h"
20
#include "access/sysattr.h"
21
#include "catalog/heap.h"
22
#include "catalog/namespace.h"
23
#include "catalog/pg_type.h"
25
#include "nodes/makefuncs.h"
26
#include "nodes/nodeFuncs.h"
27
#include "parser/parsetree.h"
28
#include "parser/parse_relation.h"
29
#include "parser/parse_type.h"
30
#include "utils/builtins.h"
31
#include "utils/lsyscache.h"
32
#include "utils/syscache.h"
36
bool add_missing_from;
38
static RangeTblEntry *scanNameSpaceForRefname(ParseState *pstate,
39
const char *refname, int location);
40
static RangeTblEntry *scanNameSpaceForRelid(ParseState *pstate, Oid relid,
42
static void markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
43
int rtindex, AttrNumber col);
44
static bool isLockedRel(ParseState *pstate, char *refname);
45
static void expandRelation(Oid relid, Alias *eref,
46
int rtindex, int sublevels_up,
47
int location, bool include_dropped,
48
List **colnames, List **colvars);
49
static void expandTupleDesc(TupleDesc tupdesc, Alias *eref,
50
int rtindex, int sublevels_up,
51
int location, bool include_dropped,
52
List **colnames, List **colvars);
53
static int specialAttNum(const char *attname);
54
static void warnAutoRange(ParseState *pstate, RangeVar *relation);
58
* refnameRangeTblEntry
59
* Given a possibly-qualified refname, look to see if it matches any RTE.
60
* If so, return a pointer to the RangeTblEntry; else return NULL.
62
* Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
63
* If sublevels_up is NULL, only consider items at the current nesting
66
* An unqualified refname (schemaname == NULL) can match any RTE with matching
67
* alias, or matching unqualified relname in the case of alias-less relation
68
* RTEs. It is possible that such a refname matches multiple RTEs in the
69
* nearest nesting level that has a match; if so, we report an error via
72
* A qualified refname (schemaname != NULL) can only match a relation RTE
73
* that (a) has no alias and (b) is for the same relation identified by
74
* schemaname.refname. In this case we convert schemaname.refname to a
75
* relation OID and search by relid, rather than by alias name. This is
76
* peculiar, but it's what SQL92 says to do.
79
refnameRangeTblEntry(ParseState *pstate,
80
const char *schemaname,
85
Oid relId = InvalidOid;
90
if (schemaname != NULL)
94
namespaceId = LookupExplicitNamespace(schemaname);
95
relId = get_relname_relid(refname, namespaceId);
96
if (!OidIsValid(relId))
100
while (pstate != NULL)
102
RangeTblEntry *result;
104
if (OidIsValid(relId))
105
result = scanNameSpaceForRelid(pstate, relId, location);
107
result = scanNameSpaceForRefname(pstate, refname, location);
117
pstate = pstate->parentParseState;
123
* Search the query's table namespace for an RTE matching the
124
* given unqualified refname. Return the RTE if a unique match, or NULL
125
* if no match. Raise error if multiple matches.
127
static RangeTblEntry *
128
scanNameSpaceForRefname(ParseState *pstate, const char *refname, int location)
130
RangeTblEntry *result = NULL;
133
foreach(l, pstate->p_relnamespace)
135
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
137
if (strcmp(rte->eref->aliasname, refname) == 0)
141
(errcode(ERRCODE_AMBIGUOUS_ALIAS),
142
errmsg("table reference \"%s\" is ambiguous",
144
parser_errposition(pstate, location)));
152
* Search the query's table namespace for a relation RTE matching the
153
* given relation OID. Return the RTE if a unique match, or NULL
154
* if no match. Raise error if multiple matches (which shouldn't
155
* happen if the namespace was checked correctly when it was created).
157
* See the comments for refnameRangeTblEntry to understand why this
158
* acts the way it does.
160
static RangeTblEntry *
161
scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location)
163
RangeTblEntry *result = NULL;
166
foreach(l, pstate->p_relnamespace)
168
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
170
/* yes, the test for alias == NULL should be there... */
171
if (rte->rtekind == RTE_RELATION &&
172
rte->relid == relid &&
177
(errcode(ERRCODE_AMBIGUOUS_ALIAS),
178
errmsg("table reference %u is ambiguous",
180
parser_errposition(pstate, location)));
188
* Search the query's CTE namespace for a CTE matching the given unqualified
189
* refname. Return the CTE (and its levelsup count) if a match, or NULL
190
* if no match. We need not worry about multiple matches, since parse_cte.c
191
* rejects WITH lists containing duplicate CTE names.
194
scanNameSpaceForCTE(ParseState *pstate, const char *refname,
201
pstate = pstate->parentParseState, levelsup++)
205
foreach(lc, pstate->p_ctenamespace)
207
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
209
if (strcmp(cte->ctename, refname) == 0)
211
*ctelevelsup = levelsup;
220
* Search for a possible "future CTE", that is one that is not yet in scope
221
* according to the WITH scoping rules. This has nothing to do with valid
222
* SQL semantics, but it's important for error reporting purposes.
225
isFutureCTE(ParseState *pstate, const char *refname)
227
for (; pstate != NULL; pstate = pstate->parentParseState)
231
foreach(lc, pstate->p_future_ctes)
233
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
235
if (strcmp(cte->ctename, refname) == 0)
244
* See if any RangeTblEntry could possibly match the RangeVar.
245
* If so, return a pointer to the RangeTblEntry; else return NULL.
247
* This is different from refnameRangeTblEntry in that it considers every
248
* entry in the ParseState's rangetable(s), not only those that are currently
249
* visible in the p_relnamespace lists. This behavior is invalid per the SQL
250
* spec, and it may give ambiguous results (there might be multiple equally
251
* valid matches, but only one will be returned). This must be used ONLY
252
* as a heuristic in giving suitable error messages. See warnAutoRange.
254
* Notice that we consider both matches on actual relation (or CTE) name
255
* and matches on alias.
257
static RangeTblEntry *
258
searchRangeTable(ParseState *pstate, RangeVar *relation)
260
const char *refname = relation->relname;
261
Oid relId = InvalidOid;
262
CommonTableExpr *cte = NULL;
263
Index ctelevelsup = 0;
267
* If it's an unqualified name, check for possible CTE matches.
268
* A CTE hides any real relation matches. If no CTE, look for
269
* a matching relation.
271
if (!relation->schemaname)
272
cte = scanNameSpaceForCTE(pstate, refname, &ctelevelsup);
274
relId = RangeVarGetRelid(relation, true);
276
/* Now look for RTEs matching either the relation/CTE or the alias */
279
pstate = pstate->parentParseState, levelsup++)
283
foreach(l, pstate->p_rtable)
285
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
287
if (rte->rtekind == RTE_RELATION &&
291
if (rte->rtekind == RTE_CTE &&
293
rte->ctelevelsup + levelsup == ctelevelsup &&
294
strcmp(rte->ctename, refname) == 0)
296
if (strcmp(rte->eref->aliasname, refname) == 0)
304
* Check for relation-name conflicts between two relnamespace lists.
305
* Raise an error if any is found.
307
* Note: we assume that each given argument does not contain conflicts
308
* itself; we just want to know if the two can be merged together.
310
* Per SQL92, two alias-less plain relation RTEs do not conflict even if
311
* they have the same eref->aliasname (ie, same relation name), if they
312
* are for different relation OIDs (implying they are in different schemas).
315
checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
320
foreach(l1, namespace1)
322
RangeTblEntry *rte1 = (RangeTblEntry *) lfirst(l1);
323
const char *aliasname1 = rte1->eref->aliasname;
326
foreach(l2, namespace2)
328
RangeTblEntry *rte2 = (RangeTblEntry *) lfirst(l2);
330
if (strcmp(rte2->eref->aliasname, aliasname1) != 0)
331
continue; /* definitely no conflict */
332
if (rte1->rtekind == RTE_RELATION && rte1->alias == NULL &&
333
rte2->rtekind == RTE_RELATION && rte2->alias == NULL &&
334
rte1->relid != rte2->relid)
335
continue; /* no conflict per SQL92 rule */
337
(errcode(ERRCODE_DUPLICATE_ALIAS),
338
errmsg("table name \"%s\" specified more than once",
345
* given an RTE, return RT index (starting with 1) of the entry,
346
* and optionally get its nesting depth (0 = current). If sublevels_up
347
* is NULL, only consider rels at the current nesting level.
348
* Raises error if RTE not found.
351
RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
359
while (pstate != NULL)
362
foreach(l, pstate->p_rtable)
364
if (rte == (RangeTblEntry *) lfirst(l))
368
pstate = pstate->parentParseState;
375
elog(ERROR, "RTE not found (internal error)");
376
return 0; /* keep compiler quiet */
380
* Given an RT index and nesting depth, find the corresponding RTE.
381
* This is the inverse of RTERangeTablePosn.
384
GetRTEByRangeTablePosn(ParseState *pstate,
388
while (sublevels_up-- > 0)
390
pstate = pstate->parentParseState;
391
Assert(pstate != NULL);
393
Assert(varno > 0 && varno <= list_length(pstate->p_rtable));
394
return rt_fetch(varno, pstate->p_rtable);
398
* Fetch the CTE for a CTE-reference RTE.
400
* rtelevelsup is the number of query levels above the given pstate that the
401
* RTE came from. Callers that don't have this information readily available
402
* may pass -1 instead.
405
GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte, int rtelevelsup)
410
/* Determine RTE's levelsup if caller didn't know it */
412
(void) RTERangeTablePosn(pstate, rte, &rtelevelsup);
414
Assert(rte->rtekind == RTE_CTE);
415
levelsup = rte->ctelevelsup + rtelevelsup;
416
while (levelsup-- > 0)
418
pstate = pstate->parentParseState;
419
if (!pstate) /* shouldn't happen */
420
elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
422
foreach(lc, pstate->p_ctenamespace)
424
CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
426
if (strcmp(cte->ctename, rte->ctename) == 0)
429
/* shouldn't happen */
430
elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
431
return NULL; /* keep compiler quiet */
436
* Search the column names of a single RTE for the given name.
437
* If found, return an appropriate Var node, else return NULL.
438
* If the name proves ambiguous within this RTE, raise error.
440
* Side effect: if we find a match, mark the RTE as requiring read access
444
scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname,
453
* Scan the user column names (or aliases) for a match. Complain if
456
* Note: eref->colnames may include entries for dropped columns, but those
457
* will be empty strings that cannot match any legal SQL identifier, so we
458
* don't bother to test for that case here.
460
* Should this somehow go wrong and we try to access a dropped column,
461
* we'll still catch it by virtue of the checks in
462
* get_rte_attribute_type(), which is called by make_var(). That routine
463
* has to do a cache lookup anyway, so the check there is cheap.
465
foreach(c, rte->eref->colnames)
468
if (strcmp(strVal(lfirst(c)), colname) == 0)
472
(errcode(ERRCODE_AMBIGUOUS_COLUMN),
473
errmsg("column reference \"%s\" is ambiguous",
475
parser_errposition(pstate, location)));
476
var = make_var(pstate, rte, attnum, location);
477
/* Require read access to the column */
478
markVarForSelectPriv(pstate, var, rte);
479
result = (Node *) var;
484
* If we have a unique match, return it. Note that this allows a user
485
* alias to override a system column name (such as OID) without error.
491
* If the RTE represents a real table, consider system column names.
493
if (rte->rtekind == RTE_RELATION)
495
/* quick check to see if name could be a system column */
496
attnum = specialAttNum(colname);
497
if (attnum != InvalidAttrNumber)
499
/* now check to see if column actually is defined */
500
if (SearchSysCacheExists(ATTNUM,
501
ObjectIdGetDatum(rte->relid),
502
Int16GetDatum(attnum),
505
var = make_var(pstate, rte, attnum, location);
506
/* Require read access to the column */
507
markVarForSelectPriv(pstate, var, rte);
508
result = (Node *) var;
518
* Search for an unqualified column name.
519
* If found, return the appropriate Var node (or expression).
520
* If not found, return NULL. If the name proves ambiguous, raise error.
521
* If localonly is true, only names in the innermost query are considered.
524
colNameToVar(ParseState *pstate, char *colname, bool localonly,
528
ParseState *orig_pstate = pstate;
530
while (pstate != NULL)
534
foreach(l, pstate->p_varnamespace)
536
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
539
/* use orig_pstate here to get the right sublevels_up */
540
newresult = scanRTEForColumn(orig_pstate, rte, colname, location);
546
(errcode(ERRCODE_AMBIGUOUS_COLUMN),
547
errmsg("column reference \"%s\" is ambiguous",
549
parser_errposition(orig_pstate, location)));
554
if (result != NULL || localonly)
555
break; /* found, or don't want to look at parent */
557
pstate = pstate->parentParseState;
565
* Search for a qualified column name: either refname.colname or
566
* schemaname.relname.colname.
568
* If found, return the appropriate Var node.
569
* If not found, return NULL. If the name proves ambiguous, raise error.
572
qualifiedNameToVar(ParseState *pstate,
582
rte = refnameRangeTblEntry(pstate, schemaname, refname, location,
589
rte = addImplicitRTE(pstate,
590
makeRangeVar(schemaname, refname, location));
593
return scanRTEForColumn(pstate, rte, colname, location);
597
* markRTEForSelectPriv
598
* Mark the specified column of an RTE as requiring SELECT privilege
600
* col == InvalidAttrNumber means a "whole row" reference
602
* The caller should pass the actual RTE if it has it handy; otherwise pass
603
* NULL, and we'll look it up here. (This uglification of the API is
604
* worthwhile because nearly all external callers have the RTE at hand.)
607
markRTEForSelectPriv(ParseState *pstate, RangeTblEntry *rte,
608
int rtindex, AttrNumber col)
611
rte = rt_fetch(rtindex, pstate->p_rtable);
613
if (rte->rtekind == RTE_RELATION)
615
/* Make sure the rel as a whole is marked for SELECT access */
616
rte->requiredPerms |= ACL_SELECT;
617
/* Must offset the attnum to fit in a bitmapset */
618
rte->selectedCols = bms_add_member(rte->selectedCols,
619
col - FirstLowInvalidHeapAttributeNumber);
621
else if (rte->rtekind == RTE_JOIN)
623
if (col == InvalidAttrNumber)
626
* A whole-row reference to a join has to be treated as
627
* whole-row references to the two inputs.
631
if (rtindex > 0 && rtindex <= list_length(pstate->p_joinexprs))
632
j = (JoinExpr *) list_nth(pstate->p_joinexprs, rtindex - 1);
636
elog(ERROR, "could not find JoinExpr for whole-row reference");
637
Assert(IsA(j, JoinExpr));
639
/* Note: we can't see FromExpr here */
640
if (IsA(j->larg, RangeTblRef))
642
int varno = ((RangeTblRef *) j->larg)->rtindex;
644
markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
646
else if (IsA(j->larg, JoinExpr))
648
int varno = ((JoinExpr *) j->larg)->rtindex;
650
markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
653
elog(ERROR, "unrecognized node type: %d",
654
(int) nodeTag(j->larg));
655
if (IsA(j->rarg, RangeTblRef))
657
int varno = ((RangeTblRef *) j->rarg)->rtindex;
659
markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
661
else if (IsA(j->rarg, JoinExpr))
663
int varno = ((JoinExpr *) j->rarg)->rtindex;
665
markRTEForSelectPriv(pstate, NULL, varno, InvalidAttrNumber);
668
elog(ERROR, "unrecognized node type: %d",
669
(int) nodeTag(j->rarg));
674
* Regular join attribute, look at the alias-variable list.
676
* The aliasvar could be either a Var or a COALESCE expression,
677
* but in the latter case we should already have marked the two
678
* referent variables as being selected, due to their use in the
679
* JOIN clause. So we need only be concerned with the simple
684
Assert(col > 0 && col <= list_length(rte->joinaliasvars));
685
aliasvar = (Var *) list_nth(rte->joinaliasvars, col - 1);
686
if (IsA(aliasvar, Var))
687
markVarForSelectPriv(pstate, aliasvar, NULL);
690
/* other RTE types don't require privilege marking */
694
* markVarForSelectPriv
695
* Mark the RTE referenced by a Var as requiring SELECT privilege
697
* The caller should pass the Var's referenced RTE if it has it handy
698
* (nearly all do); otherwise pass NULL.
701
markVarForSelectPriv(ParseState *pstate, Var *var, RangeTblEntry *rte)
705
Assert(IsA(var, Var));
706
/* Find the appropriate pstate if it's an uplevel Var */
707
for (lv = 0; lv < var->varlevelsup; lv++)
708
pstate = pstate->parentParseState;
709
markRTEForSelectPriv(pstate, rte, var->varno, var->varattno);
713
* buildRelationAliases
714
* Construct the eref column name list for a relation RTE.
715
* This code is also used for the case of a function RTE returning
716
* a named composite type.
718
* tupdesc: the physical column information
719
* alias: the user-supplied alias, or NULL if none
720
* eref: the eref Alias to store column names in
722
* eref->colnames is filled in. Also, alias->colnames is rebuilt to insert
723
* empty strings for any dropped columns, so that it will be one-to-one with
724
* physical column numbers.
727
buildRelationAliases(TupleDesc tupdesc, Alias *alias, Alias *eref)
729
int maxattrs = tupdesc->natts;
735
Assert(eref->colnames == NIL);
739
aliaslc = list_head(alias->colnames);
740
numaliases = list_length(alias->colnames);
741
/* We'll rebuild the alias colname list */
742
alias->colnames = NIL;
750
for (varattno = 0; varattno < maxattrs; varattno++)
752
Form_pg_attribute attr = tupdesc->attrs[varattno];
755
if (attr->attisdropped)
757
/* Always insert an empty string for a dropped column */
758
attrname = makeString(pstrdup(""));
760
alias->colnames = lappend(alias->colnames, attrname);
765
/* Use the next user-supplied alias */
766
attrname = (Value *) lfirst(aliaslc);
767
aliaslc = lnext(aliaslc);
768
alias->colnames = lappend(alias->colnames, attrname);
772
attrname = makeString(pstrdup(NameStr(attr->attname)));
773
/* we're done with the alias if any */
776
eref->colnames = lappend(eref->colnames, attrname);
779
/* Too many user-supplied aliases? */
782
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
783
errmsg("table \"%s\" has %d columns available but %d columns specified",
784
eref->aliasname, maxattrs - numdropped, numaliases)));
788
* buildScalarFunctionAlias
789
* Construct the eref column name list for a function RTE,
790
* when the function returns a scalar type (not composite or RECORD).
792
* funcexpr: transformed expression tree for the function call
793
* funcname: function name (used only for error message)
794
* alias: the user-supplied alias, or NULL if none
795
* eref: the eref Alias to store column names in
797
* eref->colnames is filled in.
800
buildScalarFunctionAlias(Node *funcexpr, char *funcname,
801
Alias *alias, Alias *eref)
805
Assert(eref->colnames == NIL);
807
/* Use user-specified column alias if there is one. */
808
if (alias && alias->colnames != NIL)
810
if (list_length(alias->colnames) != 1)
812
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
813
errmsg("too many column aliases specified for function %s",
815
eref->colnames = copyObject(alias->colnames);
820
* If the expression is a simple function call, and the function has a
821
* single OUT parameter that is named, use the parameter's name.
823
if (funcexpr && IsA(funcexpr, FuncExpr))
825
pname = get_func_result_name(((FuncExpr *) funcexpr)->funcid);
828
eref->colnames = list_make1(makeString(pname));
834
* Otherwise use the previously-determined alias (not necessarily the
837
eref->colnames = list_make1(makeString(eref->aliasname));
841
* Open a table during parse analysis
843
* This is essentially just the same as heap_openrv(), except that it caters
844
* to some parser-specific error reporting needs, notably that it arranges
845
* to include the RangeVar's parse location in any resulting error.
847
* Note: properly, lockmode should be declared LOCKMODE not int, but that
848
* would require importing storage/lock.h into parse_relation.h. Since
849
* LOCKMODE is typedef'd as int anyway, that seems like overkill.
852
parserOpenTable(ParseState *pstate, const RangeVar *relation, int lockmode)
855
ParseCallbackState pcbstate;
857
setup_parser_errposition_callback(&pcbstate, pstate, relation->location);
858
rel = try_heap_openrv(relation, lockmode);
861
if (relation->schemaname)
863
(errcode(ERRCODE_UNDEFINED_TABLE),
864
errmsg("relation \"%s.%s\" does not exist",
865
relation->schemaname, relation->relname)));
869
* An unqualified name might have been meant as a reference to
870
* some not-yet-in-scope CTE. The bare "does not exist" message
871
* has proven remarkably unhelpful for figuring out such problems,
872
* so we take pains to offer a specific hint.
874
if (isFutureCTE(pstate, relation->relname))
876
(errcode(ERRCODE_UNDEFINED_TABLE),
877
errmsg("relation \"%s\" does not exist",
879
errdetail("There is a WITH item named \"%s\", but it cannot be referenced from this part of the query.",
881
errhint("Use WITH RECURSIVE, or re-order the WITH items to remove forward references.")));
884
(errcode(ERRCODE_UNDEFINED_TABLE),
885
errmsg("relation \"%s\" does not exist",
886
relation->relname)));
889
cancel_parser_errposition_callback(&pcbstate);
894
* Add an entry for a relation to the pstate's range table (p_rtable).
896
* If pstate is NULL, we just build an RTE and return it without adding it
899
* Note: formerly this checked for refname conflicts, but that's wrong.
900
* Caller is responsible for checking for conflicts in the appropriate scope.
903
addRangeTableEntry(ParseState *pstate,
909
RangeTblEntry *rte = makeNode(RangeTblEntry);
910
char *refname = alias ? alias->aliasname : relation->relname;
914
rte->rtekind = RTE_RELATION;
918
* Get the rel's OID. This access also ensures that we have an up-to-date
919
* relcache entry for the rel. Since this is typically the first access
920
* to a rel in a statement, be careful to get the right access level
921
* depending on whether we're doing SELECT FOR UPDATE/SHARE.
923
lockmode = isLockedRel(pstate, refname) ? RowShareLock : AccessShareLock;
924
rel = parserOpenTable(pstate, relation, lockmode);
925
rte->relid = RelationGetRelid(rel);
928
* Build the list of effective column names using user-supplied aliases
929
* and/or actual column names.
931
rte->eref = makeAlias(refname, NIL);
932
buildRelationAliases(rel->rd_att, alias, rte->eref);
935
* Drop the rel refcount, but keep the access lock till end of transaction
936
* so that the table can't be deleted or have its schema modified
939
heap_close(rel, NoLock);
943
* - this RTE should be expanded to include descendant tables,
944
* - this RTE is in the FROM clause,
945
* - this RTE should be checked for appropriate access rights.
947
* The initial default on access checks is always check-for-READ-access,
948
* which is the right thing for all except target tables.
952
rte->inFromCl = inFromCl;
954
rte->requiredPerms = ACL_SELECT;
955
rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
956
rte->selectedCols = NULL;
957
rte->modifiedCols = NULL;
960
* Add completed RTE to pstate's range table list, but not to join list
961
* nor namespace --- caller must do that if appropriate.
964
pstate->p_rtable = lappend(pstate->p_rtable, rte);
970
* Add an entry for a relation to the pstate's range table (p_rtable).
972
* This is just like addRangeTableEntry() except that it makes an RTE
973
* given an already-open relation instead of a RangeVar reference.
976
addRangeTableEntryForRelation(ParseState *pstate,
982
RangeTblEntry *rte = makeNode(RangeTblEntry);
983
char *refname = alias ? alias->aliasname : RelationGetRelationName(rel);
985
rte->rtekind = RTE_RELATION;
987
rte->relid = RelationGetRelid(rel);
990
* Build the list of effective column names using user-supplied aliases
991
* and/or actual column names.
993
rte->eref = makeAlias(refname, NIL);
994
buildRelationAliases(rel->rd_att, alias, rte->eref);
998
* - this RTE should be expanded to include descendant tables,
999
* - this RTE is in the FROM clause,
1000
* - this RTE should be checked for appropriate access rights.
1002
* The initial default on access checks is always check-for-READ-access,
1003
* which is the right thing for all except target tables.
1007
rte->inFromCl = inFromCl;
1009
rte->requiredPerms = ACL_SELECT;
1010
rte->checkAsUser = InvalidOid; /* not set-uid by default, either */
1011
rte->selectedCols = NULL;
1012
rte->modifiedCols = NULL;
1015
* Add completed RTE to pstate's range table list, but not to join list
1016
* nor namespace --- caller must do that if appropriate.
1019
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1025
* Add an entry for a subquery to the pstate's range table (p_rtable).
1027
* This is just like addRangeTableEntry() except that it makes a subquery RTE.
1028
* Note that an alias clause *must* be supplied.
1031
addRangeTableEntryForSubquery(ParseState *pstate,
1036
RangeTblEntry *rte = makeNode(RangeTblEntry);
1037
char *refname = alias->aliasname;
1041
ListCell *tlistitem;
1043
rte->rtekind = RTE_SUBQUERY;
1044
rte->relid = InvalidOid;
1045
rte->subquery = subquery;
1048
eref = copyObject(alias);
1049
numaliases = list_length(eref->colnames);
1051
/* fill in any unspecified alias columns */
1053
foreach(tlistitem, subquery->targetList)
1055
TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1060
Assert(varattno == te->resno);
1061
if (varattno > numaliases)
1065
attrname = pstrdup(te->resname);
1066
eref->colnames = lappend(eref->colnames, makeString(attrname));
1069
if (varattno < numaliases)
1071
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1072
errmsg("table \"%s\" has %d columns available but %d columns specified",
1073
refname, varattno, numaliases)));
1079
* - this RTE should be expanded to include descendant tables,
1080
* - this RTE is in the FROM clause,
1081
* - this RTE should be checked for appropriate access rights.
1083
* Subqueries are never checked for access rights.
1086
rte->inh = false; /* never true for subqueries */
1087
rte->inFromCl = inFromCl;
1089
rte->requiredPerms = 0;
1090
rte->checkAsUser = InvalidOid;
1091
rte->selectedCols = NULL;
1092
rte->modifiedCols = NULL;
1095
* Add completed RTE to pstate's range table list, but not to join list
1096
* nor namespace --- caller must do that if appropriate.
1099
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1105
* Add an entry for a function to the pstate's range table (p_rtable).
1107
* This is just like addRangeTableEntry() except that it makes a function RTE.
1110
addRangeTableEntryForFunction(ParseState *pstate,
1113
RangeFunction *rangefunc,
1116
RangeTblEntry *rte = makeNode(RangeTblEntry);
1117
TypeFuncClass functypclass;
1120
Alias *alias = rangefunc->alias;
1121
List *coldeflist = rangefunc->coldeflist;
1124
rte->rtekind = RTE_FUNCTION;
1125
rte->relid = InvalidOid;
1126
rte->subquery = NULL;
1127
rte->funcexpr = funcexpr;
1128
rte->funccoltypes = NIL;
1129
rte->funccoltypmods = NIL;
1132
eref = makeAlias(alias ? alias->aliasname : funcname, NIL);
1136
* Now determine if the function returns a simple or composite type.
1138
functypclass = get_expr_result_type(funcexpr,
1143
* A coldeflist is required if the function returns RECORD and hasn't got
1144
* a predetermined record type, and is prohibited otherwise.
1146
if (coldeflist != NIL)
1148
if (functypclass != TYPEFUNC_RECORD)
1150
(errcode(ERRCODE_SYNTAX_ERROR),
1151
errmsg("a column definition list is only allowed for functions returning \"record\""),
1152
parser_errposition(pstate, exprLocation(funcexpr))));
1156
if (functypclass == TYPEFUNC_RECORD)
1158
(errcode(ERRCODE_SYNTAX_ERROR),
1159
errmsg("a column definition list is required for functions returning \"record\""),
1160
parser_errposition(pstate, exprLocation(funcexpr))));
1163
if (functypclass == TYPEFUNC_COMPOSITE)
1165
/* Composite data type, e.g. a table's row type */
1167
/* Build the column alias list */
1168
buildRelationAliases(tupdesc, alias, eref);
1170
else if (functypclass == TYPEFUNC_SCALAR)
1172
/* Base data type, i.e. scalar */
1173
buildScalarFunctionAlias(funcexpr, funcname, alias, eref);
1175
else if (functypclass == TYPEFUNC_RECORD)
1180
* Use the column definition list to form the alias list and
1181
* funccoltypes/funccoltypmods lists.
1183
foreach(col, coldeflist)
1185
ColumnDef *n = (ColumnDef *) lfirst(col);
1190
attrname = pstrdup(n->colname);
1191
if (n->typename->setof)
1193
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1194
errmsg("column \"%s\" cannot be declared SETOF",
1196
parser_errposition(pstate, n->typename->location)));
1197
attrtype = typenameTypeId(pstate, n->typename, &attrtypmod);
1198
eref->colnames = lappend(eref->colnames, makeString(attrname));
1199
rte->funccoltypes = lappend_oid(rte->funccoltypes, attrtype);
1200
rte->funccoltypmods = lappend_int(rte->funccoltypmods, attrtypmod);
1205
(errcode(ERRCODE_DATATYPE_MISMATCH),
1206
errmsg("function \"%s\" in FROM has unsupported return type %s",
1207
funcname, format_type_be(funcrettype)),
1208
parser_errposition(pstate, exprLocation(funcexpr))));
1212
* - this RTE should be expanded to include descendant tables,
1213
* - this RTE is in the FROM clause,
1214
* - this RTE should be checked for appropriate access rights.
1216
* Functions are never checked for access rights (at least, not by
1217
* the RTE permissions mechanism).
1220
rte->inh = false; /* never true for functions */
1221
rte->inFromCl = inFromCl;
1223
rte->requiredPerms = 0;
1224
rte->checkAsUser = InvalidOid;
1225
rte->selectedCols = NULL;
1226
rte->modifiedCols = NULL;
1229
* Add completed RTE to pstate's range table list, but not to join list
1230
* nor namespace --- caller must do that if appropriate.
1233
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1239
* Add an entry for a VALUES list to the pstate's range table (p_rtable).
1241
* This is much like addRangeTableEntry() except that it makes a values RTE.
1244
addRangeTableEntryForValues(ParseState *pstate,
1249
RangeTblEntry *rte = makeNode(RangeTblEntry);
1250
char *refname = alias ? alias->aliasname : pstrdup("*VALUES*");
1255
rte->rtekind = RTE_VALUES;
1256
rte->relid = InvalidOid;
1257
rte->subquery = NULL;
1258
rte->values_lists = exprs;
1261
eref = alias ? copyObject(alias) : makeAlias(refname, NIL);
1263
/* fill in any unspecified alias columns */
1264
numcolumns = list_length((List *) linitial(exprs));
1265
numaliases = list_length(eref->colnames);
1266
while (numaliases < numcolumns)
1271
snprintf(attrname, sizeof(attrname), "column%d", numaliases);
1272
eref->colnames = lappend(eref->colnames,
1273
makeString(pstrdup(attrname)));
1275
if (numcolumns < numaliases)
1277
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1278
errmsg("VALUES lists \"%s\" have %d columns available but %d columns specified",
1279
refname, numcolumns, numaliases)));
1285
* - this RTE should be expanded to include descendant tables,
1286
* - this RTE is in the FROM clause,
1287
* - this RTE should be checked for appropriate access rights.
1289
* Subqueries are never checked for access rights.
1292
rte->inh = false; /* never true for values RTEs */
1293
rte->inFromCl = inFromCl;
1295
rte->requiredPerms = 0;
1296
rte->checkAsUser = InvalidOid;
1297
rte->selectedCols = NULL;
1298
rte->modifiedCols = NULL;
1301
* Add completed RTE to pstate's range table list, but not to join list
1302
* nor namespace --- caller must do that if appropriate.
1305
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1311
* Add an entry for a join to the pstate's range table (p_rtable).
1313
* This is much like addRangeTableEntry() except that it makes a join RTE.
1316
addRangeTableEntryForJoin(ParseState *pstate,
1323
RangeTblEntry *rte = makeNode(RangeTblEntry);
1328
* Fail if join has too many columns --- we must be able to reference
1329
* any of the columns with an AttrNumber.
1331
if (list_length(aliasvars) > MaxAttrNumber)
1333
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1334
errmsg("joins can have at most %d columns",
1337
rte->rtekind = RTE_JOIN;
1338
rte->relid = InvalidOid;
1339
rte->subquery = NULL;
1340
rte->jointype = jointype;
1341
rte->joinaliasvars = aliasvars;
1344
eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
1345
numaliases = list_length(eref->colnames);
1347
/* fill in any unspecified alias columns */
1348
if (numaliases < list_length(colnames))
1349
eref->colnames = list_concat(eref->colnames,
1350
list_copy_tail(colnames, numaliases));
1356
* - this RTE should be expanded to include descendant tables,
1357
* - this RTE is in the FROM clause,
1358
* - this RTE should be checked for appropriate access rights.
1360
* Joins are never checked for access rights.
1363
rte->inh = false; /* never true for joins */
1364
rte->inFromCl = inFromCl;
1366
rte->requiredPerms = 0;
1367
rte->checkAsUser = InvalidOid;
1368
rte->selectedCols = NULL;
1369
rte->modifiedCols = NULL;
1372
* Add completed RTE to pstate's range table list, but not to join list
1373
* nor namespace --- caller must do that if appropriate.
1376
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1382
* Add an entry for a CTE reference to the pstate's range table (p_rtable).
1384
* This is much like addRangeTableEntry() except that it makes a CTE RTE.
1387
addRangeTableEntryForCTE(ParseState *pstate,
1388
CommonTableExpr *cte,
1393
RangeTblEntry *rte = makeNode(RangeTblEntry);
1394
char *refname = alias ? alias->aliasname : cte->ctename;
1400
rte->rtekind = RTE_CTE;
1401
rte->ctename = cte->ctename;
1402
rte->ctelevelsup = levelsup;
1404
/* Self-reference if and only if CTE's parse analysis isn't completed */
1405
rte->self_reference = !IsA(cte->ctequery, Query);
1406
Assert(cte->cterecursive || !rte->self_reference);
1407
/* Bump the CTE's refcount if this isn't a self-reference */
1408
if (!rte->self_reference)
1411
rte->ctecoltypes = cte->ctecoltypes;
1412
rte->ctecoltypmods = cte->ctecoltypmods;
1416
eref = copyObject(alias);
1418
eref = makeAlias(refname, NIL);
1419
numaliases = list_length(eref->colnames);
1421
/* fill in any unspecified alias columns */
1423
foreach(lc, cte->ctecolnames)
1426
if (varattno > numaliases)
1427
eref->colnames = lappend(eref->colnames, lfirst(lc));
1429
if (varattno < numaliases)
1431
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1432
errmsg("table \"%s\" has %d columns available but %d columns specified",
1433
refname, varattno, numaliases)));
1439
* - this RTE should be expanded to include descendant tables,
1440
* - this RTE is in the FROM clause,
1441
* - this RTE should be checked for appropriate access rights.
1443
* Subqueries are never checked for access rights.
1446
rte->inh = false; /* never true for subqueries */
1447
rte->inFromCl = inFromCl;
1449
rte->requiredPerms = 0;
1450
rte->checkAsUser = InvalidOid;
1451
rte->selectedCols = NULL;
1452
rte->modifiedCols = NULL;
1455
* Add completed RTE to pstate's range table list, but not to join list
1456
* nor namespace --- caller must do that if appropriate.
1459
pstate->p_rtable = lappend(pstate->p_rtable, rte);
1466
* Has the specified refname been selected FOR UPDATE/FOR SHARE?
1468
* Note: we pay no attention to whether it's FOR UPDATE vs FOR SHARE.
1471
isLockedRel(ParseState *pstate, char *refname)
1473
/* Outer loop to check parent query levels as well as this one */
1474
while (pstate != NULL)
1478
foreach(l, pstate->p_locking_clause)
1480
LockingClause *lc = (LockingClause *) lfirst(l);
1482
if (lc->lockedRels == NIL)
1484
/* all tables used in query */
1489
/* just the named tables */
1492
foreach(l2, lc->lockedRels)
1494
RangeVar *thisrel = (RangeVar *) lfirst(l2);
1496
if (strcmp(refname, thisrel->relname) == 0)
1501
pstate = pstate->parentParseState;
1507
* Add the given RTE as a top-level entry in the pstate's join list
1508
* and/or name space lists. (We assume caller has checked for any
1509
* namespace conflicts.)
1512
addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
1514
bool addToRelNameSpace, bool addToVarNameSpace)
1518
int rtindex = RTERangeTablePosn(pstate, rte, NULL);
1519
RangeTblRef *rtr = makeNode(RangeTblRef);
1521
rtr->rtindex = rtindex;
1522
pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1524
if (addToRelNameSpace)
1525
pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1526
if (addToVarNameSpace)
1527
pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1531
* Add a POSTQUEL-style implicit RTE.
1533
* We assume caller has already checked that there is no RTE or join with
1534
* a conflicting name.
1537
addImplicitRTE(ParseState *pstate, RangeVar *relation)
1539
CommonTableExpr *cte = NULL;
1543
/* issue warning or error as needed */
1544
warnAutoRange(pstate, relation);
1546
/* if it is an unqualified name, it might be a CTE reference */
1547
if (!relation->schemaname)
1548
cte = scanNameSpaceForCTE(pstate, relation->relname, &levelsup);
1551
* Note that we set inFromCl true, so that the RTE will be listed
1552
* explicitly if the parsetree is ever decompiled by ruleutils.c. This
1553
* provides a migration path for views/rules that were originally written
1554
* with implicit-RTE syntax.
1557
rte = addRangeTableEntryForCTE(pstate, cte, levelsup, NULL, true);
1559
rte = addRangeTableEntry(pstate, relation, NULL, false, true);
1560
/* Add to joinlist and relnamespace, but not varnamespace */
1561
addRTEtoQuery(pstate, rte, true, true, false);
1567
* expandRTE -- expand the columns of a rangetable entry
1569
* This creates lists of an RTE's column names (aliases if provided, else
1570
* real names) and Vars for each column. Only user columns are considered.
1571
* If include_dropped is FALSE then dropped columns are omitted from the
1572
* results. If include_dropped is TRUE then empty strings and NULL constants
1573
* (not Vars!) are returned for dropped columns.
1575
* rtindex, sublevels_up, and location are the varno, varlevelsup, and location
1576
* values to use in the created Vars. Ordinarily rtindex should match the
1577
* actual position of the RTE in its rangetable.
1579
* The output lists go into *colnames and *colvars.
1580
* If only one of the two kinds of output list is needed, pass NULL for the
1581
* output pointer for the unwanted one.
1584
expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
1585
int location, bool include_dropped,
1586
List **colnames, List **colvars)
1595
switch (rte->rtekind)
1598
/* Ordinary relation RTE */
1599
expandRelation(rte->relid, rte->eref,
1600
rtindex, sublevels_up, location,
1601
include_dropped, colnames, colvars);
1606
ListCell *aliasp_item = list_head(rte->eref->colnames);
1607
ListCell *tlistitem;
1610
foreach(tlistitem, rte->subquery->targetList)
1612
TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1617
Assert(varattno == te->resno);
1621
/* Assume there is one alias per target item */
1622
char *label = strVal(lfirst(aliasp_item));
1624
*colnames = lappend(*colnames, makeString(pstrdup(label)));
1625
aliasp_item = lnext(aliasp_item);
1632
varnode = makeVar(rtindex, varattno,
1633
exprType((Node *) te->expr),
1634
exprTypmod((Node *) te->expr),
1636
varnode->location = location;
1638
*colvars = lappend(*colvars, varnode);
1646
TypeFuncClass functypclass;
1650
functypclass = get_expr_result_type(rte->funcexpr,
1653
if (functypclass == TYPEFUNC_COMPOSITE)
1655
/* Composite data type, e.g. a table's row type */
1657
expandTupleDesc(tupdesc, rte->eref,
1658
rtindex, sublevels_up, location,
1659
include_dropped, colnames, colvars);
1661
else if (functypclass == TYPEFUNC_SCALAR)
1663
/* Base data type, i.e. scalar */
1665
*colnames = lappend(*colnames,
1666
linitial(rte->eref->colnames));
1672
varnode = makeVar(rtindex, 1,
1675
varnode->location = location;
1677
*colvars = lappend(*colvars, varnode);
1680
else if (functypclass == TYPEFUNC_RECORD)
1683
*colnames = copyObject(rte->eref->colnames);
1690
forboth(l1, rte->funccoltypes, l2, rte->funccoltypmods)
1692
Oid attrtype = lfirst_oid(l1);
1693
int32 attrtypmod = lfirst_int(l2);
1697
varnode = makeVar(rtindex,
1702
varnode->location = location;
1703
*colvars = lappend(*colvars, varnode);
1709
/* addRangeTableEntryForFunction should've caught this */
1710
elog(ERROR, "function in FROM has unsupported return type");
1717
ListCell *aliasp_item = list_head(rte->eref->colnames);
1721
foreach(lc, (List *) linitial(rte->values_lists))
1723
Node *col = (Node *) lfirst(lc);
1728
/* Assume there is one alias per column */
1729
char *label = strVal(lfirst(aliasp_item));
1731
*colnames = lappend(*colnames,
1732
makeString(pstrdup(label)));
1733
aliasp_item = lnext(aliasp_item);
1740
varnode = makeVar(rtindex, varattno,
1744
varnode->location = location;
1745
*colvars = lappend(*colvars, varnode);
1756
Assert(list_length(rte->eref->colnames) == list_length(rte->joinaliasvars));
1759
forboth(colname, rte->eref->colnames, aliasvar, rte->joinaliasvars)
1761
Node *avar = (Node *) lfirst(aliasvar);
1766
* During ordinary parsing, there will never be any
1767
* deleted columns in the join; but we have to check since
1768
* this routine is also used by the rewriter, and joins
1769
* found in stored rules might have join columns for
1770
* since-deleted columns. This will be signaled by a NULL
1771
* Const in the alias-vars list.
1773
if (IsA(avar, Const))
1775
if (include_dropped)
1778
*colnames = lappend(*colnames,
1779
makeString(pstrdup("")));
1781
*colvars = lappend(*colvars,
1789
char *label = strVal(lfirst(colname));
1791
*colnames = lappend(*colnames,
1792
makeString(pstrdup(label)));
1799
varnode = makeVar(rtindex, varattno,
1803
varnode->location = location;
1805
*colvars = lappend(*colvars, varnode);
1812
ListCell *aliasp_item = list_head(rte->eref->colnames);
1817
forboth(lct, rte->ctecoltypes, lcm, rte->ctecoltypmods)
1819
Oid coltype = lfirst_oid(lct);
1820
int32 coltypmod = lfirst_int(lcm);
1826
/* Assume there is one alias per output column */
1827
char *label = strVal(lfirst(aliasp_item));
1829
*colnames = lappend(*colnames, makeString(pstrdup(label)));
1830
aliasp_item = lnext(aliasp_item);
1837
varnode = makeVar(rtindex, varattno,
1840
*colvars = lappend(*colvars, varnode);
1846
elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
1851
* expandRelation -- expandRTE subroutine
1854
expandRelation(Oid relid, Alias *eref, int rtindex, int sublevels_up,
1855
int location, bool include_dropped,
1856
List **colnames, List **colvars)
1860
/* Get the tupledesc and turn it over to expandTupleDesc */
1861
rel = relation_open(relid, AccessShareLock);
1862
expandTupleDesc(rel->rd_att, eref, rtindex, sublevels_up,
1863
location, include_dropped,
1865
relation_close(rel, AccessShareLock);
1869
* expandTupleDesc -- expandRTE subroutine
1872
expandTupleDesc(TupleDesc tupdesc, Alias *eref,
1873
int rtindex, int sublevels_up,
1874
int location, bool include_dropped,
1875
List **colnames, List **colvars)
1877
int maxattrs = tupdesc->natts;
1878
int numaliases = list_length(eref->colnames);
1881
for (varattno = 0; varattno < maxattrs; varattno++)
1883
Form_pg_attribute attr = tupdesc->attrs[varattno];
1885
if (attr->attisdropped)
1887
if (include_dropped)
1890
*colnames = lappend(*colnames, makeString(pstrdup("")));
1894
* can't use atttypid here, but it doesn't really matter
1895
* what type the Const claims to be.
1897
*colvars = lappend(*colvars, makeNullConst(INT4OID, -1));
1907
if (varattno < numaliases)
1908
label = strVal(list_nth(eref->colnames, varattno));
1910
label = NameStr(attr->attname);
1911
*colnames = lappend(*colnames, makeString(pstrdup(label)));
1918
varnode = makeVar(rtindex, attr->attnum,
1919
attr->atttypid, attr->atttypmod,
1921
varnode->location = location;
1923
*colvars = lappend(*colvars, varnode);
1930
* Workhorse for "*" expansion: produce a list of targetentries
1931
* for the attributes of the RTE
1933
* As with expandRTE, rtindex/sublevels_up determine the varno/varlevelsup
1934
* fields of the Vars produced, and location sets their location.
1935
* pstate->p_next_resno determines the resnos assigned to the TLEs.
1936
* The referenced columns are marked as requiring SELECT access.
1939
expandRelAttrs(ParseState *pstate, RangeTblEntry *rte,
1940
int rtindex, int sublevels_up, int location)
1946
List *te_list = NIL;
1948
expandRTE(rte, rtindex, sublevels_up, location, false,
1952
* Require read access to the table. This is normally redundant with the
1953
* markVarForSelectPriv calls below, but not if the table has zero
1956
rte->requiredPerms |= ACL_SELECT;
1958
forboth(name, names, var, vars)
1960
char *label = strVal(lfirst(name));
1961
Var *varnode = (Var *) lfirst(var);
1964
te = makeTargetEntry((Expr *) varnode,
1965
(AttrNumber) pstate->p_next_resno++,
1968
te_list = lappend(te_list, te);
1970
/* Require read access to each column */
1971
markVarForSelectPriv(pstate, varnode, rte);
1974
Assert(name == NULL && var == NULL); /* lists not the same length? */
1980
* get_rte_attribute_name
1981
* Get an attribute name from a RangeTblEntry
1983
* This is unlike get_attname() because we use aliases if available.
1984
* In particular, it will work on an RTE for a subselect or join, whereas
1985
* get_attname() only works on real relations.
1987
* "*" is returned if the given attnum is InvalidAttrNumber --- this case
1988
* occurs when a Var represents a whole tuple of a relation.
1991
get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
1993
if (attnum == InvalidAttrNumber)
1997
* If there is a user-written column alias, use it.
2000
attnum > 0 && attnum <= list_length(rte->alias->colnames))
2001
return strVal(list_nth(rte->alias->colnames, attnum - 1));
2004
* If the RTE is a relation, go to the system catalogs not the
2005
* eref->colnames list. This is a little slower but it will give the
2006
* right answer if the column has been renamed since the eref list was
2007
* built (which can easily happen for rules).
2009
if (rte->rtekind == RTE_RELATION)
2010
return get_relid_attribute_name(rte->relid, attnum);
2013
* Otherwise use the column name from eref. There should always be one.
2015
if (attnum > 0 && attnum <= list_length(rte->eref->colnames))
2016
return strVal(list_nth(rte->eref->colnames, attnum - 1));
2018
/* else caller gave us a bogus attnum */
2019
elog(ERROR, "invalid attnum %d for rangetable entry %s",
2020
attnum, rte->eref->aliasname);
2021
return NULL; /* keep compiler quiet */
2025
* get_rte_attribute_type
2026
* Get attribute type information from a RangeTblEntry
2029
get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
2030
Oid *vartype, int32 *vartypmod)
2032
switch (rte->rtekind)
2036
/* Plain relation RTE --- get the attribute's type info */
2038
Form_pg_attribute att_tup;
2040
tp = SearchSysCache(ATTNUM,
2041
ObjectIdGetDatum(rte->relid),
2042
Int16GetDatum(attnum),
2044
if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2045
elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2046
attnum, rte->relid);
2047
att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2050
* If dropped column, pretend it ain't there. See notes in
2053
if (att_tup->attisdropped)
2055
(errcode(ERRCODE_UNDEFINED_COLUMN),
2056
errmsg("column \"%s\" of relation \"%s\" does not exist",
2057
NameStr(att_tup->attname),
2058
get_rel_name(rte->relid))));
2059
*vartype = att_tup->atttypid;
2060
*vartypmod = att_tup->atttypmod;
2061
ReleaseSysCache(tp);
2066
/* Subselect RTE --- get type info from subselect's tlist */
2067
TargetEntry *te = get_tle_by_resno(rte->subquery->targetList,
2070
if (te == NULL || te->resjunk)
2071
elog(ERROR, "subquery %s does not have attribute %d",
2072
rte->eref->aliasname, attnum);
2073
*vartype = exprType((Node *) te->expr);
2074
*vartypmod = exprTypmod((Node *) te->expr);
2080
TypeFuncClass functypclass;
2084
functypclass = get_expr_result_type(rte->funcexpr,
2088
if (functypclass == TYPEFUNC_COMPOSITE)
2090
/* Composite data type, e.g. a table's row type */
2091
Form_pg_attribute att_tup;
2094
/* this is probably a can't-happen case */
2095
if (attnum < 1 || attnum > tupdesc->natts)
2097
(errcode(ERRCODE_UNDEFINED_COLUMN),
2098
errmsg("column %d of relation \"%s\" does not exist",
2100
rte->eref->aliasname)));
2102
att_tup = tupdesc->attrs[attnum - 1];
2105
* If dropped column, pretend it ain't there. See notes
2106
* in scanRTEForColumn.
2108
if (att_tup->attisdropped)
2110
(errcode(ERRCODE_UNDEFINED_COLUMN),
2111
errmsg("column \"%s\" of relation \"%s\" does not exist",
2112
NameStr(att_tup->attname),
2113
rte->eref->aliasname)));
2114
*vartype = att_tup->atttypid;
2115
*vartypmod = att_tup->atttypmod;
2117
else if (functypclass == TYPEFUNC_SCALAR)
2119
/* Base data type, i.e. scalar */
2120
*vartype = funcrettype;
2123
else if (functypclass == TYPEFUNC_RECORD)
2125
*vartype = list_nth_oid(rte->funccoltypes, attnum - 1);
2126
*vartypmod = list_nth_int(rte->funccoltypmods, attnum - 1);
2130
/* addRangeTableEntryForFunction should've caught this */
2131
elog(ERROR, "function in FROM has unsupported return type");
2137
/* Values RTE --- get type info from first sublist */
2138
List *collist = (List *) linitial(rte->values_lists);
2141
if (attnum < 1 || attnum > list_length(collist))
2142
elog(ERROR, "values list %s does not have attribute %d",
2143
rte->eref->aliasname, attnum);
2144
col = (Node *) list_nth(collist, attnum - 1);
2145
*vartype = exprType(col);
2146
*vartypmod = exprTypmod(col);
2152
* Join RTE --- get type info from join RTE's alias variable
2156
Assert(attnum > 0 && attnum <= list_length(rte->joinaliasvars));
2157
aliasvar = (Node *) list_nth(rte->joinaliasvars, attnum - 1);
2158
*vartype = exprType(aliasvar);
2159
*vartypmod = exprTypmod(aliasvar);
2164
/* CTE RTE --- get type info from lists in the RTE */
2165
Assert(attnum > 0 && attnum <= list_length(rte->ctecoltypes));
2166
*vartype = list_nth_oid(rte->ctecoltypes, attnum - 1);
2167
*vartypmod = list_nth_int(rte->ctecoltypmods, attnum - 1);
2171
elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2176
* get_rte_attribute_is_dropped
2177
* Check whether attempted attribute ref is to a dropped column
2180
get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
2184
switch (rte->rtekind)
2189
* Plain relation RTE --- get the attribute's catalog entry
2192
Form_pg_attribute att_tup;
2194
tp = SearchSysCache(ATTNUM,
2195
ObjectIdGetDatum(rte->relid),
2196
Int16GetDatum(attnum),
2198
if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2199
elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2200
attnum, rte->relid);
2201
att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2202
result = att_tup->attisdropped;
2203
ReleaseSysCache(tp);
2209
/* Subselect, Values, CTE RTEs never have dropped columns */
2215
* A join RTE would not have dropped columns when constructed,
2216
* but one in a stored rule might contain columns that were
2217
* dropped from the underlying tables, if said columns are
2218
* nowhere explicitly referenced in the rule. This will be
2219
* signaled to us by a NULL Const in the joinaliasvars list.
2224
attnum > list_length(rte->joinaliasvars))
2225
elog(ERROR, "invalid varattno %d", attnum);
2226
aliasvar = (Var *) list_nth(rte->joinaliasvars, attnum - 1);
2228
result = IsA(aliasvar, Const);
2234
Oid funcrettype = exprType(rte->funcexpr);
2235
Oid funcrelid = typeidTypeRelid(funcrettype);
2237
if (OidIsValid(funcrelid))
2240
* Composite data type, i.e. a table's row type
2242
* Same as ordinary relation RTE
2245
Form_pg_attribute att_tup;
2247
tp = SearchSysCache(ATTNUM,
2248
ObjectIdGetDatum(funcrelid),
2249
Int16GetDatum(attnum),
2251
if (!HeapTupleIsValid(tp)) /* shouldn't happen */
2252
elog(ERROR, "cache lookup failed for attribute %d of relation %u",
2254
att_tup = (Form_pg_attribute) GETSTRUCT(tp);
2255
result = att_tup->attisdropped;
2256
ReleaseSysCache(tp);
2261
* Must be a base data type, i.e. scalar
2268
elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2269
result = false; /* keep compiler quiet */
2276
* Given a targetlist and a resno, return the matching TargetEntry
2278
* Returns NULL if resno is not present in list.
2280
* Note: we need to search, rather than just indexing with list_nth(),
2281
* because not all tlists are sorted by resno.
2284
get_tle_by_resno(List *tlist, AttrNumber resno)
2290
TargetEntry *tle = (TargetEntry *) lfirst(l);
2292
if (tle->resno == resno)
2299
* Given a Query and rangetable index, return relation's RowMarkClause if any
2301
* Returns NULL if relation is not selected FOR UPDATE/SHARE
2304
get_rowmark(Query *qry, Index rtindex)
2308
foreach(l, qry->rowMarks)
2310
RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2312
if (rc->rti == rtindex)
2319
* given relation and att name, return attnum of variable
2321
* Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
2323
* This should only be used if the relation is already
2324
* heap_open()'ed. Use the cache version get_attnum()
2325
* for access to non-opened relations.
2328
attnameAttNum(Relation rd, const char *attname, bool sysColOK)
2332
for (i = 0; i < rd->rd_rel->relnatts; i++)
2334
Form_pg_attribute att = rd->rd_att->attrs[i];
2336
if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
2342
if ((i = specialAttNum(attname)) != InvalidAttrNumber)
2344
if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
2350
return InvalidAttrNumber;
2355
* Check attribute name to see if it is "special", e.g. "oid".
2356
* - thomas 2000-02-07
2358
* Note: this only discovers whether the name could be a system attribute.
2359
* Caller needs to verify that it really is an attribute of the rel,
2360
* at least in the case of "oid", which is now optional.
2363
specialAttNum(const char *attname)
2365
Form_pg_attribute sysatt;
2367
sysatt = SystemAttributeByName(attname,
2368
true /* "oid" will be accepted */ );
2370
return sysatt->attnum;
2371
return InvalidAttrNumber;
2376
* given attribute id, return name of that attribute
2378
* This should only be used if the relation is already
2379
* heap_open()'ed. Use the cache version get_atttype()
2380
* for access to non-opened relations.
2383
attnumAttName(Relation rd, int attid)
2387
Form_pg_attribute sysatt;
2389
sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2390
return &sysatt->attname;
2392
if (attid > rd->rd_att->natts)
2393
elog(ERROR, "invalid attribute number %d", attid);
2394
return &rd->rd_att->attrs[attid - 1]->attname;
2398
* given attribute id, return type of that attribute
2400
* This should only be used if the relation is already
2401
* heap_open()'ed. Use the cache version get_atttype()
2402
* for access to non-opened relations.
2405
attnumTypeId(Relation rd, int attid)
2409
Form_pg_attribute sysatt;
2411
sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
2412
return sysatt->atttypid;
2414
if (attid > rd->rd_att->natts)
2415
elog(ERROR, "invalid attribute number %d", attid);
2416
return rd->rd_att->attrs[attid - 1]->atttypid;
2420
* Generate a warning or error about an implicit RTE, if appropriate.
2422
* If ADD_MISSING_FROM is not enabled, raise an error. Otherwise, emit
2426
warnAutoRange(ParseState *pstate, RangeVar *relation)
2430
const char *badAlias = NULL;
2433
* Check to see if there are any potential matches in the query's
2434
* rangetable. This affects the message we provide.
2436
rte = searchRangeTable(pstate, relation);
2439
* If we found a match that has an alias and the alias is visible in the
2440
* namespace, then the problem is probably use of the relation's real name
2441
* instead of its alias, ie "SELECT foo.* FROM foo f". This mistake is
2442
* common enough to justify a specific hint.
2444
* If we found a match that doesn't meet those criteria, assume the
2445
* problem is illegal use of a relation outside its scope, as in the
2446
* MySQL-ism "SELECT ... FROM a, b LEFT JOIN c ON (a.x = c.y)".
2448
if (rte && rte->alias &&
2449
strcmp(rte->eref->aliasname, relation->relname) != 0 &&
2450
refnameRangeTblEntry(pstate, NULL, rte->eref->aliasname,
2452
&sublevels_up) == rte)
2453
badAlias = rte->eref->aliasname;
2455
if (!add_missing_from)
2459
(errcode(ERRCODE_UNDEFINED_TABLE),
2460
errmsg("invalid reference to FROM-clause entry for table \"%s\"",
2463
errhint("Perhaps you meant to reference the table alias \"%s\".",
2465
errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2466
rte->eref->aliasname)),
2467
parser_errposition(pstate, relation->location)));
2470
(errcode(ERRCODE_UNDEFINED_TABLE),
2471
errmsg("missing FROM-clause entry for table \"%s\"",
2473
parser_errposition(pstate, relation->location)));
2477
/* just issue a warning */
2479
(errcode(ERRCODE_UNDEFINED_TABLE),
2480
errmsg("adding missing FROM-clause entry for table \"%s\"",
2483
errhint("Perhaps you meant to reference the table alias \"%s\".",
2486
errhint("There is an entry for table \"%s\", but it cannot be referenced from this part of the query.",
2487
rte->eref->aliasname) : 0)),
2488
parser_errposition(pstate, relation->location)));