prepjointree.c 67.1 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * prepjointree.c
 *	  Planner preprocessing for subqueries and join tree manipulation.
 *
6
 * NOTE: the intended sequence for invoking these operations is
7
 * 		pull_up_sublinks
8
 *		inline_set_returning_functions
9 10 11 12
 *		pull_up_subqueries
 *		do expression preprocessing (including flattening JOIN alias vars)
 *		reduce_outer_joins
 *
13
 *
14 15 16 17 18
 * In PostgreSQL, there is code here to do with pulling up "simple UNION ALLs".
 * In GPDB, there is no such thing as a simple UNION ALL as locus of the relations
 * may be different, so all that has been removed.
 *
 *
19
 * Portions Copyright (c) 2006-2008, Greenplum inc
20
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
21
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
22 23 24 25
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
26
 *	  $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.57 2008/10/21 20:42:53 tgl Exp $
27 28 29 30 31
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

32
#include "catalog/pg_type.h"
33
#include "nodes/makefuncs.h"
34
#include "optimizer/clauses.h"
35
#include "optimizer/placeholder.h"
36
#include "optimizer/prep.h"
37
#include "optimizer/subselect.h"
38
#include "optimizer/tlist.h"
39
#include "optimizer/var.h"
40
#include "parser/parse_expr.h"
41
#include "parser/parse_relation.h"
42 43
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
44
#include "cdb/cdbsubselect.h"
45

46
#include "optimizer/transform.h"
47

48 49 50 51 52 53 54 55 56 57 58
typedef struct pullup_replace_vars_context
{
	PlannerInfo *root;
	List	   *targetlist;			/* tlist of subquery being pulled up */
	RangeTblEntry *target_rte;		/* RTE of subquery */
	bool	   *outer_hasSubLinks;	/* -> outer query's hasSubLinks */
	int			varno;				/* varno of subquery */
	bool		need_phvs;			/* do we need PlaceHolderVars? */
	bool		wrap_non_vars;		/* do we need 'em on *all* non-Vars? */
	Node	  **rv_cache;			/* cache for results with PHVs */
} pullup_replace_vars_context;
59

60 61 62
typedef struct reduce_outer_joins_state
{
	Relids		relids;			/* base relids within this subtree */
B
Bruce Momjian 已提交
63
	bool		contains_outer; /* does subtree contain outer join(s)? */
64
	List	   *sub_states;		/* List of states for subtree components */
65
} reduce_outer_joins_state;
66

67 68 69
static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
								  Relids *relids);
static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
70
							  Relids available_rels, Node **jtlink);
71 72 73
static void pull_up_fromlist_subqueries(PlannerInfo    *root,
                                        List          **inout_fromlist,
				                        bool            below_outer_join);
74
static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
B
Bruce Momjian 已提交
75
						RangeTblEntry *rte,
76 77
						JoinExpr *lowest_outer_join,
						AppendRelInfo *containing_appendrel);
78
bool is_simple_subquery(PlannerInfo *root, Query *subquery);
79
static bool is_safe_append_member(Query *subquery);
80 81 82 83 84 85 86
static void replace_vars_in_jointree(Node *jtnode,
									 pullup_replace_vars_context *context,
									 JoinExpr *lowest_outer_join);
static Node *pullup_replace_vars(Node *expr,
								 pullup_replace_vars_context *context);
static Node *pullup_replace_vars_callback(Var *var,
										  replace_rte_variables_context *context);
87 88
static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
static void reduce_outer_joins_pass2(Node *jtnode,
89
						 reduce_outer_joins_state *state,
90
						 PlannerInfo *root,
91 92 93
						 Relids nonnullable_rels,
						 List *nonnullable_vars,
						 List *forced_null_vars);
94 95
static void substitute_multiple_relids(Node *node,
									   int varno, Relids subrelids);
96
static void fix_append_rel_relids(List *append_rel_list, int varno,
B
Bruce Momjian 已提交
97
					  Relids subrelids);
98
static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
99
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes);
100

101
extern void UpdateScatterClause(Query *query, List *newtlist);
102

103 104
/*
 * pull_up_sublinks
105 106
 *		Attempt to pull up ANY and EXISTS SubLinks to be treated as
 *		semijoins or anti-semijoins.
107
 *
108 109 110 111 112 113 114
 * A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
 * sub-SELECT up to become a rangetable entry and treating the implied
 * comparisons as quals of a semijoin.  However, this optimization *only*
 * works at the top level of WHERE or a JOIN/ON clause, because we cannot
 * distinguish whether the ANY ought to return FALSE or NULL in cases
 * involving NULL inputs.  Also, in an outer join's ON clause we can only
 * do this if the sublink is degenerate (ie, references only the nullable
115
 * side of the join).  In that case it is legal to push the semijoin
116 117 118 119 120 121
 * down into the nullable side of the join.  If the sublink references any
 * nonnullable-side variables then it would have to be evaluated as part
 * of the outer join, which makes things way too complicated.
 *
 * Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
 * by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
122 123 124 125
 *
 * This routine searches for such clauses and does the necessary parsetree
 * transformations if any are found.
 *
126 127
 * This routine has to run before preprocess_expression(), so the quals
 * clauses are not yet reduced to implicit-AND format.  That means we need
128 129
 * to recursively search through explicit AND clauses, which are
 * probably only binary ANDs.  We stop as soon as we hit a non-AND item.
130 131 132 133
 */
void
pull_up_sublinks(PlannerInfo *root)
{
134
	Node	   *jtnode;
135 136 137
	Relids		relids;

	/* Begin recursion through the jointree */
138 139 140 141 142 143 144 145 146 147 148 149
	jtnode = pull_up_sublinks_jointree_recurse(root,
 											   (Node *) root->parse->jointree,
 											   &relids);

 	/*
 	 * root->parse->jointree must always be a FromExpr, so insert a dummy one
 	 * if we got a bare RangeTblRef or JoinExpr out of the recursion.
 	 */
 	if (IsA(jtnode, FromExpr))
 		root->parse->jointree = (FromExpr *) jtnode;
 	else
 		root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
150 151 152 153
}

/*
 * Recurse through jointree nodes for pull_up_sublinks()
154
 *
155 156
 * In addition to returning the possibly-modified jointree node, we return
 * a relids set of the contained rels into *relids.
157
 */
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static Node *
pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
								  Relids *relids)
{
	if (jtnode == NULL)
	{
		*relids = NULL;
	}
	else if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;

		*relids = bms_make_singleton(varno);
		/* jtnode is returned unmodified */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
		List	   *newfromlist = NIL;
		Relids		frelids = NULL;
178 179
		FromExpr   *newf;
		Node	   *jtlink;
180 181 182 183 184 185 186 187 188 189 190 191 192 193
		ListCell   *l;

		/* First, recurse to process children and collect their relids */
		foreach(l, f->fromlist)
		{
			Node   *newchild;
			Relids	childrelids;

			newchild = pull_up_sublinks_jointree_recurse(root,
														 lfirst(l),
														 &childrelids);
			newfromlist = lappend(newfromlist, newchild);
			frelids = bms_join(frelids, childrelids);
		}
194 195 196 197
		/* Build the replacement FromExpr; no quals yet */
		newf = makeFromExpr(newfromlist, NULL);
		/* Set up a link representing the rebuilt jointree */
		jtlink = (Node *) newf;
198
		/* Now process qual --- all children are available for use */
199 200
		newf->quals = pull_up_sublinks_qual_recurse(root, f->quals, frelids,
													&jtlink);
201

202 203 204 205 206 207 208 209 210 211 212
		/*
		 * Note that the result will be either newf, or a stack of JoinExprs
 		 * with newf at the base.  We rely on subsequent optimization steps
 		 * to flatten this and rearrange the joins as needed.
		 *
		 * Although we could include the pulled-up subqueries in the returned
		 * relids, there's no need since upper quals couldn't refer to their
		 * outputs anyway.
		 */
		*relids = frelids;
		jtnode = jtlink;;
213 214 215 216
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j;
217 218
		Relids		leftrelids = NULL;
		Relids		rightrelids = NULL;
219
		Node	   *jtlink;
220 221 222 223 224 225 226

		/*
		 * Make a modifiable copy of join node, but don't bother copying
		 * its subnodes (yet).
		 */
		j = (JoinExpr *) palloc(sizeof(JoinExpr));
		memcpy(j, jtnode, sizeof(JoinExpr));
227 228 229 230 231 232
		jtlink = (Node *) j;

		/*
		 * We support flattening of sublinks in JOIN...ON only for
		 * inner joins
		 */
233 234 235 236 237 238 239
		if (j->jointype == JOIN_INNER)
		{
			/* Recurse to process children and collect their relids */
			j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
														&leftrelids);
			j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
														&rightrelids);
240

