prepjointree.c 45.5 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * prepjointree.c
 *	  Planner preprocessing for subqueries and join tree manipulation.
 *
6 7
 * NOTE: the intended sequence for invoking these operations is
 *		pull_up_IN_clauses
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.50 2008/03/18 22:04:14 tgl Exp $
27 28 29 30 31
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

32
#include "nodes/makefuncs.h"
33 34
#include "optimizer/clauses.h"
#include "optimizer/prep.h"
35
#include "optimizer/subselect.h"
36
#include "optimizer/tlist.h"
37
#include "optimizer/var.h"
38
#include "parser/parse_expr.h"
39 40 41
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"

42
#include "cdb/cdbsubselect.h"           /* cdbsubselect_flatten_sublinks() */
43
#include "optimizer/transform.h"
44

45

46 47 48
typedef struct reduce_outer_joins_state
{
	Relids		relids;			/* base relids within this subtree */
B
Bruce Momjian 已提交
49
	bool		contains_outer; /* does subtree contain outer join(s)? */
50
	List	   *sub_states;		/* List of states for subtree components */
51
} reduce_outer_joins_state;
52

53 54 55
static void pull_up_fromlist_subqueries(PlannerInfo    *root,
                                        List          **inout_fromlist,
				                        bool            below_outer_join);
56
static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
B
Bruce Momjian 已提交
57 58 59
						RangeTblEntry *rte,
						bool below_outer_join,
						bool append_rel_member);
60
bool is_simple_subquery(PlannerInfo *root, Query *subquery);
61
static bool has_nullable_targetlist(Query *subquery);
62
static bool is_safe_append_member(Query *subquery);
63
static void resolvenew_in_jointree(Node *jtnode, int varno,
64
					   RangeTblEntry *rte, List *subtlist);
65 66
static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
static void reduce_outer_joins_pass2(Node *jtnode,
67
						 reduce_outer_joins_state *state,
68
						 PlannerInfo *root,
B
Bruce Momjian 已提交
69
						 Relids nonnullable_rels);
70
static void fix_in_clause_relids(List *in_info_list, int varno,
B
Bruce Momjian 已提交
71
					 Relids subrelids);
72
static void fix_append_rel_relids(List *append_rel_list, int varno,
B
Bruce Momjian 已提交
73
					  Relids subrelids);
74
static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
75
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes);
76

77
extern void UpdateScatterClause(Query *query, List *newtlist);
78

79

80 81
/*
 * pull_up_IN_clauses
82 83 84 85 86 87 88 89 90 91
 *		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.
92
 *
93 94 95 96 97 98
 * 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.
99
 */
