prepjointree.c 33.9 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * prepjointree.c
 *	  Planner preprocessing for subqueries and join tree manipulation.
 *
6 7 8 9 10 11 12
 * NOTE: the intended sequence for invoking these operations is
 *		pull_up_IN_clauses
 *		pull_up_subqueries
 *		do expression preprocessing (including flattening JOIN alias vars)
 *		reduce_outer_joins
 *		simplify_jointree
 *
13
 *
P
 
PostgreSQL Daemon 已提交
14
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
15 16 17 18
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
19
 *	  $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.28 2005/06/04 19:19:41 tgl Exp $
20 21 22 23 24 25 26 27 28 29 30
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "optimizer/clauses.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
31
#include "utils/lsyscache.h"
32 33


34
/* These parameters are set by GUC */
B
Bruce Momjian 已提交
35 36
int			from_collapse_limit;
int			join_collapse_limit;
37 38


39 40 41
typedef struct reduce_outer_joins_state
{
	Relids		relids;			/* base relids within this subtree */
B
Bruce Momjian 已提交
42
	bool		contains_outer; /* does subtree contain outer join(s)? */
43
	List	   *sub_states;		/* List of states for subtree components */
44
} reduce_outer_joins_state;
45

46 47
static bool is_simple_subquery(Query *subquery);
static bool has_nullable_targetlist(Query *subquery);
48
static void resolvenew_in_jointree(Node *jtnode, int varno,
49
					   RangeTblEntry *rte, List *subtlist);
50 51
static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
static void reduce_outer_joins_pass2(Node *jtnode,
52
						 reduce_outer_joins_state *state,
B
Bruce Momjian 已提交
53 54
						 Query *parse,
						 Relids nonnullable_rels);
55
static Relids find_nonnullable_rels(Node *node, bool top_level);
56
static void fix_in_clause_relids(List *in_info_list, int varno,
B
Bruce Momjian 已提交
57
					 Relids subrelids);
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
static Node *find_jointree_node_for_rel(Node *jtnode, int relid);


/*
 * pull_up_IN_clauses
 *		Attempt to pull up top-level IN clauses to be treated like joins.
 *
 * A clause "foo IN (sub-SELECT)" appearing at the top level of WHERE can
 * be processed by pulling the sub-SELECT up to become a rangetable entry
 * and handling the implied equality comparisons as join operators (with
 * special join rules).
 * This optimization *only* works at the top level of WHERE, because
 * it cannot distinguish whether the IN ought to return FALSE or NULL in
 * cases involving NULL inputs.  This routine searches for such clauses
 * and does the necessary parsetree transformations if any are found.
 *
 * This routine has to run before preprocess_expression(), so the WHERE
 * clause is not yet reduced to implicit-AND format.  That means we need
 * to recursively search through explicit AND clauses, which are
 * probably only binary ANDs.  We stop as soon as we hit a non-AND item.
 *
 * Returns the possibly-modified version of the given qual-tree node.
 */
Node *
pull_up_IN_clauses(Query *parse, Node *node)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, SubLink))
	{
B
Bruce Momjian 已提交
88
		SubLink    *sublink = (SubLink *) node;
89 90 91 92 93 94 95 96 97 98
		Node	   *subst;

		/* Is it a convertible IN clause?  If not, return it as-is */
		subst = convert_IN_to_join(parse, sublink);
		if (subst == NULL)
			return node;
		return subst;
	}
	if (and_clause(node))
	{
B
Bruce Momjian 已提交
99
		List	   *newclauses = NIL;
100
		ListCell   *l;
101

102
		foreach(l, ((BoolExpr *) node)->args)
103
		{
104
			Node	   *oldclause = (Node *) lfirst(l);
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

			newclauses = lappend(newclauses,
								 pull_up_IN_clauses(parse,
													oldclause));
		}
		return (Node *) make_andclause(newclauses);
	}
	/* Stop if not an AND */
	return node;
}

/*
 * pull_up_subqueries
 *		Look for subqueries in the rangetable that can be pulled up into
 *		the parent query.  If the subquery has no special features like
 *		grouping/aggregation then we can merge it into the parent's jointree.
 *
 * below_outer_join is true if this jointree node is within the nullable
 * side of an outer join.  This restricts what we can do.
 *
 * A tricky aspect of this code is that if we pull up a subquery we have
 * to replace Vars that reference the subquery's outputs throughout the
 * parent query, including quals attached to jointree nodes above the one
 * we are currently processing!  We handle this by being careful not to
 * change the jointree structure while recursing: no nodes other than
 * subquery RangeTblRef entries will be replaced.  Also, we can't turn
 * ResolveNew loose on the whole jointree, because it'll return a mutated
 * copy of the tree; we have to invoke it just on the quals, instead.
 */