241 242 243 244 245 246 247 248 249 250 251 252 253
			/*
			 * Now process qual, showing appropriate child relids as available,
			 * and attach any pulled-up jointree items at the right place.
			 * We put new JoinExprs above the existing one (much as for a
			 * FromExpr-style join). The point of the available_rels
			 * machinations is to ensure that we only pull up quals for
			 * which that's okay.
			 */
			j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
													 bms_union(leftrelids,
															   rightrelids),
													 &jtlink);
		}
254 255 256 257 258 259 260 261 262

		/*
		 * Although we could include the pulled-up subqueries in the returned
		 * relids, there's no need since upper quals couldn't refer to their
		 * outputs anyway.  But we *do* need to include the join's own rtindex
		 * because we haven't yet collapsed join alias variables, so upper
		 * levels would mistakenly think they couldn't use references to this
		 * join.
		 */
263 264 265 266
		*relids = bms_join(leftrelids, rightrelids);
		if (j->rtindex)
			*relids = bms_add_member(*relids, j->rtindex);
		jtnode = jtlink;
267 268 269 270 271 272 273 274 275 276
	}
	else
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
	return jtnode;
}

/*
 * Recurse through top-level qual nodes for pull_up_sublinks()
 *
277 278 279 280
 * jtlink points to the link in the jointree where any new JoinExprs should be
 * inserted.  If we find multiple pull-up-able SubLinks, they'll get stacked
 * there in the order we encounter them.  We rely on subsequent optimization
 * to rearrange the stack if appropriate.
281 282 283
 */
static Node *
pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
284
							  Relids available_rels, Node **jtlink)
285 286 287 288 289 290
{
	if (node == NULL)
		return NULL;
	if (IsA(node, SubLink))
	{
		SubLink    *sublink = (SubLink *) node;
291
		JoinExpr   *j;
292 293 294 295

		/* Is it a convertible ANY or EXISTS clause? */
		if (sublink->subLinkType == ANY_SUBLINK)
		{
296 297
			j = convert_ANY_sublink_to_join(root, sublink, available_rels);
			if (j)
298
			{
299 300 301 302 303
				/* Yes, insert the new join node into the join tree */
				j->larg = *jtlink;
				*jtlink = (Node *) j;
				/* and return NULL representing constant TRUE */
				return NULL;
304
			}
305 306 307
		}
		else if (sublink->subLinkType == EXISTS_SUBLINK)
		{
308 309 310
			Node* subst;
			subst = convert_EXISTS_sublink_to_join(root, sublink, false, available_rels);
			if (subst && IsA(subst, JoinExpr))
311
			{
312 313 314 315 316 317
				j = (JoinExpr *) subst;
				/* Yes, insert the new join node into the join tree */
				j->larg = *jtlink;
				*jtlink = (Node *) j;
				/* and return NULL representing constant TRUE */
				return NULL;
318
			}
319 320
			else if(subst)
				return subst;
E
Ekta Khanna 已提交
321 322 323
		}
		else if (sublink->subLinkType == ALL_SUBLINK)
		{
324
			/* GPDB_84_MERGE_FIXME: Should convert_IN_to_antijoin() also use available_rels ? */
325 326 327 328 329 330 331 332 333
			j = convert_IN_to_antijoin(root, sublink);
			if (j)
			{
				/* Yes, insert the new join node into the join tree */
				j->larg = *jtlink;
				*jtlink = (Node *) j;
				/* and return NULL representing constant TRUE */
				return NULL;
			}
E
Ekta Khanna 已提交
334
		}
335 336 337 338 339 340 341
		/* Else return it unmodified */
		return node;
	}
	if (not_clause(node))
	{
		/* If the immediate argument of NOT is EXISTS, try to convert */
		SubLink    *sublink = (SubLink *) get_notclausearg((Expr *) node);
342
		Node	   *arg = (Node *) get_notclausearg((Expr *) node);
343
		JoinExpr   *j;
344 345 346 347 348

		if (sublink && IsA(sublink, SubLink))
		{
			if (sublink->subLinkType == EXISTS_SUBLINK)
			{
349 350 351
				Node* subst;
				subst = convert_EXISTS_sublink_to_join(root, sublink, true, available_rels);
				if (subst && IsA(subst, JoinExpr))
352
				{
353 354 355 356 357 358
					j = (JoinExpr *) subst;
					/* Yes, insert the new join node into the join tree */
					j->larg = *jtlink;
					*jtlink = (Node *) j;
					/* and return NULL representing constant TRUE */
					return NULL;
359
				}
360 361 362 363 364
				else if (subst)
					return subst;

				/* Else return it unmodified */
				return node;
E
Ekta Khanna 已提交
365
			}
366

E
Ekta Khanna 已提交
367 368 369 370 371 372 373 374 375 376
			/*
			 *	 We normalize NOT subqueries using the following axioms:
			 *
			 *		 val NOT IN (subq)		 =>  val <> ALL (subq)
			 *		 NOT val op ANY (subq)	 =>  val op' ALL (subq)
			 *		 NOT val op ALL (subq)	 =>  val op' ANY (subq)
			 */
			else if (sublink->subLinkType == ANY_SUBLINK)
			{
				sublink->subLinkType = ALL_SUBLINK;
377
				sublink->testexpr = (Node *) canonicalize_qual(make_notclause((Expr *) sublink->testexpr));
E
Ekta Khanna 已提交
378 379 380 381
			}
			else if (sublink->subLinkType == ALL_SUBLINK)
			{
				sublink->subLinkType = ANY_SUBLINK;
382
				sublink->testexpr = (Node *) canonicalize_qual(make_notclause((Expr *) sublink->testexpr));
E
Ekta Khanna 已提交
383
			}
384
			return pull_up_sublinks_qual_recurse(root, (Node *) sublink, available_rels, jtlink);
E
Ekta Khanna 已提交
385
		}
386

E
Ekta Khanna 已提交
387 388 389
		else if (not_clause(arg))
		{
			/* NOT NOT (expr) => (expr)  */
390 391
			return (Node *) pull_up_sublinks_qual_recurse(root,
														 (Node *) get_notclausearg((Expr *) arg),
392
														 available_rels, jtlink);
E
Ekta Khanna 已提交
393 394 395 396
		}
		else if (or_clause(arg))
		{
			/* NOT OR (expr1) (expr2) => (expr1) AND (expr2) */
397 398
			return (Node *) pull_up_sublinks_qual_recurse(root,
														 (Node *) canonicalize_qual((Expr *) node),
399
														 available_rels, jtlink);
400
		}
401

402 403 404
		/* Else return it unmodified */
		return node;
	}
405 406 407 408 409 410 411 412 413 414 415 416 417 418
	if (and_clause(node))
	{
		/* Recurse into AND clause */
		List	   *newclauses = NIL;
		ListCell   *l;

		foreach(l, ((BoolExpr *) node)->args)
		{
			Node	   *oldclause = (Node *) lfirst(l);
			Node	   *newclause;

			newclause = pull_up_sublinks_qual_recurse(root,
													  oldclause,
													  available_rels,
419
													  jtlink);
420 421 422 423 424
			if(newclause)
				newclauses = lappend(newclauses, newclause);
		}
		return (Node *) make_ands_explicit(newclauses);
	}
E
Ekta Khanna 已提交
425

426
	/*
E
Ekta Khanna 已提交
427 428 429
	 * (expr) op SUBLINK
	 */
	if (IsA(node, OpExpr))
430
	{
E
Ekta Khanna 已提交
431
		OpExpr *opexp = (OpExpr *) node;
432
		JoinExpr   *j;
433 434 435 436 437 438 439 440 441 442

		if (list_length(opexp->args) == 2)
		{
			/**
			 * Check if second arg is sublink
			 */
			Node *rarg = list_nth(opexp->args, 1);

			if (IsA(rarg, SubLink))
			{
443
				/* GPDB_84_MERGE_FIXME: Should convert_EXPR_to_join() also use available_rels ? */
444 445 446 447 448 449 450 451
				j = convert_EXPR_to_join(root, opexp);
				if (j)
				{
					/* Yes, insert the new join node into the join tree */
					j->larg = *jtlink;
					*jtlink = (Node *) j;
				}
				return node;
452 453 454
			}
		}
	}
455

456 457 458
	/* Stop if not an AND */
	return node;
}
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
/*
 * inline_set_returning_functions
 *		Attempt to "inline" set-returning functions in the FROM clause.
 *
 * If an RTE_FUNCTION rtable entry invokes a set-returning function that
 * contains just a simple SELECT, we can convert the rtable entry to an
 * RTE_SUBQUERY entry exposing the SELECT directly.  This is especially
 * useful if the subquery can then be "pulled up" for further optimization,
 * but we do it even if not, to reduce executor overhead.
 *
 * This has to be done before we have started to do any optimization of
 * subqueries, else any such steps wouldn't get applied to subqueries
 * obtained via inlining.  However, we do it after pull_up_IN_clauses
 * so that we can inline any functions used in IN subselects.
 *
 * Like most of the planner, this feels free to scribble on its input data
 * structure.
 */
