parse_relation.c 43.3 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.75 2002/08/06 05:34:10 momjian 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"
Bruce Momjian's avatar
Bruce Momjian committed
22
#include "catalog/pg_type.h"
23
#include "nodes/makefuncs.h"
24
#include "parser/parsetree.h"
25
#include "parser/parse_coerce.h"
26
#include "parser/parse_expr.h"
Bruce Momjian's avatar
Bruce Momjian committed
27 28
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
29
#include "rewrite/rewriteManip.h"
30
#include "utils/builtins.h"
Bruce Momjian's avatar
Bruce Momjian committed
31
#include "utils/lsyscache.h"
32
#include "utils/syscache.h"
33

34

35
static Node *scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
36
						char *refname);
37
static Node *scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte,
38
				 char *colname);
39
static bool isForUpdate(ParseState *pstate, char *refname);
40 41 42
static bool get_rte_attribute_is_dropped(RangeTblEntry *rte,
										 AttrNumber attnum);
static int	specialAttNum(const char *attname);
43
static void warnAutoRange(ParseState *pstate, RangeVar *relation);
44 45 46


/*
47 48 49
 * refnameRangeTblEntry
 *	  Given a refname, look to see if it matches any RTE.
 *	  If so, return a pointer to the RangeTblEntry.
50 51
 *	  Optionally get its nesting depth (0 = current).	If sublevels_up
 *	  is NULL, only consider items at the current nesting level.
52
 */
53 54 55 56
RangeTblEntry *
refnameRangeTblEntry(ParseState *pstate,
					 char *refname,
					 int *sublevels_up)
57
{
58 59
	if (sublevels_up)
		*sublevels_up = 0;
60 61 62

	while (pstate != NULL)
	{
63
		Node	   *nsnode;
64

65 66 67 68 69 70 71 72 73 74 75
		nsnode = scanNameSpaceForRefname(pstate,
										 (Node *) pstate->p_namespace,
										 refname);
		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);
		}
76

77
		pstate = pstate->parentParseState;
78 79 80 81
		if (sublevels_up)
			(*sublevels_up)++;
		else
			break;
82
	}
83
	return NULL;
84 85
}

86
/*
87 88 89 90 91
 * Recursively search a namespace for an RTE or joinexpr with given refname.
 *
 * The top level of p_namespace is a list, and we recurse into any joins
 * that are not subqueries.  It is also possible to pass an individual
 * join subtree (useful when checking for name conflicts within a scope).
92
 *
93 94
 * Note: we do not worry about the possibility of multiple matches;
 * we assume the code that built the namespace checked for duplicates.
95
 */
96 97 98
static Node *
scanNameSpaceForRefname(ParseState *pstate, Node *nsnode,
						char *refname)