Node *
pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
{
	if (jtnode == NULL)
		return NULL;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;
		RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
		Query	   *subquery = rte->subquery;

		/*
		 * Is this a subquery RTE, and if so, is the subquery simple
		 * enough to pull up?  (If not, do nothing at this node.)
		 *
		 * If we are inside an outer join, only pull up subqueries whose
		 * targetlists are nullable --- otherwise substituting their tlist
		 * entries for upper Var references would do the wrong thing (the
152 153
		 * results wouldn't become NULL when they're supposed to).
		 *
B
Bruce Momjian 已提交
154 155
		 * XXX This could be improved by generating pseudo-variables for such
		 * expressions; we'd have to figure out how to get the pseudo-
156 157 158
		 * variables evaluated at the right place in the modified plan
		 * tree. Fix it someday.
		 */
159 160 161
		if (rte->rtekind == RTE_SUBQUERY &&
			is_simple_subquery(subquery) &&
			(!below_outer_join || has_nullable_targetlist(subquery)))
162 163 164
		{
			int			rtoffset;
			List	   *subtlist;
165
			ListCell   *rt;
166 167

			/*
168 169
			 * Need a modifiable copy of the subquery to hack on.  Even if
			 * we didn't sometimes choose not to pull up below, we must do
B
Bruce Momjian 已提交
170 171 172
			 * this to avoid problems if the same subquery is referenced
			 * from multiple jointree items (which can't happen normally,
			 * but might after rule rewriting).
173 174 175 176
			 */
			subquery = copyObject(subquery);

			/*
B
Bruce Momjian 已提交
177 178
			 * Pull up any IN clauses within the subquery's WHERE, so that
			 * we don't leave unoptimized INs behind.
179 180 181
			 */
			if (subquery->hasSubLinks)
				subquery->jointree->quals = pull_up_IN_clauses(subquery,
B
Bruce Momjian 已提交
182
											  subquery->jointree->quals);
183 184

			/*
B
Bruce Momjian 已提交
185 186
			 * Recursively pull up the subquery's subqueries, so that this
			 * routine's processing is complete for its jointree and
187
			 * rangetable.
188 189
			 *
			 * Note: 'false' is correct here even if we are within an outer
B
Bruce Momjian 已提交
190 191
			 * join in the upper query; the lower query starts with a
			 * clean slate for outer-join semantics.
192 193 194 195 196
			 */
			subquery->jointree = (FromExpr *)
				pull_up_subqueries(subquery, (Node *) subquery->jointree,
								   false);

197 198 199 200 201 202 203 204 205
			/*
			 * Now we must recheck whether the subquery is still simple
			 * enough to pull up.  If not, abandon processing it.
			 *
			 * We don't really need to recheck all the conditions involved,
			 * but it's easier just to keep this "if" looking the same as
			 * the one above.
			 */
			if (is_simple_subquery(subquery) &&
206
				(!below_outer_join || has_nullable_targetlist(subquery)))
207 208 209 210 211 212 213 214 215
			{
				/* good to go */
			}
			else
			{
				/*
				 * Give up, return unmodified RangeTblRef.
				 *
				 * Note: The work we just did will be redone when the
B
Bruce Momjian 已提交
216 217 218
				 * subquery gets planned on its own.  Perhaps we could
				 * avoid that by storing the modified subquery back into
				 * the rangetable, but I'm not gonna risk it now.
219 220 221 222
				 */
				return jtnode;
			}

223 224 225 226
			/*
			 * Adjust level-0 varnos in subquery so that we can append its
			 * rangetable to upper query's.
			 */
227
			rtoffset = list_length(parse->rtable);
228 229 230
			OffsetVarNodes((Node *) subquery, rtoffset, 0);

			/*
B
Bruce Momjian 已提交
231 232
			 * Upper-level vars in subquery are now one level closer to
			 * their parent than before.
233 234 235 236 237 238 239 240 241 242 243 244 245
			 */
			IncrementVarSublevelsUp((Node *) subquery, -1, 1);

			/*
			 * Replace all of the top query's references to the subquery's
			 * outputs with copies of the adjusted subtlist items, being
			 * careful not to replace any of the jointree structure.
			 * (This'd be a lot cleaner if we could use
			 * query_tree_mutator.)
			 */
			subtlist = subquery->targetList;
			parse->targetList = (List *)
				ResolveNew((Node *) parse->targetList,
246
						   varno, 0, rte,
247
						   subtlist, CMD_SELECT, 0);
248
			resolvenew_in_jointree((Node *) parse->jointree, varno,
249
								   rte, subtlist);
250 251 252
			Assert(parse->setOperations == NULL);
			parse->havingQual =
				ResolveNew(parse->havingQual,
253
						   varno, 0, rte,
254
						   subtlist, CMD_SELECT, 0);
255 256
			parse->in_info_list = (List *)
				ResolveNew((Node *) parse->in_info_list,
257
						   varno, 0, rte,
258
						   subtlist, CMD_SELECT, 0);
259 260 261

			foreach(rt, parse->rtable)
			{
262
				RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(rt);
263

264 265 266
				if (otherrte->rtekind == RTE_JOIN)
					otherrte->joinaliasvars = (List *)
						ResolveNew((Node *) otherrte->joinaliasvars,
267
								   varno, 0, rte,
268
								   subtlist, CMD_SELECT, 0);
269 270 271 272 273 274 275
			}

			/*
			 * Now append the adjusted rtable entries to upper query. (We
			 * hold off until after fixing the upper rtable entries; no
			 * point in running that code on the subquery ones too.)
			 */
276
			parse->rtable = list_concat(parse->rtable, subquery->rtable);
277 278

			/*
279
			 * Pull up any FOR UPDATE/SHARE markers, too.  (OffsetVarNodes
B
Bruce Momjian 已提交
280 281
			 * already adjusted the marker values, so just list_concat the
			 * list.)
282 283 284
			 *
			 * Executor can't handle multiple FOR UPDATE/SHARE flags, so
			 * complain if they are valid but different
285
			 */
286 287 288 289 290 291
			if (parse->rowMarks && subquery->rowMarks &&
				parse->forUpdate != subquery->forUpdate)
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("cannot use both FOR UPDATE and FOR SHARE in one query")));

