parse_relation.c 47.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * parse_relation.c
4 5
 *	  parser support routines dealing with relations
 *
Bruce Momjian's avatar
Bruce Momjian committed
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/parser/parse_relation.c,v 1.80 2002/12/12 15:49:39 tgl Exp $
12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
16

17 18
#include <ctype.h>

19
#include "access/heapam.h"
Bruce Momjian's avatar
Bruce Momjian committed
20
#include "access/htup.h"
21
#include "catalog/heap.h"
22
#include "catalog/namespace.h"
Bruce Momjian's avatar
Bruce Momjian committed
23
#include "catalog/pg_type.h"
24
#include "nodes/makefuncs.h"
25
#include "parser/parsetree.h"
26
#include "parser/parse_coerce.h"
27
#include "parser/parse_expr.h"
Bruce Momjian's avatar
Bruce Momjian committed
28 29
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
30
#include "rewrite/rewriteManip.h"
31
#include "utils/builtins.h"
Bruce Momjian's avatar
Bruce Momjian committed
32
#include "utils/lsyscache.h"
33
#include "utils/syscache.h"
34

35

36
static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
37 38
						const char *refname);
static Node *scanNameSpaceForRelid(ParseState *pstate, Node *nsnode,
Bruce Momjian's avatar
Bruce Momjian committed
39
					  Oid relid);
40 41
static void scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
						 RangeTblEntry *rte1, const char *aliasname1);
42
static Node *scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
43
				 char *colname);
44
static bool isForUpdate(ParseState *pstate, char *refname);
45
static bool get_rte_attribute_is_dropped(RangeTblEntry *rte,
Bruce Momjian's avatar
Bruce Momjian committed
46
							 AttrNumber attnum);
47
static int	specialAttNum(const char *attname);
48
static void warnAutoRange(ParseState *pstate, RangeVar *relation);
49 50 51


/*
52
 * refnameRangeTblEntry
53 54 55 56 57 58 59 60 61 62 63 64 65 66
 *	  Given a possibly-qualified refname, look to see if it matches any RTE.
 *	  If so, return a pointer to the RangeTblEntry; else return NULL.
 *
 *	  Optionally get RTE's nesting depth (0 = current) into *sublevels_up.
 *	  If sublevels_up is NULL, only consider items at the current nesting
 *	  level.
 *
 * An unqualified refname (schemaname == NULL) can match any RTE with matching
 * alias, or matching unqualified relname in the case of alias-less relation
 * RTEs.  It is possible that such a refname matches multiple RTEs in the
 * nearest nesting level that has a match; if so, we report an error via elog.
 *
 * A qualified refname (schemaname != NULL) can only match a relation RTE
 * that (a) has no alias and (b) is for the same relation identified by
Bruce Momjian's avatar
Bruce Momjian committed
67
 * schemaname.refname.	In this case we convert schemaname.refname to a
68 69
 * relation OID and search by relid, rather than by alias name.  This is
 * peculiar, but it's what SQL92 says to do.
70
 */
71 72
RangeTblEntry *
refnameRangeTblEntry(ParseState *pstate,
73 74
					 const char *schemaname,
					 const char *refname,
75
					 int *sublevels_up)
76
{
77 78
	Oid			relId = InvalidOid;

79 80
	if (sublevels_up)
		*sublevels_up = 0;
81

82 83 84 85 86 87 88 89 90 91
	if (schemaname != NULL)
	{
		Oid			namespaceId;

		namespaceId = LookupExplicitNamespace(schemaname);
		relId = get_relname_relid(refname, namespaceId);
		if (!OidIsValid(relId))
			return NULL;
	}

92 93
	while (pstate != NULL)
	{
94
		Node	   *nsnode;
95

96 97 98 99 100 101 102 103 104
		if (OidIsValid(relId))
			nsnode = scanNameSpaceForRelid(pstate,
										   (Node *) pstate->p_namespace,
										   relId);
		else
			nsnode = scanNameSpaceForRefname(pstate,
											 (Node *) pstate->p_namespace,
											 refname);

105 106 107 108 109 110 111 112
		if (nsnode)
		{
			/* should get an RTE or JoinExpr */
			if (IsA(nsnode, RangeTblEntry))
				return (RangeTblEntry *) nsnode;
			Assert(IsA(nsnode, JoinExpr));
			return rt_fetch(((JoinExpr *) nsnode)->rtindex, pstate->p_rtable);
		}
113

114
		pstate = pstate->parentParseState;
115 116 117 118
		if (sublevels_up)
			(*sublevels_up)++;
		else
			break;
119
	}
120
	return NULL;
121 122
}

123
/*
124 125 126
 * Recursively search a namespace for an RTE or joinexpr matching the
 * given unqualified refname.  Return the node if a unique match, or NULL
 * if no match.  Raise error if multiple matches.
127 128
 *
 * The top level of p_namespace is a list, and we recurse into any joins
129
 * that are not subqueries.
130
 */
131 132
static Node *
scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
133
						const char *refname)
134
{
135
	Node	   *result = NULL;
136
	Node	   *newresult;
137

138
	if (nsnode == NULL)
139
		return NULL;
140
	if (IsA(nsnode, RangeTblRef))
141
	{
142 143
		int			varno = ((RangeTblRef *) nsnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
144

145
		if (strcmp(rte->eref->aliasname, refname) == 0)
146
			result = (Node *) rte;
147
	}
148
	else if (IsA(nsnode, JoinExpr))
149
	{
150 151 152 153
		JoinExpr   *j = (JoinExpr *) nsnode;

		if (j->alias)
		{
154
			if (strcmp(j->alias->aliasname, refname) == 0)
155 156
				return (Node *) j;		/* matched a join alias */

157 158 159 160 161 162 163 164
			/*
			 * Tables within an aliased join are invisible from outside
			 * the join, according to the scope rules of SQL92 (the join
			 * is considered a subquery).  So, stop here.
			 */
			return NULL;
		}
		result = scanNameSpaceForRefname(pstate, j->larg, refname);
165
		newresult = scanNameSpaceForRefname(pstate, j->rarg, refname);
166
		if (!result)
167 168 169
			result = newresult;
		else if (newresult)
			elog(ERROR, "Table reference \"%s\" is ambiguous", refname);
170
	}
171
	else if (IsA(nsnode, List))
172
	{
173
		List	   *l;
174

175 176
		foreach(l, (List *) nsnode)
		{
177 178 179 180 181
			newresult = scanNameSpaceForRefname(pstate, lfirst(l), refname);
			if (!result)
				result = newresult;
			else if (newresult)
				elog(ERROR, "Table reference \"%s\" is ambiguous", refname);
182
		}
183 184
	}
	else
185 186
		elog(ERROR, "scanNameSpaceForRefname: unexpected node type %d",
			 nodeTag(nsnode));
187 188 189
	return result;
}

190 191
/*
 * Recursively search a namespace for a relation RTE matching the
Bruce Momjian's avatar
Bruce Momjian committed
192
 * given relation OID.	Return the node if a unique match, or NULL
193 194 195 196 197 198 199 200 201 202 203
 * if no match.  Raise error if multiple matches (which shouldn't
 * happen if the namespace was checked correctly when it was created).
 *
 * The top level of p_namespace is a list, and we recurse into any joins
 * that are not subqueries.
 *
 * See the comments for refnameRangeTblEntry to understand why this
 * acts the way it does.
 */
static Node *
scanNameSpaceForRelid(ParseState *pstate, Node *nsnode, Oid relid)
204
{
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
	Node	   *result = NULL;
	Node	   *newresult;

	if (nsnode == NULL)
		return NULL;
	if (IsA(nsnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) nsnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);

		/* yes, the test for alias==NULL should be there... */
		if (rte->rtekind == RTE_RELATION &&
			rte->relid == relid &&
			rte->alias == NULL)
			result = (Node *) rte;
	}
	else if (IsA(nsnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) nsnode;

		if (j->alias)
		{
			/*
			 * Tables within an aliased join are invisible from outside
			 * the join, according to the scope rules of SQL92 (the join
			 * is considered a subquery).  So, stop here.
			 */
			return NULL;
		}
		result = scanNameSpaceForRelid(pstate, j->larg, relid);
		newresult = scanNameSpaceForRelid(pstate, j->rarg, relid);
		if (!result)
			result = newresult;
		else if (newresult)
			elog(ERROR, "Table reference %u is ambiguous", relid);
	}
	else if (IsA(nsnode, List))
	{
		List	   *l;

		foreach(l, (List *) nsnode)
		{
			newresult = scanNameSpaceForRelid(pstate, lfirst(l), relid);
			if (!result)
				result = newresult;
			else if (newresult)
				elog(ERROR, "Table reference %u is ambiguous", relid);
		}
	}
	else
		elog(ERROR, "scanNameSpaceForRelid: unexpected node type %d",
			 nodeTag(nsnode));
	return result;
258 259
}