void
inline_set_returning_functions(PlannerInfo *root)
{
	ListCell   *rt;

	foreach(rt, root->parse->rtable)
	{
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);

		if (rte->rtekind == RTE_FUNCTION)
		{
			Query  *funcquery;

			/* Check safety of expansion, and expand if possible */
			funcquery = inline_set_returning_function(root, rte->funcexpr);
			if (funcquery)
			{
495 496 497 498 499 500 501

				/*
				 * GPDB: Normalize the resulting query, like standard_planner()
				 * does for the main query.
				 */
				funcquery = normalize_query(funcquery);

502 503 504 505 506 507 508 509 510 511 512
				/* Successful expansion, replace the rtable entry */
				rte->rtekind = RTE_SUBQUERY;
				rte->subquery = funcquery;
				rte->funcexpr = NULL;
				rte->funccoltypes = NIL;
				rte->funccoltypmods = NIL;
			}
		}
	}
}

513 514 515 516 517
/*
 * 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.
518 519
 *		Also, subqueries that are simple UNION ALL structures can be
 *		converted into "append relations".
520 521
 *
 * below_outer_join is true if this jointree node is within the nullable
522 523
 * side of an outer join.  This forces use of the PlaceHolderVar mechanism
 * for non-nullable targetlist items.
524
 *
525
 * append_rel_member is true if we are looking at a member subquery of
526 527 528
 * an append relation.	This forces use of the PlaceHolderVar mechanism
 * for all non-Var targetlist items, and puts some additional restrictions
 * on what can be pulled up.
529
 *
530 531 532 533 534 535 536 537 538 539
 * 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 *
540
pull_up_subqueries(PlannerInfo *root, Node *jtnode,
541
				   JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
542
{
543
	if (jtnode == NULL)
544 545 546 547
		return NULL;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;
548
		RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
549 550

		/*
B
Bruce Momjian 已提交
551
		 * Is this a subquery RTE, and if so, is the subquery simple enough to
552
		 * pull up?
553
		 *
B
Bruce Momjian 已提交
554 555
		 * If we are looking at an append-relation member, we can't pull it up
		 * unless is_safe_append_member says so.
556
		 */
557 558
		if (rte->rtekind == RTE_SUBQUERY &&
			!rte->forceDistRandom &&
559
			is_simple_subquery(root, rte->subquery) &&
560
			(containing_appendrel == NULL || is_safe_append_member(rte->subquery)))
561
			return pull_up_simple_subquery(root, jtnode, rte,
562 563
										   lowest_outer_join,
										   containing_appendrel);
564

565
		/* PG:
566
		 * Alternatively, is it a simple UNION ALL subquery?  If so, flatten
567
		 * into an "append relation".
568
		 *
569
		 * It's safe to do this regardless of whether this query is
B
Bruce Momjian 已提交
570 571 572
		 * itself an appendrel member.	(If you're thinking we should try to
		 * flatten the two levels of appendrel together, you're right; but we
		 * handle that in set_append_rel_pathlist, not here.)
573 574 575 576 577
		 * 
		 * GPDB: 
		 * Flattening to an append relation works in PG but is not safe to do in GPDB. 
		 * A "simple" UNION ALL may involve relations with different loci and would require resolving
		 * locus issues. It is preferable to avoid pulling up simple UNION ALL in GPDB.
578
		 */
579 580 581 582
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
583
		ListCell   *l;
584

585 586 587
		Assert(containing_appendrel == NULL);
		foreach(l, f->fromlist)
			lfirst(l) = pull_up_subqueries(root, lfirst(l), lowest_outer_join, NULL);
588 589 590 591 592
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

593
		Assert(containing_appendrel == NULL);
594 595 596 597
		/* Recurse, being careful to tell myself when inside outer join */
		switch (j->jointype)
		{
			case JOIN_INNER:
598
			case JOIN_SEMI:
599
				j->larg = pull_up_subqueries(root, j->larg,
600
											 lowest_outer_join, NULL);
601
				j->rarg = pull_up_subqueries(root, j->rarg,
602
											 lowest_outer_join, NULL);
603 604
				break;
			case JOIN_LEFT:
E
Ekta Khanna 已提交
605
			case JOIN_ANTI:
606
			case JOIN_LASJ_NOTIN:
607
				j->larg = pull_up_subqueries(root, j->larg,
608
											 lowest_outer_join, NULL);
609
				j->rarg = pull_up_subqueries(root, j->rarg,
610
											 j, NULL);
611 612
				break;
			case JOIN_FULL:
613
				j->larg = pull_up_subqueries(root, j->larg,
614
											 j, NULL);
615
				j->rarg = pull_up_subqueries(root, j->rarg,
616
											 j, NULL);
617 618
				break;
			case JOIN_RIGHT:
619
				j->larg = pull_up_subqueries(root, j->larg,
620
											 j, NULL);
621
				j->rarg = pull_up_subqueries(root, j->rarg,
622
											 lowest_outer_join, NULL);
623 624
				break;
			default:
625 626
				elog(ERROR, "unrecognized join type: %d",
					 (int) j->jointype);
627 628
				break;
		}
629 630 631 632 633 634 635 636 637

        /*
         * CDB: If subqueries from the JOIN...ON search condition were
         * flattened, 'subqfromlist' is a list of RangeTblRef nodes to be
         * included in the cross product with larg and rarg.  Try to pull up
         * the referenced subqueries.  For outer joins, let below_outer_join
         * be true, because the subquery tables belong in the null-augmented
         * side of the JOIN (right side of LEFT JOIN).
         */
638
		ListCell   *l;
639
        if (j->subqfromlist)
640 641 642 643 644 645 646 647 648
			foreach(l, j->subqfromlist)
			{
				if(lowest_outer_join != NULL)
					lfirst(l) = pull_up_subqueries(root, lfirst(l), lowest_outer_join, NULL);
				else if(j->jointype != JOIN_INNER)
					lfirst(l) = pull_up_subqueries(root, lfirst(l), j, NULL);
				else
					lfirst(l) = pull_up_subqueries(root, lfirst(l), NULL, NULL);
			}
649 650
	}
	else
651 652
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
653 654 655
	return jtnode;
}

656 657

/*
658
 * GPDB_84_MERGE_FIXME: Check if can be removed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
 * pull_up_fromlist_subqueries
 *		Attempt to pull up subqueries in a List of jointree nodes.
 */
static void
pull_up_fromlist_subqueries(PlannerInfo    *root,
                            List          **inout_fromlist,
				            bool            below_outer_join)
{
    ListCell   *l;

    foreach(l, *inout_fromlist)
    {
        Node   *oldkid = (Node *)lfirst(l);
        Node   *newkid = pull_up_subqueries(root, oldkid,
											below_outer_join, false);

        lfirst(l) = newkid;
    }
}                               /* pull_up_fromlist_subqueries */


680 681 682 683 684
/*
 * pull_up_simple_subquery
 *		Attempt to pull up a single simple subquery.
 *
 * jtnode is a RangeTblRef that has been tentatively identified as a simple
B
Bruce Momjian 已提交
685
 * subquery by pull_up_subqueries.	We return the replacement jointree node,
686 687
 * or jtnode itself if we determine that the subquery can't be pulled up after
 * all.
688 689 690
 *
 * rte is the RangeTblEntry referenced by jtnode.  Remaining parameters are
 * as for pull_up_subqueries.
691 692 693
 */
static Node *
pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
694
						JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