292
			parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
293 294
			if (subquery->rowMarks)
				parse->forUpdate = subquery->forUpdate;
295 296

			/*
B
Bruce Momjian 已提交
297 298 299 300
			 * We also have to fix the relid sets of any parent
			 * InClauseInfo nodes.	(This could perhaps be done by
			 * ResolveNew, but it would clutter that routine's API
			 * unreasonably.)
301 302 303
			 */
			if (parse->in_info_list)
			{
B
Bruce Momjian 已提交
304
				Relids		subrelids;
305 306 307 308 309 310 311 312

				subrelids = get_relids_in_jointree((Node *) subquery->jointree);
				fix_in_clause_relids(parse->in_info_list, varno, subrelids);
			}

			/*
			 * And now append any subquery InClauseInfos to our list.
			 */
313 314
			parse->in_info_list = list_concat(parse->in_info_list,
											  subquery->in_info_list);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

			/*
			 * Miscellaneous housekeeping.
			 */
			parse->hasSubLinks |= subquery->hasSubLinks;
			/* subquery won't be pulled up if it hasAggs, so no work there */

			/*
			 * Return the adjusted subquery jointree to replace the
			 * RangeTblRef entry in my jointree.
			 */
			return (Node *) subquery->jointree;
		}
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
332
		ListCell   *l;
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

		foreach(l, f->fromlist)
			lfirst(l) = pull_up_subqueries(parse, lfirst(l),
										   below_outer_join);
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

		/* Recurse, being careful to tell myself when inside outer join */
		switch (j->jointype)
		{
			case JOIN_INNER:
				j->larg = pull_up_subqueries(parse, j->larg,
											 below_outer_join);
				j->rarg = pull_up_subqueries(parse, j->rarg,
											 below_outer_join);
				break;
			case JOIN_LEFT:
				j->larg = pull_up_subqueries(parse, j->larg,
											 below_outer_join);
				j->rarg = pull_up_subqueries(parse, j->rarg,
											 true);
				break;
			case JOIN_FULL:
				j->larg = pull_up_subqueries(parse, j->larg,
											 true);
				j->rarg = pull_up_subqueries(parse, j->rarg,
											 true);
				break;
			case JOIN_RIGHT:
				j->larg = pull_up_subqueries(parse, j->larg,
											 true);
				j->rarg = pull_up_subqueries(parse, j->rarg,
											 below_outer_join);
				break;
			case JOIN_UNION:

				/*
				 * This is where we fail if upper levels of planner
				 * haven't rewritten UNION JOIN as an Append ...
				 */
375 376
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
377
						 errmsg("UNION JOIN is not implemented")));
378 379
				break;
			default:
380 381
				elog(ERROR, "unrecognized join type: %d",
					 (int) j->jointype);
382 383 384 385
				break;
		}
	}
	else
386 387
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	return jtnode;
}

/*
 * is_simple_subquery
 *	  Check a subquery in the range table to see if it's simple enough
 *	  to pull up into the parent query.
 */