100 101 102 103 104 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
Node *
pull_up_IN_clauses(PlannerInfo * root, List **rtrlist_inout, Node *node)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, SubLink))
	{
		SubLink    *sublink = (SubLink *) node;
		Node	   *subst;

		/* Is it a convertible IN clause?  If not, return it as-is */
		subst = convert_sublink_to_join(root, rtrlist_inout, sublink);
		return subst;
	}
	if (and_clause(node))
	{
		List	   *newclauses = NIL;
		ListCell   *l;

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

			if (newclause)
				newclauses = lappend(newclauses, newclause);
		}
		return (Node *) make_ands_explicit(newclauses);
	}
	if (not_clause(node))
	{
		Node	   *arg = (Node *) get_notclausearg((Expr *) node);

		/*
		 *	 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)
		 */

		if (IsA(arg, SubLink))
		{
			SubLink    *sublink = (SubLink *) arg;

			if (sublink->subLinkType == ANY_SUBLINK)
			{
				sublink->subLinkType = ALL_SUBLINK;
				sublink->testexpr = (Node *) canonicalize_qual(
									 make_notclause((Expr *) sublink->testexpr));
			}
			else if (sublink->subLinkType == ALL_SUBLINK)
			{
				sublink->subLinkType = ANY_SUBLINK;
				sublink->testexpr = (Node *) canonicalize_qual(
									 make_notclause((Expr *) sublink->testexpr));
			}
			else if (sublink->subLinkType == EXISTS_SUBLINK)
			{
				sublink->subLinkType = NOT_EXISTS_SUBLINK;
			}
			else
			{
				return node;	/* do nothing for other sublinks */
			}

			return (Node *) pull_up_IN_clauses(root, rtrlist_inout, (Node *) sublink);
		}
		else if (not_clause(arg))
		{
			/* NOT NOT (expr) => (expr)  */
			return (Node *) pull_up_IN_clauses(root, rtrlist_inout,
									(Node *) get_notclausearg((Expr *) arg));
		}
		else if (or_clause(arg))
		{
			/* NOT OR (expr1) (expr2) => (expr1) AND (expr2) */
			return (Node *) pull_up_IN_clauses(root, rtrlist_inout,
									(Node *) canonicalize_qual((Expr *) node));
			
		}
	}

	/**
	 * (expr) op SUBLINK
	 */
	if (IsA(node, OpExpr))
	{
		OpExpr *opexp = (OpExpr *) node;

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

			if (IsA(rarg, SubLink))
			{
				return (Node *) convert_EXPR_to_join(root, rtrlist_inout, opexp);
			}
		}
	}
	/* Stop if not an AND */
	return node;
}
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
/*
 * 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)
			{
242 243 244 245 246 247 248

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

249 250 251 252 253 254 255 256 257 258 259
				/* Successful expansion, replace the rtable entry */
				rte->rtekind = RTE_SUBQUERY;
				rte->subquery = funcquery;
				rte->funcexpr = NULL;
				rte->funccoltypes = NIL;
				rte->funccoltypmods = NIL;
			}
		}
	}
}

260 261 262 263 264
/*
 * 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.
265 266
 *		Also, subqueries that are simple UNION ALL structures can be
 *		converted into "append relations".
267 268 269 270
 *
 * below_outer_join is true if this jointree node is within the nullable
 * side of an outer join.  This restricts what we can do.
 *
271
 * append_rel_member is true if we are looking at a member subquery of
B
Bruce Momjian 已提交
272
 * an append relation.	This puts some different restrictions on what
273 274
 * we can do.
 *
275 276 277 278 279 280 281 282 283 284
 * 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 *
285 286
pull_up_subqueries(PlannerInfo *root, Node *jtnode,
				   bool below_outer_join, bool append_rel_member)
287
{
288
	if (jtnode == NULL)
289 290 291 292
		return NULL;
	if (IsA(jtnode, RangeTblRef))
	{
		int			varno = ((RangeTblRef *) jtnode)->rtindex;
293
		RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
294 295

		/*
B
Bruce Momjian 已提交
296 297
		 * Is this a subquery RTE, and if so, is the subquery simple enough to
		 * pull up?  (If not, do nothing at this node.)
298 299 300 301
		 *
		 * 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
302 303
		 * results wouldn't become NULL when they're supposed to).
		 *
B
Bruce Momjian 已提交
304 305
		 * XXX This could be improved by generating pseudo-variables for such
		 * expressions; we'd have to figure out how to get the pseudo-
B
Bruce Momjian 已提交
306 307
		 * variables evaluated at the right place in the modified plan tree.
		 * Fix it someday.
308
		 *
B
Bruce Momjian 已提交
309 310
		 * If we are looking at an append-relation member, we can't pull it up
		 * unless is_safe_append_member says so.
311
		 */
312 313
		if (rte->rtekind == RTE_SUBQUERY &&
			!rte->forceDistRandom &&
314
			is_simple_subquery(root, rte->subquery) &&
315 316 317 318 319
			(!below_outer_join || has_nullable_targetlist(rte->subquery)) &&
			(!append_rel_member || is_safe_append_member(rte->subquery)))
			return pull_up_simple_subquery(root, jtnode, rte,
										   below_outer_join,
										   append_rel_member);
320

321
		/* PG:
322
		 * Alternatively, is it a simple UNION ALL subquery?  If so, flatten
B
Bruce Momjian 已提交
323 324 325 326
		 * into an "append relation".  We can do this regardless of
		 * nullability considerations since this transformation does not
		 * result in propagating non-Var expressions into upper levels of the
		 * query.
327 328
		 *
		 * It's also safe to do this regardless of whether this query is
B
Bruce Momjian 已提交
329 330 331
		 * 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.)
332 333 334 335 336
		 * 
		 * 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.
337
		 */