695 696 697 698 699 700
{
	Query	   *parse = root->parse;
	int			varno = ((RangeTblRef *) jtnode)->rtindex;
	Query	   *subquery;
	PlannerInfo *subroot;
	int			rtoffset;
701
	pullup_replace_vars_context rvcontext;
702
	ListCell   *rt;
703
    ListCell   *cell;
704 705

	/*
B
Bruce Momjian 已提交
706 707 708 709
	 * 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 this to avoid
	 * problems if the same subquery is referenced from multiple jointree
	 * items (which can't happen normally, but might after rule rewriting).
710 711 712 713 714 715 716
	 */
	subquery = copyObject(rte->subquery);

	/*
	 * Create a PlannerInfo data structure for this subquery.
	 *
	 * NOTE: the next few steps should match the first processing in
B
Bruce Momjian 已提交
717 718
	 * subquery_planner().	Can we refactor to avoid code duplication, or
	 * would that just make things uglier?
719 720 721
	 */
	subroot = makeNode(PlannerInfo);
	subroot->parse = subquery;
722 723
	subroot->glob = root->glob;
	subroot->query_level = root->query_level;
724
	subroot->parent_root = root->parent_root;
725
	subroot->planner_cxt = CurrentMemoryContext;
726
	subroot->init_plans = NIL;
727 728
	subroot->cte_plan_ids = NIL;
	subroot->eq_classes = NIL;
729
	subroot->append_rel_list = NIL;
730 731 732 733 734 735
	subroot->hasRecursion = false;
	subroot->wt_param_id = -1;
	subroot->non_recursive_plan = NULL;

	/* No CTEs to worry about */
	Assert(subquery->cteList == NIL);
736

737 738 739 740 741 742 743
	subroot->list_cteplaninfo = NIL;
	if (subroot->parse->cteList != NIL)
	{
		subroot->list_cteplaninfo = init_list_cteplaninfo(list_length(subroot->parse->cteList));
	}

    /* CDB: Stash subquery jointree relids before flattening subqueries. */
744
    subroot->currlevel_relids = get_relids_in_jointree((Node *)subquery->jointree, false);
745 746 747 748 749
    
    /* Ensure that jointree has been normalized. See normalize_query_jointree_mutator() */
    AssertImply(subquery->jointree->fromlist, list_length(subquery->jointree->fromlist) == 1);
    
    subroot->config = CopyPlannerConfig(root->config);
750
	subroot->config->honor_order_by = false;
751 752 753
	/* CDB: Clear fallback */
	subroot->config->mpp_trying_fallback_plan = false;

754
	/*
755 756
	 * Pull up any SubLinks within the subquery's WHERE, so that we don't
	 * leave unoptimized SubLinks behind.
757 758
	 */
	if (subquery->hasSubLinks)
759
        pull_up_sublinks(subroot);
760

761 762 763 764 765
	/*
	 * Similarly, inline any set-returning functions in its rangetable.
	 */
	inline_set_returning_functions(subroot);

766 767 768 769 770
	/*
	 * Recursively pull up the subquery's subqueries, so that
	 * pull_up_subqueries' processing is complete for its jointree and
	 * rangetable.
	 *
771 772 773
	 * Note: we should pass NULL for containing-join info even if we are within an
	 * an outer join in the upper query; the lower query starts with a clean
	 * slate for outer-join semantics. Likewise, we say we aren't handling an
B
Bruce Momjian 已提交
774
	 * appendrel member.
775 776
	 */
	subquery->jointree = (FromExpr *)
777
		pull_up_subqueries(subroot, (Node *) subquery->jointree, NULL, NULL);
778 779

	/*
B
Bruce Momjian 已提交
780 781
	 * Now we must recheck whether the subquery is still simple enough to pull
	 * up.	If not, abandon processing it.
782
	 *
B
Bruce Momjian 已提交
783 784 785
	 * 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 in
	 * pull_up_subqueries.
786
	 */
787
	if (is_simple_subquery(root, subquery) &&
788
		(containing_appendrel == NULL || is_safe_append_member(subquery)))
789 790 791 792 793 794 795 796
	{
		/* good to go */
	}
	else
	{
		/*
		 * Give up, return unmodified RangeTblRef.
		 *
B
Bruce Momjian 已提交
797 798 799 800
		 * Note: The work we just did will be redone when the 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.
801 802 803 804
		 */
		return jtnode;
	}

805 806 807 808 809 810 811 812 813 814
    /* CDB: If parent RTE belongs to subquery's query level, children do too. */
    foreach (cell, subroot->append_rel_list)
    {
        AppendRelInfo  *appinfo = (AppendRelInfo *)lfirst(cell);

        if (bms_is_member(appinfo->parent_relid, subroot->currlevel_relids))
            subroot->currlevel_relids = bms_add_member(subroot->currlevel_relids,
                                                       appinfo->child_relid);
    }

815
	/*
B
Bruce Momjian 已提交
816
	 * Adjust level-0 varnos in subquery so that we can append its rangetable
817
	 * to upper query's.  We have to fix the subquery's append_rel_list
818
	 * as well.
819 820 821 822 823 824
	 */
	rtoffset = list_length(parse->rtable);
	OffsetVarNodes((Node *) subquery, rtoffset, 0);
	OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);

	/*
B
Bruce Momjian 已提交
825 826
	 * Upper-level vars in subquery are now one level closer to their parent
	 * than before.
827 828 829 830 831
	 */
	IncrementVarSublevelsUp((Node *) subquery, -1, 1);
	IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);

	/*
832 833
	 * The subquery's targetlist items are now in the appropriate form to
	 * insert into the top query, but if we are under an outer join then
834
	 * non-nullable items may have to be turned into PlaceHolderVars.  If we
835 836
	 * are dealing with an appendrel member then anything that's not a
	 * simple Var has to be turned into a PlaceHolderVar.
837
	 */
838 839 840 841 842 843 844 845 846
	rvcontext.root = root;
	rvcontext.targetlist = subquery->targetList;
	rvcontext.target_rte = rte;
	rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
	rvcontext.varno = varno;
	rvcontext.need_phvs = (lowest_outer_join != NULL || containing_appendrel != NULL);
	rvcontext.wrap_non_vars = (containing_appendrel != NULL);
	/* initialize cache array with indexes 0 .. length(tlist) */
	rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) * sizeof(Node *));
847 848

	List *newTList = (List *)
849
		pullup_replace_vars((Node *) parse->targetList, &rvcontext);
850 851 852 853 854 855

	if (parse->scatterClause)
	{
		UpdateScatterClause(parse, newTList);
	}

856 857 858 859
	/*
	 * 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
860 861
	 * could use query_tree_mutator.)  We have to use PHVs in the targetList,
	 * returningList, and havingQual, since those are certainly above any
862
	 * outer join.  replace_vars_in_jointree tracks its location in the jointree
863
	 * and uses PHVs or not appropriately.
864
	 */
865 866
	parse->targetList = newTList;

867
	parse->returningList = (List *)
868 869 870
		pullup_replace_vars((Node *) parse->returningList, &rvcontext);
	replace_vars_in_jointree((Node *) parse->jointree, &rvcontext, lowest_outer_join);

871
	Assert(parse->setOperations == NULL);
872
	parse->havingQual = pullup_replace_vars(parse->havingQual, &rvcontext);
873

874 875 876 877
	if (parse->windowClause)
	{
		foreach(cell, parse->windowClause)
		{
878 879
			WindowClause *wc = (WindowClause *) lfirst(cell);

880 881 882 883
			if (wc->startOffset)
				wc->startOffset =
					ResolveNew((Node *) wc->startOffset,
							   varno, 0, rte,
884
							   subquery->targetList, CMD_SELECT, 0, NULL);
885 886 887 888
			if (wc->endOffset)
				wc->endOffset =
					ResolveNew((Node *) wc->endOffset,
							   varno, 0, rte,
889
							   subquery->targetList, CMD_SELECT, 0, NULL);
890 891 892
		}
	}

893 894 895 896 897 898 899 900 901 902
	/*
	 * Replace references in the translated_vars lists of appendrels.
	 * When pulling up an appendrel member, we do not need PHVs in the list
	 * of the parent appendrel --- there isn't any outer join between.
	 * Elsewhere, use PHVs for safety.  (This analysis could be made tighter
	 * but it seems unlikely to be worth much trouble.)
	 */
	foreach(cell, root->append_rel_list)
	{
		AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(cell);
903
		bool	save_need_phvs = rvcontext.need_phvs;
904

905 906
		if (appinfo == containing_appendrel)
			rvcontext.need_phvs = false;
907
		appinfo->translated_vars = (List *)
908 909
				pullup_replace_vars((Node *) appinfo->translated_vars, &rvcontext);
		rvcontext.need_phvs = save_need_phvs;
910 911 912 913 914 915 916 917 918 919 920
	}

	/*
	 * Replace references in the joinaliasvars lists of join RTEs.
	 *
	 * You might think that we could avoid using PHVs for alias vars of joins
	 * below lowest_outer_join, but that doesn't work because the alias vars
	 * could be referenced above that join; we need the PHVs to be present
	 * in such references after the alias vars get flattened.  (It might be
	 * worth trying to be smarter here, someday.)
	 */
921 922 923 924 925 926
	foreach(rt, parse->rtable)
	{
		RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(rt);

		if (otherrte->rtekind == RTE_JOIN)
			otherrte->joinaliasvars = (List *)
927
				pullup_replace_vars((Node *) otherrte->joinaliasvars, &rvcontext);
928 929 930 931 932 933 934 935 936 937

		else if (otherrte->rtekind == RTE_SUBQUERY && rte != otherrte)
		{
			otherrte->subquery = (Query *)
				ResolveNew((Node *) otherrte->subquery,
							varno, 1, rte, /* here the sublevels_up can only be 1, because if larger than 1,
											  then the sublink is multilevel correlated, and cannot be pulled
											  up to be a subquery range table; while on the other hand, we
											  cannot directly put a subquery which refer to other relations
											  of the same level after FROM. */
938
							subquery->targetList, CMD_SELECT, 0, NULL);
939
		}
940 941 942
	}

	/*
B
Bruce Momjian 已提交
943 944 945
	 * 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.)
946 947 948 949
	 */
	parse->rtable = list_concat(parse->rtable, subquery->rtable);

	/*
B
Bruce Momjian 已提交
950 951
	 * Pull up any FOR UPDATE/SHARE markers, too.  (OffsetVarNodes already
	 * adjusted the marker rtindexes, so just concat the lists.)
952 953 954
	 */
	parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);