260
/*
261
 * Recursively check for name conflicts between two namespaces or
262
 * namespace subtrees.	Raise an error if any is found.
263
 *
264 265
 * Works by recursively scanning namespace1 for RTEs and join nodes,
 * and for each one recursively scanning namespace2 for a match.
266
 *
267 268
 * Note: we assume that each given argument does not contain conflicts
 * itself; we just want to know if the two can be merged together.
269 270 271 272
 *
 * Per SQL92, two alias-less plain relation RTEs do not conflict even if
 * they have the same eref->aliasname (ie, same relation name), if they
 * are for different relation OIDs (implying they are in different schemas).
273
 */
274 275 276
void
checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
						Node *namespace2)
277
{
278 279 280 281 282 283
	if (namespace1 == NULL)
		return;
	if (IsA(namespace1, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) namespace1)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
284

285 286 287 288 289 290
		if (rte->rtekind == RTE_RELATION && rte->alias == NULL)
			scanNameSpaceForConflict(pstate, namespace2,
									 rte, rte->eref->aliasname);
		else
			scanNameSpaceForConflict(pstate, namespace2,
									 NULL, rte->eref->aliasname);
291 292
	}
	else if (IsA(namespace1, JoinExpr))
293
	{
294 295 296
		JoinExpr   *j = (JoinExpr *) namespace1;

		if (j->alias)
297
		{
298 299
			scanNameSpaceForConflict(pstate, namespace2,
									 NULL, j->alias->aliasname);
300

301 302 303 304 305 306 307 308 309 310 311 312 313
			/*
			 * Tables within an aliased join are invisible from outside
			 * the join, according to the scope rules of SQL92 (the join
			 * is considered a subquery).  So, stop here.
			 */
			return;
		}
		checkNameSpaceConflicts(pstate, j->larg, namespace2);
		checkNameSpaceConflicts(pstate, j->rarg, namespace2);
	}
	else if (IsA(namespace1, List))
	{
		List	   *l;
314

315 316
		foreach(l, (List *) namespace1)
			checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
317
	}
318 319 320
	else
		elog(ERROR, "checkNameSpaceConflicts: unexpected node type %d",
			 nodeTag(namespace1));
321 322
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
/*
 * Subroutine for checkNameSpaceConflicts: scan namespace2
 */
static void
scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
						 RangeTblEntry *rte1, const char *aliasname1)
{
	if (nsnode == NULL)
		return;
	if (IsA(nsnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) nsnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);

		if (strcmp(rte->eref->aliasname, aliasname1) != 0)
			return;				/* definitely no conflict */
		if (rte->rtekind == RTE_RELATION && rte->alias == NULL &&
			rte1 != NULL && rte->relid != rte1->relid)
			return;				/* no conflict per SQL92 rule */
		elog(ERROR, "Table name \"%s\" specified more than once",
			 aliasname1);
	}
	else if (IsA(nsnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) nsnode;

		if (j->alias)
		{
			if (strcmp(j->alias->aliasname, aliasname1) == 0)
				elog(ERROR, "Table name \"%s\" specified more than once",
					 aliasname1);
Bruce Momjian's avatar
Bruce Momjian committed
354

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
			/*
			 * Tables within an aliased join are invisible from outside
			 * the join, according to the scope rules of SQL92 (the join
			 * is considered a subquery).  So, stop here.
			 */
			return;
		}
		scanNameSpaceForConflict(pstate, j->larg, rte1, aliasname1);
		scanNameSpaceForConflict(pstate, j->rarg, rte1, aliasname1);
	}
	else if (IsA(nsnode, List))
	{
		List	   *l;

		foreach(l, (List *) nsnode)
			scanNameSpaceForConflict(pstate, lfirst(l), rte1, aliasname1);
	}
	else
		elog(ERROR, "scanNameSpaceForConflict: unexpected node type %d",
			 nodeTag(nsnode));
}

377
/*
378 379 380 381
 * given an RTE, return RT index (starting with 1) of the entry,
 * and optionally get its nesting depth (0 = current).	If sublevels_up
 * is NULL, only consider rels at the current nesting level.
 * Raises error if RTE not found.
382
 */
383 384
int
RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
385
{
386 387 388 389 390
	int			index;
	List	   *temp;

	if (sublevels_up)
		*sublevels_up = 0;
391

392
	while (pstate != NULL)
393
	{
394 395 396 397 398 399 400 401 402 403
		index = 1;
		foreach(temp, pstate->p_rtable)
		{
			if (rte == (RangeTblEntry *) lfirst(temp))
				return index;
			index++;
		}
		pstate = pstate->parentParseState;
		if (sublevels_up)
			(*sublevels_up)++;
404
		else
405 406
			break;
	}
407

408 409 410 411 412 413 414 415 416
	elog(ERROR, "RTERangeTablePosn: RTE not found (internal error)");
	return 0;					/* keep compiler quiet */
}

/*
 * scanRTEForColumn
 *	  Search the column names of a single RTE for the given name.
 *	  If found, return an appropriate Var node, else return NULL.
 *	  If the name proves ambiguous within this RTE, raise error.
417 418 419
 *
 * Side effect: if we find a match, mark the RTE as requiring read access.
 * See comments in setTargetTable().
420 421 422 423 424 425
 *
 * NOTE: if the RTE is for a join, marking it as requiring read access does
 * nothing.  It might seem that we need to propagate the mark to all the
 * contained RTEs, but that is not necessary.  This is so because a join
 * expression can only appear in a FROM clause, and any table named in
 * FROM will be marked checkForRead from the beginning.
426 427 428 429 430 431 432
 */
