parse_clause.c 34.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * parse_clause.c
4 5
 *	  handle clauses in parser
 *
6
 * Portions Copyright (c) 1996-2001, 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_clause.c,v 1.76 2001/02/14 21:35:03 tgl Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
Bruce Momjian's avatar
Bruce Momjian committed
15

16
#include "postgres.h"
17

18
#include "access/heapam.h"
19
#include "nodes/makefuncs.h"
20 21
#include "optimizer/tlist.h"
#include "optimizer/var.h"
22
#include "parser/analyze.h"
23
#include "parser/parse.h"
24
#include "parser/parsetree.h"
25
#include "parser/parse_clause.h"
Bruce Momjian's avatar
Bruce Momjian committed
26
#include "parser/parse_coerce.h"
27 28 29 30
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
Bruce Momjian's avatar
Bruce Momjian committed
31
#include "parser/parse_type.h"
32 33
#include "utils/guc.h"

34

35 36
#define ORDER_CLAUSE 0
#define GROUP_CLAUSE 1
37
#define DISTINCT_ON_CLAUSE 2
38

39
static char *clauseText[] = {"ORDER BY", "GROUP BY", "DISTINCT ON"};
40

41 42 43
static void extractUniqueColumns(List *common_colnames,
								 List *src_colnames, List *src_colvars,
								 List **res_colnames, List **res_colvars);
44 45 46 47
static Node *transformJoinUsingClause(ParseState *pstate,
									  List *leftVars, List *rightVars);
static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
								   List *containedRels);
48 49 50
static RangeTblRef *transformTableEntry(ParseState *pstate, RangeVar *r);
static RangeTblRef *transformRangeSubselect(ParseState *pstate,
											RangeSubselect *r);
51 52
static Node *transformFromClauseItem(ParseState *pstate, Node *n,
									 List **containedRels);
53
static TargetEntry *findTargetlistEntry(ParseState *pstate, Node *node,
54
					List *tlist, int clause);
55
static List *addTargetToSortList(TargetEntry *tle, List *sortlist,
56
					List *targetlist, char *opname);
57
static bool exprIsInSortList(Node *expr, List *sortList, List *targetList);
58

59 60

/*
61 62 63
 * transformFromClause -
 *	  Process the FROM clause and add items to the query's range table,
 *	  joinlist, and namespace.
64
 *
65 66 67 68
 * Note: we assume that pstate's p_rtable, p_joinlist, and p_namespace lists
 * were initialized to NIL when the pstate was created.  We will add onto
 * any entries already present --- this is needed for rule processing, as
 * well as for UPDATE and DELETE.
69
 *
70 71 72 73
 * The range table may grow still further when we transform the expressions
 * in the query's quals and target list. (This is possible because in
 * POSTQUEL, we allowed references to relations not specified in the
 * from-clause.  PostgreSQL keeps this extension to standard SQL.)
74 75
 */
void
76
transformFromClause(ParseState *pstate, List *frmList)
77
{
78 79 80 81
	List	   *fl;

	/*
	 * The grammar will have produced a list of RangeVars, RangeSubselects,
82 83 84
	 * and/or JoinExprs. Transform each one (possibly adding entries to the
	 * rtable), check for duplicate refnames, and then add it to the joinlist
	 * and namespace.
85 86 87 88
	 */
	foreach(fl, frmList)
	{
		Node	   *n = lfirst(fl);
89
		List	   *containedRels;
90

91
		n = transformFromClauseItem(pstate, n, &containedRels);
92
		checkNameSpaceConflicts(pstate, (Node *) pstate->p_namespace, n);
93
		pstate->p_joinlist = lappend(pstate->p_joinlist, n);
94
		pstate->p_namespace = lappend(pstate->p_namespace, n);
95
	}
96
}
97

98
/*
99 100 101 102 103 104 105 106
 * setTargetTable
 *	  Add the target relation of INSERT/UPDATE/DELETE to the range table,
 *	  and make the special links to it in the ParseState.
 *
 *	  We also open the target relation and acquire a write lock on it.
 *	  This must be done before processing the FROM list, in case the target
 *	  is also mentioned as a source relation --- we want to be sure to grab
 *	  the write lock before any read lock.
107
 *
108 109 110 111 112 113 114 115
 *	  If alsoSource is true, add the target to the query's joinlist and
 *	  namespace.  For INSERT, we don't want the target to be joined to;
 *	  it's a destination of tuples, not a source.	For UPDATE/DELETE,
 *	  we do need to scan or join the target.  (NOTE: we do not bother
 *	  to check for namespace conflict; we assume that the namespace was
 *	  initially empty in these cases.)
 *
 *	  Returns the rangetable index of the target relation.
116
 */
117 118 119
int
setTargetTable(ParseState *pstate, char *relname,
			   bool inh, bool alsoSource)