338 339 340 341 342
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;

343
		Assert(!append_rel_member);
344
        pull_up_fromlist_subqueries(root, &f->fromlist, below_outer_join);
345 346 347 348 349
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

350
		Assert(!append_rel_member);
351 352 353 354
		/* Recurse, being careful to tell myself when inside outer join */
		switch (j->jointype)
		{
			case JOIN_INNER:
355
				j->larg = pull_up_subqueries(root, j->larg,
356
											 below_outer_join, false);
357
				j->rarg = pull_up_subqueries(root, j->rarg,
358
											 below_outer_join, false);
359 360
				break;
			case JOIN_LEFT:
361 362
			case JOIN_LASJ:
			case JOIN_LASJ_NOTIN:
363
				j->larg = pull_up_subqueries(root, j->larg,
364
											 below_outer_join, false);
365
				j->rarg = pull_up_subqueries(root, j->rarg,
366
											 true, false);
367 368
				break;
			case JOIN_FULL:
369
				j->larg = pull_up_subqueries(root, j->larg,
370
											 true, false);
371
				j->rarg = pull_up_subqueries(root, j->rarg,
372
											 true, false);
373 374
				break;
			case JOIN_RIGHT:
375
				j->larg = pull_up_subqueries(root, j->larg,
376
											 true, false);
377
				j->rarg = pull_up_subqueries(root, j->rarg,
378
											 below_outer_join, false);
379 380
				break;
			default:
381 382
				elog(ERROR, "unrecognized join type: %d",
					 (int) j->jointype);
383 384
				break;
		}
385 386 387 388 389 390 391 392 393 394 395 396

        /*
         * 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).
         */
        if (j->subqfromlist)
            pull_up_fromlist_subqueries(root, &j->subqfromlist,
                                        below_outer_join || (j->jointype != JOIN_INNER));
397 398
	}
	else
399 400
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
401 402 403
	return jtnode;
}

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

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


427 428 429 430 431
/*
 * 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 已提交
432
 * subquery by pull_up_subqueries.	We return the replacement jointree node,
433 434 435 436 437 438 439 440 441 442 443 444 445 446
 * or jtnode itself if we determine that the subquery can't be pulled up after
 * all.
 */