static Node *
scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
{
	Node	   *result = NULL;
	int			attnum = 0;
	List	   *c;
433

434
	/*
435 436
	 * Scan the user column names (or aliases) for a match. Complain if
	 * multiple matches.
437
	 *
Bruce Momjian's avatar
Bruce Momjian committed
438 439 440 441 442 443
	 * Note: because eref->colnames may include names of dropped columns, we
	 * need to check for non-droppedness before accepting a match. This
	 * takes an extra cache lookup, but we can skip the lookup most of the
	 * time by exploiting the knowledge that dropped columns are assigned
	 * dummy names starting with '.', which is an unusual choice for
	 * actual column names.
444
	 *
Bruce Momjian's avatar
Bruce Momjian committed
445 446 447
	 * Should the user try to fool us by altering pg_attribute.attname for a
	 * dropped column, we'll still catch it by virtue of the checks in
	 * get_rte_attribute_type(), which is called by make_var().  That
448 449
	 * routine has to do a cache lookup anyway, so the check there is
	 * cheap.
450
	 */
451
	foreach(c, rte->eref->colnames)
452 453 454
	{
		attnum++;
		if (strcmp(strVal(lfirst(c)), colname) == 0)
455
		{
Bruce Momjian's avatar
Bruce Momjian committed
456
			if (colname[0] == '.' &&	/* see note above */
457 458
				get_rte_attribute_is_dropped(rte, attnum))
				continue;
459 460 461
			if (result)
				elog(ERROR, "Column reference \"%s\" is ambiguous", colname);
			result = (Node *) make_var(pstate, rte, attnum);
462
			rte->checkForRead = true;
463 464
		}
	}
465

466 467 468 469 470 471
	/*
	 * If we have a unique match, return it.  Note that this allows a user
	 * alias to override a system column name (such as OID) without error.
	 */
	if (result)
		return result;
472

473
	/*
474
	 * If the RTE represents a real table, consider system column names.
475
	 */
476
	if (rte->rtekind == RTE_RELATION)
477
	{
478
		/* quick check to see if name could be a system column */
479 480
		attnum = specialAttNum(colname);
		if (attnum != InvalidAttrNumber)
481
		{
482 483 484 485 486 487 488 489 490
			/* now check to see if column actually is defined */
			if (SearchSysCacheExists(ATTNUM,
									 ObjectIdGetDatum(rte->relid),
									 Int16GetDatum(attnum),
									 0, 0))
			{
				result = (Node *) make_var(pstate, rte, attnum);
				rte->checkForRead = true;
			}
491
		}
492 493 494 495
	}

	return result;
}
496

497 498 499 500 501 502 503 504 505 506 507 508
/*
 * colnameToVar
 *	  Search for an unqualified column name.
 *	  If found, return the appropriate Var node (or expression).
 *	  If not found, return NULL.  If the name proves ambiguous, raise error.
 */
Node *
colnameToVar(ParseState *pstate, char *colname)
{
	Node	   *result = NULL;
	ParseState *orig_pstate = pstate;
	int			levels_up = 0;
509

510 511
	while (pstate != NULL)
	{
512
		List	   *ns;
513

514
		/*
515
		 * We need to look only at top-level namespace items, and even for
516 517
		 * those, ignore RTEs that are marked as not inFromCl and not the
		 * query's target relation.
518
		 */
519
		foreach(ns, pstate->p_namespace)
520
		{
521 522
			Node	   *nsnode = (Node *) lfirst(ns);
			Node	   *newresult = NULL;
523

524
			if (IsA(nsnode, RangeTblRef))
525
			{
526
				int			varno = ((RangeTblRef *) nsnode)->rtindex;
527 528
				RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);

529
				if (!rte->inFromCl &&
530
					rte != pstate->p_target_rangetblentry)
531 532 533 534 535
					continue;

				/* use orig_pstate here to get the right sublevels_up */
				newresult = scanRTEForColumn(orig_pstate, rte, colname);
			}
536
			else if (IsA(nsnode, JoinExpr))
537
			{
538 539
				int			varno = ((JoinExpr *) nsnode)->rtindex;
				RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
540

541 542 543 544
				/* joins are always inFromCl, so no need to check */

				/* use orig_pstate here to get the right sublevels_up */
				newresult = scanRTEForColumn(orig_pstate, rte, colname);
545 546
			}
			else
547
				elog(ERROR, "colnameToVar: unexpected node type %d",
548
					 nodeTag(nsnode));
549 550 551 552 553 554 555 556

			if (newresult)
			{
				if (result)
					elog(ERROR, "Column reference \"%s\" is ambiguous",
						 colname);
				result = newresult;
			}
557
		}
558

559
		if (result != NULL)
560 561 562
			break;				/* found */

		pstate = pstate->parentParseState;
563
		levels_up++;
564
	}
565 566

	return result;
567 568 569
}

/*
570
 * qualifiedNameToVar
571 572 573
 *	  Search for a qualified column name: either refname.colname or
 *	  schemaname.relname.colname.
 *
574
 *	  If found, return the appropriate Var node.
575 576 577
 *	  If not found, return NULL.  If the name proves ambiguous, raise error.
 */
Node *
578 579 580 581
qualifiedNameToVar(ParseState *pstate,
				   char *schemaname,
				   char *refname,
				   char *colname,
582 583
				   bool implicitRTEOK)
{
584
	RangeTblEntry *rte;
585 586
	int			sublevels_up;

587
	rte = refnameRangeTblEntry(pstate, schemaname, refname, &sublevels_up);
588

589
	if (rte == NULL)
590
	{
591
		if (!implicitRTEOK)
592
			return NULL;
593
		rte = addImplicitRTE(pstate, makeRangeVar(schemaname, refname));
594 595
	}

596
	return scanRTEForColumn(pstate, rte, colname);
597 598 599
}

/*
600 601
 * Add an entry for a relation to the pstate's range table (p_rtable).
 *
602 603
 * If pstate is NULL, we just build an RTE and return it without adding it
 * to an rtable list.
604
 *
605 606
 * Note: formerly this checked for refname conflicts, but that's wrong.
 * Caller is responsible for checking for conflicts in the appropriate scope.
607
 */
608 609
RangeTblEntry *
addRangeTableEntry(ParseState *pstate,
610
				   RangeVar *relation,
611
				   Alias *alias,
612
				   bool inh,
613
				   bool inFromCl)
614
{
615
	RangeTblEntry *rte = makeNode(RangeTblEntry);
616
	char	   *refname = alias ? alias->aliasname : relation->relname;
617
	LOCKMODE	lockmode;
618
	Relation	rel;
619
	Alias	   *eref;
620
	int			maxattrs;
621
	int			numaliases;
622
	int			varattno;
623

624
	rte->rtekind = RTE_RELATION;
625
	rte->alias = alias;
626

627 628
	/*
	 * Get the rel's OID.  This access also ensures that we have an
629 630 631
	 * up-to-date relcache entry for the rel.  Since this is typically the
	 * first access to a rel in a statement, be careful to get the right
	 * access level depending on whether we're doing SELECT FOR UPDATE.
632
	 */
633
	lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
634
	rel = heap_openrv(relation, lockmode);
635
	rte->relid = RelationGetRelid(rel);
636

637 638
	eref = alias ? (Alias *) copyObject(alias) : makeAlias(refname, NIL);
	numaliases = length(eref->colnames);
639

640
	/*
641 642
	 * Since the rel is open anyway, let's check that the number of column
	 * aliases is reasonable. - Thomas 2000-02-04
643 644
	 */
	maxattrs = RelationGetNumberOfAttributes(rel);
645 646
	if (maxattrs < numaliases)
		elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
			 RelationGetRelationName(rel), maxattrs, numaliases);

	/* fill in any unspecified alias columns using actual column names */
	for (varattno = numaliases; varattno < maxattrs; varattno++)
	{
		char	   *attrname;

		attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
		eref->colnames = lappend(eref->colnames, makeString(attrname));
	}
	rte->eref = eref;

	/*
	 * Drop the rel refcount, but keep the access lock till end of
	 * transaction so that the table can't be deleted or have its schema
	 * modified underneath us.
	 */
	heap_close(rel, NoLock);

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
	 * - this RTE should be checked for read/write access rights.
	 *
	 * The initial default on access checks is always check-for-READ-access,
	 * which is the right thing for all except target tables.
	 *----------
	 */
	rte->inh = inh;
	rte->inFromCl = inFromCl;
	rte->checkForRead = true;
	rte->checkForWrite = false;

	rte->checkAsUser = InvalidOid;		/* not set-uid by default, either */

	/*
	 * Add completed RTE to pstate's range table list, but not to join
	 * list nor namespace --- caller must do that if appropriate.
	 */
	if (pstate != NULL)
		pstate->p_rtable = lappend(pstate->p_rtable, rte);

	return rte;
}