static bool
is_simple_subquery(Query *subquery)
{
	/*
	 * Let's just make sure it's a valid subselect ...
	 */
	if (!IsA(subquery, Query) ||
		subquery->commandType != CMD_SELECT ||
		subquery->resultRelation != 0 ||
405
		subquery->into != NULL)
406
		elog(ERROR, "subquery is bogus");
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

	/*
	 * Can't currently pull up a query with setops. Maybe after querytree
	 * redesign...
	 */
	if (subquery->setOperations)
		return false;

	/*
	 * Can't pull up a subquery involving grouping, aggregation, sorting,
	 * or limiting.
	 */
	if (subquery->hasAggs ||
		subquery->groupClause ||
		subquery->havingQual ||
		subquery->sortClause ||
		subquery->distinctClause ||
		subquery->limitOffset ||
		subquery->limitCount)
		return false;

	/*
	 * Don't pull up a subquery that has any set-returning functions in
	 * its targetlist.	Otherwise we might well wind up inserting
	 * set-returning functions into places where they mustn't go, such as
	 * quals of higher queries.
	 */
	if (expression_returns_set((Node *) subquery->targetList))
		return false;

	/*
	 * Hack: don't try to pull up a subquery with an empty jointree.
	 * query_planner() will correctly generate a Result plan for a
	 * jointree that's totally empty, but I don't think the right things
	 * happen if an empty FromExpr appears lower down in a jointree. Not
	 * worth working hard on this, just to collapse SubqueryScan/Result
	 * into Result...
	 */
	if (subquery->jointree->fromlist == NIL)
		return false;

	return true;
}

/*
 * has_nullable_targetlist
 *	  Check a subquery in the range table to see if all the non-junk
454 455 456
 *	  targetlist items are simple variables or strict functions of simple
 *	  variables (and, hence, will correctly go to NULL when examined above
 *	  the point of an outer join).
457
 *
458 459 460
 * NOTE: it would be correct (and useful) to ignore output columns that aren't
 * actually referenced by the enclosing query ... but we do not have that
 * information available at this point.
461 462 463 464
 */
static bool
has_nullable_targetlist(Query *subquery)
{
465
	ListCell   *l;
466 467 468 469 470 471

	foreach(l, subquery->targetList)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);

		/* ignore resjunk columns */
472
		if (tle->resjunk)
473 474
			continue;

475 476 477
		/* Must contain a Var of current level */
		if (!contain_vars_of_level((Node *) tle->expr, 0))
			return false;
478

479 480 481 482 483
		/* Must not contain any non-strict constructs */
		if (contain_nonstrict_functions((Node *) tle->expr))
			return false;

		/* This one's OK, keep scanning */
484 485 486 487 488 489 490 491 492 493
	}
	return true;
}

/*
 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
 * in the jointree, without changing the jointree structure itself.  Ugly,
 * but there's no other way...
 */
static void
494
resolvenew_in_jointree(Node *jtnode, int varno,
495
					   RangeTblEntry *rte, List *subtlist)