static Node *
pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
						bool below_outer_join, bool append_rel_member)
{
	Query	   *parse = root->parse;
	int			varno = ((RangeTblRef *) jtnode)->rtindex;
	Query	   *subquery;
	PlannerInfo *subroot;
	int			rtoffset;
	List	   *subtlist;
	ListCell   *rt;
447
    ListCell   *cell;
448 449

	/*
B
Bruce Momjian 已提交
450 451 452 453
	 * 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).
454 455 456 457 458 459 460
	 */
	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 已提交
461 462
	 * subquery_planner().	Can we refactor to avoid code duplication, or
	 * would that just make things uglier?
463 464 465
	 */
	subroot = makeNode(PlannerInfo);
	subroot->parse = subquery;
466 467
	subroot->glob = root->glob;
	subroot->query_level = root->query_level;
468
	subroot->parent_root = root->parent_root;
469
	subroot->planner_cxt = CurrentMemoryContext;
470
	subroot->init_plans = NIL;
471 472
	subroot->cte_plan_ids = NIL;
	subroot->eq_classes = NIL;
473 474
	subroot->in_info_list = NIL;
	subroot->append_rel_list = NIL;
475 476 477 478 479 480
	subroot->hasRecursion = false;
	subroot->wt_param_id = -1;
	subroot->non_recursive_plan = NULL;

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

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	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. */
    subroot->currlevel_relids = get_relids_in_jointree((Node *)subquery->jointree);
    
    /* 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);
	/* CDB: Clear fallback */
	subroot->config->mpp_trying_fallback_plan = false;

498
	/*
B
Bruce Momjian 已提交
499 500
	 * Pull up any IN clauses within the subquery's WHERE, so that we don't
	 * leave unoptimized INs behind.
501 502
	 */
	if (subquery->hasSubLinks)
503
        cdbsubselect_flatten_sublinks(subroot, (Node *)subquery);
504

505 506 507 508 509
	/*
	 * Similarly, inline any set-returning functions in its rangetable.
	 */
	inline_set_returning_functions(subroot);

510 511 512 513 514 515 516
	/*
	 * Recursively pull up the subquery's subqueries, so that
	 * pull_up_subqueries' processing is complete for its jointree and
	 * rangetable.
	 *
	 * Note: below_outer_join = false is correct here even if we are within an
	 * outer join in the upper query; the lower query starts with a clean
B
Bruce Momjian 已提交
517 518
	 * slate for outer-join semantics.	Likewise, we say we aren't handling an
	 * appendrel member.
519 520 521 522 523
	 */
	subquery->jointree = (FromExpr *)
		pull_up_subqueries(subroot, (Node *) subquery->jointree, false, false);

	/*
B
Bruce Momjian 已提交
524 525
	 * Now we must recheck whether the subquery is still simple enough to pull
	 * up.	If not, abandon processing it.
526
	 *
B
Bruce Momjian 已提交
527 528 529
	 * 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.
530
	 */
531
	if (is_simple_subquery(root, subquery) &&
532 533 534 535 536 537 538 539 540 541
		(!below_outer_join || has_nullable_targetlist(subquery)) &&
		(!append_rel_member || is_safe_append_member(subquery)))
	{
		/* good to go */
	}
	else
	{
		/*
		 * Give up, return unmodified RangeTblRef.
		 *
B
Bruce Momjian 已提交
542 543 544 545
		 * 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.
546 547 548 549
		 */
		return jtnode;
	}

550 551 552 553 554 555 556 557 558 559
    /* 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);
    }

560
	/*
B
Bruce Momjian 已提交
561 562 563
	 * Adjust level-0 varnos in subquery so that we can append its rangetable
	 * to upper query's.  We have to fix the subquery's in_info_list and
	 * append_rel_list, as well.
564 565 566 567 568 569 570
	 */
	rtoffset = list_length(parse->rtable);
	OffsetVarNodes((Node *) subquery, rtoffset, 0);
	OffsetVarNodes((Node *) subroot->in_info_list, rtoffset, 0);
	OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);

	/*
B
Bruce Momjian 已提交
571 572
	 * Upper-level vars in subquery are now one level closer to their parent
	 * than before.
573 574 575 576 577 578
	 */
	IncrementVarSublevelsUp((Node *) subquery, -1, 1);
	IncrementVarSublevelsUp((Node *) subroot->in_info_list, -1, 1);
	IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);

	/*
B
Bruce Momjian 已提交
579 580 581 582
	 * 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.)
583 584
	 */
	subtlist = subquery->targetList;
585 586

	List *newTList = (List *)
587 588 589
		ResolveNew((Node *) parse->targetList,
				   varno, 0, rte,
				   subtlist, CMD_SELECT, 0);
590 591 592 593 594 595 596 597

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

	parse->targetList = newTList;

598 599 600 601
	parse->returningList = (List *)
		ResolveNew((Node *) parse->returningList,
				   varno, 0, rte,
				   subtlist, CMD_SELECT, 0);
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	resolvenew_in_jointree((Node *) parse->jointree, varno,
						   rte, subtlist);
	Assert(parse->setOperations == NULL);
	parse->havingQual =
		ResolveNew(parse->havingQual,
				   varno, 0, rte,
				   subtlist, CMD_SELECT, 0);
	root->in_info_list = (List *)
		ResolveNew((Node *) root->in_info_list,
				   varno, 0, rte,
				   subtlist, CMD_SELECT, 0);
	root->append_rel_list = (List *)
		ResolveNew((Node *) root->append_rel_list,
				   varno, 0, rte,
				   subtlist, CMD_SELECT, 0);