/*
 * Add an entry for a relation to the pstate's range table (p_rtable).
 *
 * This is just like addRangeTableEntry() except that it makes an RTE
 * given a relation OID instead of a RangeVar reference.
 *
 * Note that an alias clause *must* be supplied.
 */
RangeTblEntry *
addRangeTableEntryForRelation(ParseState *pstate,
							  Oid relid,
							  Alias *alias,
							  bool inh,
							  bool inFromCl)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	char	   *refname = alias->aliasname;
	LOCKMODE	lockmode;
	Relation	rel;
	Alias	   *eref;
	int			maxattrs;
	int			numaliases;
	int			varattno;

	rte->rtekind = RTE_RELATION;
	rte->alias = alias;

	/*
	 * Get the rel's relcache entry.  This access ensures that we have an
	 * up-to-date relcache entry for the rel.  Since this is typically the
	 * first access to a rel in a statement, be careful to get the right
	 * access level depending on whether we're doing SELECT FOR UPDATE.
	 */
	lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
	rel = heap_open(relid, lockmode);
	rte->relid = relid;

	eref = (Alias *) copyObject(alias);
	numaliases = length(eref->colnames);

	/*
	 * Since the rel is open anyway, let's check that the number of column
	 * aliases is reasonable. - Thomas 2000-02-04
	 */
	maxattrs = RelationGetNumberOfAttributes(rel);
	if (maxattrs < numaliases)
		elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
			 RelationGetRelationName(rel), maxattrs, numaliases);
741

742
	/* fill in any unspecified alias columns using actual column names */
743
	for (varattno = numaliases; varattno < maxattrs; varattno++)
744 745 746 747
	{
		char	   *attrname;

		attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
748
		eref->colnames = lappend(eref->colnames, makeString(attrname));
749
	}
750
	rte->eref = eref;
751

752
	/*
753 754 755
	 * Drop the rel refcount, but keep the access lock till end of
	 * transaction so that the table can't be deleted or have its schema
	 * modified underneath us.
756 757
	 */
	heap_close(rel, NoLock);
758 759 760 761 762

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
763 764 765 766
	 * - this RTE should be checked for read/write access rights.
	 *
	 * The initial default on access checks is always check-for-READ-access,
	 * which is the right thing for all except target tables.
767
	 *----------
768 769 770
	 */
	rte->inh = inh;
	rte->inFromCl = inFromCl;
771 772 773
	rte->checkForRead = true;
	rte->checkForWrite = false;

774
	rte->checkAsUser = InvalidOid;		/* not set-uid by default, either */
775 776

	/*
777 778
	 * Add completed RTE to pstate's range table list, but not to join
	 * list nor namespace --- caller must do that if appropriate.
779 780 781 782 783 784 785
	 */
	if (pstate != NULL)
		pstate->p_rtable = lappend(pstate->p_rtable, rte);

	return rte;
}

786
/*
787 788 789 790 791 792 793 794
 * Add an entry for a subquery to the pstate's range table (p_rtable).
 *
 * This is just like addRangeTableEntry() except that it makes a subquery RTE.
 * Note that an alias clause *must* be supplied.
 */
RangeTblEntry *
addRangeTableEntryForSubquery(ParseState *pstate,
							  Query *subquery,
795
							  Alias *alias,
796 797
							  bool inFromCl)
{
798
	RangeTblEntry *rte = makeNode(RangeTblEntry);
799 800
	char	   *refname = alias->aliasname;
	Alias	   *eref;
801 802 803 804
	int			numaliases;
	int			varattno;
	List	   *tlistitem;

805
	rte->rtekind = RTE_SUBQUERY;
806 807 808 809 810
	rte->relid = InvalidOid;
	rte->subquery = subquery;
	rte->alias = alias;

	eref = copyObject(alias);
811
	numaliases = length(eref->colnames);
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

	/* fill in any unspecified alias columns */
	varattno = 0;
	foreach(tlistitem, subquery->targetList)
	{
		TargetEntry *te = (TargetEntry *) lfirst(tlistitem);

		if (te->resdom->resjunk)
			continue;
		varattno++;
		Assert(varattno == te->resdom->resno);
		if (varattno > numaliases)
		{
			char	   *attrname;

			attrname = pstrdup(te->resdom->resname);
828
			eref->colnames = lappend(eref->colnames, makeString(attrname));
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
		}
	}
	if (varattno < numaliases)
		elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
			 refname, varattno, numaliases);

	rte->eref = eref;

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
	 * - this RTE should be checked for read/write access rights.
	 *
	 * Subqueries are never checked for access rights.
	 *----------
	 */
	rte->inh = false;			/* never true for subqueries */
	rte->inFromCl = inFromCl;
	rte->checkForRead = false;
	rte->checkForWrite = false;

	rte->checkAsUser = InvalidOid;

	/*
854 855
	 * Add completed RTE to pstate's range table list, but not to join
	 * list nor namespace --- caller must do that if appropriate.
856 857 858 859 860 861 862
	 */
	if (pstate != NULL)
		pstate->p_rtable = lappend(pstate->p_rtable, rte);

	return rte;
}

863 864 865 866 867 868 869 870 871
/*
 * Add an entry for a function to the pstate's range table (p_rtable).
 *
 * This is just like addRangeTableEntry() except that it makes a function RTE.
 */
RangeTblEntry *
addRangeTableEntryForFunction(ParseState *pstate,
							  char *funcname,
							  Node *funcexpr,
872
							  RangeFunction *rangefunc,
873 874 875 876
							  bool inFromCl)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	Oid			funcrettype = exprType(funcexpr);
877 878 879
	char		functyptype;
	Alias	   *alias = rangefunc->alias;
	List	   *coldeflist = rangefunc->coldeflist;
880 881 882 883 884 885 886 887
	Alias	   *eref;
	int			numaliases;
	int			varattno;

	rte->rtekind = RTE_FUNCTION;
	rte->relid = InvalidOid;
	rte->subquery = NULL;
	rte->funcexpr = funcexpr;
888
	rte->coldeflist = coldeflist;
889 890 891 892 893 894 895 896 897 898 899
	rte->alias = alias;

	eref = alias ? (Alias *) copyObject(alias) : makeAlias(funcname, NIL);
	rte->eref = eref;

	numaliases = length(eref->colnames);

	/*
	 * Now determine if the function returns a simple or composite type,
	 * and check/add column aliases.
	 */
900 901 902
	if (coldeflist != NIL)
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
903 904
		 * we *only* allow a coldeflist for functions returning a RECORD
		 * pseudo-type
905
		 */
906 907
		if (funcrettype != RECORDOID)
			elog(ERROR, "A column definition list is only allowed for functions returning RECORD");
908 909 910 911 912 913 914
	}
	else
	{
		/*
		 * ... and a coldeflist is *required* for functions returning a
		 * RECORD pseudo-type
		 */
915 916
		if (funcrettype == RECORDOID)
			elog(ERROR, "A column definition list is required for functions returning RECORD");
917 918
	}

919 920
	functyptype = get_typtype(funcrettype);

921
	if (functyptype == 'c')