496 497 498 499 500 501 502 503 504 505
{
	if (jtnode == NULL)
		return;
	if (IsA(jtnode, RangeTblRef))
	{
		/* nothing to do here */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
506
		ListCell   *l;
507 508

		foreach(l, f->fromlist)
509
			resolvenew_in_jointree(lfirst(l), varno, rte, subtlist);
510
		f->quals = ResolveNew(f->quals,
511
							  varno, 0, rte,
512
							  subtlist, CMD_SELECT, 0);
513 514 515 516 517
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

518 519
		resolvenew_in_jointree(j->larg, varno, rte, subtlist);
		resolvenew_in_jointree(j->rarg, varno, rte, subtlist);
520
		j->quals = ResolveNew(j->quals,
521
							  varno, 0, rte,
522
							  subtlist, CMD_SELECT, 0);
523 524 525 526 527 528 529

		/*
		 * We don't bother to update the colvars list, since it won't be
		 * used again ...
		 */
	}
	else
530 531
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
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
 * reduce_outer_joins
 *		Attempt to reduce outer joins to plain inner joins.
 *
 * The idea here is that given a query like
 *		SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
 * we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
 * is strict.  The strict operator will always return NULL, causing the outer
 * WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
 * columns.  Therefore, there's no need for the join to produce null-extended
 * rows in the first place --- which makes it a plain join not an outer join.
 * (This scenario may not be very likely in a query written out by hand, but
 * it's reasonably likely when pushing quals down into complex views.)
 *
 * More generally, an outer join can be reduced in strength if there is a
 * strict qual above it in the qual tree that constrains a Var from the
 * nullable side of the join to be non-null.  (For FULL joins this applies
 * to each side separately.)
 *
 * To ease recognition of strict qual clauses, we require this routine to be
 * run after expression preprocessing (i.e., qual canonicalization and JOIN
 * alias-var expansion).
 */
void
reduce_outer_joins(Query *parse)
{
	reduce_outer_joins_state *state;

	/*
B
Bruce Momjian 已提交
563 564 565 566
	 * To avoid doing strictness checks on more quals than necessary, we
	 * want to stop descending the jointree as soon as there are no outer
	 * joins below our current point.  This consideration forces a
	 * two-pass process.  The first pass gathers information about which
567
	 * base rels appear below each side of each join clause, and about
B
Bruce Momjian 已提交
568 569 570
	 * whether there are outer join(s) below each side of each join
	 * clause. The second pass examines qual clauses and changes join
	 * types as it descends the tree.
571 572 573 574 575
	 */
	state = reduce_outer_joins_pass1((Node *) parse->jointree);

	/* planner.c shouldn't have called me if no outer joins */
	if (state == NULL || !state->contains_outer)
576
		elog(ERROR, "so where are the outer joins?");
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

	reduce_outer_joins_pass2((Node *) parse->jointree, state, parse, NULL);
}

/*
 * reduce_outer_joins_pass1 - phase 1 data collection
 *
 * Returns a state node describing the given jointree node.
 */
static reduce_outer_joins_state *
reduce_outer_joins_pass1(Node *jtnode)
{
	reduce_outer_joins_state *result;

	result = (reduce_outer_joins_state *)
		palloc(sizeof(reduce_outer_joins_state));
	result->relids = NULL;
	result->contains_outer = false;
	result->sub_states = NIL;

	if (jtnode == NULL)
		return result;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;

		result->relids = bms_make_singleton(varno);
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
608
		ListCell   *l;
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

		foreach(l, f->fromlist)
		{
			reduce_outer_joins_state *sub_state;

			sub_state = reduce_outer_joins_pass1(lfirst(l));
			result->relids = bms_add_members(result->relids,
											 sub_state->relids);
			result->contains_outer |= sub_state->contains_outer;
			result->sub_states = lappend(result->sub_states, sub_state);
		}
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
		reduce_outer_joins_state *sub_state;

		/* join's own RT index is not wanted in result->relids */
		if (IS_OUTER_JOIN(j->jointype))
			result->contains_outer = true;

		sub_state = reduce_outer_joins_pass1(j->larg);
		result->relids = bms_add_members(result->relids,
										 sub_state->relids);
		result->contains_outer |= sub_state->contains_outer;
		result->sub_states = lappend(result->sub_states, sub_state);

		sub_state = reduce_outer_joins_pass1(j->rarg);
		result->relids = bms_add_members(result->relids,
										 sub_state->relids);
		result->contains_outer |= sub_state->contains_outer;
		result->sub_states = lappend(result->sub_states, sub_state);
	}
	else
643 644
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
645 646 647 648 649 650 651 652 653 654 655 656 657
	return result;
}

/*
 * reduce_outer_joins_pass2 - phase 2 processing
 *
 *	jtnode: current jointree node
 *	state: state data collected by phase 1 for this node
 *	parse: toplevel Query
 *	nonnullable_rels: set of base relids forced non-null by upper quals
 */
static void
reduce_outer_joins_pass2(Node *jtnode,
658
						 reduce_outer_joins_state *state,
659 660 661 662 663 664 665 666
						 Query *parse,
						 Relids nonnullable_rels)
{
	/*
	 * pass 2 should never descend as far as an empty subnode or base rel,
	 * because it's only called on subtrees marked as contains_outer.
	 */
	if (jtnode == NULL)
667
		elog(ERROR, "reached empty jointree");
668
	if (IsA(jtnode, RangeTblRef))
669
		elog(ERROR, "reached base rel");
670 671 672
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
673 674
		ListCell   *l;
		ListCell   *s;
675 676 677 678 679 680 681
		Relids		pass_nonnullable;

		/* Scan quals to see if we can add any nonnullability constraints */
		pass_nonnullable = find_nonnullable_rels(f->quals, true);
		pass_nonnullable = bms_add_members(pass_nonnullable,
										   nonnullable_rels);
		/* And recurse --- but only into interesting subtrees */
682
		Assert(list_length(f->fromlist) == list_length(state->sub_states));
683
		forboth(l, f->fromlist, s, state->sub_states)
684 685 686 687 688 689 690 691 692 693 694 695 696 697
		{
			reduce_outer_joins_state *sub_state = lfirst(s);

			if (sub_state->contains_outer)
				reduce_outer_joins_pass2(lfirst(l), sub_state, parse,
										 pass_nonnullable);
		}
		bms_free(pass_nonnullable);
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
		int			rtindex = j->rtindex;
		JoinType	jointype = j->jointype;
698
		reduce_outer_joins_state *left_state = linitial(state->sub_states);
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
		reduce_outer_joins_state *right_state = lsecond(state->sub_states);

		/* Can we simplify this join? */
		switch (jointype)
		{
			case JOIN_LEFT:
				if (bms_overlap(nonnullable_rels, right_state->relids))
					jointype = JOIN_INNER;
				break;
			case JOIN_RIGHT:
				if (bms_overlap(nonnullable_rels, left_state->relids))
					jointype = JOIN_INNER;
				break;
			case JOIN_FULL:
				if (bms_overlap(nonnullable_rels, left_state->relids))
				{
					if (bms_overlap(nonnullable_rels, right_state->relids))
						jointype = JOIN_INNER;
					else
						jointype = JOIN_LEFT;
				}
				else
				{
					if (bms_overlap(nonnullable_rels, right_state->relids))
						jointype = JOIN_RIGHT;
				}
				break;
			default:
				break;
		}
		if (jointype != j->jointype)
		{
			/* apply the change to both jointree node and RTE */
			RangeTblEntry *rte = rt_fetch(rtindex, parse->rtable);

			Assert(rte->rtekind == RTE_JOIN);
			Assert(rte->jointype == j->jointype);
			rte->jointype = j->jointype = jointype;
		}

		/* Only recurse if there's more to do below here */
		if (left_state->contains_outer || right_state->contains_outer)
		{
742
			Relids		local_nonnullable;
743 744 745
			Relids		pass_nonnullable;

			/*
746 747
			 * If this join is (now) inner, we can add any nonnullability
			 * constraints its quals provide to those we got from above.
B
Bruce Momjian 已提交
748 749 750 751 752
			 * But if it is outer, we can only pass down the local
			 * constraints into the nullable side, because an outer join
			 * never eliminates any rows from its non-nullable side.  If
			 * it's a FULL join then it doesn't eliminate anything from
			 * either side.
753
			 */
754 755 756 757 758 759 760
			if (jointype != JOIN_FULL)
			{
				local_nonnullable = find_nonnullable_rels(j->quals, true);
				local_nonnullable = bms_add_members(local_nonnullable,
													nonnullable_rels);
			}
			else
B
Bruce Momjian 已提交
761 762
				local_nonnullable = NULL;		/* no use in calculating
												 * it */
763

764
			if (left_state->contains_outer)
765 766 767 768 769
			{
				if (jointype == JOIN_INNER || jointype == JOIN_RIGHT)
					pass_nonnullable = local_nonnullable;
				else
					pass_nonnullable = nonnullable_rels;
770 771
				reduce_outer_joins_pass2(j->larg, left_state, parse,
										 pass_nonnullable);
772
			}
773
			if (right_state->contains_outer)
774 775 776 777 778
			{
				if (jointype == JOIN_INNER || jointype == JOIN_LEFT)
					pass_nonnullable = local_nonnullable;
				else
					pass_nonnullable = nonnullable_rels;
779 780
				reduce_outer_joins_pass2(j->rarg, right_state, parse,
										 pass_nonnullable);
781 782
			}
			bms_free(local_nonnullable);
783 784 785
		}
	}
	else
786 787
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
788 789 790 791 792 793 794 795
}