618 619 620 621
	if (parse->windowClause)
	{
		foreach(cell, parse->windowClause)
		{
622 623
			WindowClause *wc = (WindowClause *) lfirst(cell);

624 625 626 627 628 629 630 631 632 633
			if (wc->startOffset)
				wc->startOffset =
					ResolveNew((Node *) wc->startOffset,
							   varno, 0, rte,
							   subtlist, CMD_SELECT, 0);
			if (wc->endOffset)
				wc->endOffset =
					ResolveNew((Node *) wc->endOffset,
							   varno, 0, rte,
							   subtlist, CMD_SELECT, 0);
634 635 636
		}
	}

637 638 639 640 641 642 643 644 645
	foreach(rt, parse->rtable)
	{
		RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(rt);

		if (otherrte->rtekind == RTE_JOIN)
			otherrte->joinaliasvars = (List *)
				ResolveNew((Node *) otherrte->joinaliasvars,
						   varno, 0, rte,
						   subtlist, CMD_SELECT, 0);
646 647 648 649 650 651 652 653 654 655 656 657

		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. */
							subtlist, CMD_SELECT, 0);
		}
658 659 660
	}

	/*
B
Bruce Momjian 已提交
661 662 663
	 * 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.)
664 665 666 667
	 */
	parse->rtable = list_concat(parse->rtable, subquery->rtable);

	/*
B
Bruce Momjian 已提交
668 669
	 * Pull up any FOR UPDATE/SHARE markers, too.  (OffsetVarNodes already
	 * adjusted the marker rtindexes, so just concat the lists.)
670 671 672
	 */
	parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);

673 674 675 676 677 678 679 680 681 682 683 684 685 686
    /*
     * 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);
    }

687
	/*
B
Bruce Momjian 已提交
688 689 690
	 * 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.)
691
	 *
B
Bruce Momjian 已提交
692 693 694 695
	 * 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.
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
	 */
	if (root->in_info_list || root->append_rel_list)
	{
		Relids		subrelids;

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

	/*
	 * And now add any subquery InClauseInfos and AppendRelInfos to our lists.
	 */
	root->in_info_list = list_concat(root->in_info_list,
									 subroot->in_info_list);
	root->append_rel_list = list_concat(root->append_rel_list,
										subroot->append_rel_list);

	/*
B
Bruce Momjian 已提交
715 716
	 * We don't have to do the equivalent bookkeeping for outer-join info,
	 * because that hasn't been set up yet.
717 718 719 720 721 722 723 724 725 726
	 */
	Assert(root->oj_info_list == NIL);
	Assert(subroot->oj_info_list == NIL);

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

727 728 729 730 731 732 733 734 735 736

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

737
	/*
B
Bruce Momjian 已提交
738 739
	 * Return the adjusted subquery jointree to replace the RangeTblRef entry
	 * in parent's jointree.
740 741 742 743 744
	 */
	return (Node *) subquery->jointree;
}


745 746 747 748 749
/*
 * is_simple_subquery
 *	  Check a subquery in the range table to see if it's simple enough
 *	  to pull up into the parent query.
 */
750
bool
751
is_simple_subquery(PlannerInfo *root, Query *subquery)
752 753 754 755 756 757
{
	/*
	 * Let's just make sure it's a valid subselect ...
	 */
	if (!IsA(subquery, Query) ||
		subquery->commandType != CMD_SELECT ||
758
		subquery->utilityStmt != NULL ||
759
		subquery->intoClause != NULL)
760
		elog(ERROR, "subquery is bogus");
761 762

	/*
763 764
	 * 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
765 766 767 768 769 770
	 * redesign...
	 */
	if (subquery->setOperations)
		return false;

	/*
771 772
	 * Can't pull up a subquery involving grouping, aggregation, sorting,
	 * limiting, or WITH.  (XXX WITH could possibly be allowed later)
773 774
	 */
	if (subquery->hasAggs ||
775
	    subquery->hasWindowFuncs ||
776 777
		subquery->groupClause ||
		subquery->havingQual ||
778
		subquery->windowClause ||
779 780 781
		subquery->sortClause ||
		subquery->distinctClause ||
		subquery->limitOffset ||
782 783 784
		subquery->limitCount ||
		subquery->cteList ||
		root->parse->cteList)
785 786 787
		return false;

	/*
B
Bruce Momjian 已提交
788 789 790 791
	 * 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.
792 793
	 */
	if (expression_returns_set((Node *) subquery->targetList))
794 795 796 797
		return false;

	/*
	 * Don't pull up a subquery that has any volatile functions in its
B
Bruce Momjian 已提交
798 799 800
	 * targetlist.	Otherwise we might introduce multiple evaluations of these
	 * functions, if they get copied to multiple places in the upper query,
	 * leading to surprising results.
801 802
	 */
	if (contain_volatile_functions((Node *) subquery->targetList))
803 804 805 806
		return false;

	/*
	 * Hack: don't try to pull up a subquery with an empty jointree.
B
Bruce Momjian 已提交
807 808 809 810
	 * 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...
811 812 813 814 815 816 817
	 */
	if (subquery->jointree->fromlist == NIL)
		return false;

	return true;
}