922 923
	{
		/*
924
		 * Named composite data type, i.e. a table's row type
925
		 */
926
		Oid			funcrelid = typeidTypeRelid(funcrettype);
927 928
		Relation	rel;
		int			maxattrs;
929

930 931 932
		if (!OidIsValid(funcrelid))
			elog(ERROR, "Invalid typrelid for complex type %u",
				 funcrettype);
933

934
		/*
Bruce Momjian's avatar
Bruce Momjian committed
935 936
		 * Get the rel's relcache entry.  This access ensures that we have
		 * an up-to-date relcache entry for the rel.
937 938
		 */
		rel = relation_open(funcrelid, AccessShareLock);
939

940
		/*
Bruce Momjian's avatar
Bruce Momjian committed
941 942
		 * Since the rel is open anyway, let's check that the number of
		 * column aliases is reasonable.
943 944 945 946 947
		 */
		maxattrs = RelationGetNumberOfAttributes(rel);
		if (maxattrs < numaliases)
			elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
				 RelationGetRelationName(rel), maxattrs, numaliases);
948

949 950 951 952
		/* fill in alias columns using actual column names */
		for (varattno = numaliases; varattno < maxattrs; varattno++)
		{
			char	   *attrname;
953

954 955
			attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
			eref->colnames = lappend(eref->colnames, makeString(attrname));
956
		}
957 958 959

		/*
		 * Drop the rel refcount, but keep the access lock till end of
Bruce Momjian's avatar
Bruce Momjian committed
960 961
		 * transaction so that the table can't be deleted or have its
		 * schema modified underneath us.
962 963
		 */
		relation_close(rel, NoLock);
964
	}
965
	else if (functyptype == 'b' || functyptype == 'd')
966 967
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
968 969
		 * Must be a base data type, i.e. scalar. Just add one alias
		 * column named for the function.
970 971 972 973 974
		 */
		if (numaliases > 1)
			elog(ERROR, "Too many column aliases specified for function %s",
				 funcname);
		if (numaliases == 0)
975
			eref->colnames = makeList1(makeString(eref->aliasname));
976
	}
977 978 979 980
	else if (functyptype == 'p' && funcrettype == RECORDOID)
	{
		List	   *col;

981 982
		/* Use the column definition list to form the alias list */
		eref->colnames = NIL;
983 984 985
		foreach(col, coldeflist)
		{
			ColumnDef  *n = lfirst(col);
986
			char	   *attrname;
987 988 989 990 991 992 993 994

			attrname = pstrdup(n->colname);
			eref->colnames = lappend(eref->colnames, makeString(attrname));
		}
	}
	else
		elog(ERROR, "Unknown kind of return type specified for function %s",
			 funcname);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
	 * - this RTE should be checked for read/write access rights.
	 *----------
	 */
	rte->inh = false;			/* never true for functions */
	rte->inFromCl = inFromCl;
	rte->checkForRead = true;
	rte->checkForWrite = false;

	rte->checkAsUser = InvalidOid;

	/*
	 * Add completed RTE to pstate's range table list, but not to join
	 * list nor namespace --- caller must do that if appropriate.
	 */
	if (pstate != NULL)
		pstate->p_rtable = lappend(pstate->p_rtable, rte);

	return rte;
}

1020 1021 1022 1023 1024 1025 1026 1027 1028
/*
 * Add an entry for a join to the pstate's range table (p_rtable).
 *
 * This is much like addRangeTableEntry() except that it makes a join RTE.
 */
RangeTblEntry *
addRangeTableEntryForJoin(ParseState *pstate,
						  List *colnames,
						  JoinType jointype,
1029
						  List *aliasvars,
1030
						  Alias *alias,
1031 1032 1033
						  bool inFromCl)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
1034
	Alias	   *eref;
1035 1036 1037 1038 1039 1040
	int			numaliases;

	rte->rtekind = RTE_JOIN;
	rte->relid = InvalidOid;
	rte->subquery = NULL;
	rte->jointype = jointype;
1041
	rte->joinaliasvars = aliasvars;
1042 1043
	rte->alias = alias;

1044 1045
	eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
	numaliases = length(eref->colnames);
1046 1047 1048 1049 1050 1051

	/* fill in any unspecified alias columns */
	if (numaliases < length(colnames))
	{
		while (numaliases-- > 0)
			colnames = lnext(colnames);
1052
		eref->colnames = nconc(eref->colnames, colnames);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
	}

	rte->eref = eref;

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
	 * - this RTE should be checked for read/write access rights.
	 *
	 * Joins are never checked for access rights.
	 *----------
	 */
	rte->inh = false;			/* never true for joins */
	rte->inFromCl = inFromCl;
	rte->checkForRead = false;
	rte->checkForWrite = false;

	rte->checkAsUser = InvalidOid;

	/*
	 * Add completed RTE to pstate's range table list, but not to join
	 * list nor namespace --- caller must do that if appropriate.
	 */
	if (pstate != NULL)
		pstate->p_rtable = lappend(pstate->p_rtable, rte);

	return rte;
}

1083
/*
1084
 * Has the specified refname been selected FOR UPDATE?
1085 1086
 */
static bool
1087
isForUpdate(ParseState *pstate, char *refname)
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
{
	/* Outer loop to check parent query levels as well as this one */
	while (pstate != NULL)
	{
		if (pstate->p_forUpdate != NIL)
		{
			if (lfirst(pstate->p_forUpdate) == NULL)
			{
				/* all tables used in query */
				return true;
			}
			else
			{
				/* just the named tables */
1102
				List	   *l;
1103 1104 1105

				foreach(l, pstate->p_forUpdate)
				{
1106
					char	   *rname = strVal(lfirst(l));
1107

1108
					if (strcmp(refname, rname) == 0)
1109 1110 1111 1112 1113 1114 1115 1116 1117
						return true;
				}
			}
		}
		pstate = pstate->parentParseState;
	}
	return false;
}

1118
/*
1119
 * Add the given RTE as a top-level entry in the pstate's join list
1120
 * and/or name space list.	(We assume caller has checked for any
1121
 * namespace conflict.)
1122
 */
1123
void
1124 1125
addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
			  bool addToJoinList, bool addToNameSpace)
1126 1127
{
	int			rtindex = RTERangeTablePosn(pstate, rte, NULL);
1128
	RangeTblRef *rtr = makeNode(RangeTblRef);
1129 1130

	rtr->rtindex = rtindex;
1131 1132 1133 1134 1135

	if (addToJoinList)
		pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
	if (addToNameSpace)
		pstate->p_namespace = lappend(pstate->p_namespace, rtr);
1136 1137 1138 1139 1140
}

/*
 * Add a POSTQUEL-style implicit RTE.
 *
1141 1142
 * We assume caller has already checked that there is no RTE or join with
 * a conflicting name.
1143 1144
 */
RangeTblEntry *
1145
addImplicitRTE(ParseState *pstate, RangeVar *relation)
1146
{
1147
	RangeTblEntry *rte;
1148

1149
	rte = addRangeTableEntry(pstate, relation, NULL, false, false);
1150
	addRTEtoQuery(pstate, rte, true, true);
1151
	warnAutoRange(pstate, relation);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

	return rte;
}

/* expandRTE()
 *
 * Given a rangetable entry, create lists of its column names (aliases if
 * provided, else real names) and Vars for each column.  Only user columns
 * are considered, since this is primarily used to expand '*' and determine
 * the contents of JOIN tables.
 *
 * If only one of the two kinds of output list is needed, pass NULL for the
 * output pointer for the unwanted one.
 */