/*
 * find_nonnullable_rels
 *		Determine which base rels are forced nonnullable by given quals
 *
 * We don't use expression_tree_walker here because we don't want to
 * descend through very many kinds of nodes; only the ones we can be sure
B
Bruce Momjian 已提交
796
 * are strict.	We can descend through the top level of implicit AND'ing,
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
 * but not through any explicit ANDs (or ORs) below that, since those are not
 * strict constructs.  The List case handles the top-level implicit AND list
 * as well as lists of arguments to strict operators/functions.
 */
static Relids
find_nonnullable_rels(Node *node, bool top_level)
{
	Relids		result = NULL;

	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;

		if (var->varlevelsup == 0)
			result = bms_make_singleton(var->varno);
	}
	else if (IsA(node, List))
	{
817
		ListCell   *l;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

		foreach(l, (List *) node)
		{
			result = bms_join(result, find_nonnullable_rels(lfirst(l),
															top_level));
		}
	}
	else if (IsA(node, FuncExpr))
	{
		FuncExpr   *expr = (FuncExpr *) node;

		if (func_strict(expr->funcid))
			result = find_nonnullable_rels((Node *) expr->args, false);
	}
	else if (IsA(node, OpExpr))
	{
B
Bruce Momjian 已提交
834
		OpExpr	   *expr = (OpExpr *) node;
835 836 837 838 839 840 841 842 843 844 845 846 847 848

		if (op_strict(expr->opno))
			result = find_nonnullable_rels((Node *) expr->args, false);
	}
	else if (IsA(node, BoolExpr))
	{
		BoolExpr   *expr = (BoolExpr *) node;

		/* NOT is strict, others are not */
		if (expr->boolop == NOT_EXPR)
			result = find_nonnullable_rels((Node *) expr->args, false);
	}
	else if (IsA(node, RelabelType))
	{
B
Bruce Momjian 已提交
849
		RelabelType *expr = (RelabelType *) node;
850 851 852

		result = find_nonnullable_rels((Node *) expr->arg, top_level);
	}
853 854 855 856 857 858 859
	else if (IsA(node, ConvertRowtypeExpr))
	{
		/* not clear this is useful, but it can't hurt */
		ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;

		result = find_nonnullable_rels((Node *) expr->arg, top_level);
	}
860 861 862 863 864 865 866 867 868 869 870 871 872
	else if (IsA(node, NullTest))
	{
		NullTest   *expr = (NullTest *) node;

		/*
		 * IS NOT NULL can be considered strict, but only at top level;
		 * else we might have something like NOT (x IS NOT NULL).
		 */
		if (top_level && expr->nulltesttype == IS_NOT_NULL)
			result = find_nonnullable_rels((Node *) expr->arg, false);
	}
	else if (IsA(node, BooleanTest))
	{
B
Bruce Momjian 已提交
873
		BooleanTest *expr = (BooleanTest *) node;
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888

		/*
		 * Appropriate boolean tests are strict at top level.
		 */
		if (top_level &&
			(expr->booltesttype == IS_TRUE ||
			 expr->booltesttype == IS_FALSE ||
			 expr->booltesttype == IS_NOT_UNKNOWN))
			result = find_nonnullable_rels((Node *) expr->arg, false);
	}
	return result;
}