955 956 957 958 959 960 961 962 963 964 965 966 967 968
    /*
     * CDB: Fix current query level's FROM clause relid set if the subquery
     * was in the FROM clause of current query (not a flattened sublink).
     */
    if (bms_is_member(varno, root->currlevel_relids))
    {
        int     subrelid;

        root->currlevel_relids = bms_del_member(root->currlevel_relids, varno);
        bms_foreach(subrelid, subroot->currlevel_relids)
            root->currlevel_relids = bms_add_member(root->currlevel_relids,
                                                    subrelid + rtoffset);
    }

969
	/*
970
	 * We also have to fix the relid sets of any append_rel nodes, 
971
	 * PlaceHolderVar nodes in the parent query. (This could perhaps be done
972
	 * by pullup_replace_vars(), but it seems cleaner to use two passes.)
973
	 * Note in particular that any placeholder nodes just created by
974
	 * pullup_replace_vars() will be adjusted.
975
	 *
B
Bruce Momjian 已提交
976 977 978 979
	 * Likewise, relids appearing in AppendRelInfo nodes have to be fixed (but
	 * we took care of their translated_vars lists above).	We already checked
	 * that this won't require introducing multiple subrelids into the
	 * single-slot AppendRelInfo structs.
980
	 */
981 982
	if (parse->hasSubLinks || root->glob->lastPHId != 0 ||
		root->append_rel_list)
983 984 985
	{
		Relids		subrelids;

986
		subrelids = get_relids_in_jointree((Node *) subquery->jointree, false);
987
		substitute_multiple_relids((Node *) parse, varno, subrelids);
988 989 990 991
		fix_append_rel_relids(root->append_rel_list, varno, subrelids);
	}

	/*
992
	 * And now add subquery's AppendRelInfos to our list.
993 994 995 996 997
	 */
	root->append_rel_list = list_concat(root->append_rel_list,
										subroot->append_rel_list);

	/*
B
Bruce Momjian 已提交
998
	 * We don't have to do the equivalent bookkeeping for outer-join info,
999
	 * because that hasn't been set up yet. placeholder_list likewise.
1000
	 */
1001 1002
	Assert(root->join_info_list == NIL);
	Assert(subroot->join_info_list == NIL);
1003 1004
	Assert(root->placeholder_list == NIL);
	Assert(subroot->placeholder_list == NIL);
1005 1006 1007

	/*
	 * Miscellaneous housekeeping.
1008 1009 1010 1011 1012 1013 1014
	 *
	 *
	 * Although replace_rte_variables() faithfully updated parse->hasSubLinks
	 * if it copied any SubLinks out of the subquery's targetlist, we still
	 * could have SubLinks added to the query in the expressions of FUNCTION
	 * and VALUES RTEs copied up from the subquery.  So it's necessary to copy
	 * subquery->hasSubLinks anyway.  Perhaps this can be improved someday.
1015 1016 1017 1018
	 */
	parse->hasSubLinks |= subquery->hasSubLinks;
	/* subquery won't be pulled up if it hasAggs, so no work there */

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

    /*
     * CDB: Wipe old RTE so subquery parse tree won't be sent to QEs.
     */
    Assert(rte->rtekind == RTE_SUBQUERY);
    rte->rtekind = RTE_VOID;
    rte->subquery = NULL;
    rte->alias = NULL;
    rte->eref = NULL;

1029
	/*
B
Bruce Momjian 已提交
1030 1031
	 * Return the adjusted subquery jointree to replace the RangeTblRef entry
	 * in parent's jointree.
1032 1033 1034 1035 1036
	 */
	return (Node *) subquery->jointree;
}


1037 1038 1039 1040 1041
/*
 * is_simple_subquery
 *	  Check a subquery in the range table to see if it's simple enough
 *	  to pull up into the parent query.
 */
1042
bool
1043
is_simple_subquery(PlannerInfo *root, Query *subquery)
1044 1045 1046 1047 1048 1049
{
	/*
	 * Let's just make sure it's a valid subselect ...
	 */
	if (!IsA(subquery, Query) ||
		subquery->commandType != CMD_SELECT ||
1050
		subquery->utilityStmt != NULL ||
1051
		subquery->intoClause != NULL)
1052
		elog(ERROR, "subquery is bogus");
1053 1054

	/*
1055 1056
	 * Can't currently pull up a query with setops (unless it's simple UNION
	 * ALL, which is handled by a different code path). Maybe after querytree
1057 1058 1059 1060 1061 1062
	 * redesign...
	 */
	if (subquery->setOperations)
		return false;

	/*
1063 1064
	 * Can't pull up a subquery involving grouping, aggregation, sorting,
	 * limiting, or WITH.  (XXX WITH could possibly be allowed later)
1065 1066
	 */
	if (subquery->hasAggs ||
1067
	    subquery->hasWindowFuncs ||
1068 1069
		subquery->groupClause ||
		subquery->havingQual ||
1070
		subquery->windowClause ||
1071 1072 1073
		subquery->sortClause ||
		subquery->distinctClause ||
		subquery->limitOffset ||
1074 1075 1076
		subquery->limitCount ||
		subquery->cteList ||
		root->parse->cteList)
1077 1078 1079
		return false;

	/*
B
Bruce Momjian 已提交
1080 1081 1082 1083
	 * 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.
1084 1085
	 */
	if (expression_returns_set((Node *) subquery->targetList))
1086 1087 1088 1089
		return false;

	/*
	 * Don't pull up a subquery that has any volatile functions in its
B
Bruce Momjian 已提交
1090 1091
	 * targetlist.	Otherwise we might introduce multiple evaluations of these
	 * functions, if they get copied to multiple places in the upper query,
1092 1093 1094
	 * leading to surprising results.  (Note: the PlaceHolderVar mechanism
	 * doesn't quite guarantee single evaluation; else we could pull up anyway
	 * and just wrap such items in PlaceHolderVars ...)
1095 1096
	 */
	if (contain_volatile_functions((Node *) subquery->targetList))
1097 1098 1099 1100
		return false;

	/*
	 * Hack: don't try to pull up a subquery with an empty jointree.
B
Bruce Momjian 已提交
1101 1102
	 * 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
1103 1104 1105 1106 1107 1108
	 * empty FromExpr appears lower down in a jointree.  It would pose a
	 * problem for the PlaceHolderVar mechanism too, since we'd have no
	 * way to identify where to evaluate a PHV coming out of the subquery.
	 * Not worth working hard on this, just to collapse SubqueryScan/Result
	 * into Result; especially since the SubqueryScan can often be optimized
	 * away by setrefs.c anyway.
1109 1110 1111 1112 1113 1114 1115
	 */
	if (subquery->jointree->fromlist == NIL)
		return false;

	return true;
}

1116 1117 1118 1119 1120 1121 1122 1123
/*
 * is_simple_union_all
 *	  Check a subquery to see if it's a simple UNION ALL.
 *
 * We require all the setops to be UNION ALL (no mixing) and there can't be
 * any datatype coercions involved, ie, all the leaf queries must emit the
 * same datatypes.
 */
1124
static bool pg_attribute_unused()
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
is_simple_union_all(Query *subquery)
{
	SetOperationStmt *topop;

	/* Let's just make sure it's a valid subselect ... */
	if (!IsA(subquery, Query) ||
		subquery->commandType != CMD_SELECT ||
		subquery->utilityStmt != NULL ||
		subquery->intoClause != NULL)
		elog(ERROR, "subquery is bogus");

	/* Is it a set-operation query at all? */
	topop = (SetOperationStmt *) subquery->setOperations;
	if (!topop)
		return false;
	Assert(IsA(topop, SetOperationStmt));

	/* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
	if (subquery->sortClause ||
		subquery->limitOffset ||
		subquery->limitCount ||
		subquery->rowMarks ||
		subquery->cteList)
		return false;
1149

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	/* Recursively check the tree of set operations */
	return is_simple_union_all_recurse((Node *) topop, subquery,
									   topop->colTypes);
}

static bool
is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
{
	if (IsA(setOp, RangeTblRef))
	{
		RangeTblRef *rtr = (RangeTblRef *) setOp;
		RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
		Query	   *subquery = rte->subquery;

		Assert(subquery != NULL);

		/* Leaf nodes are OK if they match the toplevel column types */
		/* We don't have to compare typmods here */
		return tlist_same_datatypes(subquery->targetList, colTypes, true);
	}
	else if (IsA(setOp, SetOperationStmt))
	{
		SetOperationStmt *op = (SetOperationStmt *) setOp;

		/* Must be UNION ALL */
		if (op->op != SETOP_UNION || !op->all)
			return false;

		/* Recurse to check inputs */
		return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
			is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
	}
	else
	{
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(setOp));
		return false;			/* keep compiler quiet */
	}
}
1189

1190

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
/*
 * is_safe_append_member
 *	  Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
 *	  safe to pull up.
 */