void
expandRTE(ParseState *pstate, RangeTblEntry *rte,
		  List **colnames, List **colvars)
{
1170 1171 1172
	int			rtindex,
				sublevels_up,
				varattno;
1173

1174 1175 1176 1177
	if (colnames)
		*colnames = NIL;
	if (colvars)
		*colvars = NIL;
1178

1179 1180
	/* Need the RT index of the entry for creating Vars */
	rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1181

1182
	switch (rte->rtekind)
1183
	{
1184 1185 1186 1187 1188 1189
		case RTE_RELATION:
			{
				/* Ordinary relation RTE */
				Relation	rel;
				int			maxattrs;
				int			numaliases;
1190

1191 1192 1193
				rel = heap_open(rte->relid, AccessShareLock);
				maxattrs = RelationGetNumberOfAttributes(rel);
				numaliases = length(rte->eref->colnames);
1194

1195 1196 1197
				for (varattno = 0; varattno < maxattrs; varattno++)
				{
					Form_pg_attribute attr = rel->rd_att->attrs[varattno];
1198

1199 1200 1201
					if (attr->attisdropped)
						continue;

1202 1203 1204
					if (colnames)
					{
						char	   *label;
1205

1206 1207 1208 1209 1210 1211
						if (varattno < numaliases)
							label = strVal(nth(varattno, rte->eref->colnames));
						else
							label = NameStr(attr->attname);
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
					}
1212

1213 1214 1215
					if (colvars)
					{
						Var		   *varnode;
1216

1217 1218 1219 1220 1221 1222 1223
						varnode = makeVar(rtindex, attr->attnum,
										  attr->atttypid, attr->atttypmod,
										  sublevels_up);

						*colvars = lappend(*colvars, varnode);
					}
				}
1224

1225
				heap_close(rel, AccessShareLock);
1226
			}
1227 1228 1229 1230 1231 1232
			break;
		case RTE_SUBQUERY:
			{
				/* Subquery RTE */
				List	   *aliasp = rte->eref->colnames;
				List	   *tlistitem;
1233

1234 1235 1236 1237
				varattno = 0;
				foreach(tlistitem, rte->subquery->targetList)
				{
					TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1238

1239 1240 1241 1242
					if (te->resdom->resjunk)
						continue;
					varattno++;
					Assert(varattno == te->resdom->resno);
1243

1244 1245 1246 1247
					if (colnames)
					{
						/* Assume there is one alias per target item */
						char	   *label = strVal(lfirst(aliasp));
1248

1249 1250 1251
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
						aliasp = lnext(aliasp);
					}
1252

1253 1254 1255
					if (colvars)
					{
						Var		   *varnode;
1256

1257 1258 1259 1260
						varnode = makeVar(rtindex, varattno,
										  te->resdom->restype,
										  te->resdom->restypmod,
										  sublevels_up);
1261

1262 1263 1264 1265 1266 1267 1268 1269
						*colvars = lappend(*colvars, varnode);
					}
				}
			}
			break;
		case RTE_FUNCTION:
			{
				/* Function RTE */
Bruce Momjian's avatar
Bruce Momjian committed
1270 1271 1272
				Oid			funcrettype = exprType(rte->funcexpr);
				char		functyptype = get_typtype(funcrettype);
				List	   *coldeflist = rte->coldeflist;
1273

1274
				if (functyptype == 'c')
1275
				{
1276
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1277 1278
					 * Composite data type, i.e. a table's row type Same
					 * as ordinary relation RTE
1279
					 */
Bruce Momjian's avatar
Bruce Momjian committed
1280
					Oid			funcrelid = typeidTypeRelid(funcrettype);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
					Relation	rel;
					int			maxattrs;
					int			numaliases;

					if (!OidIsValid(funcrelid))
						elog(ERROR, "Invalid typrelid for complex type %u",
							 funcrettype);

					rel = relation_open(funcrelid, AccessShareLock);
					maxattrs = RelationGetNumberOfAttributes(rel);
					numaliases = length(rte->eref->colnames);

					for (varattno = 0; varattno < maxattrs; varattno++)
1294
					{
1295 1296 1297 1298 1299 1300
						Form_pg_attribute attr = rel->rd_att->attrs[varattno];

						if (attr->attisdropped)
							continue;

						if (colnames)
1301
						{
1302 1303 1304 1305 1306 1307 1308
							char	   *label;

							if (varattno < numaliases)
								label = strVal(nth(varattno, rte->eref->colnames));
							else
								label = NameStr(attr->attname);
							*colnames = lappend(*colnames, makeString(pstrdup(label)));
1309 1310
						}

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
						if (colvars)
						{
							Var		   *varnode;

							varnode = makeVar(rtindex,
											  attr->attnum,
											  attr->atttypid,
											  attr->atttypmod,
											  sublevels_up);

							*colvars = lappend(*colvars, varnode);
						}
1323
					}
1324 1325

					relation_close(rel, AccessShareLock);
1326
				}
1327
				else if (functyptype == 'b' || functyptype == 'd')
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
				{
					/*
					 * Must be a base data type, i.e. scalar
					 */
					if (colnames)
						*colnames = lappend(*colnames,
											lfirst(rte->eref->colnames));

					if (colvars)
					{
						Var		   *varnode;

						varnode = makeVar(rtindex, 1,
										  funcrettype, -1,
										  sublevels_up);

						*colvars = lappend(*colvars, varnode);
					}
				}
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
				else if (functyptype == 'p' && funcrettype == RECORDOID)
				{
					List	   *col;
					int			attnum = 0;

					foreach(col, coldeflist)
					{
						ColumnDef  *colDef = lfirst(col);

						attnum++;
						if (colnames)
						{
							char	   *attrname;

							attrname = pstrdup(colDef->colname);
							*colnames = lappend(*colnames, makeString(attrname));
						}

						if (colvars)
						{
							Var		   *varnode;
							Oid			atttypid;

1370
							atttypid = typenameTypeId(colDef->typename);
1371 1372

							varnode = makeVar(rtindex,
Bruce Momjian's avatar
Bruce Momjian committed
1373 1374 1375 1376
											  attnum,
											  atttypid,
											  -1,
											  sublevels_up);
1377 1378 1379 1380 1381 1382

							*colvars = lappend(*colvars, varnode);
						}
					}
				}
				else
1383
					elog(ERROR, "Unknown kind of return type specified for function");
1384
			}
1385 1386 1387 1388 1389 1390
			break;
		case RTE_JOIN:
			{
				/* Join RTE */
				List	   *aliasp = rte->eref->colnames;
				List	   *aliasvars = rte->joinaliasvars;
1391

1392 1393 1394 1395 1396
				varattno = 0;
				while (aliasp)
				{
					Assert(aliasvars);
					varattno++;
1397

1398 1399 1400
					if (colnames)
					{
						char	   *label = strVal(lfirst(aliasp));
1401

1402 1403
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
					}
Bruce Momjian's avatar
Bruce Momjian committed
1404

1405 1406 1407 1408
					if (colvars)
					{
						Node	   *aliasvar = (Node *) lfirst(aliasvars);
						Var		   *varnode;
1409

1410 1411 1412 1413
						varnode = makeVar(rtindex, varattno,
										  exprType(aliasvar),
										  exprTypmod(aliasvar),
										  sublevels_up);
1414

1415 1416
						*colvars = lappend(*colvars, varnode);
					}
1417

1418 1419 1420 1421 1422 1423 1424 1425 1426
					aliasp = lnext(aliasp);
					aliasvars = lnext(aliasvars);
				}
				Assert(aliasvars == NIL);
			}
			break;
		default:
			elog(ERROR, "expandRTE: unsupported RTE kind %d",
				 (int) rte->rtekind);
1427
	}
1428
}
1429

1430
/*
1431 1432 1433
 * expandRelAttrs -
 *	  Workhorse for "*" expansion: produce a list of targetentries
 *	  for the attributes of the rte
1434
 */