/*
 * simplify_jointree
889 890 891 892 893 894 895
 *		Attempt to simplify a query's jointree.
 *
 * If we succeed in pulling up a subquery then we might form a jointree
 * in which a FromExpr is a direct child of another FromExpr.  In that
 * case we can consider collapsing the two FromExprs into one.	This is
 * an optional conversion, since the planner will work correctly either
 * way.  But we may find a better plan (at the cost of more planning time)
896 897 898 899 900 901 902 903 904 905
 * if we merge the two nodes, creating a single join search space out of
 * two.  To allow the user to trade off planning time against plan quality,
 * we provide a control parameter from_collapse_limit that limits the size
 * of the join search space that can be created this way.
 *
 * We also consider flattening explicit inner JOINs into FromExprs (which
 * will in turn allow them to be merged into parent FromExprs).  The tradeoffs
 * here are the same as for flattening FromExprs, but we use a different
 * control parameter so that the user can use explicit JOINs to control the
 * join order even when they are inner JOINs.
906 907 908 909 910 911
 *
 * NOTE: don't try to do this in the same jointree scan that does subquery
 * pullup!	Since we're changing the jointree structure here, that wouldn't
 * work reliably --- see comments for pull_up_subqueries().
 */
Node *
912
simplify_jointree(Query *parse, Node *jtnode)
913 914 915 916 917 918 919 920 921 922 923
{
	if (jtnode == NULL)
		return NULL;
	if (IsA(jtnode, RangeTblRef))
	{
		/* nothing to do here... */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
		List	   *newlist = NIL;
924
		int			children_remaining;
925
		ListCell   *l;
926

927
		children_remaining = list_length(f->fromlist);
928 929 930 931
		foreach(l, f->fromlist)
		{
			Node	   *child = (Node *) lfirst(l);

932
			children_remaining--;
933
			/* Recursively simplify this child... */
934
			child = simplify_jointree(parse, child);
935 936 937 938 939 940
			/* Now, is it a FromExpr? */
			if (child && IsA(child, FromExpr))
			{
				/*
				 * Yes, so do we want to merge it into parent?	Always do
				 * so if child has just one element (since that doesn't
941 942 943
				 * make the parent's list any longer).  Otherwise merge if
				 * the resulting join list would be no longer than
				 * from_collapse_limit.
944 945
				 */
				FromExpr   *subf = (FromExpr *) child;
946 947
				int			childlen = list_length(subf->fromlist);
				int			myothers = list_length(newlist) + children_remaining;
948

949 950
				if (childlen <= 1 ||
					(childlen + myothers) <= from_collapse_limit)
951
				{
952
					newlist = list_concat(newlist, subf->fromlist);
B
Bruce Momjian 已提交
953

954
					/*
B
Bruce Momjian 已提交
955 956 957
					 * By now, the quals have been converted to
					 * implicit-AND lists, so we just need to join the
					 * lists.  NOTE: we put the pulled-up quals first.
958
					 */
959
					f->quals = (Node *) list_concat((List *) subf->quals,
B
Bruce Momjian 已提交
960
													(List *) f->quals);
961 962 963 964 965 966 967 968 969 970 971 972 973
				}
				else
					newlist = lappend(newlist, child);
			}
			else
				newlist = lappend(newlist, child);
		}
		f->fromlist = newlist;
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

974
		/* Recursively simplify the children... */
975 976
		j->larg = simplify_jointree(parse, j->larg);
		j->rarg = simplify_jointree(parse, j->rarg);
B
Bruce Momjian 已提交
977

978
		/*
B
Bruce Momjian 已提交
979
		 * If it is an outer join, we must not flatten it.	An inner join
980 981 982 983 984 985
		 * is semantically equivalent to a FromExpr; we convert it to one,
		 * allowing it to be flattened into its parent, if the resulting
		 * FromExpr would have no more than join_collapse_limit members.
		 */
		if (j->jointype == JOIN_INNER && join_collapse_limit > 1)
		{
B
Bruce Momjian 已提交
986 987
			int			leftlen,
						rightlen;
988 989

			if (j->larg && IsA(j->larg, FromExpr))
990
				leftlen = list_length(((FromExpr *) j->larg)->fromlist);
991 992 993
			else
				leftlen = 1;
			if (j->rarg && IsA(j->rarg, FromExpr))
994
				rightlen = list_length(((FromExpr *) j->rarg)->fromlist);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
			else
				rightlen = 1;
			if ((leftlen + rightlen) <= join_collapse_limit)
			{
				FromExpr   *f = makeNode(FromExpr);

				f->fromlist = NIL;
				f->quals = NULL;

				if (j->larg && IsA(j->larg, FromExpr))
				{
					FromExpr   *subf = (FromExpr *) j->larg;

					f->fromlist = subf->fromlist;
					f->quals = subf->quals;
				}
				else
1012
					f->fromlist = list_make1(j->larg);
1013 1014 1015 1016 1017

				if (j->rarg && IsA(j->rarg, FromExpr))
				{
					FromExpr   *subf = (FromExpr *) j->rarg;

1018 1019 1020
					f->fromlist = list_concat(f->fromlist,
											  subf->fromlist);
					f->quals = (Node *) list_concat((List *) f->quals,
B
Bruce Momjian 已提交
1021
													(List *) subf->quals);
1022 1023 1024 1025 1026
				}
				else
					f->fromlist = lappend(f->fromlist, j->rarg);

				/* pulled-up quals first */
1027
				f->quals = (Node *) list_concat((List *) f->quals,
B
Bruce Momjian 已提交
1028
												(List *) j->quals);
1029 1030 1031 1032

				return (Node *) f;
			}
		}
1033 1034
	}
	else
1035 1036
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1037 1038 1039 1040
	return jtnode;
}