818 819 820 821 822 823 824 825
/*
 * 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.
 */
826
static bool pg_attribute_unused()
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
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;
851

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
	/* 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 */
	}
}
891

892 893 894
/*
 * has_nullable_targetlist
 *	  Check a subquery in the range table to see if all the non-junk
895 896 897
 *	  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).
898
 *
899 900 901
 * 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.
902 903 904 905
 */
static bool
has_nullable_targetlist(Query *subquery)
{
906
	ListCell   *l;
907 908 909 910 911 912

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

		/* ignore resjunk columns */
913
		if (tle->resjunk)
914 915
			continue;

916 917 918
		/* Must contain a Var of current level */
		if (!contain_vars_of_level((Node *) tle->expr, 0))
			return false;
919

920 921 922 923 924
		/* Must not contain any non-strict constructs */
		if (contain_nonstrict_functions((Node *) tle->expr))
			return false;

		/* This one's OK, keep scanning */
925 926 927 928
	}
	return true;
}

929 930 931 932 933 934 935 936 937 938 939 940
/*
 * 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;
	ListCell   *l;

	/*
B
Bruce Momjian 已提交
941 942 943
	 * 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.
944
	 *
B
Bruce Momjian 已提交
945 946 947 948 949
	 * 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().
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
	 */
	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;

	/*
	 * XXX For the moment we also have to insist that the subquery's tlist
	 * includes only simple Vars.  This is pretty annoying, but fixing it
B
Bruce Momjian 已提交
966 967 968 969
	 * seems to require nontrivial changes --- mainly because joinrel tlists
	 * are presently assumed to contain only Vars.	Perhaps a pseudo-variable
	 * mechanism similar to the one speculated about in pull_up_subqueries'
	 * comments would help?  FIXME someday.
970 971 972 973 974 975 976 977 978 979 980 981 982 983
	 */
	foreach(l, subquery->targetList)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(l);

		if (tle->resjunk)
			continue;
		if (!(tle->expr && IsA(tle->expr, Var)))
			return false;
	}

	return true;
}

984 985 986 987 988 989
/*
 * 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
990
resolvenew_in_jointree(Node *jtnode, int varno,
991
					   RangeTblEntry *rte, List *subtlist)
992
{
993 994
	ListCell   *l;

995 996 997 998 999 1000 1001 1002 1003 1004 1005
	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)
1006
			resolvenew_in_jointree(lfirst(l), varno, rte, subtlist);
1007
		f->quals = ResolveNew(f->quals,
1008
							  varno, 0, rte,
1009
							  subtlist, CMD_SELECT, 0);
1010 1011 1012 1013 1014
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

1015 1016
		resolvenew_in_jointree(j->larg, varno, rte, subtlist);
		resolvenew_in_jointree(j->rarg, varno, rte, subtlist);
1017 1018
		foreach(l, j->subqfromlist)
			resolvenew_in_jointree(lfirst(l), varno, rte, subtlist);
1019
		j->quals = ResolveNew(j->quals,
1020
							  varno, 0, rte,
1021
							  subtlist, CMD_SELECT, 0);
1022 1023

		/*
B
Bruce Momjian 已提交
1024 1025
		 * We don't bother to update the colvars list, since it won't be used
		 * again ...
1026 1027 1028
		 */
	}
	else