1435 1436
List *
expandRelAttrs(ParseState *pstate, RangeTblEntry *rte)
1437
{
1438 1439
	List	   *names,
			   *vars;
1440
	List	   *te_list = NIL;
1441

1442 1443
	expandRTE(pstate, rte, &names, &vars);

1444 1445 1446 1447 1448
	while (names)
	{
		char	   *label = strVal(lfirst(names));
		Node	   *varnode = (Node *) lfirst(vars);
		TargetEntry *te = makeNode(TargetEntry);
1449

1450 1451 1452
		te->resdom = makeResdom((AttrNumber) (pstate->p_last_resno)++,
								exprType(varnode),
								exprTypmod(varnode),
1453
								label,
Bruce Momjian's avatar
Bruce Momjian committed
1454
								false);
1455
		te->expr = (Expr *) varnode;
1456
		te_list = lappend(te_list, te);
1457 1458 1459

		names = lnext(names);
		vars = lnext(vars);
1460 1461
	}

1462
	Assert(vars == NIL);		/* lists not same length? */
Bruce Momjian's avatar
Bruce Momjian committed
1463

1464
	return te_list;
1465 1466
}

1467
/*
1468 1469 1470 1471
 * get_rte_attribute_name
 *		Get an attribute name from a RangeTblEntry
 *
 * This is unlike get_attname() because we use aliases if available.
1472
 * In particular, it will work on an RTE for a subselect or join, whereas
1473
 * get_attname() only works on real relations.
1474
 *
1475 1476
 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
 * occurs when a Var represents a whole tuple of a relation.
1477 1478 1479 1480 1481 1482
 */
char *
get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
{
	char	   *attname;

1483 1484 1485
	if (attnum == InvalidAttrNumber)
		return "*";

1486
	/*
1487
	 * If there is a user-written column alias, use it.
1488
	 */
1489 1490 1491
	if (rte->alias &&
		attnum > 0 && attnum <= length(rte->alias->colnames))
		return strVal(nth(attnum - 1, rte->alias->colnames));
1492

1493
	/*
1494
	 * If the RTE is a relation, go to the system catalogs not the
Bruce Momjian's avatar
Bruce Momjian committed
1495 1496 1497
	 * eref->colnames list.  This is a little slower but it will give the
	 * right answer if the column has been renamed since the eref list was
	 * built (which can easily happen for rules).
1498
	 */
1499 1500 1501 1502 1503 1504 1505 1506
	if (rte->rtekind == RTE_RELATION)
	{
		attname = get_attname(rte->relid, attnum);
		if (attname == NULL)
			elog(ERROR, "cache lookup of attribute %d in relation %u failed",
				 attnum, rte->relid);
		return attname;
	}
1507

1508
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1509 1510
	 * Otherwise use the column name from eref.  There should always be
	 * one.
1511
	 */
1512 1513 1514 1515 1516 1517
	if (attnum > 0 && attnum <= length(rte->eref->colnames))
		return strVal(nth(attnum - 1, rte->eref->colnames));

	elog(ERROR, "Invalid attnum %d for rangetable entry %s",
		 attnum, rte->eref->aliasname);
	return NULL;				/* keep compiler quiet */
1518 1519
}

1520 1521 1522 1523 1524 1525 1526 1527
/*
 * get_rte_attribute_type
 *		Get attribute type information from a RangeTblEntry
 */
void
get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
					   Oid *vartype, int32 *vartypmod)
{
1528
	switch (rte->rtekind)
1529
	{
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
		case RTE_RELATION:
			{
				/* Plain relation RTE --- get the attribute's type info */
				HeapTuple	tp;
				Form_pg_attribute att_tup;

				tp = SearchSysCache(ATTNUM,
									ObjectIdGetDatum(rte->relid),
									Int16GetDatum(attnum),
									0, 0);
				/* this shouldn't happen... */
				if (!HeapTupleIsValid(tp))
1542
					elog(ERROR, "Relation \"%s\" does not have attribute %d",
1543 1544
						 get_rel_name(rte->relid), attnum);
				att_tup = (Form_pg_attribute) GETSTRUCT(tp);
Bruce Momjian's avatar
Bruce Momjian committed
1545

1546 1547 1548 1549 1550 1551
				/*
				 * If dropped column, pretend it ain't there.  See notes
				 * in scanRTEForColumn.
				 */
				if (att_tup->attisdropped)
					elog(ERROR, "Relation \"%s\" has no column \"%s\"",
Bruce Momjian's avatar
Bruce Momjian committed
1552
					get_rel_name(rte->relid), NameStr(att_tup->attname));
1553 1554 1555 1556 1557 1558 1559 1560 1561
				*vartype = att_tup->atttypid;
				*vartypmod = att_tup->atttypmod;
				ReleaseSysCache(tp);
			}
			break;
		case RTE_SUBQUERY:
			{
				/* Subselect RTE --- get type info from subselect's tlist */
				List	   *tlistitem;
1562

1563 1564 1565
				foreach(tlistitem, rte->subquery->targetList)
				{
					TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1566

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
					if (te->resdom->resjunk || te->resdom->resno != attnum)
						continue;
					*vartype = te->resdom->restype;
					*vartypmod = te->resdom->restypmod;
					return;
				}
				/* falling off end of list shouldn't happen... */
				elog(ERROR, "Subquery %s does not have attribute %d",
					 rte->eref->aliasname, attnum);
			}
			break;
		case RTE_FUNCTION:
			{
				/* Function RTE */
Bruce Momjian's avatar
Bruce Momjian committed
1581 1582 1583
				Oid			funcrettype = exprType(rte->funcexpr);
				char		functyptype = get_typtype(funcrettype);
				List	   *coldeflist = rte->coldeflist;
1584

1585
				if (functyptype == 'c')
1586 1587
				{
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1588 1589
					 * Composite data type, i.e. a table's row type Same
					 * as ordinary relation RTE
1590
					 */
Bruce Momjian's avatar
Bruce Momjian committed
1591 1592 1593
					Oid			funcrelid = typeidTypeRelid(funcrettype);
					HeapTuple	tp;
					Form_pg_attribute att_tup;
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607

					if (!OidIsValid(funcrelid))
						elog(ERROR, "Invalid typrelid for complex type %u",
							 funcrettype);

					tp = SearchSysCache(ATTNUM,
										ObjectIdGetDatum(funcrelid),
										Int16GetDatum(attnum),
										0, 0);
					/* this shouldn't happen... */
					if (!HeapTupleIsValid(tp))
						elog(ERROR, "Relation \"%s\" does not have attribute %d",
							 get_rel_name(funcrelid), attnum);
					att_tup = (Form_pg_attribute) GETSTRUCT(tp);
Bruce Momjian's avatar
Bruce Momjian committed
1608

1609
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1610 1611
					 * If dropped column, pretend it ain't there.  See
					 * notes in scanRTEForColumn.
1612 1613 1614 1615 1616 1617 1618 1619
					 */
					if (att_tup->attisdropped)
						elog(ERROR, "Relation \"%s\" has no column \"%s\"",
							 get_rel_name(funcrelid),
							 NameStr(att_tup->attname));
					*vartype = att_tup->atttypid;
					*vartypmod = att_tup->atttypmod;
					ReleaseSysCache(tp);
1620
				}
1621
				else if (functyptype == 'b' || functyptype == 'd')
1622 1623 1624 1625 1626 1627 1628
				{
					/*
					 * Must be a base data type, i.e. scalar
					 */
					*vartype = funcrettype;
					*vartypmod = -1;
				}
1629 1630 1631 1632
				else if (functyptype == 'p' && funcrettype == RECORDOID)
				{
					ColumnDef  *colDef = nth(attnum - 1, coldeflist);

1633
					*vartype = typenameTypeId(colDef->typename);
1634 1635 1636
					*vartypmod = -1;
				}
				else
1637
					elog(ERROR, "Unknown kind of return type specified for function");
1638 1639 1640 1641
			}
			break;
		case RTE_JOIN:
			{
Bruce Momjian's avatar
Bruce Momjian committed
1642 1643 1644 1645 1646
				/*
				 * Join RTE --- get type info from join RTE's alias
				 * variable
				 */
				Node	   *aliasvar;
1647

1648
				Assert(attnum > 0 && attnum <= length(rte->joinaliasvars));
Bruce Momjian's avatar
Bruce Momjian committed
1649
				aliasvar = (Node *) nth(attnum - 1, rte->joinaliasvars);
1650 1651 1652 1653 1654 1655 1656
				*vartype = exprType(aliasvar);
				*vartypmod = exprTypmod(aliasvar);
			}
			break;
		default:
			elog(ERROR, "get_rte_attribute_type: unsupported RTE kind %d",
				 (int) rte->rtekind);
1657 1658 1659
	}
}