/*
1041
 * fix_in_clause_relids: update RT-index sets of InClauseInfo nodes
1042 1043
 *
 * When we pull up a subquery, any InClauseInfo references to the subquery's
1044
 * RT index have to be replaced by the set of substituted relids.
1045 1046 1047 1048 1049 1050
 *
 * We assume we may modify the InClauseInfo nodes in-place.
 */
static void
fix_in_clause_relids(List *in_info_list, int varno, Relids subrelids)
{
1051
	ListCell   *l;
1052 1053 1054 1055 1056

	foreach(l, in_info_list)
	{
		InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);

1057
		if (bms_is_member(varno, ininfo->lefthand))
1058
		{
1059 1060
			ininfo->lefthand = bms_del_member(ininfo->lefthand, varno);
			ininfo->lefthand = bms_add_members(ininfo->lefthand, subrelids);
1061
		}
1062
		if (bms_is_member(varno, ininfo->righthand))
1063
		{
1064 1065
			ininfo->righthand = bms_del_member(ininfo->righthand, varno);
			ininfo->righthand = bms_add_members(ininfo->righthand, subrelids);
1066 1067 1068 1069 1070
		}
	}
}

/*
1071
 * get_relids_in_jointree: get set of base RT indexes present in a jointree
1072
 */
1073
Relids
1074 1075
get_relids_in_jointree(Node *jtnode)
{
1076
	Relids		result = NULL;
1077 1078 1079 1080 1081 1082 1083

	if (jtnode == NULL)
		return result;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;

1084
		result = bms_make_singleton(varno);
1085 1086 1087 1088
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
1089
		ListCell   *l;
1090 1091 1092

		foreach(l, f->fromlist)
		{
1093 1094
			result = bms_join(result,
							  get_relids_in_jointree(lfirst(l)));
1095 1096 1097 1098 1099 1100 1101 1102
		}
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

		/* join's own RT index is not wanted in result */
		result = get_relids_in_jointree(j->larg);
1103
		result = bms_join(result, get_relids_in_jointree(j->rarg));
1104 1105
	}
	else
1106 1107
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1108 1109 1110 1111
	return result;
}

/*
1112
 * get_relids_for_join: get set of base RT indexes making up a join
1113
 *
1114
 * NB: this will not work reliably after simplify_jointree() is run,
1115
 * since that may eliminate join nodes from the jointree.
1116
 */
1117
Relids
1118 1119 1120 1121 1122 1123
get_relids_for_join(Query *parse, int joinrelid)
{
	Node	   *jtnode;

	jtnode = find_jointree_node_for_rel((Node *) parse->jointree, joinrelid);
	if (!jtnode)
1124
		elog(ERROR, "could not find join node %d", joinrelid);
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
	return get_relids_in_jointree(jtnode);
}

/*
 * find_jointree_node_for_rel: locate jointree node for a base or join RT index
 *
 * Returns NULL if not found
 */
static Node *
find_jointree_node_for_rel(Node *jtnode, int relid)
{
	if (jtnode == NULL)
		return NULL;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;

		if (relid == varno)
			return jtnode;
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
1148
		ListCell   *l;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

		foreach(l, f->fromlist)
		{
			jtnode = find_jointree_node_for_rel(lfirst(l), relid);
			if (jtnode)
				return jtnode;
		}
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

		if (relid == j->rtindex)
			return jtnode;
		jtnode = find_jointree_node_for_rel(j->larg, relid);
		if (jtnode)
			return jtnode;
		jtnode = find_jointree_node_for_rel(j->rarg, relid);
		if (jtnode)
			return jtnode;
	}
	else
1171 1172
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1173 1174
	return NULL;
}