99
{
100
	Node	   *result = NULL;
101

102
	if (nsnode == NULL)
103
		return NULL;
104
	if (IsA(nsnode, RangeTblRef))
105
	{
106 107
		int			varno = ((RangeTblRef *) nsnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
108

109
		if (strcmp(rte->eref->aliasname, refname) == 0)
110
			result = (Node *) rte;
111
	}
112
	else if (IsA(nsnode, JoinExpr))
113
	{
114 115 116 117
		JoinExpr   *j = (JoinExpr *) nsnode;

		if (j->alias)
		{
118
			if (strcmp(j->alias->aliasname, refname) == 0)
119 120
				return (Node *) j;		/* matched a join alias */

121 122 123 124 125 126 127 128
			/*
			 * 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);
129
		if (!result)
130
			result = scanNameSpaceForRefname(pstate, j->rarg, refname);
131
	}
132
	else if (IsA(nsnode, List))
133
	{
134
		List	   *l;
135

136 137 138 139 140 141
		foreach(l, (List *) nsnode)
		{
			result = scanNameSpaceForRefname(pstate, lfirst(l), refname);
			if (result)
				break;
		}
142 143
	}
	else
144 145
		elog(ERROR, "scanNameSpaceForRefname: unexpected node type %d",
			 nodeTag(nsnode));
146 147 148
	return result;
}

149 150 151 152
/* Convenience subroutine for checkNameSpaceConflicts */
static void
scanNameSpaceForConflict(ParseState *pstate, Node *nsnode,
						 char *refname)
153
{
154 155
	if (scanNameSpaceForRefname(pstate, nsnode, refname) != NULL)
		elog(ERROR, "Table name \"%s\" specified more than once", refname);
156 157
}

158
/*
159
 * Recursively check for refname conflicts between two namespaces or
160
 * namespace subtrees.	Raise an error if any is found.
161 162 163 164
 *
 * Works by recursively scanning namespace1 in the same way that
 * scanNameSpaceForRefname does, and then looking in namespace2 for
 * a match to each refname found in namespace1.
165
 *
166 167
 * Note: we assume that each given argument does not contain conflicts
 * itself; we just want to know if the two can be merged together.
168
 */
169 170 171
void
checkNameSpaceConflicts(ParseState *pstate, Node *namespace1,
						Node *namespace2)
172
{
173 174 175 176 177 178
	if (namespace1 == NULL)
		return;
	if (IsA(namespace1, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) namespace1)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
179

180
		scanNameSpaceForConflict(pstate, namespace2, rte->eref->aliasname);
181 182
	}
	else if (IsA(namespace1, JoinExpr))
183
	{
184 185 186
		JoinExpr   *j = (JoinExpr *) namespace1;

		if (j->alias)
187
		{
188
			scanNameSpaceForConflict(pstate, namespace2, j->alias->aliasname);
189

190 191 192 193 194 195 196 197 198 199 200 201 202
			/*
			 * 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;
203

204 205
		foreach(l, (List *) namespace1)
			checkNameSpaceConflicts(pstate, lfirst(l), namespace2);
206
	}
207 208 209
	else
		elog(ERROR, "checkNameSpaceConflicts: unexpected node type %d",
			 nodeTag(namespace1));
210 211 212
}

/*
213 214 215 216
 * 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.
217
 */
218 219
int
RTERangeTablePosn(ParseState *pstate, RangeTblEntry *rte, int *sublevels_up)
220
{
221 222 223 224 225
	int			index;
	List	   *temp;

	if (sublevels_up)
		*sublevels_up = 0;
226

227
	while (pstate != NULL)
228
	{
229 230 231 232 233 234 235 236 237 238
		index = 1;
		foreach(temp, pstate->p_rtable)
		{
			if (rte == (RangeTblEntry *) lfirst(temp))
				return index;
			index++;
		}
		pstate = pstate->parentParseState;
		if (sublevels_up)
			(*sublevels_up)++;
239
		else
240 241
			break;
	}
242

243 244 245 246 247 248 249 250 251
	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.
252 253 254
 *
 * Side effect: if we find a match, mark the RTE as requiring read access.
 * See comments in setTargetTable().
255 256 257 258 259 260
 *
 * 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.
261 262 263 264 265 266 267
 */
static Node *
scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname)
{
	Node	   *result = NULL;
	int			attnum = 0;
	List	   *c;
268

269
	/*
270 271
	 * Scan the user column names (or aliases) for a match. Complain if
	 * multiple matches.
272 273 274 275 276 277 278 279 280 281 282 283 284
	 *
	 * 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.
	 *
	 * 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
	 * routine has to do a cache lookup anyway, so the check there is
	 * cheap.
285
	 */
286
	foreach(c, rte->eref->colnames)
287 288 289
	{
		attnum++;
		if (strcmp(strVal(lfirst(c)), colname) == 0)
290
		{
291 292 293
			if (colname[0] == '.' && /* see note above */
				get_rte_attribute_is_dropped(rte, attnum))
				continue;
294 295 296
			if (result)
				elog(ERROR, "Column reference \"%s\" is ambiguous", colname);
			result = (Node *) make_var(pstate, rte, attnum);
297
			rte->checkForRead = true;
298 299
		}
	}
300

301 302 303 304 305 306
	/*
	 * 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;
307

308
	/*
309
	 * If the RTE represents a real table, consider system column names.
310
	 */
311
	if (rte->rtekind == RTE_RELATION)
312
	{
313
		/* quick check to see if name could be a system column */
314 315
		attnum = specialAttNum(colname);
		if (attnum != InvalidAttrNumber)
316
		{
317 318 319 320 321 322 323 324 325
			/* 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;
			}
326
		}
327 328 329 330
	}

	return result;
}
331

332 333 334 335 336 337 338 339 340 341 342 343
/*
 * 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;
344

345 346
	while (pstate != NULL)
	{
347
		List	   *ns;
348

349
		/*
350
		 * We need to look only at top-level namespace items, and even for
351 352
		 * those, ignore RTEs that are marked as not inFromCl and not the
		 * query's target relation.
353
		 */
354
		foreach(ns, pstate->p_namespace)
355
		{
356 357
			Node	   *nsnode = (Node *) lfirst(ns);
			Node	   *newresult = NULL;
358

359
			if (IsA(nsnode, RangeTblRef))
360
			{
361
				int			varno = ((RangeTblRef *) nsnode)->rtindex;
362 363
				RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);

364
				if (!rte->inFromCl &&
365
					rte != pstate->p_target_rangetblentry)
366 367 368 369 370
					continue;

				/* use orig_pstate here to get the right sublevels_up */
				newresult = scanRTEForColumn(orig_pstate, rte, colname);
			}
371
			else if (IsA(nsnode, JoinExpr))
372
			{
373 374
				int			varno = ((JoinExpr *) nsnode)->rtindex;
				RangeTblEntry *rte = rt_fetch(varno, pstate->p_rtable);
375

376 377 378 379
				/* 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);
380 381
			}
			else
382
				elog(ERROR, "colnameToVar: unexpected node type %d",
383
					 nodeTag(nsnode));
384 385 386 387 388 389 390 391

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

394
		if (result != NULL)
395 396 397
			break;				/* found */

		pstate = pstate->parentParseState;
398
		levels_up++;
399
	}
400 401

	return result;
402 403 404
}

/*
405 406
 * qualifiedNameToVar
 *	  Search for a qualified column name (refname + column name).
407
 *	  If found, return the appropriate Var node.
408 409 410 411 412 413
 *	  If not found, return NULL.  If the name proves ambiguous, raise error.
 */
Node *
qualifiedNameToVar(ParseState *pstate, char *refname, char *colname,
				   bool implicitRTEOK)
{
414
	RangeTblEntry *rte;
415 416
	int			sublevels_up;

417
	rte = refnameRangeTblEntry(pstate, refname, &sublevels_up);
418

419
	if (rte == NULL)
420
	{
421
		if (!implicitRTEOK)
422
			return NULL;
423
		rte = addImplicitRTE(pstate, makeRangeVar(NULL, refname));
424 425
	}

426
	return scanRTEForColumn(pstate, rte, colname);
427 428 429
}

/*
430 431
 * Add an entry for a relation to the pstate's range table (p_rtable).
 *
432 433
 * If pstate is NULL, we just build an RTE and return it without adding it
 * to an rtable list.
434
 *
435 436
 * Note: formerly this checked for refname conflicts, but that's wrong.
 * Caller is responsible for checking for conflicts in the appropriate scope.
437
 */
438 439
RangeTblEntry *
addRangeTableEntry(ParseState *pstate,
440
				   RangeVar *relation,
441
				   Alias *alias,
442
				   bool inh,
443
				   bool inFromCl)
444
{
445
	RangeTblEntry *rte = makeNode(RangeTblEntry);
446
	char	   *refname = alias ? alias->aliasname : relation->relname;
447
	LOCKMODE	lockmode;
448
	Relation	rel;
449
	Alias	   *eref;
450
	int			maxattrs;
451
	int			numaliases;
452
	int			varattno;
453

454
	rte->rtekind = RTE_RELATION;
455
	rte->alias = alias;
456

457 458
	/*
	 * Get the rel's OID.  This access also ensures that we have an
459 460 461
	 * 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.
462
	 */
463
	lockmode = isForUpdate(pstate, refname) ? RowShareLock : AccessShareLock;
464
	rel = heap_openrv(relation, lockmode);
465
	rte->relid = RelationGetRelid(rel);
466

467 468
	eref = alias ? (Alias *) copyObject(alias) : makeAlias(refname, NIL);
	numaliases = length(eref->colnames);
469

470
	/*
471 472
	 * Since the rel is open anyway, let's check that the number of column
	 * aliases is reasonable. - Thomas 2000-02-04
473 474
	 */
	maxattrs = RelationGetNumberOfAttributes(rel);
475 476
	if (maxattrs < numaliases)
		elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
			 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);
571

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

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

582
	/*
583 584 585
	 * 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.
586 587
	 */
	heap_close(rel, NoLock);
588 589 590 591 592

	/*----------
	 * Flags:
	 * - this RTE should be expanded to include descendant tables,
	 * - this RTE is in the FROM clause,
593 594 595 596
	 * - 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.
597
	 *----------
598 599 600
	 */
	rte->inh = inh;
	rte->inFromCl = inFromCl;
601 602 603
	rte->checkForRead = true;
	rte->checkForWrite = false;

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

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

	return rte;
}

616
/*
617 618 619 620 621 622 623 624
 * 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,
625
							  Alias *alias,
626 627
							  bool inFromCl)
{
628
	RangeTblEntry *rte = makeNode(RangeTblEntry);
629 630
	char	   *refname = alias->aliasname;
	Alias	   *eref;
631 632 633 634
	int			numaliases;
	int			varattno;
	List	   *tlistitem;

635
	rte->rtekind = RTE_SUBQUERY;
636 637 638 639 640
	rte->relid = InvalidOid;
	rte->subquery = subquery;
	rte->alias = alias;

	eref = copyObject(alias);
641
	numaliases = length(eref->colnames);
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

	/* 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);
658
			eref->colnames = lappend(eref->colnames, makeString(attrname));
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
		}
	}
	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;

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

	return rte;
}

693 694 695 696 697 698 699 700 701
/*
 * 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,
702
							  RangeFunction *rangefunc,
703 704 705 706
							  bool inFromCl)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
	Oid			funcrettype = exprType(funcexpr);
707 708 709
	char		functyptype;
	Alias	   *alias = rangefunc->alias;
	List	   *coldeflist = rangefunc->coldeflist;
710 711 712 713 714 715 716 717
	Alias	   *eref;
	int			numaliases;
	int			varattno;

	rte->rtekind = RTE_FUNCTION;
	rte->relid = InvalidOid;
	rte->subquery = NULL;
	rte->funcexpr = funcexpr;
718
	rte->coldeflist = coldeflist;
719 720 721 722 723 724 725 726 727 728 729
	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.
	 */
730
	functyptype = get_typtype(funcrettype);
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	if (coldeflist != NIL)
	{
		/*
		 * we *only* allow a coldeflist for functions returning a
		 * RECORD pseudo-type
		 */
		if (functyptype != 'p' || (functyptype == 'p' && funcrettype != RECORDOID))
			elog(ERROR, "A column definition list is only allowed for"
						" functions returning RECORD");
	}
	else
	{
		/*
		 * ... and a coldeflist is *required* for functions returning a
		 * RECORD pseudo-type
		 */
		if (functyptype == 'p' && funcrettype == RECORDOID)
			elog(ERROR, "A column definition list is required for functions"
						" returning RECORD");
	}

753
	if (functyptype == 'c')
754 755
	{
		/*
756
		 * Named composite data type, i.e. a table's row type
757
		 */
758
		Oid			funcrelid = typeidTypeRelid(funcrettype);
759

760 761 762 763 764 765 766 767
		if (OidIsValid(funcrelid))
		{
			/*
			 * Get the rel's relcache entry.  This access ensures that we have an
			 * up-to-date relcache entry for the rel.
			 */
			Relation	rel;
			int			maxattrs;
768

769
			rel = heap_open(funcrelid, AccessShareLock);
770

771 772 773 774 775 776 777 778
			/*
			 * Since the rel is open anyway, let's check that the number of column
			 * aliases is reasonable.
			 */
			maxattrs = RelationGetNumberOfAttributes(rel);
			if (maxattrs < numaliases)
				elog(ERROR, "Table \"%s\" has %d columns available but %d columns specified",
					 RelationGetRelationName(rel), maxattrs, numaliases);
779

780 781 782 783
			/* fill in alias columns using actual column names */
			for (varattno = numaliases; varattno < maxattrs; varattno++)
			{
				char	   *attrname;
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798
				attrname = pstrdup(NameStr(rel->rd_att->attrs[varattno]->attname));
				eref->colnames = lappend(eref->colnames, makeString(attrname));
			}

			/*
			 * 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);
		}
		else
			elog(ERROR, "Invalid return relation specified for function %s",
				 funcname);
799
	}
800
	else if (functyptype == 'b' || functyptype == 'd')
801 802 803 804 805 806 807 808 809
	{
		/*
		 * Must be a base data type, i.e. scalar.
		 * Just add one alias column named for the function.
		 */
		if (numaliases > 1)
			elog(ERROR, "Too many column aliases specified for function %s",
				 funcname);
		if (numaliases == 0)
810
			eref->colnames = makeList1(makeString(eref->aliasname));
811
	}
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	else if (functyptype == 'p' && funcrettype == RECORDOID)
	{
		List	   *col;

		foreach(col, coldeflist)
		{
			char	   *attrname;
			ColumnDef  *n = lfirst(col);

			attrname = pstrdup(n->colname);
			eref->colnames = lappend(eref->colnames, makeString(attrname));
		}
	}
	else
		elog(ERROR, "Unknown kind of return type specified for function %s",
			 funcname);
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

	/*----------
	 * 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;
}

853 854 855 856 857 858 859 860 861
/*
 * 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,
862
						  List *aliasvars,
863
						  Alias *alias,
864 865 866
						  bool inFromCl)
{
	RangeTblEntry *rte = makeNode(RangeTblEntry);
867
	Alias	   *eref;
868 869 870 871 872 873
	int			numaliases;

	rte->rtekind = RTE_JOIN;
	rte->relid = InvalidOid;
	rte->subquery = NULL;
	rte->jointype = jointype;
874
	rte->joinaliasvars = aliasvars;
875 876
	rte->alias = alias;

877 878
	eref = alias ? (Alias *) copyObject(alias) : makeAlias("unnamed_join", NIL);
	numaliases = length(eref->colnames);
879 880 881 882 883 884

	/* fill in any unspecified alias columns */
	if (numaliases < length(colnames))
	{
		while (numaliases-- > 0)
			colnames = lnext(colnames);
885
		eref->colnames = nconc(eref->colnames, colnames);
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
	}

	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;
}

916
/*
917
 * Has the specified refname been selected FOR UPDATE?
918 919
 */
static bool
920
isForUpdate(ParseState *pstate, char *refname)
921 922 923 924 925 926 927 928 929 930 931 932 933 934
{
	/* 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 */
935
				List	   *l;
936 937 938

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

941
					if (strcmp(refname, rname) == 0)
942 943 944 945 946 947 948 949 950
						return true;
				}
			}
		}
		pstate = pstate->parentParseState;
	}
	return false;
}

951
/*
952
 * Add the given RTE as a top-level entry in the pstate's join list
953
 * and/or name space list.	(We assume caller has checked for any
954
 * namespace conflict.)
955
 */
956
void
957 958
addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte,
			  bool addToJoinList, bool addToNameSpace)
959 960
{
	int			rtindex = RTERangeTablePosn(pstate, rte, NULL);
961
	RangeTblRef *rtr = makeNode(RangeTblRef);
962 963

	rtr->rtindex = rtindex;
964 965 966 967 968

	if (addToJoinList)
		pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
	if (addToNameSpace)
		pstate->p_namespace = lappend(pstate->p_namespace, rtr);
969 970 971 972 973
}

/*
 * Add a POSTQUEL-style implicit RTE.
 *
974 975
 * We assume caller has already checked that there is no RTE or join with
 * a conflicting name.
976 977
 */
RangeTblEntry *
978
addImplicitRTE(ParseState *pstate, RangeVar *relation)
979
{
980
	RangeTblEntry *rte;
981

982
	rte = addRangeTableEntry(pstate, relation, NULL, false, false);
983
	addRTEtoQuery(pstate, rte, true, true);
984
	warnAutoRange(pstate, relation);
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002

	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)
{
1003 1004 1005
	int			rtindex,
				sublevels_up,
				varattno;
1006

1007 1008 1009 1010
	if (colnames)
		*colnames = NIL;
	if (colvars)
		*colvars = NIL;
1011

1012 1013
	/* Need the RT index of the entry for creating Vars */
	rtindex = RTERangeTablePosn(pstate, rte, &sublevels_up);
1014

1015
	switch (rte->rtekind)
1016
	{
1017 1018 1019 1020 1021 1022
		case RTE_RELATION:
			{
				/* Ordinary relation RTE */
				Relation	rel;
				int			maxattrs;
				int			numaliases;
1023

1024 1025 1026
				rel = heap_open(rte->relid, AccessShareLock);
				maxattrs = RelationGetNumberOfAttributes(rel);
				numaliases = length(rte->eref->colnames);
1027

1028 1029 1030
				for (varattno = 0; varattno < maxattrs; varattno++)
				{
					Form_pg_attribute attr = rel->rd_att->attrs[varattno];
1031

1032 1033 1034
					if (attr->attisdropped)
						continue;

1035 1036 1037
					if (colnames)
					{
						char	   *label;
1038

1039 1040 1041 1042 1043 1044
						if (varattno < numaliases)
							label = strVal(nth(varattno, rte->eref->colnames));
						else
							label = NameStr(attr->attname);
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
					}
1045

1046 1047 1048
					if (colvars)
					{
						Var		   *varnode;
1049

1050 1051 1052 1053 1054 1055 1056
						varnode = makeVar(rtindex, attr->attnum,
										  attr->atttypid, attr->atttypmod,
										  sublevels_up);

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

1058
				heap_close(rel, AccessShareLock);
1059
			}
1060 1061 1062 1063 1064 1065
			break;
		case RTE_SUBQUERY:
			{
				/* Subquery RTE */
				List	   *aliasp = rte->eref->colnames;
				List	   *tlistitem;
1066

1067 1068 1069 1070
				varattno = 0;
				foreach(tlistitem, rte->subquery->targetList)
				{
					TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1071

1072 1073 1074 1075
					if (te->resdom->resjunk)
						continue;
					varattno++;
					Assert(varattno == te->resdom->resno);
1076

1077 1078 1079 1080
					if (colnames)
					{
						/* Assume there is one alias per target item */
						char	   *label = strVal(lfirst(aliasp));
1081

1082 1083 1084
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
						aliasp = lnext(aliasp);
					}
1085

1086 1087 1088
					if (colvars)
					{
						Var		   *varnode;
1089

1090 1091 1092 1093
						varnode = makeVar(rtindex, varattno,
										  te->resdom->restype,
										  te->resdom->restypmod,
										  sublevels_up);
1094

1095 1096 1097 1098 1099 1100 1101 1102
						*colvars = lappend(*colvars, varnode);
					}
				}
			}
			break;
		case RTE_FUNCTION:
			{
				/* Function RTE */
1103
				Oid	funcrettype = exprType(rte->funcexpr);
1104
				char functyptype = get_typtype(funcrettype);
1105
				List *coldeflist = rte->coldeflist;
1106

1107 1108 1109 1110
				/*
				 * Build a suitable tupledesc representing the output rows
				 */
				if (functyptype == 'c')
1111
				{
1112 1113
					Oid	funcrelid = typeidTypeRelid(funcrettype);
					if (OidIsValid(funcrelid))
1114
					{
1115 1116 1117 1118 1119 1120 1121
						/*
						 * Composite data type, i.e. a table's row type
						 * Same as ordinary relation RTE
						 */
						Relation	rel;
						int			maxattrs;
						int			numaliases;
1122

1123 1124 1125
						rel = heap_open(funcrelid, AccessShareLock);
						maxattrs = RelationGetNumberOfAttributes(rel);
						numaliases = length(rte->eref->colnames);
1126

1127
						for (varattno = 0; varattno < maxattrs; varattno++)
1128
						{
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
							Form_pg_attribute attr = rel->rd_att->attrs[varattno];

							if (attr->attisdropped)
								continue;

							if (colnames)
							{
								char	   *label;

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

							if (colvars)
							{
								Var		   *varnode;

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

								*colvars = lappend(*colvars, varnode);
							}
1157 1158
						}

1159 1160 1161 1162 1163
						heap_close(rel, AccessShareLock);
					}
					else
						elog(ERROR, "Invalid return relation specified"
									" for function");
1164
				}
1165
				else if (functyptype == 'b' || functyptype == 'd')
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
				{
					/*
					 * 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);
					}
				}
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
				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;
							HeapTuple	typeTuple;
							Oid			atttypid;

							typeTuple = typenameType(colDef->typename);
							atttypid = HeapTupleGetOid(typeTuple);
							ReleaseSysCache(typeTuple);

							varnode = makeVar(rtindex,
											attnum,
											atttypid,
											-1,
											sublevels_up);

							*colvars = lappend(*colvars, varnode);
						}
					}
				}
				else
					elog(ERROR, "Unknown kind of return type specified"
								" for function");
1226
			}
1227 1228 1229 1230 1231 1232
			break;
		case RTE_JOIN:
			{
				/* Join RTE */
				List	   *aliasp = rte->eref->colnames;
				List	   *aliasvars = rte->joinaliasvars;
1233

1234 1235 1236 1237 1238
				varattno = 0;
				while (aliasp)
				{
					Assert(aliasvars);
					varattno++;
1239

1240 1241 1242
					if (colnames)
					{
						char	   *label = strVal(lfirst(aliasp));
1243

1244 1245
						*colnames = lappend(*colnames, makeString(pstrdup(label)));
					}
Bruce Momjian's avatar
Bruce Momjian committed
1246

1247 1248 1249 1250
					if (colvars)
					{
						Node	   *aliasvar = (Node *) lfirst(aliasvars);
						Var		   *varnode;
1251

1252 1253 1254 1255
						varnode = makeVar(rtindex, varattno,
										  exprType(aliasvar),
										  exprTypmod(aliasvar),
										  sublevels_up);
1256

1257 1258
						*colvars = lappend(*colvars, varnode);
					}
1259

1260 1261 1262 1263 1264 1265 1266 1267 1268
					aliasp = lnext(aliasp);
					aliasvars = lnext(aliasvars);
				}
				Assert(aliasvars == NIL);
			}
			break;
		default:
			elog(ERROR, "expandRTE: unsupported RTE kind %d",
				 (int) rte->rtekind);
1269
	}
1270
}
1271

1272
/*
1273 1274 1275
 * expandRelAttrs -
 *	  Workhorse for "*" expansion: produce a list of targetentries
 *	  for the attributes of the rte
1276
 */
1277 1278
List *
expandRelAttrs(ParseState *pstate, RangeTblEntry *rte)
1279
{
1280 1281
	List	   *names,
			   *vars;
1282
	List	   *te_list = NIL;
1283

1284 1285
	expandRTE(pstate, rte, &names, &vars);

1286 1287 1288 1289 1290
	while (names)
	{
		char	   *label = strVal(lfirst(names));
		Node	   *varnode = (Node *) lfirst(vars);
		TargetEntry *te = makeNode(TargetEntry);
1291

1292 1293 1294
		te->resdom = makeResdom((AttrNumber) (pstate->p_last_resno)++,
								exprType(varnode),
								exprTypmod(varnode),
1295
								label,
Bruce Momjian's avatar
Bruce Momjian committed
1296
								false);
1297
		te->expr = varnode;
1298
		te_list = lappend(te_list, te);
1299 1300 1301

		names = lnext(names);
		vars = lnext(vars);
1302 1303
	}

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

1306
	return te_list;
1307 1308
}

1309
/*
1310 1311 1312 1313
 * get_rte_attribute_name
 *		Get an attribute name from a RangeTblEntry
 *
 * This is unlike get_attname() because we use aliases if available.
1314
 * In particular, it will work on an RTE for a subselect or join, whereas
1315
 * get_attname() only works on real relations.
1316
 *
1317 1318
 * "*" is returned if the given attnum is InvalidAttrNumber --- this case
 * occurs when a Var represents a whole tuple of a relation.
1319 1320 1321 1322 1323 1324
 */
char *
get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
{
	char	   *attname;

1325 1326 1327
	if (attnum == InvalidAttrNumber)
		return "*";

1328
	/*
1329 1330
	 * If there is an alias, use it.  (This path should always be taken
	 * for non-relation RTEs.)
1331
	 */
1332 1333
	if (attnum > 0 && attnum <= length(rte->eref->colnames))
		return strVal(nth(attnum - 1, rte->eref->colnames));
1334

1335
	/*
1336 1337
	 * Can get here for a system attribute (which never has an alias), or
	 * if alias name list is too short (which probably can't happen
1338
	 * anymore).  Neither of these cases is valid for a non-relation RTE.
1339
	 */
1340
	if (rte->rtekind != RTE_RELATION)
1341
		elog(ERROR, "Invalid attnum %d for rangetable entry %s",
1342
			 attnum, rte->eref->aliasname);
1343

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	/*
	 * Use the real name of the table's column
	 */
	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;
}

1354 1355 1356 1357 1358 1359 1360 1361
/*
 * get_rte_attribute_type
 *		Get attribute type information from a RangeTblEntry
 */
void
get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum,
					   Oid *vartype, int32 *vartypmod)
{
1362
	switch (rte->rtekind)
1363
	{
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
		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))
1376
					elog(ERROR, "Relation \"%s\" does not have attribute %d",
1377 1378
						 get_rel_name(rte->relid), attnum);
				att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1379 1380 1381 1382 1383 1384 1385
				/*
				 * If dropped column, pretend it ain't there.  See notes
				 * in scanRTEForColumn.
				 */
				if (att_tup->attisdropped)
					elog(ERROR, "Relation \"%s\" has no column \"%s\"",
						 get_rel_name(rte->relid), NameStr(att_tup->attname));
1386 1387 1388 1389 1390 1391 1392 1393 1394
				*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;
1395

1396 1397 1398
				foreach(tlistitem, rte->subquery->targetList)
				{
					TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
1399

1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
					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 */
1414
				Oid funcrettype = exprType(rte->funcexpr);
1415
				char functyptype = get_typtype(funcrettype);
1416
				List *coldeflist = rte->coldeflist;
1417

1418 1419 1420 1421
				/*
				 * Build a suitable tupledesc representing the output rows
				 */
				if (functyptype == 'c')
1422 1423 1424 1425 1426
				{
					/*
					 * Composite data type, i.e. a table's row type
					 * Same as ordinary relation RTE
					 */
1427
					Oid funcrelid = typeidTypeRelid(funcrettype);
1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
					if (OidIsValid(funcrelid))
					{
						HeapTuple			tp;
						Form_pg_attribute	att_tup;

						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);
						/*
						 * If dropped column, pretend it ain't there.  See notes
						 * in scanRTEForColumn.
						 */
						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);
					}
					else
						elog(ERROR, "Invalid return relation specified"
									" for function");
1458
				}
1459
				else if (functyptype == 'b' || functyptype == 'd')
1460 1461 1462 1463 1464 1465 1466
				{
					/*
					 * Must be a base data type, i.e. scalar
					 */
					*vartype = funcrettype;
					*vartypmod = -1;
				}
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
				else if (functyptype == 'p' && funcrettype == RECORDOID)
				{
					ColumnDef  *colDef = nth(attnum - 1, coldeflist);
					HeapTuple	typeTuple;
					Oid			atttypid;

					typeTuple = typenameType(colDef->typename);
					atttypid = HeapTupleGetOid(typeTuple);
					ReleaseSysCache(typeTuple);

					*vartype = atttypid;
					*vartypmod = -1;
				}
				else
					elog(ERROR, "Unknown kind of return type specified"
								" for function");
1483 1484 1485 1486 1487 1488
			}
			break;
		case RTE_JOIN:
			{
				/* Join RTE --- get type info from join RTE's alias variable */
				Node   *aliasvar;
1489

1490 1491 1492 1493 1494 1495 1496 1497 1498
				Assert(attnum > 0 && attnum <= length(rte->joinaliasvars));
				aliasvar = (Node *) nth(attnum-1, rte->joinaliasvars);
				*vartype = exprType(aliasvar);
				*vartypmod = exprTypmod(aliasvar);
			}
			break;
		default:
			elog(ERROR, "get_rte_attribute_type: unsupported RTE kind %d",
				 (int) rte->rtekind);
1499 1500 1501
	}
}

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
/*
 * 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)
{
	bool result;

	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))
				{
					/*
					 * Composite data type, i.e. a table's row type
					 * Same as ordinary relation RTE
					 */
					HeapTuple			tp;
					Form_pg_attribute	att_tup;

					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
1582 1583 1584 1585 1586 1587 1588
/*
 *	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.
 */
1589
int
1590
attnameAttNum(Relation rd, const char *attname, bool sysColOK)
1591 1592 1593 1594
{
	int			i;

	for (i = 0; i < rd->rd_rel->relnatts; i++)
1595 1596 1597 1598
	{
		Form_pg_attribute	att = rd->rd_att->attrs[i];

		if (namestrcmp(&(att->attname), attname) == 0 && !att->attisdropped)
1599
			return i + 1;
1600
	}
1601

1602
	if (sysColOK)
1603
	{
1604 1605 1606 1607 1608
		if ((i = specialAttNum(attname)) != InvalidAttrNumber)
		{
			if (i != ObjectIdAttributeNumber || rd->rd_rel->relhasoids)
				return i;
		}
1609
	}
1610 1611

	/* on failure */
1612 1613
	elog(ERROR, "Relation \"%s\" has no column \"%s\"",
		 RelationGetRelationName(rd), attname);
1614
	return InvalidAttrNumber;	/* lint */
1615 1616
}

1617
/* specialAttNum()
1618
 *
1619 1620
 * Check attribute name to see if it is "special", e.g. "oid".
 * - thomas 2000-02-07
1621 1622 1623 1624
 *
 * 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.
1625
 */
1626
static int
1627
specialAttNum(const char *attname)
1628
{
1629
	Form_pg_attribute sysatt;
1630

1631 1632
	sysatt = SystemAttributeByName(attname,
								   true /* "oid" will be accepted */ );
1633 1634
	if (sysatt != NULL)
		return sysatt->attnum;
1635 1636 1637 1638
	return InvalidAttrNumber;
}


1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
/*
 * 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
1661
/*
1662 1663
 * given attribute id, return type of that attribute
 *
Bruce Momjian's avatar
Bruce Momjian committed
1664 1665 1666 1667
 *	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.
 */
1668 1669 1670
Oid
attnumTypeId(Relation rd, int attid)
{
1671
	if (attid <= 0)
1672
	{
1673
		Form_pg_attribute sysatt;
1674

1675 1676
		sysatt = SystemAttributeDefinition(attid, rd->rd_rel->relhasoids);
		return sysatt->atttypid;
1677
	}
1678 1679
	if (attid > rd->rd_att->natts)
		elog(ERROR, "attnumTypeId: invalid attribute number %d", attid);
1680
	return rd->rd_att->attrs[attid - 1]->atttypid;
1681
}
1682

1683 1684 1685 1686 1687 1688 1689
/*
 * 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
1690
warnAutoRange(ParseState *pstate, RangeVar *relation)
1691 1692
{
	bool		foundInFromCl = false;
1693
	List	   *temp;
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

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

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