1660 1661 1662 1663 1664 1665 1666
/*
 * get_rte_attribute_is_dropped
 *		Check whether attempted attribute ref is to a dropped column
 */
static bool
get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
{
Bruce Momjian's avatar
Bruce Momjian committed
1667
	bool		result;
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703

	switch (rte->rtekind)
	{
		case RTE_RELATION:
			{
				/* Plain relation RTE --- get the attribute's type info */
				HeapTuple	tp;
				Form_pg_attribute att_tup;

				tp = SearchSysCache(ATTNUM,
									ObjectIdGetDatum(rte->relid),
									Int16GetDatum(attnum),
									0, 0);
				/* this shouldn't happen... */
				if (!HeapTupleIsValid(tp))
					elog(ERROR, "Relation \"%s\" does not have attribute %d",
						 get_rel_name(rte->relid), attnum);
				att_tup = (Form_pg_attribute) GETSTRUCT(tp);
				result = att_tup->attisdropped;
				ReleaseSysCache(tp);
			}
			break;
		case RTE_SUBQUERY:
		case RTE_JOIN:
			/* Subselect and join RTEs never have dropped columns */
			result = false;
			break;
		case RTE_FUNCTION:
			{
				/* Function RTE */
				Oid			funcrettype = exprType(rte->funcexpr);
				Oid			funcrelid = typeidTypeRelid(funcrettype);

				if (OidIsValid(funcrelid))
				{
					/*
Bruce Momjian's avatar
Bruce Momjian committed
1704 1705
					 * Composite data type, i.e. a table's row type Same
					 * as ordinary relation RTE
1706
					 */
Bruce Momjian's avatar
Bruce Momjian committed
1707 1708
					HeapTuple	tp;
					Form_pg_attribute att_tup;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739

					tp = SearchSysCache(ATTNUM,
										ObjectIdGetDatum(funcrelid),
										Int16GetDatum(attnum),
										0, 0);
					/* this shouldn't happen... */
					if (!HeapTupleIsValid(tp))
						elog(ERROR, "Relation %s does not have attribute %d",
							 get_rel_name(funcrelid), attnum);
					att_tup = (Form_pg_attribute) GETSTRUCT(tp);
					result = att_tup->attisdropped;
					ReleaseSysCache(tp);
				}
				else
				{
					/*
					 * Must be a base data type, i.e. scalar
					 */
					result = false;
				}
			}
			break;
		default:
			elog(ERROR, "get_rte_attribute_is_dropped: unsupported RTE kind %d",
				 (int) rte->rtekind);
			result = false;		/* keep compiler quiet */
	}

	return result;
}

Bruce Momjian's avatar
Bruce Momjian committed
1740 1741 1742 1743 1744 1745 1746
/*
 *	given relation and att name, return id of variable
 *
 *	This should only be used if the relation is already
 *	heap_open()'ed.  Use the cache version get_attnum()
 *	for access to non-opened relations.
 */
1747
int
1748
attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1749 1750 1751 1752
{
	int			i;

	for (i = 0; i < rd->rd_rel->relnatts; i++)
1753
	{
Bruce Momjian's avatar
Bruce Momjian committed
1754
		Form_pg_attribute att = rd->rd_att->attrs[i];
1755 1756

		if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1757
			return i + 1;
1758
	}
1759

1760
	if (sysColOK)
1761
	{
1762 1763 1764 1765 1766
		if ((i = specialAttNum(attname)) != InvalidAttrNumber)
		{
			if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
				return i;
		}
1767
	}
1768 1769

	/* on failure */
1770 1771
	elog(ERROR, "Relation \"%s\" has no column \"%s\"",
		 RelationGetRelationName(rd), attname);
1772
	return InvalidAttrNumber;	/* lint */
1773 1774
}

1775
/* specialAttNum()
1776
 *
1777 1778
 * Check attribute name to see if it is "special", e.g. "oid".
 * - thomas 2000-02-07
1779 1780 1781 1782
 *
 * Note: this only discovers whether the name could be a system attribute.
 * Caller needs to verify that it really is an attribute of the rel,
 * at least in the case of "oid", which is now optional.
1783
 */
1784
static int
1785
specialAttNum(const char *attname)
1786
{
1787
	Form_pg_attribute sysatt;
1788

1789 1790
	sysatt = SystemAttributeByName(attname,
								   true /* "oid" will be accepted */ );
1791 1792
	if (sysatt != NULL)
		return sysatt->attnum;
1793 1794 1795 1796
	return InvalidAttrNumber;
}


1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
/*
 * given attribute id, return name of that attribute
 *
 *	This should only be used if the relation is already
 *	heap_open()'ed.  Use the cache version get_atttype()
 *	for access to non-opened relations.
 */
Name
attnumAttName(Relation rd, int attid)
{
	if (attid <= 0)
	{
		Form_pg_attribute sysatt;

		sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
		return &sysatt->attname;
	}
	if (attid > rd->rd_att->natts)
		elog(ERROR, "attnumAttName: invalid attribute number %d", attid);
	return &rd->rd_att->attrs[attid - 1]->attname;
}

Bruce Momjian's avatar
Bruce Momjian committed
1819
/*
1820 1821
 * given attribute id, return type of that attribute
 *
Bruce Momjian's avatar
Bruce Momjian committed
1822 1823 1824 1825
 *	This should only be used if the relation is already
 *	heap_open()'ed.  Use the cache version get_atttype()
 *	for access to non-opened relations.
 */
1826 1827 1828
Oid
attnumTypeId(Relation rd, int attid)
{
1829
	if (attid <= 0)
1830
	{
1831
		Form_pg_attribute sysatt;
1832

1833 1834
		sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
		return sysatt->atttypid;
1835
	}
1836 1837
	if (attid > rd->rd_att->natts)
		elog(ERROR, "attnumTypeId: invalid attribute number %d", attid);
1838
	return rd->rd_att->attrs[attid - 1]->atttypid;
1839
}
1840

1841 1842 1843 1844 1845 1846 1847
/*
 * Generate a warning about an implicit RTE, if appropriate.
 *
 * Our current theory on this is that we should allow "SELECT foo.*"
 * but warn about a mixture of explicit and implicit RTEs.
 */
static void
1848
warnAutoRange(ParseState *pstate, RangeVar *relation)
1849 1850
{
	bool		foundInFromCl = false;
1851
	List	   *temp;
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863

	foreach(temp, pstate->p_rtable)
	{
		RangeTblEntry *rte = lfirst(temp);

		if (rte->inFromCl)
		{
			foundInFromCl = true;
			break;
		}
	}
	if (foundInFromCl)
Bruce Momjian's avatar
Bruce Momjian committed
1864
		elog(NOTICE, "Adding missing FROM-clause entry%s for table \"%s\"",
1865
			 pstate->parentParseState != NULL ? " in subquery" : "",
1866
			 relation->relname);
1867
}