120
{
121 122 123
	RangeTblEntry *rte;
	int			rtindex;

124 125 126 127 128 129 130 131 132 133 134 135 136
	/* Close old target; this could only happen for multi-action rules */
	if (pstate->p_target_relation != NULL)
		heap_close(pstate->p_target_relation, NoLock);

	/*
	 * Open target rel and grab suitable lock (which we will hold till
	 * end of transaction).
	 *
	 * analyze.c will eventually do the corresponding heap_close(),
	 * but *not* release the lock.
	 */
	pstate->p_target_relation = heap_openr(relname, RowExclusiveLock);

137 138 139 140 141
	/*
	 * Now build an RTE.
	 */
	rte = addRangeTableEntry(pstate, relname, NULL, inh, false);
	pstate->p_target_rangetblentry = rte;
142

143 144 145
	/* assume new rte is at end */
	rtindex = length(pstate->p_rtable);
	Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
146

147 148 149 150 151 152 153 154 155 156
	/*
	 * Override addRangeTableEntry's default checkForRead, and instead
	 * mark target table as requiring write access.
	 *
	 * If we find an explicit reference to the rel later during
	 * parse analysis, scanRTEForColumn will change checkForRead
	 * to 'true' again.  That can't happen for INSERT but it is
	 * possible for UPDATE and DELETE.
	 */
	rte->checkForRead = false;
157 158
	rte->checkForWrite = true;

159 160 161 162 163
	/*
	 * If UPDATE/DELETE, add table to joinlist and namespace.
	 */
	if (alsoSource)
		addRTEtoQuery(pstate, rte, true, true);
164

165
	return rtindex;
166 167
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
/*
 * Simplify InhOption (yes/no/default) into boolean yes/no.
 *
 * The reason we do things this way is that we don't want to examine the
 * SQL_inheritance option flag until parse_analyze is run.  Otherwise,
 * we'd do the wrong thing with query strings that intermix SET commands
 * with queries.
 */
bool
interpretInhOption(InhOption inhOpt)
{
	switch (inhOpt)
	{
		case INH_NO:
			return false;
		case INH_YES:
			return true;
		case INH_DEFAULT:
			return SQL_inheritance;
	}
	elog(ERROR, "Bogus InhOption value");
	return false;				/* keep compiler quiet */
}
191 192

/*
193
 * Extract all not-in-common columns from column lists of a source table
194
 */
195 196 197 198
static void
extractUniqueColumns(List *common_colnames,
					 List *src_colnames, List *src_colvars,
					 List **res_colnames, List **res_colvars)
199
{
200 201 202 203
	List	   *new_colnames = NIL;
	List	   *new_colvars = NIL;
	List	   *lnames,
			   *lvars = src_colvars;
204

205
	foreach(lnames, src_colnames)
206
	{
207 208 209
		char	   *colname = strVal(lfirst(lnames));
		bool		match = false;
		List	   *cnames;
210

211
		foreach(cnames, common_colnames)
212
		{
213
			char	   *ccolname = strVal(lfirst(cnames));
214

215
			if (strcmp(colname, ccolname) == 0)
216
			{
217
				match = true;
218 219 220 221 222
				break;
			}
		}

		if (!match)
223 224 225 226
		{
			new_colnames = lappend(new_colnames, lfirst(lnames));
			new_colvars = lappend(new_colvars, lfirst(lvars));
		}
227

228
		lvars = lnext(lvars);
229 230
	}

231 232
	*res_colnames = new_colnames;
	*res_colvars = new_colvars;
233 234
}

235 236 237 238
/* transformJoinUsingClause()
 *	  Build a complete ON clause from a partially-transformed USING list.
 *	  We are given lists of nodes representing left and right match columns.
 *	  Result is a transformed qualification expression.
239
 */
240
static Node *
241
transformJoinUsingClause(ParseState *pstate, List *leftVars, List *rightVars)
242
{
243 244 245
	Node	   *result = NULL;
	List	   *lvars,
			   *rvars = rightVars;
246

247 248 249 250 251 252 253
	/*
	 * We cheat a little bit here by building an untransformed operator
	 * tree whose leaves are the already-transformed Vars.  This is OK
	 * because transformExpr() won't complain about already-transformed
	 * subnodes.
	 */
	foreach(lvars, leftVars)
254
	{
255 256
		Node	   *lvar = (Node *) lfirst(lvars);
		Node	   *rvar = (Node *) lfirst(rvars);
257
		A_Expr	   *e;
258

259 260 261 262 263
		e = makeNode(A_Expr);
		e->oper = OP;
		e->opname = "=";
		e->lexpr = copyObject(lvar);
		e->rexpr = copyObject(rvar);
264

265 266 267
		if (result == NULL)
			result = (Node *) e;
		else
268
		{
269
			A_Expr	   *a = makeNode(A_Expr);
Bruce Momjian's avatar
Bruce Momjian committed
270

271 272 273 274 275
			a->oper = AND;
			a->opname = NULL;
			a->lexpr = result;
			a->rexpr = (Node *) e;
			result = (Node *) a;
276 277
		}

278 279
		rvars = lnext(rvars);
	}
280

281 282 283 284 285 286
	/*
	 * Since the references are already Vars, and are certainly from the
	 * input relations, we don't have to go through the same pushups that
	 * transformJoinOnClause() does.  Just invoke transformExpr() to fix
	 * up the operators, and we're done.
	 */
287
	result = transformExpr(pstate, result, EXPR_COLUMN_FIRST);
288

289 290 291
	if (exprType(result) != BOOLOID)
	{
		/* This could only happen if someone defines a funny version of '=' */
292
		elog(ERROR, "JOIN/USING clause must return type bool, not type %s",
293
			 typeidTypeName(exprType(result)));
294
	}
Bruce Momjian's avatar
Bruce Momjian committed
295

296
	return result;
297 298 299 300 301 302 303 304 305 306 307
}	/* transformJoinUsingClause() */

/* transformJoinOnClause()
 *	  Transform the qual conditions for JOIN/ON.
 *	  Result is a transformed qualification expression.
 */
static Node *
transformJoinOnClause(ParseState *pstate, JoinExpr *j,
					  List *containedRels)
{
	Node	   *result;
308
	List	   *save_namespace;
309 310 311 312
	List	   *clause_varnos,
			   *l;

	/*
313 314 315 316 317 318 319
	 * This is a tad tricky, for two reasons.  First, the namespace that
	 * the join expression should see is just the two subtrees of the JOIN
	 * plus any outer references from upper pstate levels.  So, temporarily
	 * set this pstate's namespace accordingly.  (We need not check for
	 * refname conflicts, because transformFromClauseItem() already did.)
	 * NOTE: this code is OK only because the ON clause can't legally alter
	 * the namespace by causing implicit relation refs to be added.
320
	 */
321 322
	save_namespace = pstate->p_namespace;
	pstate->p_namespace = makeList2(j->larg, j->rarg);
323 324 325 326 327 328 329 330 331

	/* This part is just like transformWhereClause() */
	result = transformExpr(pstate, j->quals, EXPR_COLUMN_FIRST);
	if (exprType(result) != BOOLOID)
	{
		elog(ERROR, "JOIN/ON clause must return type bool, not type %s",
			 typeidTypeName(exprType(result)));
	}

332
	pstate->p_namespace = save_namespace;
333 334 335 336

	/*
	 * Second, we need to check that the ON condition doesn't refer to any
	 * rels outside the input subtrees of the JOIN.  It could do that despite
337
	 * our hack on the namespace if it uses fully-qualified names.  So, grovel
338
	 * through the transformed clause and make sure there are no bogus
339
	 * references.  (Outer references are OK, and are ignored here.)
340 341 342 343 344
	 */
	clause_varnos = pull_varnos(result);
	foreach(l, clause_varnos)
	{
		int		varno = lfirsti(l);
345

346 347 348 349 350 351 352 353 354 355
		if (! intMember(varno, containedRels))
		{
			elog(ERROR, "JOIN/ON clause refers to \"%s\", which is not part of JOIN",
				 rt_fetch(varno, pstate->p_rtable)->eref->relname);
		}
	}
	freeList(clause_varnos);

	return result;
}
356

357 358 359 360
/*
 * transformTableEntry --- transform a RangeVar (simple relation reference)
 */
static RangeTblRef *
361 362
transformTableEntry(ParseState *pstate, RangeVar *r)
{
363
	char	   *relname = r->relname;
364
	RangeTblEntry *rte;
365
	RangeTblRef *rtr;
366 367

	/*
368
	 * mark this entry to indicate it comes from the FROM clause. In SQL,
Bruce Momjian's avatar
Bruce Momjian committed
369 370 371 372
	 * the target list can only refer to range variables specified in the
	 * from clause but we follow the more powerful POSTQUEL semantics and
	 * automatically generate the range variable if not specified. However
	 * there are times we need to know whether the entries are legitimate.
373
	 */
374 375
	rte = addRangeTableEntry(pstate, relname, r->name,
							 interpretInhOption(r->inhOpt), true);
376

377
	/*
378 379
	 * We create a RangeTblRef, but we do not add it to the joinlist or
	 * namespace; our caller must do that if appropriate.
380 381 382 383 384
	 */
	rtr = makeNode(RangeTblRef);
	/* assume new rte is at end */
	rtr->rtindex = length(pstate->p_rtable);
	Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
385

386 387
	return rtr;
}
388

389

390
/*
391
 * transformRangeSubselect --- transform a sub-SELECT appearing in FROM
392
 */
393 394
static RangeTblRef *
transformRangeSubselect(ParseState *pstate, RangeSubselect *r)
395
{
396
	List	   *save_namespace;
397 398
	List	   *parsetrees;
	Query	   *query;
399 400 401 402 403 404 405 406 407 408
	RangeTblEntry *rte;
	RangeTblRef *rtr;

	/*
	 * We require user to supply an alias for a subselect, per SQL92.
	 * To relax this, we'd have to be prepared to gin up a unique alias
	 * for an unlabeled subselect.
	 */
	if (r->name == NULL)
		elog(ERROR, "sub-select in FROM must have an alias");
409

410
	/*
411 412 413 414 415 416
	 * Analyze and transform the subquery.  This is a bit tricky because
	 * we don't want the subquery to be able to see any FROM items already
	 * created in the current query (per SQL92, the scope of a FROM item
	 * does not include other FROM items).  But it does need to be able to
	 * see any further-up parent states, so we can't just pass a null parent
	 * pstate link.  So, temporarily make the current query level have an
417
	 * empty namespace.
418
	 */
419 420
	save_namespace = pstate->p_namespace;
	pstate->p_namespace = NIL;
421
	parsetrees = parse_analyze(r->subquery, pstate);
422
	pstate->p_namespace = save_namespace;
423

424 425 426 427 428 429 430 431 432 433
	/*
	 * Check that we got something reasonable.  Some of these conditions
	 * are probably impossible given restrictions of the grammar, but
	 * check 'em anyway.
	 */
	if (length(parsetrees) != 1)
		elog(ERROR, "Unexpected parse analysis result for subselect in FROM");
	query = (Query *) lfirst(parsetrees);
	if (query == NULL || !IsA(query, Query))
		elog(ERROR, "Unexpected parse analysis result for subselect in FROM");
434

435 436
	if (query->commandType != CMD_SELECT)
		elog(ERROR, "Expected SELECT query from subselect in FROM");
437
	if (query->resultRelation != 0 || query->into != NULL || query->isPortal)
438
		elog(ERROR, "Subselect in FROM may not have SELECT INTO");
439

440 441 442 443
	/*
	 * OK, build an RTE for the subquery.
	 */
	rte = addRangeTableEntryForSubquery(pstate, query, r->name, true);
444

445
	/*
446 447
	 * We create a RangeTblRef, but we do not add it to the joinlist or
	 * namespace; our caller must do that if appropriate.
448 449 450 451 452
	 */
	rtr = makeNode(RangeTblRef);
	/* assume new rte is at end */
	rtr->rtindex = length(pstate->p_rtable);
	Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
453

454
	return rtr;
455
}
456

457

458 459 460 461
/*
 * transformFromClauseItem -
 *	  Transform a FROM-clause item, adding any required entries to the
 *	  range table list being built in the ParseState, and return the
462
 *	  transformed item ready to include in the joinlist and namespace.
463
 *	  This routine can recurse to handle SQL92 JOIN expressions.
464
 *
465
 *	  Aside from the primary return value (the transformed joinlist item)
466
 *	  this routine also returns an integer list of the rangetable indexes
467
 *	  of all the base relations represented in the joinlist item.  This
468
 *	  list is needed for checking JOIN/ON conditions in higher levels.
469 470
 */
static Node *
471
transformFromClauseItem(ParseState *pstate, Node *n, List **containedRels)
472 473 474 475
{
	if (IsA(n, RangeVar))
	{
		/* Plain relation reference */
476 477 478
		RangeTblRef *rtr;

		rtr = transformTableEntry(pstate, (RangeVar *) n);
479
		*containedRels = makeListi1(rtr->rtindex);
480
		return (Node *) rtr;
481 482 483
	}
	else if (IsA(n, RangeSubselect))
	{
484 485 486 487
		/* sub-SELECT is like a plain relation */
		RangeTblRef *rtr;

		rtr = transformRangeSubselect(pstate, (RangeSubselect *) n);
488
		*containedRels = makeListi1(rtr->rtindex);
489
		return (Node *) rtr;
490 491 492 493 494
	}
	else if (IsA(n, JoinExpr))
	{
		/* A newfangled join expression */
		JoinExpr   *j = (JoinExpr *) n;
495 496 497
		List	   *l_containedRels,
				   *r_containedRels,
				   *l_colnames,
498 499 500 501 502
				   *r_colnames,
				   *res_colnames,
				   *l_colvars,
				   *r_colvars,
				   *res_colvars;
503

504 505 506
		/*
		 * Recursively process the left and right subtrees
		 */
507 508 509 510 511 512 513
		j->larg = transformFromClauseItem(pstate, j->larg, &l_containedRels);
		j->rarg = transformFromClauseItem(pstate, j->rarg, &r_containedRels);

		/*
		 * Generate combined list of relation indexes
		 */
		*containedRels = nconc(l_containedRels, r_containedRels);
514

515 516 517 518 519 520 521
		/*
		 * Check for conflicting refnames in left and right subtrees.  Must
		 * do this because higher levels will assume I hand back a self-
		 * consistent namespace subtree.
		 */
		checkNameSpaceConflicts(pstate, j->larg, j->rarg);

522 523 524 525 526 527 528 529 530 531 532 533
		/*
		 * Extract column name and var lists from both subtrees
		 */
		if (IsA(j->larg, JoinExpr))
		{
			/* Make a copy of the subtree's lists so we can modify! */
			l_colnames = copyObject(((JoinExpr *) j->larg)->colnames);
			l_colvars = copyObject(((JoinExpr *) j->larg)->colvars);
		}
		else
		{
			RangeTblEntry *rte;
534

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
			Assert(IsA(j->larg, RangeTblRef));
			rte = rt_fetch(((RangeTblRef *) j->larg)->rtindex,
						   pstate->p_rtable);
			expandRTE(pstate, rte, &l_colnames, &l_colvars);
			/* expandRTE returns new lists, so no need for copyObject */
		}
		if (IsA(j->rarg, JoinExpr))
		{
			/* Make a copy of the subtree's lists so we can modify! */
			r_colnames = copyObject(((JoinExpr *) j->rarg)->colnames);
			r_colvars = copyObject(((JoinExpr *) j->rarg)->colvars);
		}
		else
		{
			RangeTblEntry *rte;
550

551 552 553 554 555 556
			Assert(IsA(j->rarg, RangeTblRef));
			rte = rt_fetch(((RangeTblRef *) j->rarg)->rtindex,
						   pstate->p_rtable);
			expandRTE(pstate, rte, &r_colnames, &r_colvars);
			/* expandRTE returns new lists, so no need for copyObject */
		}
557

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
		/*
		 * Natural join does not explicitly specify columns; must
		 * generate columns to join. Need to run through the list of
		 * columns from each table or join result and match up the
		 * column names. Use the first table, and check every column
		 * in the second table for a match.  (We'll check that the
		 * matches were unique later on.)
		 * The result of this step is a list of column names just like an
		 * explicitly-written USING list.
		 */
		if (j->isNatural)
		{
			List	   *rlist = NIL;
			List	   *lx,
					   *rx;

			Assert(j->using == NIL); /* shouldn't have USING() too */

			foreach(lx, l_colnames)
577
			{
578 579 580 581
				char	   *l_colname = strVal(lfirst(lx));
				Value	   *m_name = NULL;

				foreach(rx, r_colnames)
582
				{
583
					char	   *r_colname = strVal(lfirst(rx));
584

585
					if (strcmp(l_colname, r_colname) == 0)
586
					{
587 588
						m_name = makeString(l_colname);
						break;
589
					}
590
				}
591

592 593 594 595
				/* matched a right column? then keep as join column... */
				if (m_name != NULL)
					rlist = lappend(rlist, m_name);
			}
596

597 598
			j->using = rlist;
		}
599

600 601 602 603 604
		/*
		 * Now transform the join qualifications, if any.
		 */
		res_colnames = NIL;
		res_colvars = NIL;
605

606 607 608 609 610 611 612 613 614 615 616
		if (j->using)
		{
			/*
			 * JOIN/USING (or NATURAL JOIN, as transformed above).
			 * Transform the list into an explicit ON-condition,
			 * and generate a list of result columns.
			 */
			List	   *ucols = j->using;
			List	   *l_usingvars = NIL;
			List	   *r_usingvars = NIL;
			List	   *ucol;
617

618
			Assert(j->quals == NULL); /* shouldn't have ON() too */
619

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
			foreach(ucol, ucols)
			{
				char	   *u_colname = strVal(lfirst(ucol));
				List	   *col;
				Node	   *l_colvar,
						   *r_colvar,
						   *colvar;
				int			ndx;
				int			l_index = -1;
				int			r_index = -1;

				ndx = 0;
				foreach(col, l_colnames)
				{
					char	   *l_colname = strVal(lfirst(col));
635

636 637 638 639 640 641 642
					if (strcmp(l_colname, u_colname) == 0)
					{
						if (l_index >= 0)
							elog(ERROR, "Common column name \"%s\" appears more than once in left table", u_colname);
						l_index = ndx;
					}
					ndx++;
643
				}
644
				if (l_index < 0)
645
					elog(ERROR, "JOIN/USING column \"%s\" not found in left table",
646
						 u_colname);
647

648 649
				ndx = 0;
				foreach(col, r_colnames)
650
				{
651 652 653
					char	   *r_colname = strVal(lfirst(col));

					if (strcmp(r_colname, u_colname) == 0)
654
					{
655 656 657
						if (r_index >= 0)
							elog(ERROR, "Common column name \"%s\" appears more than once in right table", u_colname);
						r_index = ndx;
658
					}
659
					ndx++;
660
				}
661
				if (r_index < 0)
662
					elog(ERROR, "JOIN/USING column \"%s\" not found in right table",
663 664 665 666 667 668 669 670 671 672
						 u_colname);

				l_colvar = nth(l_index, l_colvars);
				l_usingvars = lappend(l_usingvars, l_colvar);
				r_colvar = nth(r_index, r_colvars);
				r_usingvars = lappend(r_usingvars, r_colvar);

				res_colnames = lappend(res_colnames,
									   nth(l_index, l_colnames));
				switch (j->jointype)
673
				{
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
					case JOIN_INNER:
					case JOIN_LEFT:
						colvar = l_colvar;
						break;
					case JOIN_RIGHT:
						colvar = r_colvar;
						break;
					default:
					{
						/* Need COALESCE(l_colvar, r_colvar) */
						CaseExpr *c = makeNode(CaseExpr);
						CaseWhen *w = makeNode(CaseWhen);
						A_Expr *a = makeNode(A_Expr);

						a->oper = NOTNULL;
						a->lexpr = l_colvar;
						w->expr = (Node *) a;
						w->result = l_colvar;
692
						c->args = makeList1(w);
693 694 695 696 697
						c->defresult = r_colvar;
						colvar = transformExpr(pstate, (Node *) c,
											   EXPR_COLUMN_FIRST);
						break;
					}
698
				}
699 700
				res_colvars = lappend(res_colvars, colvar);
			}
701

702 703 704
			j->quals = transformJoinUsingClause(pstate,
												l_usingvars,
												r_usingvars);
705 706 707 708
		}
		else if (j->quals)
		{
			/* User-written ON-condition; transform it */
709
			j->quals = transformJoinOnClause(pstate, j, *containedRels);
710 711
		}
		else
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 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
		{
			/* CROSS JOIN: no quals */
		}

		/* Add remaining columns from each side to the output columns */
		extractUniqueColumns(res_colnames,
							 l_colnames, l_colvars,
							 &l_colnames, &l_colvars);
		extractUniqueColumns(res_colnames,
							 r_colnames, r_colvars,
							 &r_colnames, &r_colvars);
		res_colnames = nconc(res_colnames, l_colnames);
		res_colvars = nconc(res_colvars, l_colvars);
		res_colnames = nconc(res_colnames, r_colnames);
		res_colvars = nconc(res_colvars, r_colvars);

		/*
		 * Process alias (AS clause), if any.
		 */
		if (j->alias)
		{
			/*
			 * If a column alias list is specified, substitute the alias
			 * names into my output-column list
			 */
			if (j->alias->attrs != NIL)
			{
				if (length(j->alias->attrs) != length(res_colnames))
					elog(ERROR, "Column alias list for \"%s\" has wrong number of entries (need %d)",
						 j->alias->relname, length(res_colnames));
				res_colnames = j->alias->attrs;
			}
		}

		j->colnames = res_colnames;
		j->colvars = res_colvars;

		return (Node *) j;
	}
	else
		elog(ERROR, "transformFromClauseItem: unexpected node (internal error)"
			 "\n\t%s", nodeToString(n));
	return NULL;				/* can't get here, just keep compiler quiet */
}


/*
 * transformWhereClause -
 *	  transforms the qualification and make sure it is of type Boolean
 */
Node *
transformWhereClause(ParseState *pstate, Node *clause)
{
	Node	   *qual;

	if (clause == NULL)
		return NULL;

	qual = transformExpr(pstate, clause, EXPR_COLUMN_FIRST);

	if (exprType(qual) != BOOLOID)
	{
		elog(ERROR, "WHERE clause must return type bool, not type %s",
			 typeidTypeName(exprType(qual)));
776
	}
777 778
	return qual;
}
779

780

781
/*
782
 *	findTargetlistEntry -
783 784 785
 *	  Returns the targetlist entry matching the given (untransformed) node.
 *	  If no matching entry exists, one is created and appended to the target
 *	  list as a "resjunk" node.
786
 *
787
 * node		the ORDER BY, GROUP BY, or DISTINCT ON expression to be matched
788 789 790
 * tlist	the existing target list (NB: this will never be NIL, which is a
 *			good thing since we'd be unable to append to it if it were...)
 * clause	identifies clause type being processed.
791
 */
792
static TargetEntry *
793
findTargetlistEntry(ParseState *pstate, Node *node, List *tlist, int clause)
794 795
{
	TargetEntry *target_result = NULL;
796 797
	List	   *tl;
	Node	   *expr;
798

799 800 801
	/*----------
	 * Handle two special cases as mandated by the SQL92 spec:
	 *
802
	 * 1. Bare ColumnName (no qualifier or subscripts)
803 804
	 *	  For a bare identifier, we search for a matching column name
	 *	  in the existing target list.	Multiple matches are an error
805
	 *	  unless they refer to identical values; for example,
806 807
	 *	  we allow	SELECT a, a FROM table ORDER BY a
	 *	  but not	SELECT a AS b, b FROM table ORDER BY b
808 809
	 *	  If no match is found, we fall through and treat the identifier
	 *	  as an expression.
810 811 812
	 *	  For GROUP BY, it is incorrect to match the grouping item against
	 *	  targetlist entries: according to SQL92, an identifier in GROUP BY
	 *	  is a reference to a column name exposed by FROM, not to a target
813
	 *	  list column.	However, many implementations (including pre-7.0
814 815 816 817 818 819 820
	 *	  PostgreSQL) accept this anyway.  So for GROUP BY, we look first
	 *	  to see if the identifier matches any FROM column name, and only
	 *	  try for a targetlist name if it doesn't.  This ensures that we
	 *	  adhere to the spec in the case where the name could be both.
	 *	  DISTINCT ON isn't in the standard, so we can do what we like there;
	 *	  we choose to make it work like ORDER BY, on the rather flimsy
	 *	  grounds that ordinary DISTINCT works on targetlist entries.
821
	 *
822
	 * 2. IntegerConstant
823
	 *	  This means to use the n'th item in the existing target list.
824 825 826
	 *	  Note that it would make no sense to order/group/distinct by an
	 *	  actual constant, so this does not create a conflict with our
	 *	  extension to order/group by an expression.
827 828 829
	 *	  GROUP BY column-number is not allowed by SQL92, but since
	 *	  the standard has no other behavior defined for this syntax,
	 *	  we may as well accept this common extension.
830
	 *
831 832 833 834 835
	 * Note that pre-existing resjunk targets must not be used in either case,
	 * since the user didn't write them in his SELECT list.
	 *
	 * If neither special case applies, fall through to treat the item as
	 * an expression.
836
	 *----------
837
	 */
838
	if (IsA(node, Ident) &&((Ident *) node)->indirection == NIL)
839
	{
840
		char	   *name = ((Ident *) node)->name;
841 842

		if (clause == GROUP_CLAUSE)
843
		{
844

845 846
			/*
			 * In GROUP BY, we must prefer a match against a FROM-clause
847 848 849 850
			 * column to one against the targetlist.  Look to see if there
			 * is a matching column.  If so, fall through to let
			 * transformExpr() do the rest.  NOTE: if name could refer
			 * ambiguously to more than one column name exposed by FROM,
851
			 * colnameToVar will elog(ERROR).  That's just what
852
			 * we want here.
853
			 */
854
			if (colnameToVar(pstate, name) != NULL)
855 856
				name = NULL;
		}
857

858 859 860
		if (name != NULL)
		{
			foreach(tl, tlist)
861
			{
862 863 864 865 866
				TargetEntry *tle = (TargetEntry *) lfirst(tl);
				Resdom	   *resnode = tle->resdom;

				if (!resnode->resjunk &&
					strcmp(resnode->resname, name) == 0)
867
				{
868 869
					if (target_result != NULL)
					{
870
						if (!equal(target_result->expr, tle->expr))
871 872 873 874 875 876
							elog(ERROR, "%s '%s' is ambiguous",
								 clauseText[clause], name);
					}
					else
						target_result = tle;
					/* Stay in loop to check for ambiguity */
877
				}
878
			}
879
			if (target_result != NULL)
880
				return target_result;	/* return the first match */
881 882 883 884 885 886 887 888
		}
	}
	if (IsA(node, A_Const))
	{
		Value	   *val = &((A_Const *) node)->val;
		int			targetlist_pos = 0;
		int			target_pos;

889
		if (!IsA(val, Integer))
890
			elog(ERROR, "Non-integer constant in %s", clauseText[clause]);
891 892 893 894 895
		target_pos = intVal(val);
		foreach(tl, tlist)
		{
			TargetEntry *tle = (TargetEntry *) lfirst(tl);
			Resdom	   *resnode = tle->resdom;
896

897 898 899
			if (!resnode->resjunk)
			{
				if (++targetlist_pos == target_pos)
900
					return tle; /* return the unique match */
901 902
			}
		}
903
		elog(ERROR, "%s position %d is not in target list",
904 905
			 clauseText[clause], target_pos);
	}
906

907
	/*
908 909 910 911 912 913
	 * Otherwise, we have an expression (this is a Postgres extension not
	 * found in SQL92).  Convert the untransformed node to a transformed
	 * expression, and search for a match in the tlist. NOTE: it doesn't
	 * really matter whether there is more than one match.	Also, we are
	 * willing to match a resjunk target here, though the above cases must
	 * ignore resjunk targets.
914 915
	 */
	expr = transformExpr(pstate, node, EXPR_COLUMN_FIRST);
916

917 918 919
	foreach(tl, tlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(tl);
920

921 922
		if (equal(expr, tle->expr))
			return tle;
923
	}
924

925 926
	/*
	 * If no matches, construct a new target entry which is appended to
927 928
	 * the end of the target list.	This target is given resjunk = TRUE so
	 * that it will not be projected into the final tuple.
929
	 */
930 931
	target_result = transformTargetEntry(pstate, node, expr, NULL, true);
	lappend(tlist, target_result);
932

933 934 935
	return target_result;
}

936

937 938 939 940 941 942 943 944 945
/*
 * transformGroupClause -
 *	  transform a Group By clause
 *
 */
List *
transformGroupClause(ParseState *pstate, List *grouplist, List *targetlist)
{
	List	   *glist = NIL,
946
			   *gl;
947

948
	foreach(gl, grouplist)
949
	{
950
		TargetEntry *tle;
951

952
		tle = findTargetlistEntry(pstate, lfirst(gl),
953
								  targetlist, GROUP_CLAUSE);
954

955
		/* avoid making duplicate grouplist entries */
956
		if (!exprIsInSortList(tle->expr, glist, targetlist))
957 958
		{
			GroupClause *grpcl = makeNode(GroupClause);
959

960
			grpcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
961

962
			grpcl->sortop = any_ordering_op(tle->resdom->restype);
963

964
			glist = lappend(glist, grpcl);
965 966 967 968 969 970 971 972
		}
	}

	return glist;
}

/*
 * transformSortClause -
973
 *	  transform an ORDER BY clause
974 975 976
 */
List *
transformSortClause(ParseState *pstate,
Bruce Momjian's avatar
Bruce Momjian committed
977
					List *orderlist,
978
					List *targetlist)
979
{
980 981
	List	   *sortlist = NIL;
	List	   *olitem;
982

983 984
	foreach(olitem, orderlist)
	{
985 986
		SortGroupBy *sortby = lfirst(olitem);
		TargetEntry *tle;
987

988
		tle = findTargetlistEntry(pstate, sortby->node,
989
								  targetlist, ORDER_CLAUSE);
990

991 992
		sortlist = addTargetToSortList(tle, sortlist, targetlist,
									   sortby->useOp);
993 994
	}

995 996
	return sortlist;
}
997

998 999 1000 1001 1002
/*
 * transformDistinctClause -
 *	  transform a DISTINCT or DISTINCT ON clause
 *
 * Since we may need to add items to the query's sortClause list, that list
1003
 * is passed by reference.	We might also need to add items to the query's
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
 * targetlist, but we assume that cannot be empty initially, so we can
 * lappend to it even though the pointer is passed by value.
 */
List *
transformDistinctClause(ParseState *pstate, List *distinctlist,
						List *targetlist, List **sortClause)
{
	List	   *result = NIL;
	List	   *slitem;
	List	   *dlitem;

	/* No work if there was no DISTINCT clause */
	if (distinctlist == NIL)
		return NIL;

	if (lfirst(distinctlist) == NIL)
1020
	{
1021 1022 1023 1024
		/* We had SELECT DISTINCT */

		/*
		 * All non-resjunk elements from target list that are not already
1025
		 * in the sort list should be added to it.	(We don't really care
1026
		 * what order the DISTINCT fields are checked in, so we can leave
1027 1028
		 * the user's ORDER BY spec alone, and just add additional sort
		 * keys to it to ensure that all targetlist items get sorted.)
1029 1030 1031 1032 1033 1034 1035
		 */
		*sortClause = addAllTargetsToSortList(*sortClause, targetlist);

		/*
		 * Now, DISTINCT list consists of all non-resjunk sortlist items.
		 * Actually, all the sortlist items had better be non-resjunk!
		 * Otherwise, user wrote SELECT DISTINCT with an ORDER BY item
1036 1037
		 * that does not appear anywhere in the SELECT targetlist, and we
		 * can't implement that with only one sorting pass...
1038 1039
		 */
		foreach(slitem, *sortClause)
1040
		{
1041 1042 1043 1044 1045 1046 1047
			SortClause *scl = (SortClause *) lfirst(slitem);
			TargetEntry *tle = get_sortgroupclause_tle(scl, targetlist);

			if (tle->resdom->resjunk)
				elog(ERROR, "For SELECT DISTINCT, ORDER BY expressions must appear in target list");
			else
				result = lappend(result, copyObject(scl));
1048
		}
1049 1050 1051 1052 1053 1054 1055 1056 1057
	}
	else
	{
		/* We had SELECT DISTINCT ON (expr, ...) */

		/*
		 * If the user writes both DISTINCT ON and ORDER BY, then the two
		 * expression lists must match (until one or the other runs out).
		 * Otherwise the ORDER BY requires a different sort order than the
1058 1059 1060 1061 1062 1063
		 * DISTINCT does, and we can't implement that with only one sort
		 * pass (and if we do two passes, the results will be rather
		 * unpredictable). However, it's OK to have more DISTINCT ON
		 * expressions than ORDER BY expressions; we can just add the
		 * extra DISTINCT values to the sort list, much as we did above
		 * for ordinary DISTINCT fields.
1064 1065 1066 1067 1068 1069 1070 1071
		 *
		 * Actually, it'd be OK for the common prefixes of the two lists to
		 * match in any order, but implementing that check seems like more
		 * trouble than it's worth.
		 */
		List	   *nextsortlist = *sortClause;

		foreach(dlitem, distinctlist)
1072
		{
1073 1074 1075 1076
			TargetEntry *tle;

			tle = findTargetlistEntry(pstate, lfirst(dlitem),
									  targetlist, DISTINCT_ON_CLAUSE);
1077

1078
			if (nextsortlist != NIL)
1079
			{
1080 1081 1082 1083 1084 1085
				SortClause *scl = (SortClause *) lfirst(nextsortlist);

				if (tle->resdom->ressortgroupref != scl->tleSortGroupRef)
					elog(ERROR, "SELECT DISTINCT ON expressions must match initial ORDER BY expressions");
				result = lappend(result, copyObject(scl));
				nextsortlist = lnext(nextsortlist);
1086
			}
1087 1088 1089 1090
			else
			{
				*sortClause = addTargetToSortList(tle, *sortClause,
												  targetlist, NULL);
1091 1092 1093

				/*
				 * Probably, the tle should always have been added at the
1094 1095 1096 1097 1098
				 * end of the sort list ... but search to be safe.
				 */
				foreach(slitem, *sortClause)
				{
					SortClause *scl = (SortClause *) lfirst(slitem);
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108
					if (tle->resdom->ressortgroupref == scl->tleSortGroupRef)
					{
						result = lappend(result, copyObject(scl));
						break;
					}
				}
				if (slitem == NIL)
					elog(ERROR, "transformDistinctClause: failed to add DISTINCT ON clause to target list");
			}
1109 1110
		}
	}
1111

1112
	return result;
1113
}
1114

1115 1116
/*
 * addAllTargetsToSortList
1117 1118
 *		Make sure all non-resjunk targets in the targetlist are in the
 *		ORDER BY list, adding the not-yet-sorted ones to the end of the list.
1119 1120 1121 1122 1123 1124 1125 1126
 *		This is typically used to help implement SELECT DISTINCT.
 *
 * Returns the updated ORDER BY list.
 */
List *
addAllTargetsToSortList(List *sortlist, List *targetlist)
{
	List	   *i;
1127

1128 1129 1130 1131
	foreach(i, targetlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(i);

1132
		if (!tle->resdom->resjunk)
1133
			sortlist = addTargetToSortList(tle, sortlist, targetlist, NULL);
1134
	}
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	return sortlist;
}

/*
 * addTargetToSortList
 *		If the given targetlist entry isn't already in the ORDER BY list,
 *		add it to the end of the list, using the sortop with given name
 *		or any available sort operator if opname == NULL.
 *
 * Returns the updated ORDER BY list.
 */
static List *
addTargetToSortList(TargetEntry *tle, List *sortlist, List *targetlist,
					char *opname)
{
	/* avoid making duplicate sortlist entries */
1151
	if (!exprIsInSortList(tle->expr, sortlist, targetlist))
1152 1153 1154 1155 1156 1157
	{
		SortClause *sortcl = makeNode(SortClause);

		sortcl->tleSortGroupRef = assignSortGroupRef(tle, targetlist);

		if (opname)
1158 1159 1160 1161
			sortcl->sortop = oper_oid(opname,
									  tle->resdom->restype,
									  tle->resdom->restype,
									  false);
1162 1163
		else
			sortcl->sortop = any_ordering_op(tle->resdom->restype);
1164

1165 1166
		sortlist = lappend(sortlist, sortcl);
	}
1167 1168
	return sortlist;
}
1169

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
/*
 * assignSortGroupRef
 *	  Assign the targetentry an unused ressortgroupref, if it doesn't
 *	  already have one.  Return the assigned or pre-existing refnumber.
 *
 * 'tlist' is the targetlist containing (or to contain) the given targetentry.
 */
Index
assignSortGroupRef(TargetEntry *tle, List *tlist)
{
	Index		maxRef;
	List	   *l;

1183
	if (tle->resdom->ressortgroupref)	/* already has one? */
1184 1185 1186 1187 1188 1189
		return tle->resdom->ressortgroupref;

	/* easiest way to pick an unused refnumber: max used + 1 */
	maxRef = 0;
	foreach(l, tlist)
	{
1190
		Index		ref = ((TargetEntry *) lfirst(l))->resdom->ressortgroupref;
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

		if (ref > maxRef)
			maxRef = ref;
	}
	tle->resdom->ressortgroupref = maxRef + 1;
	return tle->resdom->ressortgroupref;
}

/*
 * exprIsInSortList
 *		Is the given expression already in the sortlist?
 *		Note we will say 'yes' if it is equal() to any sortlist item,
 *		even though that might be a different targetlist member.
 *
 * Works for both SortClause and GroupClause lists.
 */
static bool
exprIsInSortList(Node *expr, List *sortList, List *targetList)
{
	List	   *i;

	foreach(i, sortList)
	{
		SortClause *scl = (SortClause *) lfirst(i);

		if (equal(expr, get_sortgroupclause_expr(scl, targetList)))
			return true;
	}
	return false;
}