1029 1030
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1031 1032 1033
}

/*
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
 * 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
1057
reduce_outer_joins(PlannerInfo *root)
1058 1059 1060 1061
{
	reduce_outer_joins_state *state;

	/*
B
Bruce Momjian 已提交
1062 1063 1064 1065 1066 1067 1068
	 * 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.
1069
	 */
1070
	state = reduce_outer_joins_pass1((Node *) root->parse->jointree);
1071 1072 1073

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

1076 1077
	reduce_outer_joins_pass2((Node *) root->parse->jointree,
							 state, root, NULL);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
}

/*
 * 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;
1089
	ListCell   *l;
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

	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);
1140 1141 1142 1143 1144 1145 1146 1147 1148

		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);
		}
1149 1150
	}
	else
1151 1152
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1153 1154 1155 1156 1157 1158 1159 1160
	return result;
}

/*
 * reduce_outer_joins_pass2 - phase 2 processing
 *
 *	jtnode: current jointree node
 *	state: state data collected by phase 1 for this node
1161
 *	root: toplevel planner state
1162 1163 1164 1165
 *	nonnullable_rels: set of base relids forced non-null by upper quals
 */
static void
reduce_outer_joins_pass2(Node *jtnode,
1166
						 reduce_outer_joins_state *state,
1167
						 PlannerInfo *root,
1168 1169
						 Relids nonnullable_rels)
{
1170 1171 1172
	ListCell   *l;
	ListCell   *s;

1173 1174 1175 1176 1177
	/*
	 * 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)
1178
		elog(ERROR, "reached empty jointree");
1179
	if (IsA(jtnode, RangeTblRef))
1180
		elog(ERROR, "reached base rel");
1181 1182 1183 1184 1185 1186
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
		Relids		pass_nonnullable;

		/* Scan quals to see if we can add any nonnullability constraints */
1187
		pass_nonnullable = find_nonnullable_rels(f->quals);
1188 1189 1190
		pass_nonnullable = bms_add_members(pass_nonnullable,
										   nonnullable_rels);
		/* And recurse --- but only into interesting subtrees */
1191
		Assert(list_length(f->fromlist) == list_length(state->sub_states));
1192
		forboth(l, f->fromlist, s, state->sub_states)
1193 1194 1195 1196
		{
			reduce_outer_joins_state *sub_state = lfirst(s);

			if (sub_state->contains_outer)
1197
				reduce_outer_joins_pass2(lfirst(l), sub_state, root,
1198 1199 1200 1201 1202 1203 1204 1205 1206
										 pass_nonnullable);
		}
		bms_free(pass_nonnullable);
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
		int			rtindex = j->rtindex;
		JoinType	jointype = j->jointype;
1207
		reduce_outer_joins_state *left_state = linitial(state->sub_states);
1208
		reduce_outer_joins_state *right_state = lsecond(state->sub_states);
1209
		reduce_outer_joins_state *sub_state;
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

		/* 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 */
1242
			RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
1243 1244 1245 1246 1247 1248 1249

			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 */
1250 1251 1252 1253 1254 1255 1256
        foreach(l, state->sub_states)
        {
            sub_state = (reduce_outer_joins_state *)lfirst(l);
            if (sub_state->contains_outer)
                break;
        }
		if (l)
1257
		{
1258
			Relids		local_nonnullable;
1259 1260 1261
			Relids		pass_nonnullable;

			/*
1262
			 * If this join is (now) inner, we can add any nonnullability
B
Bruce Momjian 已提交
1263 1264 1265 1266 1267
			 * constraints its quals provide to those we got from above. 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.
1268
			 */
1269 1270
			if (jointype != JOIN_FULL)
			{
1271
				local_nonnullable = find_nonnullable_rels(j->quals);
1272 1273 1274 1275
				local_nonnullable = bms_add_members(local_nonnullable,
													nonnullable_rels);
			}
			else
B
Bruce Momjian 已提交
1276
				local_nonnullable = NULL;		/* no use in calculating it */
1277

1278
			if (left_state->contains_outer)
1279 1280 1281 1282 1283
			{
				if (jointype == JOIN_INNER || jointype == JOIN_RIGHT)
					pass_nonnullable = local_nonnullable;
				else
					pass_nonnullable = nonnullable_rels;
1284
				reduce_outer_joins_pass2(j->larg, left_state, root,
1285
										 pass_nonnullable);
1286
			}
1287
			if (right_state->contains_outer)
1288 1289 1290 1291 1292
			{
				if (jointype == JOIN_INNER || jointype == JOIN_LEFT)
					pass_nonnullable = local_nonnullable;
				else
					pass_nonnullable = nonnullable_rels;
1293
				reduce_outer_joins_pass2(j->rarg, right_state, root,
1294
										 pass_nonnullable);
1295
			}
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313

            /*
             * 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,
										     local_nonnullable);
                s = lnext(s);
            }

1314
			bms_free(local_nonnullable);
1315 1316 1317
		}
	}
	else
1318 1319
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1320 1321
}

1322
/*
1323
 * fix_in_clause_relids: update RT-index sets of InClauseInfo nodes
1324 1325
 *
 * When we pull up a subquery, any InClauseInfo references to the subquery's
1326
 * RT index have to be replaced by the set of substituted relids.
1327 1328 1329 1330 1331 1332
 *
 * We assume we may modify the InClauseInfo nodes in-place.
 */
static void
fix_in_clause_relids(List *in_info_list, int varno, Relids subrelids)
{
1333
	ListCell   *l;
1334 1335 1336 1337 1338

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

1339
		if (bms_is_member(varno, ininfo->righthand))
1340
		{
1341 1342
			ininfo->righthand = bms_del_member(ininfo->righthand, varno);
			ininfo->righthand = bms_add_members(ininfo->righthand, subrelids);
1343 1344 1345 1346
		}
	}
}

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
/*
 * 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
1357
fix_append_rel_relids(List *append_rel_list, int varno, Relids subrelids)
1358 1359 1360 1361 1362 1363
{
	ListCell   *l;
	int			subvarno = -1;

	/*
	 * We only want to extract the member relid once, but we mustn't fail
B
Bruce Momjian 已提交
1364 1365 1366
	 * 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.
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
	 */
	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;
		}
	}
}