static bool
is_safe_append_member(Query *subquery)
{
	FromExpr   *jtnode;

	/*
B
Bruce Momjian 已提交
1202 1203 1204
	 * It's only safe to pull up the child if its jointree contains exactly
	 * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
	 * could be buried in several levels of FromExpr, however.
1205
	 *
B
Bruce Momjian 已提交
1206 1207 1208 1209 1210
	 * Also, the child can't have any WHERE quals because there's no place to
	 * put them in an appendrel.  (This is a bit annoying...) If we didn't
	 * need to check this, we'd just test whether get_relids_in_jointree()
	 * yields a singleton set, to be more consistent with the coding of
	 * fix_append_rel_relids().
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
	 */
	jtnode = subquery->jointree;
	while (IsA(jtnode, FromExpr))
	{
		if (jtnode->quals != NULL)
			return false;
		if (list_length(jtnode->fromlist) != 1)
			return false;
		jtnode = linitial(jtnode->fromlist);
	}
	if (!IsA(jtnode, RangeTblRef))
		return false;

	return true;
}

1227
/*
1228
 * Helper routine for pull_up_subqueries: do pullup_replace_vars on every expression
1229 1230
 * in the jointree, without changing the jointree structure itself.  Ugly,
 * but there's no other way...
1231 1232 1233 1234
 *
 * If we are above lowest_outer_join then use subtlist_with_phvs; at or
 * below it, use subtlist.  (When no outer joins are in the picture,
 * these will be the same list.)
1235 1236
 */
static void
1237
replace_vars_in_jointree(Node *jtnode, pullup_replace_vars_context *context,
1238
					   JoinExpr *lowest_outer_join)
1239
{
1240 1241
	ListCell   *l;

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	if (jtnode == NULL)
		return;
	if (IsA(jtnode, RangeTblRef))
	{
		/* nothing to do here */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;

		foreach(l, f->fromlist)
1253 1254
			replace_vars_in_jointree(lfirst(l), context, lowest_outer_join);
		f->quals = pullup_replace_vars(f->quals, context);
1255 1256 1257 1258
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
1259
		bool	save_need_phvs = context->need_phvs;
1260

1261 1262 1263
		if (j == lowest_outer_join)
		{
			/* no more PHVs in or below this join */
1264
			context->need_phvs = false;
1265 1266
			lowest_outer_join = NULL;
		}
1267 1268 1269
		replace_vars_in_jointree(j->larg, context, lowest_outer_join);
		replace_vars_in_jointree(j->rarg, context, lowest_outer_join);

1270
		foreach(l, j->subqfromlist)
1271 1272 1273
			replace_vars_in_jointree(lfirst(l), context, lowest_outer_join);

		j->quals = pullup_replace_vars(j->quals, context);
1274 1275

		/*
B
Bruce Momjian 已提交
1276 1277
		 * We don't bother to update the colvars list, since it won't be used
		 * again ...
1278
		 */
1279
		context->need_phvs = save_need_phvs;
1280 1281
	}
	else
1282 1283
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1284 1285
}

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 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
/*
 * Apply pullup variable replacement throughout an expression tree
 *
 * Returns a modified copy of the tree, so this can't be used where we
 * need to do in-place replacement.
 */
static Node *
pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
{
	return replace_rte_variables(expr,
								 context->varno, 0,
								 pullup_replace_vars_callback,
								 (void *) context,
								 context->outer_hasSubLinks);
}


static Node *
pullup_replace_vars_callback(Var *var,
							 replace_rte_variables_context *context)
{
	pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
	int			varattno = var->varattno;
	Node	   *newnode;

	/*
	 * If PlaceHolderVars are needed, we cache the modified expressions in
	 * rcon->rv_cache[].  This is not in hopes of any material speed gain
	 * within this function, but to avoid generating identical PHVs with
	 * different IDs.  That would result in duplicate evaluations at runtime,
	 * and possibly prevent optimizations that rely on recognizing different
	 * references to the same subquery output as being equal().  So it's worth
	 * a bit of extra effort to avoid it.
	 */
	if (rcon->need_phvs &&
		varattno >= InvalidAttrNumber &&
		varattno <= list_length(rcon->targetlist) &&
		rcon->rv_cache[varattno] != NULL)
	{
		/* Just copy the entry and fall through to adjust its varlevelsup */
		newnode = copyObject(rcon->rv_cache[varattno]);
	}
	else if (varattno == InvalidAttrNumber)
	{
		/* Must expand whole-tuple reference into RowExpr */
		RowExpr    *rowexpr;
		List	   *colnames;
		List	   *fields;
		bool		save_need_phvs = rcon->need_phvs;

		/*
		 * If generating an expansion for a var of a named rowtype (ie, this
		 * is a plain relation RTE), then we must include dummy items for
		 * dropped columns.  If the var is RECORD (ie, this is a JOIN), then
		 * omit dropped columns. Either way, attach column names to the
		 * RowExpr for use of ruleutils.c.
		 *
		 * In order to be able to cache the results, we always generate the
		 * expansion with varlevelsup = 0, and then adjust if needed.
		 */
		expandRTE(rcon->target_rte,
				  var->varno, 0 /* not varlevelsup */, var->location,
				  (var->vartype != RECORDOID),
				  &colnames, &fields);
		/* Adjust the generated per-field Vars, but don't insert PHVs */
		rcon->need_phvs = false;
		fields = (List *) replace_rte_variables_mutator((Node *) fields,
														context);
		rcon->need_phvs = save_need_phvs;
		rowexpr = makeNode(RowExpr);
		rowexpr->args = fields;
		rowexpr->row_typeid = var->vartype;
		rowexpr->row_format = COERCE_IMPLICIT_CAST;
		rowexpr->colnames = colnames;
		rowexpr->location = var->location;
		newnode = (Node *) rowexpr;

		/*
		 * Insert PlaceHolderVar if needed.  Notice that we are wrapping
		 * one PlaceHolderVar around the whole RowExpr, rather than putting
		 * one around each element of the row.  This is because we need
		 * the expression to yield NULL, not ROW(NULL,NULL,...) when it
		 * is forced to null by an outer join.
		 */
		if (rcon->need_phvs)
		{
			/* RowExpr is certainly not strict, so always need PHV */
			newnode = (Node *)
			make_placeholder_expr(rcon->root,
								  (Expr *) newnode,
								  bms_make_singleton(rcon->varno));
			/* cache it with the PHV, and with varlevelsup still zero */
			rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
		}
	}
	else
	{
		/* Normal case referencing one targetlist element */
		TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
		
		if (tle == NULL)		/* shouldn't happen */
			elog(ERROR, "could not find attribute %d in subquery targetlist",
				 varattno);
		
		/* Make a copy of the tlist item to return */
		newnode = copyObject(tle->expr);
		
		/* Insert PlaceHolderVar if needed */
		if (rcon->need_phvs)
		{
			bool	wrap;
			
			if (newnode && IsA(newnode, Var) &&
				((Var *) newnode)->varlevelsup == 0)
			{
				/* Simple Vars always escape being wrapped */
				wrap = false;
			}
			else if (rcon->wrap_non_vars)
			{
				/* Wrap all non-Vars in a PlaceHolderVar */
				wrap = true;
			}
			else
			{
				/*
				 * If it contains a Var of current level, and does not contain
				 * any non-strict constructs, then it's certainly nullable and
				 * we don't need to insert a PlaceHolderVar.  (Note: in future
				 * maybe we should insert PlaceHolderVars anyway, when a tlist
				 * item is expensive to evaluate?
				 */
				if (contain_vars_of_level((Node *) newnode, 0) &&
					!contain_nonstrict_functions((Node *) newnode))
				{
					/* No wrap needed */
					wrap = false;
				}
				else
				{
					/* Else wrap it in a PlaceHolderVar */
					wrap = true;
				}
			}

			if (wrap)
				newnode = (Node *)
				make_placeholder_expr(rcon->root,
									  (Expr *) newnode,
									  bms_make_singleton(rcon->varno));

			/*
			 * Cache it if possible (ie, if the attno is in range, which it
			 * probably always should be).  We can cache the value even if
			 * we decided we didn't need a PHV, since this result will be
			 * suitable for any request that has need_phvs.
			 */
			if (varattno > InvalidAttrNumber &&
				varattno <= list_length(rcon->targetlist))
				rcon->rv_cache[varattno] = copyObject(newnode);
		}
	}

	/* Must adjust varlevelsup if tlist item is from higher query */
	if (var->varlevelsup > 0)
		IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);

	return newnode;
}


1457
/*
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
 * 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.)
 *
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
 * Another transformation we apply here is to recognize cases like
 *		SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
 * If the join clause is strict for b.y, then only null-extended rows could
 * pass the upper WHERE, and we can conclude that what the query is really
 * specifying is an anti-semijoin.  We change the join type from JOIN_LEFT
 * to JOIN_ANTI.  The IS NULL clause then becomes redundant, and must be
 * removed to prevent bogus selectivity calculations, but we leave it to
 * distribute_qual_to_rels to get rid of such clauses.
 *
 * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
 * JOIN_LEFT.  This saves some code here and in some later planner routines,
 * but the main reason to do it is to not need to invent a JOIN_REVERSE_ANTI
 * join type.
 *
1490 1491 1492 1493 1494
 * 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
1495
reduce_outer_joins(PlannerInfo *root)
1496 1497 1498 1499
{
	reduce_outer_joins_state *state;

	/*
B
Bruce Momjian 已提交
1500 1501 1502 1503 1504 1505 1506
	 * 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 base rels appear below
	 * each side of each join clause, and about 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.
1507
	 */