1384
/*
1385
 * get_relids_in_jointree: get set of base RT indexes present in a jointree
1386
 */
1387
Relids
1388 1389
get_relids_in_jointree(Node *jtnode)
{
1390
	Relids		result = NULL;
1391
	ListCell   *l;
1392 1393 1394 1395 1396 1397 1398

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

1399
		result = bms_make_singleton(varno);
1400 1401 1402 1403 1404 1405 1406
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;

		foreach(l, f->fromlist)
		{
1407 1408
			result = bms_join(result,
							  get_relids_in_jointree(lfirst(l)));
1409 1410 1411 1412 1413 1414 1415 1416
		}
	}
	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);
1417
		result = bms_join(result, get_relids_in_jointree(j->rarg));
1418 1419 1420

		foreach(l, j->subqfromlist)
			result = bms_join(result, get_relids_in_jointree((Node *)lfirst(l)));
1421 1422
	}
	else
1423 1424
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1425 1426 1427 1428
	return result;
}

/*
1429
 * get_relids_for_join: get set of base RT indexes making up a join
1430
 */
1431
Relids
1432
get_relids_for_join(PlannerInfo *root, int joinrelid)
1433 1434 1435
{
	Node	   *jtnode;

1436 1437
	jtnode = find_jointree_node_for_rel((Node *) root->parse->jointree,
										joinrelid);
1438
	if (!jtnode)
1439
		elog(ERROR, "could not find join node %d", joinrelid);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
	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)
{
1451 1452
	ListCell   *l;

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
	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;
1485 1486 1487 1488 1489 1490 1491

		foreach(l, j->subqfromlist)
		{
			jtnode = find_jointree_node_for_rel(lfirst(l), relid);
			if (jtnode)
				return jtnode;
		}
1492 1493
	}
	else
1494 1495
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
1496 1497
	return NULL;
}
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516

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