1508
	state = reduce_outer_joins_pass1((Node *) root->parse->jointree);
1509 1510 1511

	/* planner.c shouldn't have called me if no outer joins */
	if (state == NULL || !state->contains_outer)
1512
		elog(ERROR, "so where are the outer joins?");
1513

1514
	reduce_outer_joins_pass2((Node *) root->parse->jointree,
1515
							 state, root, NULL, NIL, NIL);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
}

/*
 * 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;
1527
	ListCell   *l;
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

	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;

		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);
1578 1579 1580 1581 1582 1583 1584 1585 1586

		foreach(l, j->subqfromlist)
		{
			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);
		}
1587 1588
	}
	else
1589 1590
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1591 1592 1593 1594 1595 1596 1597 1598
	return result;
}

/*
 * reduce_outer_joins_pass2 - phase 2 processing
 *
 *	jtnode: current jointree node
 *	state: state data collected by phase 1 for this node
1599
 *	root: toplevel planner state
1600
 *	nonnullable_rels: set of base relids forced non-null by upper quals
1601 1602
 *	nonnullable_vars: list of Vars forced non-null by upper quals
 *	forced_null_vars: list of Vars forced null by upper quals
1603 1604 1605
 */
static void
reduce_outer_joins_pass2(Node *jtnode,
1606
						 reduce_outer_joins_state *state,
1607
						 PlannerInfo *root,
1608 1609 1610
						 Relids nonnullable_rels,
						 List *nonnullable_vars,
						 List *forced_null_vars)
1611
{
1612 1613 1614
	ListCell   *l;
	ListCell   *s;

1615 1616 1617 1618 1619
	/*
	 * 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)
1620
		elog(ERROR, "reached empty jointree");
1621
	if (IsA(jtnode, RangeTblRef))
1622
		elog(ERROR, "reached base rel");
1623 1624 1625
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
1626 1627 1628 1629 1630 1631 1632 1633 1634
		ListCell   *l;
		ListCell   *s;
		Relids		pass_nonnullable_rels;
		List       *pass_nonnullable_vars;
		List       *pass_forced_null_vars;

		/* Scan quals to see if we can add any constraints */
		pass_nonnullable_rels = find_nonnullable_rels(f->quals);
		pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
1635
										   nonnullable_rels);
1636 1637 1638 1639 1640 1641 1642
		/* NB: we rely on list_concat to not damage its second argument */
		pass_nonnullable_vars = find_nonnullable_vars(f->quals);
		pass_nonnullable_vars = list_concat(pass_nonnullable_vars,
											nonnullable_vars);
		pass_forced_null_vars = find_forced_null_vars(f->quals);
		pass_forced_null_vars = list_concat(pass_forced_null_vars,
											forced_null_vars);
1643
		/* And recurse --- but only into interesting subtrees */
1644
		Assert(list_length(f->fromlist) == list_length(state->sub_states));
1645
		forboth(l, f->fromlist, s, state->sub_states)
1646 1647 1648 1649
		{
			reduce_outer_joins_state *sub_state = lfirst(s);

			if (sub_state->contains_outer)
1650
				reduce_outer_joins_pass2(lfirst(l), sub_state, root,
1651 1652 1653
										 pass_nonnullable_rels,
										 pass_nonnullable_vars,
										 pass_forced_null_vars);
1654
		}
1655 1656
		bms_free(pass_nonnullable_rels);
		/* can't so easily clean up var lists, unfortunately */
1657 1658 1659 1660 1661 1662
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
		int			rtindex = j->rtindex;
		JoinType	jointype = j->jointype;
1663
		reduce_outer_joins_state *left_state = linitial(state->sub_states);
1664
		reduce_outer_joins_state *right_state = lsecond(state->sub_states);
1665
		reduce_outer_joins_state *sub_state;
1666 1667 1668
		List       *local_nonnullable_vars = NIL;
		bool        computed_local_nonnullable_vars = false;

1669 1670 1671 1672

		/* Can we simplify this join? */
		switch (jointype)
		{
1673 1674
			case JOIN_INNER:
				break;
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
			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;
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
			case JOIN_LASJ_NOTIN:
			case JOIN_SEMI:
			case JOIN_ANTI:

				/*
				 * These could only have been introduced by pull_up_sublinks,
				 * so there's no way that upper quals could refer to their
				 * righthand sides, and no point in checking.
				 */
				break;
1707
			default:
1708 1709
				elog(ERROR, "unrecognized join type: %d",
					 (int) jointype);
1710 1711
				break;
		}
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763

		/*
		 * Convert JOIN_RIGHT to JOIN_LEFT.  Note that in the case where we
		 * reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
		 * longer matches the internal ordering of any CoalesceExpr's built to
		 * represent merged join variables.  We don't care about that at
		 * present, but be wary of it ...
		 */
		if (jointype == JOIN_RIGHT)
		{
			Node	   *tmparg;

			tmparg = j->larg;
			j->larg = j->rarg;
			j->rarg = tmparg;
			jointype = JOIN_LEFT;
			right_state = linitial(state->sub_states);
			left_state = lsecond(state->sub_states);
		}

		/*
		 * See if we can reduce JOIN_LEFT to JOIN_ANTI.  This is the case
		 * if the join's own quals are strict for any var that was forced
		 * null by higher qual levels.  NOTE: there are other ways that we
		 * could detect an anti-join, in particular if we were to check
		 * whether Vars coming from the RHS must be non-null because of
		 * table constraints.  That seems complicated and expensive though
		 * (in particular, one would have to be wary of lower outer joins).
		 * For the moment this seems sufficient.
		 */
		if (jointype == JOIN_LEFT)
		{
			List	   *overlap;

			local_nonnullable_vars = find_nonnullable_vars(j->quals);
			computed_local_nonnullable_vars = true;

			/*
			 * It's not sufficient to check whether local_nonnullable_vars
			 * and forced_null_vars overlap: we need to know if the overlap
			 * includes any RHS variables.
			 */
			overlap = list_intersection(local_nonnullable_vars,
										forced_null_vars);
			if (overlap != NIL &&
				bms_overlap(pull_varnos((Node *) overlap),
							right_state->relids))
				jointype = JOIN_ANTI;
		}

		/* Apply the jointype change, if any, to both jointree node and RTE */
		if (rtindex && jointype != j->jointype)
1764
		{
1765
			RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
1766 1767 1768

			Assert(rte->rtekind == RTE_JOIN);
			Assert(rte->jointype == j->jointype);
1769
			rte->jointype = jointype;
1770
		}
1771
		j->jointype = jointype;
1772

1773
		if (left_state->contains_outer || right_state->contains_outer)
1774
		{
1775 1776 1777 1778 1779
			Relids          local_nonnullable_rels;
			List       *local_forced_null_vars;
			Relids          pass_nonnullable_rels;
			List       *pass_nonnullable_vars;
			List       *pass_forced_null_vars;
1780 1781

			/*
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
			 * If this join is (now) inner, we can add any constraints its
			 * quals provide to those we got from above.  But if it is outer,
			 * we can pass down the local constraints only into the nullable
			 * side, because an outer join never eliminates any rows from its
			 * non-nullable side.  Also, there is no point in passing upper
			 * constraints into the nullable side, since if there were any
			 * we'd have been able to reduce the join.  (In the case of
			 * upper forced-null constraints, we *must not* pass them into
			 * the nullable side --- they either applied here, or not.)
			 * The upshot is that we pass either the local or the upper
			 * constraints, never both, to the children of an outer join.
			 *
			 * At a FULL join we just punt and pass nothing down --- is it
			 * possible to be smarter?
1796
			 */
1797 1798
			if (jointype != JOIN_FULL)
			{
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
				local_nonnullable_rels = find_nonnullable_rels(j->quals);
				if (!computed_local_nonnullable_vars)
					local_nonnullable_vars = find_nonnullable_vars(j->quals);
				local_forced_null_vars = find_forced_null_vars(j->quals);
				if (jointype == JOIN_INNER)
				{
					/* OK to merge upper and local constraints */
					local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
															 nonnullable_rels);
					local_nonnullable_vars = list_concat(local_nonnullable_vars,
														 nonnullable_vars);
					local_forced_null_vars = list_concat(local_forced_null_vars,
														 forced_null_vars);
				}
1813 1814
			}
			else
1815 1816 1817 1818 1819
			{
				/* no use in calculating these */
				local_nonnullable_rels = NULL;
				local_forced_null_vars = NIL;
			}
1820

1821
			if (left_state->contains_outer)
1822
			{
1823 1824 1825 1826 1827 1828 1829
				if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
				{
					/* pass union of local and upper constraints */
					pass_nonnullable_rels = local_nonnullable_rels;
					pass_nonnullable_vars = local_nonnullable_vars;
					pass_forced_null_vars = local_forced_null_vars;
				}
1830
				else if (jointype != JOIN_FULL)		/* ie, LEFT/SEMI/ANTI */
1831 1832 1833 1834 1835 1836
				{
					/* can't pass local constraints to non-nullable side */
					pass_nonnullable_rels = nonnullable_rels;
					pass_nonnullable_vars = nonnullable_vars;
					pass_forced_null_vars = forced_null_vars;
				}
1837
				else
1838 1839 1840 1841 1842 1843
				{
					/* no constraints pass through JOIN_FULL */
					pass_nonnullable_rels = NULL;
					pass_nonnullable_vars = NIL;
					pass_forced_null_vars = NIL;
				}
1844
				reduce_outer_joins_pass2(j->larg, left_state, root,
1845 1846 1847
										 pass_nonnullable_rels,
										 pass_nonnullable_vars,
										 pass_forced_null_vars);
1848
			}
1849
			if (right_state->contains_outer)
1850
			{
1851
				if (jointype != JOIN_FULL)		/* ie, INNER/LEFT/SEMI/ANTI */
1852 1853 1854 1855 1856 1857
				{
					/* pass appropriate constraints, per comment above */
					pass_nonnullable_rels = local_nonnullable_rels;
					pass_nonnullable_vars = local_nonnullable_vars;
					pass_forced_null_vars = local_forced_null_vars;
				}
1858
				else
1859 1860 1861 1862 1863 1864
				{
					/* no constraints pass through JOIN_FULL */
					pass_nonnullable_rels = NULL;
					pass_nonnullable_vars = NIL;
					pass_forced_null_vars = NIL;
				}
1865
				reduce_outer_joins_pass2(j->rarg, right_state, root,
1866 1867 1868
										 pass_nonnullable_rels,
										 pass_nonnullable_vars,
										 pass_forced_null_vars);
1869
			}
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

            /*
             * CDB: Simplify outer joins pulled up from flattened subqueries.
             * For a left or right outer join, the subqfromlist items belong
             * to the null-augmented side; so we pass local_nonnullable down
             * regardless of the jointype.  (For FULL JOIN, subqfromlist is
             * always empty.)
             */
            s = lnext(lnext(list_head(state->sub_states)));
            foreach(l, j->subqfromlist)
            {
                sub_state = (reduce_outer_joins_state *)lfirst(s);
                if (sub_state->contains_outer)
				    reduce_outer_joins_pass2(lfirst(l), sub_state, root,
1884 1885 1886
											 pass_nonnullable_rels,
											 pass_nonnullable_vars,
											 pass_forced_null_vars);
1887 1888 1889
                s = lnext(s);
            }

1890
			bms_free(local_nonnullable_rels);
1891 1892 1893
		}
	}
	else
1894 1895
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1896 1897
}

1898 1899 1900 1901
/*
 * substitute_multiple_relids - adjust node relid sets after pulling up
 * a subquery
 *
1902 1903 1904 1905
 * Find any PlaceHolderVar nodes in the given tree that
 * reference the pulled-up relid, and change them to reference the replacement
 * relid(s).  We do not need to recurse into subqueries, since no subquery of
 * the current top query could (yet) contain such a reference.
1906 1907
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
1908
 * nodes in-place.  This should be OK since the tree was copied by pullup_replace_vars
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
 * earlier.  Avoid scribbling on the original values of the bitmapsets, though,
 * because expression_tree_mutator doesn't copy those.
 */

typedef struct
{
	int			varno;
	Relids		subrelids;
} substitute_multiple_relids_context;

static bool
substitute_multiple_relids_walker(Node *node,
								  substitute_multiple_relids_context *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, PlaceHolderVar))
	{
		PlaceHolderVar *phv = (PlaceHolderVar *) node;
		
		if (bms_is_member(context->varno, phv->phrels))
		{
			phv->phrels = bms_union(phv->phrels,
									context->subrelids);
			phv->phrels = bms_del_member(phv->phrels,
										 context->varno);
		}
		/* fall through to examine children */
	}
1938 1939 1940 1941 1942
	/* Shouldn't need to handle planner auxiliary nodes here */
	Assert(!IsA(node, SpecialJoinInfo));
	Assert(!IsA(node, AppendRelInfo));
	Assert(!IsA(node, PlaceHolderInfo));

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
	return expression_tree_walker(node, substitute_multiple_relids_walker,
								  (void *) context);
}

static void
substitute_multiple_relids(Node *node, int varno, Relids subrelids)
{
	substitute_multiple_relids_context context;
	
	context.varno = varno;
	context.subrelids = subrelids;
	
	/*
	 * Must be prepared to start with a Query or a bare expression tree.
	 */
	query_or_expression_tree_walker(node,
									substitute_multiple_relids_walker,
									(void *) &context,
									0);
}


1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
/*
 * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
 *
 * When we pull up a subquery, any AppendRelInfo references to the subquery's
 * RT index have to be replaced by the substituted relid (and there had better
 * be only one).
 *
 * We assume we may modify the AppendRelInfo nodes in-place.
 */
static void
1975
fix_append_rel_relids(List *append_rel_list, int varno, Relids subrelids)
1976 1977 1978 1979 1980 1981
{
	ListCell   *l;
	int			subvarno = -1;

	/*
	 * We only want to extract the member relid once, but we mustn't fail
B
Bruce Momjian 已提交
1982 1983 1984
	 * immediately if there are multiple members; it could be that none of the
	 * AppendRelInfo nodes refer to it.  So compute it on first use. Note that
	 * bms_singleton_member will complain if set is not singleton.
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
	 */
	foreach(l, append_rel_list)
	{
		AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);

		/* The parent_relid shouldn't ever be a pullup target */
		Assert(appinfo->parent_relid != varno);

		if (appinfo->child_relid == varno)
		{
			if (subvarno < 0)
				subvarno = bms_singleton_member(subrelids);
			appinfo->child_relid = subvarno;
		}
	}
}

2002
/*
2003 2004 2005 2006
 * get_relids_in_jointree: get set of RT indexes present in a jointree
 *
 * If include_joins is true, join RT indexes are included; if false,
 * only base rels are included.
2007
 */
2008
Relids
2009
get_relids_in_jointree(Node *jtnode, bool include_joins)
2010
{
2011
	Relids		result = NULL;
2012
	ListCell   *l;
2013 2014 2015 2016 2017 2018 2019

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

2020
		result = bms_make_singleton(varno);
2021 2022 2023 2024 2025 2026 2027
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;

		foreach(l, f->fromlist)
		{
2028
			result = bms_join(result,
2029 2030
							  get_relids_in_jointree(lfirst(l),
													 include_joins));
2031 2032 2033 2034 2035 2036
		}
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

2037 2038 2039
		result = get_relids_in_jointree(j->larg, include_joins);
		result = bms_join(result, get_relids_in_jointree(j->rarg, include_joins));

2040
		if (include_joins && j->rtindex)
2041
			result = bms_add_member(result, j->rtindex);
2042

2043
		/* GPDB_84_MERGE_FIXME: Not present upstream; is this really needed? */
2044
		foreach(l, j->subqfromlist)
2045
			result = bms_join(result, get_relids_in_jointree((Node *)lfirst(l), include_joins));
2046 2047
	}
	else
2048 2049
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
2050 2051 2052 2053
	return result;
}

/*
2054
 * get_relids_for_join: get set of base RT indexes making up a join
2055
 */
2056
Relids
2057
get_relids_for_join(PlannerInfo *root, int joinrelid)
2058 2059 2060
{
	Node	   *jtnode;

2061 2062
	jtnode = find_jointree_node_for_rel((Node *) root->parse->jointree,
										joinrelid);
2063
	if (!jtnode)
2064
		elog(ERROR, "could not find join node %d", joinrelid);
2065
	return get_relids_in_jointree(jtnode, false);
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
}

/*
 * 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)
{
2076 2077
	ListCell   *l;

2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
	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;

		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;
2110 2111 2112 2113 2114 2115 2116

		foreach(l, j->subqfromlist)
		{
			jtnode = find_jointree_node_for_rel(lfirst(l), relid);
			if (jtnode)
				return jtnode;
		}
2117 2118
	}
	else
2119 2120
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
2121 2122
	return NULL;
}
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141

/*
 * init_list_cteplaninfo
 *   Create a list of CtePlanInfos of size 'numCtes', and initialize each CtePlanInfo.
 */
List *
init_list_cteplaninfo(int numCtes)
{
	List *list_cteplaninfo = NULL;
	
	for (int cteNo = 0; cteNo < numCtes; cteNo++)
	{
		CtePlanInfo *ctePlanInfo = palloc0(sizeof(CtePlanInfo));
		list_cteplaninfo = lappend(list_cteplaninfo, ctePlanInfo);
	}

	return list_cteplaninfo;
	
}