planner.c 110.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * planner.c
4
 *	  The query optimizer external interface.
5
 *
6
 * Portions Copyright (c) 2005-2008, Greenplum inc
7
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
8
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
9
 * Portions Copyright (c) 1994, Regents of the University of California
10 11 12
 *
 *
 * IDENTIFICATION
13
 *	  $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.245 2008/10/21 20:42:53 tgl Exp $
14 15 16
 *
 *-------------------------------------------------------------------------
 */
M
Marc G. Fournier 已提交
17

18 19
#include "postgres.h"

20 21
#include <limits.h>

22
#include "catalog/pg_operator.h"
23
#include "executor/executor.h"
24
#include "executor/execHHashagg.h"
25
#include "executor/nodeAgg.h"
26
#include "miscadmin.h"
B
Bruce Momjian 已提交
27 28
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
29
#include "optimizer/cost.h"
30
#include "optimizer/orca.h"
31
#include "optimizer/pathnode.h"
32
#include "optimizer/paths.h"
B
Bruce Momjian 已提交
33
#include "optimizer/planmain.h"
34 35
#include "optimizer/planner.h"
#include "optimizer/prep.h"
36
#include "optimizer/subselect.h"
37
#include "optimizer/transform.h"
38 39
#include "optimizer/tlist.h"
#include "optimizer/var.h"
40 41 42
#ifdef OPTIMIZER_DEBUG
#include "nodes/print.h"
#endif
B
Bruce Momjian 已提交
43
#include "parser/parse_expr.h"
44
#include "parser/parse_oper.h"
45
#include "parser/parse_relation.h"
46
#include "parser/parsetree.h"
47
#include "utils/lsyscache.h"
48
#include "utils/selfuncs.h"
49
#include "utils/syscache.h"
50

51
#include "catalog/pg_proc.h"
52
#include "cdb/cdbllize.h"
53
#include "cdb/cdbmutate.h"		/* apply_shareinput */
H
Heikki Linnakangas 已提交
54
#include "cdb/cdbpartition.h"
55 56 57 58
#include "cdb/cdbpath.h"		/* cdbpath_segments */
#include "cdb/cdbpathtoplan.h"	/* cdbpathtoplan_create_flow() */
#include "cdb/cdbgroup.h"		/* grouping_planner extensions */
#include "cdb/cdbsetop.h"		/* motion utilities */
H
Heikki Linnakangas 已提交
59
#include "cdb/cdbvars.h"
60

61

62 63
/* GUC parameter */
double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
64

65 66 67
/* Hook for plugins to get control in planner() */
planner_hook_type planner_hook = NULL;

68

69
/* Expression kind codes for preprocess_expression */
70 71 72 73 74
#define EXPRKIND_QUAL		0
#define EXPRKIND_TARGET		1
#define EXPRKIND_RTFUNC		2
#define EXPRKIND_VALUES		3
#define EXPRKIND_LIMIT		4
75
#define EXPRKIND_APPINFO	5
76
#define EXPRKIND_WINDOW_BOUND 6
77

78

79 80
static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
81
static Plan *inheritance_planner(PlannerInfo *root);
82
static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
83
static double preprocess_limit(PlannerInfo *root,
B
Bruce Momjian 已提交
84
				 double tuple_fraction,
B
Bruce Momjian 已提交
85
				 int64 *offset_est, int64 *count_est);
86 87 88
#ifdef NOT_USED
static Oid *extract_grouping_ops(List *groupClause, int *numGroupOps);
#endif
89
static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
90
					   AttrNumber **groupColIdx, Oid **groupOperators, bool *need_tlist_eval);
91 92 93 94
static List *register_ordered_aggs(List *tlist, Node *havingqual, List *sub_tlist);

typedef struct
{
95 96 97 98 99
	List	   *tlist;
	Node	   *havingqual;
	List	   *sub_tlist;
	Index		last_sgr;
}	register_ordered_aggs_context;
100 101


102 103 104 105
static Node *register_ordered_aggs_mutator(Node *node,
							  register_ordered_aggs_context * context);
static void register_AggOrder(AggOrder * aggorder,
				  register_ordered_aggs_context * context);
106
static void locate_grouping_columns(PlannerInfo *root,
107
						List *stlist,
B
Bruce Momjian 已提交
108 109
						List *sub_tlist,
						AttrNumber *groupColIdx);
110 111
static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);

112
static Bitmapset *canonicalize_colref_list(Node *node);
113 114 115 116 117
static List *canonicalize_gs_list(List *gsl, bool ordinary);
static List *rollup_gs_list(List *gsl);
static List *add_gs_combinations(List *list, int n, int i, Bitmapset **base, Bitmapset **work);
static List *cube_gs_list(List *gsl);
static CanonicalGroupingSets *make_canonical_groupingsets(List *groupClause);
118
static int	gs_compare(const void *a, const void *b);
119 120 121
static void sort_canonical_gs_list(List *gs, int *p_nsets, Bitmapset ***p_sets);

static Plan *pushdown_preliminary_limit(Plan *plan, Node *limitCount, int64 count_est, Node *limitOffset, int64 offset_est);
122
static bool is_dummy_plan(Plan *plan);
123

124 125
static bool isSimplyUpdatableQuery(Query *query);

126

127 128
/*****************************************************************************
 *
129 130
 *	   Query optimizer entry point
 *
131 132 133 134 135 136 137 138
 * To support loadable plugins that monitor or modify planner behavior,
 * we provide a hook variable that lets a plugin get control before and
 * after the standard planning process.  The plugin would normally call
 * standard_planner().
 *
 * Note to plugin authors: standard_planner() scribbles on its Query input,
 * so you'd better copy that data structure if you want to plan more than once.
 *
139
 *****************************************************************************/
140
PlannedStmt *
141
planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
142
{
143
	PlannedStmt *result;
144 145
	instr_time	starttime, endtime;

146
	if (planner_hook)
147 148 149
	{
		if (gp_log_optimization_time)
			INSTR_TIME_SET_CURRENT(starttime);
150 151

		START_MEMORY_ACCOUNT(MemoryAccounting_CreateAccount(0, MEMORY_OWNER_TYPE_PlannerHook));
152
		{
153
			result = (*planner_hook) (parse, cursorOptions, boundParams);
154 155 156 157 158 159 160
		}
		END_MEMORY_ACCOUNT();

		if (gp_log_optimization_time)
		{
			INSTR_TIME_SET_CURRENT(endtime);
			INSTR_TIME_SUBTRACT(endtime, starttime);
161
			elog(LOG, "Planner Hook(s): %.3f ms", INSTR_TIME_GET_MILLISEC(endtime));
162 163
		}
	}
164 165
	else
		result = standard_planner(parse, cursorOptions, boundParams);
166 167 168 169 170 171 172 173 174

	return result;
}

PlannedStmt *
standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
{
	PlannedStmt *result;
	PlannerGlobal *glob;
175
	double		tuple_fraction;
176 177 178 179
	PlannerInfo *root;
	Plan	   *top_plan;
	ListCell   *lp,
			   *lr;
180
	PlannerConfig *config;
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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	instr_time		starttime;
	instr_time		endtime;

	/*
	 * If ORCA has been enabled, and we are in a state in which ORCA planning
	 * is supported, then go ahead.
	 */
	if (optimizer &&
		GP_ROLE_UTILITY != Gp_role && MASTER_CONTENT_ID == GpIdentity.segindex)
	{
		if (gp_log_optimization_time)
			INSTR_TIME_SET_CURRENT(starttime);

		START_MEMORY_ACCOUNT(MemoryAccounting_CreateAccount(0, MEMORY_OWNER_TYPE_Optimizer));
		{
			result = optimize_query(parse, boundParams);
		}
		END_MEMORY_ACCOUNT();

		if (gp_log_optimization_time)
		{
			INSTR_TIME_SET_CURRENT(endtime);
			INSTR_TIME_SUBTRACT(endtime, starttime);
			elog(LOG, "Optimizer Time: %.3f ms", INSTR_TIME_GET_MILLISEC(endtime));
		}

		if (result)
			return result;
	}

	/*
	 * Fall back to using the PostgreSQL planner in case Orca didn't run (in
	 * utility mode or on a segment) or if it didn't produce a plan.
	 */
	if (gp_log_optimization_time)
		INSTR_TIME_SET_CURRENT(starttime);

	/*
	 * Incorrectly indented on purpose to avoid re-indenting an entire upstream
	 * function
	 */
	START_MEMORY_ACCOUNT(MemoryAccounting_CreateAccount(0, MEMORY_OWNER_TYPE_Planner));
	{
224

225 226 227
	/* Cursor options may come from caller or from DECLARE CURSOR stmt */
	if (parse->utilityStmt &&
		IsA(parse->utilityStmt, DeclareCursorStmt))
228
	{
229
		cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
230

231 232 233 234
		/* Also try to make any cursor declared with DECLARE CURSOR updatable. */
		cursorOptions |= CURSOR_OPT_UPDATABLE;
	}

235
	/*
236 237 238 239
	 * Set up global state for this planner invocation.  This data is needed
	 * across all levels of sub-Query that might exist in the given command,
	 * so we keep it in a separate struct that's linked to by each per-Query
	 * PlannerInfo.
240
	 */
241
	glob = makeNode(PlannerGlobal);
242

243 244 245 246
	glob->boundParams = boundParams;
	glob->paramlist = NIL;
	glob->subplans = NIL;
	glob->subrtables = NIL;
247
	glob->rewindPlanIDs = NULL;
248 249 250
	glob->finalrtable = NIL;
	glob->relationOids = NIL;
	glob->invalItems = NIL;
251
	glob->lastPHId = 0;
252
	glob->transientPlan = false;
253
	glob->oneoffPlan = false;
254
	/* ApplyShareInputContext initialization. */
255 256 257
	glob->share.producers = NULL;
	glob->share.producer_count = 0;
	glob->share.sliceMarks = NULL;
258 259 260 261
	glob->share.motStack = NIL;
	glob->share.qdShares = NIL;
	glob->share.qdSlices = NIL;
	glob->share.nextPlanId = 0;
262

263 264 265 266 267
	if ((cursorOptions & CURSOR_OPT_UPDATABLE) != 0)
		glob->simplyUpdatable = isSimplyUpdatableQuery(parse);
	else
		glob->simplyUpdatable = false;

268
	/* Determine what fraction of the plan is likely to be scanned */
269
	if (cursorOptions & CURSOR_OPT_FAST_PLAN)
270 271
	{
		/*
B
Bruce Momjian 已提交
272
		 * We have no real idea how many tuples the user will ultimately FETCH
273 274 275 276
		 * from a cursor, but it is sometimes the case that he doesn't want 'em
		 * all, or would prefer a fast-start plan anyway so that he can
		 * process some of the tuples sooner.  Use a GUC parameter to decide
		 * what fraction to optimize for.
277
		 */
278 279 280 281 282 283 284 285 286 287 288 289
		tuple_fraction = cursor_tuple_fraction;

		/*
		 * We document cursor_tuple_fraction as simply being a fraction,
		 * which means the edge cases 0 and 1 have to be treated specially
		 * here.  We convert 1 to 0 ("all the tuples") and 0 to a very small
		 * fraction.
		 */
		if (tuple_fraction >= 1.0)
			tuple_fraction = 0.0;
		else if (tuple_fraction <= 0.0)
			tuple_fraction = 1e-10;
290 291 292 293 294 295
	}
	else
	{
		/* Default assumption is we need all the tuples */
		tuple_fraction = 0.0;
	}
296

297
	parse = normalize_query(parse);
298

299
	config = DefaultPlannerConfig();
300

301
	/* primary planning entry point (may recurse for subqueries) */
302
	top_plan = subquery_planner(glob, parse, NULL, false, tuple_fraction, &root, config);
303

304
	/*
B
Bruce Momjian 已提交
305 306
	 * If creating a plan for a scrollable cursor, make sure it can run
	 * backwards on demand.  Add a Material node at the top at need.
307
	 */
308
	if (cursorOptions & CURSOR_OPT_SCROLL)
309
	{
310 311 312 313 314
		if (!ExecSupportsBackwardScan(top_plan))
			top_plan = materialize_finished_plan(root, top_plan);
	}


315 316
	/*
	 * Fix sharing id and shared id.
317 318 319 320 321 322
	 *
	 * This must be called before set_plan_references and cdbparallelize.  The other mutator
	 * or tree walker assumes the input is a tree.  If there is plan sharing, we have a DAG. 
	 *
	 * apply_shareinput will fix shared_id, and change the DAG to a tree.
	 */
323
	forboth(lp, glob->subplans, lr, glob->subrtables)
324 325
	{
		Plan	   *subplan = (Plan *) lfirst(lp);
326 327 328
		List	   *subrtable = (List *) lfirst(lr);

		lfirst(lp) = apply_shareinput_dag_to_tree(glob, subplan, subrtable);
329
	}
330
	top_plan = apply_shareinput_dag_to_tree(glob, top_plan, root->parse->rtable);
331

332
	/* final cleanup of the plan */
333 334 335 336 337 338 339 340 341
	Assert(glob->finalrtable == NIL);
	Assert(parse == root->parse);
	top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
	/* ... and the subplans (both regular subplans and initplans) */
	Assert(list_length(glob->subplans) == list_length(glob->subrtables));
	forboth(lp, glob->subplans, lr, glob->subrtables)
	{
		Plan	   *subplan = (Plan *) lfirst(lp);
		List	   *subrtable = (List *) lfirst(lr);
342

343 344 345 346 347
		lfirst(lp) = set_plan_references(glob, subplan, subrtable);
	}

	/* walk plan and remove unused initplans and their params */
	remove_unused_initplans(top_plan, root);
348

349 350 351 352
	/* walk subplans and fixup subplan node referring to same plan_id */
	SubPlanWalkerContext subplan_context;
	fixup_subplans(top_plan, root, &subplan_context);

353
	if (Gp_role == GP_ROLE_DISPATCH)
354 355
	{
		top_plan = cdbparallelize(root, top_plan, parse,
356 357 358
								  cursorOptions,
								  boundParams);

359
		/*
360 361 362 363
		 * cdbparallelize() mutates all the nodes, so the producer nodes we
		 * memorized earlier are no longer valid. apply_shareinput_xslice()
		 * will re-populate it, but clear it for now, just to make sure that
		 * we don't access the obsolete copies of the nodes.
364 365 366
		 */
		if (glob->share.producer_count > 0)
			memset(glob->share.producers, 0, glob->share.producer_count * sizeof(ShareInputScan *));
367

368 369 370 371
		/*
		 * cdbparallelize may create additional slices that may affect share
		 * input. need to mark material nodes that are split acrossed multi
		 * slices.
372 373 374 375
		 */
		top_plan = apply_shareinput_xslice(top_plan, glob);
	}

H
Haisheng Yuan 已提交
376
	/*
377
	 * Remove unused subplans.
H
Haisheng Yuan 已提交
378 379 380 381 382
	 * Executor initializes state for subplans even they are unused.
	 * When the generated subplan is not used and has motion inside,
	 * causing motionID not being assigned, which will break sanity
	 * check when executor tries to initialize subplan state.
	 */
383 384
	remove_unused_subplans(root, &subplan_context);
	bms_free(subplan_context.bms_subplans);
H
Haisheng Yuan 已提交
385

386 387
	top_plan = zap_trivial_result(root, top_plan);

388 389 390 391
	/* fix ShareInputScans for EXPLAIN */
	foreach(lp, glob->subplans)
	{
		Plan	   *subplan = (Plan *) lfirst(lp);
392

393
		lfirst(lp) = replace_shareinput_targetlists(glob, subplan, glob->finalrtable);
394
	}
395
	top_plan = replace_shareinput_targetlists(glob, top_plan, glob->finalrtable);
396

397
	/*
398 399
	 * To save on memory, and on the network bandwidth when the plan is
	 * dispatched QEs, strip all subquery RTEs of the original Query objects.
400 401 402
	 */
	remove_subquery_in_RTEs((Node *) glob->finalrtable);

403 404
	/* build the PlannedStmt result */
	result = makeNode(PlannedStmt);
405

406 407 408
	result->commandType = parse->commandType;
	result->canSetTag = parse->canSetTag;
	result->transientPlan = glob->transientPlan;
409
	result->oneoffPlan = glob->oneoffPlan;
410 411 412 413 414 415
	result->planTree = top_plan;
	result->rtable = glob->finalrtable;
	result->resultRelations = root->resultRelations;
	result->utilityStmt = parse->utilityStmt;
	result->intoClause = parse->intoClause;
	result->subplans = glob->subplans;
416
	result->rewindPlanIDs = glob->rewindPlanIDs;
417 418 419 420 421 422
	result->returningLists = root->returningLists;
	result->result_partitions = root->result_partitions;
	result->result_aosegnos = root->result_aosegnos;
	result->rowMarks = parse->rowMarks;
	result->relationOids = glob->relationOids;
	result->invalItems = glob->invalItems;
423
	result->nParamExec = list_length(glob->paramlist);
424 425 426 427 428 429
	result->nMotionNodes = top_plan->nMotionNodes;
	result->nInitPlans = top_plan->nInitPlans;
	result->intoPolicy = GpPolicyCopy(CurrentMemoryContext, parse->intoPolicy);
	result->queryPartOids = NIL;
	result->queryPartsMetadata = NIL;
	result->numSelectorsPerScanId = NIL;
430

431 432
	result->simplyUpdatable = glob->simplyUpdatable;

433 434 435 436 437 438 439 440 441 442 443 444
	{
		ListCell *lc;

		foreach(lc, glob->relationOids)
		{
			Oid reloid = lfirst_oid(lc);

			if (rel_is_partitioned(reloid))
				result->queryPartOids = lappend_oid(result->queryPartOids, reloid);
		}
	}

445
	Assert(result->utilityStmt == NULL || IsA(result->utilityStmt, DeclareCursorStmt));
446

447 448 449
	if (Gp_role == GP_ROLE_DISPATCH)
	{
		/*
450 451 452
		 * Generate a plan node id for each node. Used by gpmon. Note that
		 * this needs to be the last step of the planning when the structure
		 * of the plan is final.
453 454 455
		 */
		assign_plannode_id(result);
	}
456

457 458 459 460 461 462 463 464 465 466
	if (gp_log_optimization_time)
	{
		INSTR_TIME_SET_CURRENT(endtime);
		INSTR_TIME_SUBTRACT(endtime, starttime);
		elog(LOG, "Planner Time: %.3f ms", INSTR_TIME_GET_MILLISEC(endtime));
	}

	}
	END_MEMORY_ACCOUNT();

467 468
	return result;
}
469

470

471
/*--------------------
472 473 474
 * subquery_planner
 *	  Invokes the planner on a subquery.  We recurse to here for each
 *	  sub-SELECT found in the query tree.
475
 *
476
 * glob is the global state for the current planner run.
477
 * parse is the querytree produced by the parser & rewriter.
478 479
 * parent_root is the immediate parent Query's info (NULL at the top level).
 * hasRecursion is true if this is a recursive WITH query.
480
 * tuple_fraction is the fraction of tuples we expect will be retrieved.
481
 * tuple_fraction is interpreted as explained for grouping_planner, below.
482
 *
483 484
 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
 * among other things this tells the output sort ordering of the plan.
485
 *
486
 * Basically, this routine does the stuff that should only be done once
487 488 489 490 491
 * per Query object.  It then calls grouping_planner.  At one time,
 * grouping_planner could be invoked recursively on the same Query object;
 * that's not currently true, but we keep the separation between the two
 * routines anyway, in case we need it again someday.
 *
492 493
 * subquery_planner will be called recursively to handle sub-Query nodes
 * found within the query's expressions and rangetable.
494
 *
495 496
 * Returns a query plan.
 *--------------------
497
 */
498
Plan *
499
subquery_planner(PlannerGlobal *glob, Query *parse,
500
				 PlannerInfo *parent_root,
501
				 bool hasRecursion,
502 503 504
				 double tuple_fraction,
				 PlannerInfo **subroot,
				 PlannerConfig *config)
505
{
506
	int			num_old_subplans = list_length(glob->subplans);
507
	PlannerInfo *root;
508
	Plan	   *plan;
509
	List	   *newHaving;
510
	bool		hasOuterJoins;
511
	ListCell   *l;
512

513 514 515
	/* Create a PlannerInfo data structure for this subquery */
	root = makeNode(PlannerInfo);
	root->parse = parse;
516 517 518 519
	root->glob = glob;
	root->query_level = parent_root ? parent_root->query_level + 1 : 1;
	root->parent_root = parent_root;
	root->planner_cxt = CurrentMemoryContext;
520
	root->init_plans = NIL;
521
	root->cte_plan_ids = NIL;
522
	root->eq_classes = NIL;
523
	root->init_plans = NIL;
524

525 526 527 528 529
	root->list_cteplaninfo = NIL;
	if (parse->cteList != NIL)
	{
		root->list_cteplaninfo = init_list_cteplaninfo(list_length(parse->cteList));
	}
530

531
	root->append_rel_list = NIL;
532

533 534 535
	Assert(config);
	root->config = config;

536
	if (Gp_role == GP_ROLE_DISPATCH && gp_session_id > -1)
537 538
	{
		/* Choose a segdb to which our singleton gangs should be dispatched. */
539
		gp_singleton_segindex = gp_session_id % getgpsegmentCount();
540
	}
541

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
	root->hasRecursion = hasRecursion;
	if (hasRecursion)
		root->wt_param_id = SS_assign_worktable_param(root);
	else
		root->wt_param_id = -1;
	root->non_recursive_plan = NULL;

	/*
	 * If there is a WITH list, process each WITH query and build an
	 * initplan SubPlan structure for it.
	 *
	 * Unlike upstrem, we do not use initplan + CteScan, so SS_process_ctes
	 * will generate unused initplans. Commenting out the following two
	 * lines.
	 */

	/*
	if (parse->cteList)
		SS_process_ctes(root);
	 */

563 564 565 566 567
	/*
	 * Ensure that jointree has been normalized. See
	 * normalize_query_jointree_mutator()
	 */
	AssertImply(parse->jointree->fromlist, list_length(parse->jointree->fromlist) == 1);
568

569
	/* CDB: Stash current query level's relids before pulling up subqueries. */
570
	root->currlevel_relids = get_relids_in_jointree((Node *) parse->jointree, false);
571

572
	/*
573 574 575 576
	 * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
	 * to transform them into joins. Note that this step does not descend
	 * into subqueries; if we pull up any subqueries below, their SubLinks are
	 * processed just before pulling them up.
577 578
	 */
	if (parse->hasSubLinks)
579
		pull_up_sublinks(root);
580

581 582 583 584 585 586 587
	/*
	 * Scan the rangetable for set-returning functions, and inline them
	 * if possible (producing subqueries that might get pulled up next).
	 * Recursion issues here are handled in the same way as for IN clauses.
	 */
	inline_set_returning_functions(root);

588 589 590 591 592
	/*
	 * Check to see if any subqueries in the rangetable can be merged into
	 * this query.
	 */
	parse->jointree = (FromExpr *)
593
		pull_up_subqueries(root, (Node *) parse->jointree, false, false);
B
Bruce Momjian 已提交
594

595
	/*
B
Bruce Momjian 已提交
596 597
	 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
	 * avoid the expense of doing flatten_join_alias_vars().  Also check for
598 599
	 * outer joins --- if none, we can skip reduce_outer_joins().
	 * This must be done after we have done pull_up_subqueries, of course.
600
	 */
601
	root->hasJoinRTEs = false;
602
	hasOuterJoins = false;
603
	foreach(l, parse->rtable)
604
	{
605
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
606 607 608

		if (rte->rtekind == RTE_JOIN)
		{
609
			root->hasJoinRTEs = true;
610 611
			if (IS_OUTER_JOIN(rte->jointype))
			{
612
				hasOuterJoins = true;
613 614 615
				/* Can quit scanning once we find an outer join */
				break;
			}
616 617 618
		}
	}

619 620 621 622 623 624 625 626 627 628
	/*
	 * Expand any rangetable entries that are inheritance sets into "append
	 * relations".  This can add entries to the rangetable, but they must be
	 * plain base relations not joins, so it's OK (and marginally more
	 * efficient) to do it after checking for join RTEs.  We must do it after
	 * pulling up subqueries, else we'd fail to handle inherited tables in
	 * subqueries.
	 */
	expand_inherited_tables(root);

629 630 631 632
	/* CDB: If parent RTE belongs to current query level, children do too. */
	foreach(l, root->append_rel_list)
	{
		AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
633

634 635 636 637
		if (bms_is_member(appinfo->parent_relid, root->currlevel_relids))
			root->currlevel_relids = bms_add_member(root->currlevel_relids,
													appinfo->child_relid);
	}
638

639 640
	/*
	 * Set hasHavingQual to remember if HAVING clause is present.  Needed
B
Bruce Momjian 已提交
641 642
	 * because preprocess_expression will reduce a constant-true condition to
	 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
643
	 */
644
	root->hasHavingQual = (parse->havingQual != NULL);
645

646 647 648
	/* Clear this flag; might get set in distribute_qual_to_rels */
	root->hasPseudoConstantQuals = false;

649
	/*
650
	 * Do expression preprocessing on targetlist and quals.
651
	 */
652
	parse->targetList = (List *)
653
		preprocess_expression(root, (Node *) parse->targetList,
654 655
							  EXPRKIND_TARGET);

656 657 658 659
	parse->returningList = (List *)
		preprocess_expression(root, (Node *) parse->returningList,
							  EXPRKIND_TARGET);

660
	preprocess_qual_conditions(root, (Node *) parse->jointree);
661

662
	parse->havingQual = preprocess_expression(root, parse->havingQual,
663 664
											  EXPRKIND_QUAL);

665 666 667
	parse->scatterClause = (List *)
		preprocess_expression(root, (Node *) parse->scatterClause,
							  EXPRKIND_TARGET);
668 669

	/*
670
	 * Do expression preprocessing on other expressions.
671 672
	 */
	foreach(l, parse->windowClause)
673
	{
674
		WindowClause *wc = (WindowClause *) lfirst(l);
675

676 677 678 679 680
		/* partitionClause/orderClause are sort/group expressions */
		wc->startOffset = preprocess_expression(root, wc->startOffset,
												EXPRKIND_WINDOW_BOUND);
		wc->endOffset = preprocess_expression(root, wc->endOffset,
											  EXPRKIND_WINDOW_BOUND);
681 682
	}

683
	parse->limitOffset = preprocess_expression(root, parse->limitOffset,
684
											   EXPRKIND_LIMIT);
685
	parse->limitCount = preprocess_expression(root, parse->limitCount,
686 687
											  EXPRKIND_LIMIT);

688 689
	root->append_rel_list = (List *)
		preprocess_expression(root, (Node *) root->append_rel_list,
690
							  EXPRKIND_APPINFO);
691

692
	/* Also need to preprocess expressions for function and values RTEs */
693
	foreach(l, parse->rtable)
694
	{
695
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
696

697 698 699 700 701 702 703
		if (rte->rtekind == RTE_FUNCTION || rte->rtekind == RTE_TABLEFUNCTION)
			rte->funcexpr = preprocess_expression(root, rte->funcexpr,
												  EXPRKIND_RTFUNC);
		else if (rte->rtekind == RTE_VALUES)
			rte->values_lists = (List *)
				preprocess_expression(root, (Node *) rte->values_lists,
									  EXPRKIND_VALUES);
704 705
	}

706
	/*
B
Bruce Momjian 已提交
707 708 709
	 * In some cases we may want to transfer a HAVING clause into WHERE. We
	 * cannot do so if the HAVING clause contains aggregates (obviously) or
	 * volatile functions (since a HAVING clause is supposed to be executed
710 711 712 713
	 * only once per group).  Also, it may be that the clause is so expensive
	 * to execute that we're better off doing it only once per group, despite
	 * the loss of selectivity.  This is hard to estimate short of doing the
	 * entire planning process twice, so we use a heuristic: clauses
B
Bruce Momjian 已提交
714 715
	 * containing subplans are left in HAVING.	Otherwise, we move or copy the
	 * HAVING clause into WHERE, in hopes of eliminating tuples before
716 717
	 * aggregation instead of after.
	 *
718 719 720 721 722 723 724 725
	 * If the query has explicit grouping then we can simply move such a
	 * clause into WHERE; any group that fails the clause will not be in the
	 * output because none of its tuples will reach the grouping or
	 * aggregation stage.  Otherwise we must have a degenerate (variable-free)
	 * HAVING clause, which we put in WHERE so that query_planner() can use it
	 * in a gating Result node, but also keep in HAVING to ensure that we
	 * don't emit a bogus aggregated row. (This could be done better, but it
	 * seems not worth optimizing.)
726 727
	 *
	 * Note that both havingQual and parse->jointree->quals are in
B
Bruce Momjian 已提交
728 729
	 * implicitly-ANDed-list form at this point, even though they are declared
	 * as Node *.
730 731
	 */
	newHaving = NIL;
732
	foreach(l, (List *) parse->havingQual)
733
	{
734
		Node	   *havingclause = (Node *) lfirst(l);
735

736 737 738 739 740
		if (contain_agg_clause(havingclause) ||
			contain_volatile_functions(havingclause) ||
			contain_subplans(havingclause))
		{
			/* keep it in HAVING */
741
			newHaving = lappend(newHaving, havingclause);
742
		}
743
		else if (parse->groupClause &&
744
				 !contain_extended_grouping(parse->groupClause))
745 746
		{
			/* move it to WHERE */
747 748
			parse->jointree->quals = (Node *)
				lappend((List *) parse->jointree->quals, havingclause);
749 750 751 752 753 754 755 756 757
		}
		else
		{
			/* put a copy in WHERE, keep it in HAVING */
			parse->jointree->quals = (Node *)
				lappend((List *) parse->jointree->quals,
						copyObject(havingclause));
			newHaving = lappend(newHaving, havingclause);
		}
758 759 760
	}
	parse->havingQual = (Node *) newHaving;

761
	/*
B
Bruce Momjian 已提交
762 763
	 * If we have any outer joins, try to reduce them to plain inner joins.
	 * This step is most easily done after we've done expression
B
Bruce Momjian 已提交
764
	 * preprocessing.
765
	 */
766
	if (hasOuterJoins)
767
		reduce_outer_joins(root);
768

769
	/*
B
Bruce Momjian 已提交
770 771
	 * Do the main planning.  If we have an inherited target relation, that
	 * needs special processing, else go straight to grouping_planner.
772
	 */
773
	if (parse->resultRelation &&
774 775
		rt_fetch(parse->resultRelation, parse->rtable)->inh)
		plan = inheritance_planner(root);
776
	else
777
		plan = grouping_planner(root, tuple_fraction);
778 779

	/*
B
Bruce Momjian 已提交
780
	 * If any subplans were generated, or if we're inside a subplan, build
B
Bruce Momjian 已提交
781 782
	 * initPlan list and extParam/allParam sets for plan nodes, and attach the
	 * initPlans to the top plan node.
783
	 */
784
	if (list_length(glob->subplans) != num_old_subplans ||
785 786
		root->query_level > 1)
	{
787
		Assert(root->parse == parse); /* GPDB isn't always careful about this. */
788
		SS_finalize_plan(root, plan, true);
789
	}
790

791 792 793
	/* Return internal info if caller wants it */
	if (subroot)
		*subroot = root;
794

795
	return plan;
796
}
797

798 799 800 801 802 803 804
/*
 * preprocess_expression
 *		Do subquery_planner's preprocessing work for an expression,
 *		which can be a targetlist, a WHERE clause (including JOIN/ON
 *		conditions), or a HAVING clause.
 */
static Node *
805
preprocess_expression(PlannerInfo *root, Node *expr, int kind)
806
{
807
	/*
B
Bruce Momjian 已提交
808 809 810
	 * Fall out quickly if expression is empty.  This occurs often enough to
	 * be worth checking.  Note that null->null is the correct conversion for
	 * implicit-AND result format, too.
811 812 813 814
	 */
	if (expr == NULL)
		return NULL;

815 816 817
	/*
	 * If the query has any join RTEs, replace join alias variables with
	 * base-relation variables. We must do this before sublink processing,
B
Bruce Momjian 已提交
818 819 820
	 * else sublinks expanded out from join aliases wouldn't get processed. We
	 * can skip it in VALUES lists, however, since they can't contain any Vars
	 * at all.
821
	 */
822
	if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
823
		expr = flatten_join_alias_vars(root, expr);
824

825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
	if (root->parse->hasFuncsWithExecRestrictions)
	{
		if (kind == EXPRKIND_RTFUNC)
		{
			/* allowed */
		}
		else if (kind == EXPRKIND_TARGET)
		{
			/*
			 * Allowed in simple cases with no range table. For example,
			 * "SELECT func()" is allowed, but "SELECT func() FROM foo" is not.
			 */
			if (root->parse->rtable &&
				check_execute_on_functions((Node *) root->parse->targetList) != PROEXECLOCATION_ANY)
			{
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("function with EXECUTE ON restrictions cannot be used in the SELECT list of a query with FROM")));
			}
		}
		else
		{
			if (check_execute_on_functions((Node *) root->parse->targetList) != PROEXECLOCATION_ANY)
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("function with EXECUTE ON restrictions cannot be used here")));
		}
	}

854
	/*
855
	 * Simplify constant expressions.
856
	 *
857 858 859 860 861 862
	 * Note: one essential effect here is to insert the current actual values
	 * of any default arguments for functions.  To ensure that happens, we
	 * *must* process all expressions here.  Previous PG versions sometimes
	 * skipped const-simplification if it didn't seem worth the trouble, but
	 * we can't do that anymore.
	 *
863 864 865 866 867
	 * Note: this also flattens nested AND and OR expressions into N-argument
	 * form.  All processing of a qual expression after this point must be
	 * careful to maintain AND/OR flatness --- that is, do not generate a tree
	 * with AND directly under AND, nor OR directly under OR.
	 */
868
	expr = eval_const_expressions(root, expr);
869 870 871

	/*
	 * If it's a qual or havingQual, canonicalize it.
872
	 */
873
	if (kind == EXPRKIND_QUAL)
874
	{
875
		expr = (Node *) canonicalize_qual((Expr *) expr);
876 877 878 879 880 881

#ifdef OPTIMIZER_DEBUG
		printf("After canonicalize_qual()\n");
		pprint(expr);
#endif
	}
882

883
	/* Expand SubLinks to SubPlans */
884
	if (root->parse->hasSubLinks)
885
		expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
886

887
	/*
B
Bruce Momjian 已提交
888 889
	 * XXX do not insert anything here unless you have grokked the comments in
	 * SS_replace_correlation_vars ...
890 891
	 */

892
	/* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
893 894
	if (root->query_level > 1)
		expr = SS_replace_correlation_vars(root, expr);
895

896
	/*
B
Bruce Momjian 已提交
897 898 899
	 * If it's a qual or havingQual, convert it to implicit-AND format. (We
	 * don't want to do this before eval_const_expressions, since the latter
	 * would be unable to simplify a top-level AND correctly. Also,
900
	 * SS_process_sublinks expects explicit-AND format.)
901 902 903 904
	 */
	if (kind == EXPRKIND_QUAL)
		expr = (Node *) make_ands_implicit((Expr *) expr);

905 906 907 908 909 910 911 912 913
	return expr;
}

/*
 * preprocess_qual_conditions
 *		Recursively scan the query's jointree and do subquery_planner's
 *		preprocessing work on each qual condition found therein.
 */
static void
914
preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
915 916 917 918 919 920 921 922 923 924
{
	if (jtnode == NULL)
		return;
	if (IsA(jtnode, RangeTblRef))
	{
		/* nothing to do here */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
925
		ListCell   *l;
926

927
		foreach(l, f->fromlist)
928
			preprocess_qual_conditions(root, lfirst(l));
929

930
		f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
931 932 933 934
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;
935
		ListCell   *l;
936

937 938
		preprocess_qual_conditions(root, j->larg);
		preprocess_qual_conditions(root, j->rarg);
939

940 941
		foreach(l, j->subqfromlist)
			preprocess_qual_conditions(root, lfirst(l));
942

943
		j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
944 945
	}
	else
946 947
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
948
}
949

950
/*
951 952 953 954
 * inheritance_planner
 *	  Generate a plan in the case where the result relation is an
 *	  inheritance set.
 *
955 956 957 958 959 960 961 962 963
 * We have to handle this case differently from cases where a source relation
 * is an inheritance set. Source inheritance is expanded at the bottom of the
 * plan tree (see allpaths.c), but target inheritance has to be expanded at
 * the top.  The reason is that for UPDATE, each target relation needs a
 * different targetlist matching its own column set.  Also, for both UPDATE
 * and DELETE, the executor needs the Append plan node at the top, else it
 * can't keep track of which table is the current target table.  Fortunately,
 * the UPDATE/DELETE target can never be the nullable side of an outer join,
 * so it's OK to generate the plan this way.
964 965 966 967
 *
 * Returns a query plan.
 */
static Plan *
968
inheritance_planner(PlannerInfo *root)
969
{
970
	Query	   *parse = root->parse;
971
	Index		parentRTindex = parse->resultRelation;
972
	List	   *subplans = NIL;
973 974
	List	   *resultRelations = NIL;
	List	   *returningLists = NIL;
975
	List	   *tlist = NIL;
976
	PlannerInfo subroot;
977
	ListCell   *l;
978

979
	/* MPP */
980
	Plan	   *plan;
981
	CdbLocusType append_locustype = CdbLocusType_Null;
982
	bool		locus_ok = TRUE;
983

984
	foreach(l, root->append_rel_list)
985
	{
986
		AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
B
Bruce Momjian 已提交
987
		Plan	   *subplan;
988

989 990 991 992
		/* append_rel_list contains all append rels; ignore others */
		if (appinfo->parent_relid != parentRTindex)
			continue;

993
		/*
994
		 * Generate modified query with this rel as target.
995 996 997
		 */
		memcpy(&subroot, root, sizeof(PlannerInfo));
		subroot.parse = (Query *)
998
			adjust_appendrel_attrs(&subroot, (Node *) parse,
999
								   appinfo);
1000 1001
		subroot.returningLists = NIL;
		subroot.init_plans = NIL;
1002
		/* We needn't modify the child's append_rel_list */
1003
		/* There shouldn't be any OJ info to translate, as yet */
1004
		Assert(subroot.join_info_list == NIL);
1005 1006
		/* and we haven't created PlaceHolderInfos, either */
		Assert(subroot.placeholder_list == NIL);
1007

1008
		/* Generate plan */
1009 1010
		subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );

1011
		/*
B
Bruce Momjian 已提交
1012 1013
		 * If this child rel was excluded by constraint exclusion, exclude it
		 * from the plan.
1014 1015 1016
		 *
		 * MPP-1544: perform this check before testing for loci compatibility
		 * we might have inserted a dummy table with incorrect locus
1017 1018 1019
		 */
		if (is_dummy_plan(subplan))
			continue;
1020

1021
		/* MPP needs target loci to match. */
1022
		if (Gp_role == GP_ROLE_DISPATCH)
1023
		{
1024 1025 1026 1027
			CdbLocusType locustype = (subplan->flow == NULL) ?
			CdbLocusType_Null : subplan->flow->locustype;

			if (append_locustype == CdbLocusType_Null && locus_ok)
1028 1029 1030 1031 1032
			{
				append_locustype = locustype;
			}
			else
			{
1033
				switch (locustype)
1034
				{
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
					case CdbLocusType_Entry:
						locus_ok = locus_ok && (locustype == append_locustype);
						break;
					case CdbLocusType_Hashed:
					case CdbLocusType_HashedOJ:
					case CdbLocusType_Strewn:
						/* MPP-2023: Among subplans, these loci are okay. */
						break;
					case CdbLocusType_Null:
					case CdbLocusType_SingleQE:
					case CdbLocusType_General:
					case CdbLocusType_Replicated:
						/* These loci are not valid on base relations */
						locus_ok = FALSE;
						break;
					default:
						/* We should not be hitting this */
						locus_ok = FALSE;
						Assert(0);
						break;
1055 1056
				}
			}
1057
			if (!locus_ok)
1058 1059
			{
				ereport(ERROR, (
1060 1061
								errcode(ERRCODE_CDB_INTERNAL_ERROR),
					 errmsg("incompatible loci in target inheritance set")));
1062 1063
			}
		}
B
Bruce Momjian 已提交
1064

1065
		/* Save tlist from first rel for use below */
1066 1067
		if (subplans == NIL)
		{
1068
			tlist = subplan->targetlist;
1069 1070
		}

1071 1072 1073 1074 1075 1076
		/**
		 * The grouping planner scribbles on the rtable e.g. to add pseudo columns.
		 * We need to keep track of this.
		 */
		parse->rtable = subroot.parse->rtable;

1077 1078
		subplans = lappend(subplans, subplan);

1079 1080 1081
		/* Make sure any initplans from this rel get into the outer list */
		root->init_plans = list_concat(root->init_plans, subroot.init_plans);

1082
		/* Build target-relations list for the executor */
1083 1084 1085 1086 1087
		resultRelations = lappend_int(resultRelations, appinfo->child_relid);

		/* Build list of per-relation RETURNING targetlists */
		if (parse->returningList)
		{
1088
			Assert(list_length(subroot.returningLists) == 1);
1089
			returningLists = list_concat(returningLists,
1090
										 subroot.returningLists);
1091
		}
1092 1093
	}

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
	/**
	 * If due to constraint exclusions all the result relations have been removed,
	 * we need something upstream.
	 */
	if (resultRelations)
	{
		root->resultRelations = resultRelations;
	}
	else
	{
		root->resultRelations = list_make1_int(parse->resultRelation);
	}
	
	root->returningLists = returningLists;
1108

1109 1110 1111 1112 1113 1114 1115
	/* Mark result as unordered (probably unnecessary) */
	root->query_pathkeys = NIL;

	/*
	 * If we managed to exclude every child rel, return a dummy plan
	 */
	if (subplans == NIL)
1116 1117 1118 1119
	{
		root->resultRelations = list_make1_int(parentRTindex);
		/* although dummy, it must have a valid tlist for executor */
		tlist = preprocess_targetlist(root, parse->targetList);
1120
		plan = (Plan *) make_result(root,
1121
									tlist,
1122 1123 1124
									(Node *) list_make1(makeBoolConst(false,
																	  false)),
									NULL);
1125 1126 1127 1128 1129

		if (Gp_role == GP_ROLE_DISPATCH)
			mark_plan_general(plan);

		return plan;
1130
	}
1131

1132 1133
	/* Suppress Append if there's only one surviving child rel */
	if (list_length(subplans) == 1)
1134 1135
		plan = (Plan *) linitial(subplans);
	else
1136
	{
1137
		plan = (Plan *) make_append(subplans, true, tlist);
1138

1139
		/* MPP dispatch needs to know the kind of locus. */
1140
		if (Gp_role == GP_ROLE_DISPATCH)
1141
		{
1142
			switch (append_locustype)
1143 1144 1145 1146
			{
				case CdbLocusType_Entry:
					mark_plan_entry(plan);
					break;
1147

1148 1149 1150 1151
				case CdbLocusType_Hashed:
				case CdbLocusType_HashedOJ:
				case CdbLocusType_Strewn:
					/* Depend on caller to avoid incompatible hash keys. */
1152 1153 1154 1155 1156

					/*
					 * For our purpose (UPD/DEL target), strewn is good
					 * enough.
					 */
1157 1158 1159 1160 1161 1162
					mark_plan_strewn(plan);
					break;

				default:
					ereport(ERROR,
							(errcode(ERRCODE_CDB_INTERNAL_ERROR),
1163
							 errmsg("unexpected locus assigned to target inheritance set")));
1164
			}
1165 1166 1167 1168 1169 1170 1171 1172 1173
		}
	}

	return plan;
}

#ifdef USE_ASSERT_CHECKING

static void grouping_planner_output_asserts(PlannerInfo *root, Plan *plan);
1174

1175 1176 1177
/**
 * Ensure goodness of plans returned by grouping planner
 */
1178 1179
void
grouping_planner_output_asserts(PlannerInfo *root, Plan *plan)
1180
{
1181 1182 1183 1184 1185 1186
	/*
	 * Ensure that plan refers to vars that have varlevelsup = 0 AND varno is
	 * in the rtable
	 */
	List	   *allVars = extract_nodes(root->glob, (Node *) plan, T_Var);
	ListCell   *lc = NULL;
1187

1188
	foreach(lc, allVars)
1189
	{
1190 1191
		Var		   *var = (Var *) lfirst(lc);

1192 1193
		Assert(var->varlevelsup == 0 && "Plan contains vars that refer to outer plan.");
		Assert((var->varno == OUTER
1194 1195
		|| (var->varno > 0 && var->varno <= list_length(root->parse->rtable)))
			   && "Plan contains var that refer outside the rtable.");
1196 1197 1198 1199 1200 1201
		Assert(var->varno == var->varnoold && "Varno and varnoold do not agree!");

		/** If a pseudo column, there should be a corresponding entry in the relation */
		if (var->varattno <= FirstLowInvalidHeapAttributeNumber)
		{
			RangeTblEntry *rte = rt_fetch(var->varno, root->parse->rtable);
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
			Assert(rte);
			Assert(rte->pseudocols);
			Assert(list_length(rte->pseudocols) > var->varattno - FirstLowInvalidHeapAttributeNumber);
		}
	}
}
#endif

/*
 * getAnySubplan
1213
 *	 Return one subplan for the given node.
1214 1215 1216 1217 1218 1219 1220 1221
 *
 * If the given node is an Append, the first subplan is returned.
 * If the given node is a SubqueryScan, its subplan is returned.
 * Otherwise, the lefttree of the given node is returned.
 */
static Plan *
getAnySubplan(Plan *node)
{
1222 1223
	Assert(is_plan_node((Node *) node));

1224 1225
	if (IsA(node, Append))
	{
1226 1227
		Append	   *append = (Append *) node;

1228
		Assert(list_length(append->appendplans) > 0);
1229
		return (Plan *) linitial(append->appendplans);
1230
	}
1231

1232 1233
	else if (IsA(node, SubqueryScan))
	{
1234 1235
		SubqueryScan *subqueryScan = (SubqueryScan *) node;

1236 1237
		return subqueryScan->subplan;
	}
1238

1239
	return node->lefttree;
1240 1241 1242 1243 1244 1245 1246
}

/*--------------------
 * grouping_planner
 *	  Perform planning steps related to grouping, aggregation, etc.
 *	  This primarily means adding top-level processing to the basic
 *	  query plan produced by query_planner.
1247 1248 1249 1250
 *
 * tuple_fraction is the fraction of tuples we expect will be retrieved
 *
 * tuple_fraction is interpreted as follows:
1251
 *	  0: expect all tuples to be retrieved (normal case)
1252 1253 1254 1255 1256
 *	  0 < tuple_fraction < 1: expect the given fraction of tuples available
 *		from the plan to be retrieved
 *	  tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
 *		expected to be retrieved (ie, a LIMIT specification)
 *
1257
 * Returns a query plan.  Also, root->query_pathkeys is returned as the
1258
 * actual output ordering of the plan (in pathkey format).
1259 1260
 *--------------------
 */
1261
static Plan *
1262
grouping_planner(PlannerInfo *root, double tuple_fraction)
1263
{
1264
	Query	   *parse = root->parse;
1265
	List	   *tlist = parse->targetList;
B
Bruce Momjian 已提交
1266 1267
	int64		offset_est = 0;
	int64		count_est = 0;
1268
	double		limit_tuples = -1.0;
1269
	Plan	   *result_plan;
1270 1271
	List	   *current_pathkeys = NIL;
	CdbPathLocus current_locus;
1272
	List	   *sort_pathkeys;
1273
	Path	   *best_path = NULL;
1274
	double		dNumGroups = 0;
1275 1276 1277
	double		numDistinct = 1;
	List	   *distinctExprs = NIL;

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
	double		motion_cost_per_row =
	(gp_motion_cost_per_row > 0.0) ?
	gp_motion_cost_per_row :
	2.0 * cpu_tuple_cost;

	CdbPathLocus_MakeNull(&current_locus);

	/* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
	if (parse->limitCount || parse->limitOffset)
	{
		tuple_fraction = preprocess_limit(root, tuple_fraction,
										  &offset_est, &count_est);
1290

1291
		/*
B
Bruce Momjian 已提交
1292 1293
		 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
		 * estimate the effects of using a bounded sort.
1294 1295 1296 1297
		 */
		if (count_est > 0 && offset_est >= 0)
			limit_tuples = (double) count_est + (double) offset_est;
	}
1298

1299
	if (parse->setOperations)
B
Bruce Momjian 已提交
1300
	{
B
Bruce Momjian 已提交
1301
		List	   *set_sortclauses;
1302

1303
		/*
B
Bruce Momjian 已提交
1304 1305 1306 1307 1308
		 * If there's a top-level ORDER BY, assume we have to fetch all the
		 * tuples.	This might seem too simplistic given all the hackery below
		 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
		 * of use to plan_set_operations() when the setop is UNION ALL, and
		 * the result of UNION ALL is always unsorted.
1309 1310 1311 1312
		 */
		if (parse->sortClause)
			tuple_fraction = 0.0;

1313
		/*
B
Bruce Momjian 已提交
1314
		 * Construct the plan for set operations.  The result will not need
1315 1316 1317
		 * any work except perhaps a top-level sort and/or LIMIT.  Note that
		 * any special work for recursive unions is the responsibility of
		 * plan_set_operations.
1318
		 */
1319
		result_plan = plan_set_operations(root, tuple_fraction,
1320 1321 1322
										  &set_sortclauses);

		/*
B
Bruce Momjian 已提交
1323 1324 1325
		 * Calculate pathkeys representing the sort order (if any) of the set
		 * operation's result.  We have to do this before overwriting the sort
		 * key information...
1326
		 */
1327 1328
		current_pathkeys = make_pathkeys_for_sortclauses(root,
														 set_sortclauses,
B
Bruce Momjian 已提交
1329
													 result_plan->targetlist,
1330
														 true);
1331 1332

		/*
B
Bruce Momjian 已提交
1333 1334 1335 1336 1337
		 * We should not need to call preprocess_targetlist, since we must be
		 * in a SELECT query node.	Instead, use the targetlist returned by
		 * plan_set_operations (since this tells whether it returned any
		 * resjunk columns!), and transfer any sort key information from the
		 * original tlist.
1338 1339
		 */
		Assert(parse->commandType == CMD_SELECT);
1340

1341 1342
		tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);

1343
		/*
1344
		 * Can't handle FOR UPDATE/SHARE here (parser should have checked
B
Bruce Momjian 已提交
1345
		 * already, but let's make sure).
1346 1347
		 */
		if (parse->rowMarks)
1348 1349
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1350
					 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1351

1352
		/*
1353
		 * Calculate pathkeys that represent result ordering requirements
1354
		 */
1355 1356 1357 1358
		sort_pathkeys = make_pathkeys_for_sortclauses(root,
													  parse->sortClause,
													  tlist,
													  true);
B
Bruce Momjian 已提交
1359
	}
1360
	else if ( parse->windowClause && parse->targetList &&
1361
			  contain_window_function((Node *) parse->targetList) )
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	{
		if (extract_nodes(NULL, (Node *) tlist, T_PercentileExpr) != NIL)
		{
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("window function with WITHIN GROUP aggregate is not supported")));
		}
		/*
		 * Calculate pathkeys that represent ordering requirements. Stash
		 * them in PlannerInfo so that query_planner can canonicalize them.
		 */
		root->group_pathkeys = NIL;
		root->sort_pathkeys =
1375
			make_pathkeys_for_sortclauses(root, parse->sortClause, tlist, true);
1376 1377 1378

		
		result_plan = window_planner(root, tuple_fraction, &current_pathkeys);
1379 1380 1381 1382

		/*
		 * Recover sort pathkeys for use later.  These may or may not match
		 * the current_pathkeys resulting from the window plan.
1383
		 */
1384
		sort_pathkeys = make_pathkeys_for_sortclauses(root, parse->sortClause,
1385
											  result_plan->targetlist, true);
1386 1387
		sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
	}
1388
	else
1389
	{
1390
		/* No set operations, do regular planning */
B
Bruce Momjian 已提交
1391
		List	   *sub_tlist;
1392 1393
		List	   *group_pathkeys;
		AttrNumber *groupColIdx = NULL;
1394
		Oid		   *groupOperators = NULL;
1395
		bool		need_tlist_eval = true;
1396
		QualCost	tlist_cost;
1397 1398
		Path	   *cheapest_path;
		Path	   *sorted_path;
1399
		long		numGroups = 0;
1400
		AggClauseCounts agg_counts;
1401
		int			numGroupCols = list_length(parse->groupClause);
1402
		bool		use_hashed_grouping = false;
1403
		bool		grpext = false;
1404 1405
		bool		has_within = false;
		CanonicalGroupingSets *canonical_grpsets;
1406

1407 1408 1409 1410 1411
		MemSet(&agg_counts, 0, sizeof(AggClauseCounts));

		/* A recursive query should always have setOperations */
		Assert(!root->hasRecursion);

1412
		/* Preprocess targetlist */
1413
		tlist = preprocess_targetlist(root, tlist);
B
Bruce Momjian 已提交
1414

1415 1416 1417
		/* Obtain canonical grouping sets */
		canonical_grpsets = make_canonical_groupingsets(parse->groupClause);
		numGroupCols = canonical_grpsets->num_distcols;
1418

1419
		/*
1420 1421
		 * Clean up parse->groupClause if the grouping set is an empty
		 * set.
1422
		 */
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
		if (numGroupCols == 0)
		{
			list_free(parse->groupClause);
			parse->groupClause = NIL;
		}

		grpext = is_grouping_extension(canonical_grpsets);
		has_within = extract_nodes(NULL, (Node *) tlist, T_PercentileExpr) != NIL;
		has_within |= extract_nodes(NULL, parse->havingQual, T_PercentileExpr) != NIL;

		if (grpext && has_within)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("WITHIN GROUP aggregate cannot be used in GROUPING SETS query")));
1437

1438
		/*
1439 1440
		 * Calculate pathkeys that represent grouping/ordering requirements.
		 * Stash them in PlannerInfo so that query_planner can canonicalize
1441
		 * them after EquivalenceClasses have been formed.
1442
		 */
1443
		root->group_pathkeys =
1444
			make_pathkeys_for_groupclause(root,
1445
										  parse->groupClause,
1446
										  tlist);
1447
		root->sort_pathkeys =
1448 1449 1450 1451
			make_pathkeys_for_sortclauses(root,
										  parse->sortClause,
										  tlist,
										  false);
1452

1453 1454
		/*
		 * Will need actual number of aggregates for estimating costs.
1455
		 *
B
Bruce Momjian 已提交
1456 1457
		 * Note: we do not attempt to detect duplicate aggregates here; a
		 * somewhat-overestimated count is okay for our present purposes.
1458
		 *
1459 1460
		 * Note: think not that we can turn off hasAggs if we find no aggs. It
		 * is possible for constant-expression simplification to remove all
B
Bruce Momjian 已提交
1461 1462
		 * explicit references to aggs, but we still have to follow the
		 * aggregate semantics (eg, producing only one output row).
1463
		 */
1464 1465
		MemSet(&agg_counts, 0, sizeof(AggClauseCounts));

1466
		if (parse->hasAggs)
1467 1468 1469 1470
		{
			count_agg_clauses((Node *) tlist, &agg_counts);
			count_agg_clauses(parse->havingQual, &agg_counts);
		}
1471

1472 1473 1474 1475 1476
		/*
		 * Generate appropriate target list for subplan; may be different from
		 * tlist if grouping or aggregation is needed.
		 */
		sub_tlist = make_subplanTargetList(root, tlist,
1477 1478
										   &groupColIdx, &groupOperators,
										   &need_tlist_eval);
1479 1480 1481 1482 1483 1484

		/*
		 * Augment the subplan target list to include targets for ordered
		 * aggregates.  As a side effect, this may scribble updated sort group
		 * ref values into AggOrder nodes within Aggref nodes of the query.  A
		 * pity, but it would harder to do this earlier.
1485
		 */
1486 1487
		sub_tlist = register_ordered_aggs(tlist,
										  root->parse->havingQual,
1488 1489
										  sub_tlist);

1490 1491 1492
		/*
		 * Figure out whether we need a sorted result from query_planner.
		 *
B
Bruce Momjian 已提交
1493 1494 1495 1496 1497 1498
		 * If we have a GROUP BY clause, then we want a result sorted properly
		 * for grouping.  Otherwise, if there is an ORDER BY clause, we want
		 * to sort by the ORDER BY clause.	(Note: if we have both, and ORDER
		 * BY is a superset of GROUP BY, it would be tempting to request sort
		 * by ORDER BY --- but that might just leave us failing to exploit an
		 * available sort order at all. Needs more thought...)
1499 1500
		 */
		if (parse->groupClause)
1501
			root->query_pathkeys = root->group_pathkeys;
1502
		else if (parse->sortClause)
1503
			root->query_pathkeys = root->sort_pathkeys;
1504
		else
1505
			root->query_pathkeys = NIL;
1506

1507
		/*
B
Bruce Momjian 已提交
1508 1509 1510 1511
		 * Generate the best unsorted and presorted paths for this Query (but
		 * note there may not be any presorted path).  query_planner will also
		 * estimate the number of groups in the query, and canonicalize all
		 * the pathkeys.
1512
		 */
1513
		query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
1514
					  &cheapest_path, &sorted_path, &dNumGroups);
1515

1516 1517
		group_pathkeys = root->group_pathkeys;
		sort_pathkeys = root->sort_pathkeys;
1518

1519
		/*
1520 1521
		 * If grouping, extract the grouping operators and decide whether we
		 * want to use hashed grouping.
1522
		 */
1523
		if (parse->groupClause)
1524
		{
1525
			use_hashed_grouping =
1526
				choose_hashed_grouping(root, tuple_fraction, limit_tuples,
1527
									   cheapest_path, sorted_path,
1528
									groupOperators, numGroupCols, dNumGroups,
1529
									   &agg_counts);
1530 1531 1532

			/* Also convert # groups to long int --- but 'ware overflow! */
			numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1533 1534
		}

B
Bruce Momjian 已提交
1535
		/*
1536
		 * Select the best path.  If we are doing hashed grouping, we will
B
Bruce Momjian 已提交
1537 1538
		 * always read all the input tuples, so use the cheapest-total path.
		 * Otherwise, trust query_planner's decision about which to use.
1539
		 */
1540
		if (use_hashed_grouping || !sorted_path)
1541
			best_path = cheapest_path;
1542
		else
1543 1544
			best_path = sorted_path;

1545 1546 1547 1548
		/*
		 * CDB:  For now, we either - construct a general parallel plan, - let
		 * the sequential planner handle the situation, or - construct a
		 * sequential plan using the mix-max index optimization.
1549 1550 1551
		 *
		 * Eventually we should add a parallel version of the min-max
		 * optimization.  For now, it's either-or.
1552
		 */
1553
		if (Gp_role == GP_ROLE_DISPATCH)
1554
		{
1555 1556
			bool		querynode_changed = false;
			bool		pass_subtlist = false;
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
			GroupContext group_context;

			pass_subtlist = (agg_counts.aggOrder != NIL || has_within);
			group_context.best_path = best_path;
			group_context.cheapest_path = cheapest_path;
			group_context.subplan = NULL;
			group_context.sub_tlist = pass_subtlist ? sub_tlist : NIL;
			group_context.tlist = tlist;
			group_context.use_hashed_grouping = use_hashed_grouping;
			group_context.tuple_fraction = tuple_fraction;
			group_context.canonical_grpsets = canonical_grpsets;
			group_context.grouping = 0;
			group_context.numGroupCols = 0;
			group_context.groupColIdx = NULL;
1571
			group_context.groupOperators = NULL;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
			group_context.numDistinctCols = 0;
			group_context.distinctColIdx = NULL;
			group_context.p_dNumGroups = &dNumGroups;
			group_context.pcurrent_pathkeys = &current_pathkeys;
			group_context.querynode_changed = &querynode_changed;

			/* within_agg_planner calls cdb_grouping_planner */
			if (has_within)
				result_plan = within_agg_planner(root,
												 &agg_counts,
												 &group_context);
			else
				result_plan = cdb_grouping_planner(root,
												   &agg_counts,
												   &group_context);

			/* Add the Repeat node if needed. */
			if (result_plan != NULL &&
				canonical_grpsets != NULL &&
				canonical_grpsets->grpset_counts != NULL)
			{
1593 1594 1595 1596
				bool		need_repeat_node = false;
				int			grpset_no;
				int			repeat_count = 0;

1597 1598 1599 1600 1601 1602 1603 1604
				for (grpset_no = 0; grpset_no < canonical_grpsets->ngrpsets; grpset_no++)
				{
					if (canonical_grpsets->grpset_counts[grpset_no] > 1)
					{
						need_repeat_node = true;
						break;
					}
				}
1605

1606 1607
				if (canonical_grpsets->ngrpsets == 1)
					repeat_count = canonical_grpsets->grpset_counts[0];
1608

1609 1610 1611 1612 1613 1614
				if (need_repeat_node)
				{
					result_plan = add_repeat_node(result_plan, repeat_count, 0);
				}
			}

1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
			if (result_plan != NULL && querynode_changed)
			{
				/*
				 * We want to re-write sort_pathkeys here since the 2-stage
				 * aggregation subplan or grouping extension subplan may
				 * change the previous root->parse Query node, which makes the
				 * current sort_pathkeys invalid.
				 */
				sort_pathkeys = make_pathkeys_for_sortclauses(root, parse->sortClause,
											  result_plan->targetlist, true);
1625 1626 1627
				sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
			}
		}
1628
		else	/* Not GP_ROLE_DISPATCH */
1629 1630
		{
			/*
1631 1632 1633 1634
			 * Check to see if it's possible to optimize MIN/MAX aggregates.
			 * If so, we will forget all the work we did so far to choose a
			 * "regular" path ... but we had to do it anyway to be able to
			 * tell which way is cheaper.
1635
			 */
1636 1637 1638 1639 1640 1641
			result_plan = optimize_minmax_aggregates(root,
													 tlist,
													 best_path);
			if (result_plan != NULL)
			{
				/*
1642 1643
				 * optimize_minmax_aggregates generated the full plan, with
				 * the right tlist, and it has no sort order.
1644 1645
				 */
				current_pathkeys = NIL;
1646
				mark_plan_entry(result_plan);
1647 1648
			}

1649
		}
1650

1651
		if (result_plan == NULL)
1652
		{
1653
			/*
1654 1655
			 * Normal case --- create a plan according to query_planner's
			 * results.
1656
			 */
1657
			bool		need_sort_for_grouping = false;
1658

1659
			result_plan = create_plan(root, best_path);
1660
			current_pathkeys = best_path->pathkeys;
1661
			current_locus = best_path->locus;	/* just use keys, don't copy */
1662

1663 1664 1665 1666 1667
			/* Detect if we'll need an explicit sort for grouping */
			if (parse->groupClause && !use_hashed_grouping &&
				!pathkeys_contained_in(group_pathkeys, current_pathkeys))
			{
				need_sort_for_grouping = true;
1668

1669 1670 1671 1672 1673 1674 1675
				/*
				 * Always override query_planner's tlist, so that we don't
				 * sort useless data from a "physical" tlist.
				 */
				need_tlist_eval = true;
			}

1676 1677 1678 1679 1680 1681 1682 1683
			/*
			 * create_plan() returns a plan with just a "flat" tlist of
			 * required Vars.  Usually we need to insert the sub_tlist as the
			 * tlist of the top plan node.	However, we can skip that if we
			 * determined that whatever query_planner chose to return will be
			 * good enough.
			 */
			if (need_tlist_eval)
1684
			{
1685 1686 1687 1688 1689
				/*
				 * If the top-level plan node is one that cannot do expression
				 * evaluation, we must insert a Result node to project the
				 * desired tlist.
				 */
1690
				result_plan = plan_pushdown_tlist(root, result_plan, sub_tlist);
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710

				/*
				 * Also, account for the cost of evaluation of the sub_tlist.
				 *
				 * Up to now, we have only been dealing with "flat" tlists,
				 * containing just Vars.  So their evaluation cost is zero
				 * according to the model used by cost_qual_eval() (or if you
				 * prefer, the cost is factored into cpu_tuple_cost).  Thus we
				 * can avoid accounting for tlist cost throughout
				 * query_planner() and subroutines.  But now we've inserted a
				 * tlist that might contain actual operators, sub-selects, etc
				 * --- so we'd better account for its cost.
				 *
				 * Below this point, any tlist eval cost for added-on nodes
				 * should be accounted for as we create those nodes.
				 * Presently, of the node types we can add on, only Agg and
				 * Group project new tlists (the rest just copy their input
				 * tuples) --- so make_agg() and make_group() are responsible
				 * for computing the added cost.
				 */
1711
				cost_qual_eval(&tlist_cost, sub_tlist, root);
1712 1713 1714
				result_plan->startup_cost += tlist_cost.startup;
				result_plan->total_cost += tlist_cost.startup +
					tlist_cost.per_tuple * result_plan->plan_rows;
1715 1716 1717 1718
			}
			else
			{
				/*
1719 1720 1721
				 * Since we're using query_planner's tlist and not the one
				 * make_subplanTargetList calculated, we have to refigure any
				 * grouping-column indexes make_subplanTargetList computed.
1722
				 */
1723
				locate_grouping_columns(root, tlist, result_plan->targetlist,
1724
										groupColIdx);
1725
			}
B
Bruce Momjian 已提交
1726

1727
			Assert(result_plan->flow);
1728

1729
			/*
1730 1731
			 * Insert AGG or GROUP node if needed, plus an explicit sort step
			 * if necessary.
1732
			 *
1733
			 * HAVING clause, if any, becomes qual of the Agg or Group node.
1734
			 */
1735
			if (!grpext && use_hashed_grouping)
1736 1737
			{
				/* Hashed aggregate plan --- no sort needed */
1738
				result_plan = (Plan *) make_agg(root,
1739 1740
												tlist,
												(List *) parse->havingQual,
1741
												AGG_HASHED, false,
1742 1743
												numGroupCols,
												groupColIdx,
1744
												groupOperators,
1745
												numGroups,
1746 1747 1748 1749
												0, /* num_nullcols */
												0, /* input_grouping */
												0, /* grouping */
												0, /* rollup_gs_times */
1750
												agg_counts.numAggs,
1751
												agg_counts.transitionSpace,
1752
												result_plan);
1753 1754 1755 1756 1757

				if (canonical_grpsets != NULL &&
					canonical_grpsets->grpset_counts != NULL &&
					canonical_grpsets->grpset_counts[0] > 1)
				{
1758
					result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
1759
					result_plan = add_repeat_node(result_plan,
1760
										 canonical_grpsets->grpset_counts[0],
1761 1762 1763
												  0);
				}

1764 1765
				/* Hashed aggregation produces randomly-ordered results */
				current_pathkeys = NIL;
1766
				CdbPathLocus_MakeNull(&current_locus);
1767
			}
1768
			else if (!grpext && (parse->hasAggs || parse->groupClause))
1769
			{
1770 1771
				/* Plain aggregate plan --- sort if needed */
				AggStrategy aggstrategy;
1772

1773 1774
				if (parse->groupClause)
				{
1775
					if (need_sort_for_grouping)
1776
					{
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
						result_plan = (Plan *)
							make_sort_from_groupcols(root,
													 parse->groupClause,
													 groupColIdx,
													 false,
													 result_plan);
						current_pathkeys = group_pathkeys;

						/* Decorate the Sort node with a Flow node. */
						mark_sort_locus(result_plan);
1787
					}
1788
					aggstrategy = AGG_SORTED;
1789

1790
					/*
1791 1792
					 * The AGG node will not change the sort ordering of its
					 * groups, so current_pathkeys describes the result too.
1793 1794 1795 1796
					 */
				}
				else
				{
1797 1798 1799 1800
					aggstrategy = AGG_PLAIN;
					/* Result will be only one row anyway; no sort order */
					current_pathkeys = NIL;
				}
1801

1802 1803 1804 1805 1806 1807 1808 1809 1810
				/*
				 * We make a single Agg node if this is not a grouping extension.
				 */
				result_plan = (Plan *) make_agg(root,
												tlist,
												(List *) parse->havingQual,
												aggstrategy, false,
												numGroupCols,
												groupColIdx,
1811
												groupOperators,
1812 1813 1814 1815 1816 1817 1818 1819
												numGroups,
												0, /* num_nullcols */
												0, /* input_grouping */
												0, /* grouping */
												0, /* rollup_gs_times */
												agg_counts.numAggs,
												agg_counts.transitionSpace,
												result_plan);
1820

1821 1822 1823 1824
				if (canonical_grpsets != NULL &&
					canonical_grpsets->grpset_counts != NULL &&
					canonical_grpsets->grpset_counts[0] > 1)
				{
1825
					result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
1826
					result_plan = add_repeat_node(result_plan,
1827
										 canonical_grpsets->grpset_counts[0],
1828 1829
												  0);
				}
1830

1831 1832 1833 1834 1835
				CdbPathLocus_MakeNull(&current_locus);
			}
			else if (grpext && (parse->hasAggs || parse->groupClause))
			{
				/* Plan the grouping extension */
1836 1837
				ListCell   *lc;
				bool		querynode_changed = false;
B
Bruce Momjian 已提交
1838

1839 1840 1841
				/*
				 * Make a copy of tlist. Really need to?
				 */
1842
				List	   *new_tlist = copyObject(tlist);
1843

1844 1845 1846
				/* Make EXPLAIN output look nice */
				foreach(lc, result_plan->targetlist)
				{
1847
					TargetEntry *tle = (TargetEntry *) lfirst(lc);
1848

1849
					if (IsA(tle->expr, Var) &&tle->resname == NULL)
1850
					{
1851
						TargetEntry *vartle = tlist_member((Node *) tle->expr, tlist);
1852

1853
						if (vartle != NULL && vartle->resname != NULL)
1854
							tle->resname = pstrdup(vartle->resname);
1855 1856
					}
				}
1857 1858 1859 1860 1861 1862 1863 1864

				result_plan = plan_grouping_extension(root, best_path, tuple_fraction,
													  use_hashed_grouping,
													  &new_tlist, result_plan->targetlist,
													  true, false,
													  (List *) parse->havingQual,
													  &numGroupCols,
													  &groupColIdx,
1865
													  &groupOperators,
1866 1867 1868 1869 1870 1871 1872 1873
													  &agg_counts,
													  canonical_grpsets,
													  &dNumGroups,
													  &querynode_changed,
													  &current_pathkeys,
													  result_plan);
				if (querynode_changed)
				{
1874 1875 1876 1877 1878
					/*
					 * We want to re-write sort_pathkeys here since the
					 * 2-stage aggregation subplan or grouping extension
					 * subplan may change the previous root->parse Query node,
					 * which makes the current sort_pathkeys invalid.
1879
					 */
1880
					sort_pathkeys = make_pathkeys_for_sortclauses(root, parse->sortClause,
1881
											  result_plan->targetlist, true);
1882 1883 1884
					sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
					CdbPathLocus_MakeNull(&current_locus);
				}
1885
			}
1886
			else if (root->hasHavingQual)
1887
			{
1888 1889 1890 1891 1892
				/*
				 * No aggregates, and no GROUP BY, but we have a HAVING qual.
				 * This is a degenerate case in which we are supposed to emit
				 * either 0 or 1 row depending on whether HAVING succeeds.
				 * Furthermore, there cannot be any variables in either HAVING
B
Bruce Momjian 已提交
1893 1894 1895 1896 1897 1898
				 * or the targetlist, so we actually do not need the FROM
				 * table at all!  We can just throw away the plan-so-far and
				 * generate a Result node.	This is a sufficiently unusual
				 * corner case that it's not worth contorting the structure of
				 * this routine to avoid having to generate the plan in the
				 * first place.
1899
				 */
1900 1901
				result_plan = (Plan *) make_result(root,
												   tlist,
1902 1903
												   parse->havingQual,
												   NULL);
1904 1905 1906 1907
				/* Result will be only one row anyway; no sort order */
				current_pathkeys = NIL;
				mark_plan_general(result_plan);
				CdbPathLocus_MakeNull(&current_locus);
1908
			}
1909
		}						/* end of non-minmax-aggregate case */
1910 1911 1912

		/* free canonical_grpsets */
		free_canonical_groupingsets(canonical_grpsets);
B
Bruce Momjian 已提交
1913
	}							/* end of if (setOperations) */
1914

1915 1916 1917 1918 1919 1920
	/*
	 * Decorate the top node with a Flow node if it doesn't have one yet. (In
	 * such cases we require the next-to-top node to have a Flow node from
	 * which we can obtain the distribution info.)
	 */
	if (!result_plan->flow)
1921
		result_plan->flow = pull_up_Flow(result_plan, getAnySubplan(result_plan));
1922

1923
	/*
1924
	 * MPP: If there's a DISTINCT clause and we're not collocated on the
1925 1926 1927 1928 1929 1930 1931
	 * distinct key, we need to redistribute on that key.  In addition, we
	 * need to consider whether to "pre-unique" by doing a Sort-Unique
	 * operation on the data as currently distributed, redistributing on the
	 * district key, and doing the Sort-Unique again. This 2-phase approach
	 * will be a win, if the cost of redistributing the entire input exceeds
	 * the cost of an extra Redistribute-Sort-Unique on the pre-uniqued
	 * (reduced) input.
1932
	 */
1933
	if (parse->distinctClause != NULL)
1934
	{
1935
		distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1936
												result_plan->targetlist);
1937
		numDistinct = estimate_num_groups(root, distinctExprs,
1938
										  result_plan->plan_rows);
1939 1940

		if (CdbPathLocus_IsNull(current_locus))
1941 1942 1943
		{
			current_locus = cdbpathlocus_from_flow(result_plan->flow);
		}
1944 1945

		if (Gp_role == GP_ROLE_DISPATCH && CdbPathLocus_IsPartitioned(current_locus))
1946
		{
1947 1948 1949 1950
			List	   *distinct_pathkeys = make_pathkeys_for_sortclauses(root, parse->distinctClause,
											  result_plan->targetlist, true);
			bool		needMotion = !cdbpathlocus_collocates(root, current_locus, distinct_pathkeys, false /* exact_match */ );

1951
			/* Apply the preunique optimization, if enabled and worthwhile. */
1952
			if (root->config->gp_enable_preunique && needMotion)
1953
			{
1954 1955 1956 1957
				double		base_cost,
							alt_cost;
				Path		sort_path;	/* dummy for result of cost_sort */

1958 1959
				base_cost = motion_cost_per_row * result_plan->plan_rows;
				alt_cost = motion_cost_per_row * numDistinct;
1960
				cost_sort(&sort_path, root, NIL, alt_cost,
1961
						  numDistinct, result_plan->plan_rows, -1.0);
1962
				alt_cost += sort_path.startup_cost;
1963 1964 1965 1966
				alt_cost += cpu_operator_cost * numDistinct
					* list_length(parse->distinctClause);

				if (alt_cost < base_cost || root->config->gp_eager_preunique)
1967
				{
1968 1969 1970 1971
					/*
					 * Reduce the number of rows to move by adding a [Sort
					 * and] Unique prior to the redistribute Motion.
					 */
1972 1973 1974 1975 1976
					if (parse->sortClause)
					{
						if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
						{
							result_plan = (Plan *)
1977 1978 1979 1980
								make_sort_from_sortclauses(root,
														   parse->sortClause,
														   result_plan);
							((Sort *) result_plan)->noduplicates = gp_enable_sort_distinct;
1981 1982 1983 1984 1985 1986 1987
							current_pathkeys = sort_pathkeys;
							mark_sort_locus(result_plan);
						}
					}

					result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);

1988
					result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
1989 1990 1991 1992

					result_plan->plan_rows = numDistinct;

					/*
1993 1994 1995 1996 1997
					 * Our sort node (under the unique node), unfortunately
					 * can't guarantee uniqueness -- so we aren't allowed to
					 * push the limit into the sort; but we can avoid moving
					 * the entire sorted result-set by plunking a limit on the
					 * top of the unique-node.
1998 1999 2000 2001 2002
					 */
					if (parse->limitCount)
					{
						/*
						 * Our extra limit operation is basically a
2003 2004
						 * third-phase on multi-phase limit (see 2-phase limit
						 * below)
2005 2006 2007 2008 2009 2010
						 */
						result_plan = pushdown_preliminary_limit(result_plan, parse->limitCount, count_est, parse->limitOffset, offset_est);
					}
				}
			}

2011
			if (needMotion)
2012
			{
2013
				result_plan = (Plan *) make_motion_hash(root, result_plan, distinctExprs);
2014
				result_plan->total_cost += motion_cost_per_row * result_plan->plan_rows;
2015 2016
				current_pathkeys = NULL;		/* Any pre-existing order now
												 * lost. */
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
			}
		}
		else if ( result_plan->flow->flotype == FLOW_SINGLETON )
			; /* Already collocated. */
		else
		{
			ereport(ERROR, (errcode(ERRCODE_CDB_INTERNAL_ERROR),
							errmsg("unexpected input locus to distinct")));
		}
	}

2028
	/*
B
Bruce Momjian 已提交
2029
	 * If we were not able to make the plan come out in the right order, add
2030 2031
	 * an explicit sort step.  Note that, if we going to add a Unique node,
	 * the sort_pathkeys will have the distinct keys as a prefix.
2032
	 */
2033
	if (parse->sortClause)
2034
	{
2035
		if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
2036
		{
2037 2038
			result_plan = (Plan *) make_sort_from_pathkeys(root,
														   result_plan,
2039
														   sort_pathkeys,
2040
														limit_tuples, false);
2041 2042
			if (result_plan == NULL)
				elog(ERROR, "could not find sort pathkeys in result target list");
2043
			current_pathkeys = sort_pathkeys;
2044
			mark_sort_locus(result_plan);
2045
		}
2046 2047

		/*
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
		 * An ORDER BY doesn't make much sense, unless we bring all the data
		 * to a single node. Otherwise it's just a partial order. (If there's
		 * a LIMIT or OFFSET clause, we'll take care of this below, after
		 * inserting the Limit node).
		 *
		 * In a subquery, though, a partial order is OK. In fact, we could
		 * probably not bother with the sort at all, unless there's a LIMIT
		 * or OFFSET, because it's not going to make any difference to the
		 * overall query's result. For example, in "WHERE x IN (SELECT ...
		 * ORDER BY foo)", the ORDER BY in the subquery will make no
		 * difference. PostgreSQL honors the sort, though, and historically,
		 * GPDB has also done a partial sort, separately on each node. So
		 * keep that behavior for now.
		 *
		 * In a TABLE function's input subquery, a partial order is the
		 * documented behavior, so in that case that's definitely what we
		 * want.
2065
		 */
2066 2067 2068 2069 2070 2071 2072 2073
		if (result_plan->flow->flotype != FLOW_SINGLETON &&
			(root->config->honor_order_by || !root->parent_root) &&
			!parse->isTableValueSelect &&
			!parse->limitCount && !parse->limitOffset)
		{
			result_plan = (Plan *) make_motion_gather(root, result_plan, -1,
													  sort_pathkeys);
		}
2074
	}
2075 2076

	/*
2077
	 * If there is a DISTINCT clause, add the UNIQUE node.
2078
	 */
2079
	if (parse->distinctClause)
2080
	{
2081 2082
		if (IsA(result_plan, Sort) &&gp_enable_sort_distinct)
			((Sort *) result_plan)->noduplicates = true;
2083
		result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
2084
		result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
B
Bruce Momjian 已提交
2085

2086
		/*
B
Bruce Momjian 已提交
2087 2088 2089
		 * If there was grouping or aggregation, leave plan_rows as-is (ie,
		 * assume the result was already mostly unique).  If not, use the
		 * number of distinct-groups calculated by query_planner.
2090
		 */
2091
		if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
2092
			result_plan->plan_rows = dNumGroups;
2093
	}
2094

2095 2096 2097
	/*
	 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
	 */
2098
	if (parse->limitCount || parse->limitOffset)
2099
	{
2100 2101 2102 2103 2104 2105
		if (Gp_role == GP_ROLE_DISPATCH && result_plan->flow->flotype == FLOW_PARTITIONED)
		{
			/* pushdown the first phase of multi-phase limit (which takes offset into account) */
			result_plan = pushdown_preliminary_limit(result_plan, parse->limitCount, count_est, parse->limitOffset, offset_est);
			
			/* Focus on QE [merge to preserve order], prior to final LIMIT. */
2106
			result_plan = (Plan *) make_motion_gather_to_QE(root, result_plan, current_pathkeys);
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
			result_plan->total_cost += motion_cost_per_row * result_plan->plan_rows;
		}
			
		if (current_pathkeys == NIL)
		{
			/* This used to be a WARNING.  If reinstated, it should be a NOTICE
			 * and steps taken to avoid issuing it at inopportune times, e.g.,
			 * from the query generated by psql tab-completion.
			 */
			ereport(DEBUG1, (errmsg("LIMIT/OFFSET applied to unordered result.") ));
		}

2119
		/* For multi-phase limit, this is the final limit */
2120
		result_plan = (Plan *) make_limit(result_plan,
2121
										  parse->limitOffset,
2122 2123 2124
										  parse->limitCount,
										  offset_est,
										  count_est);
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
		result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
	}

	/*
	 * Deal with explicit redistribution requirements for TableValueExpr
	 * subplans with explicit distribitution
	 */
	if (parse->scatterClause)
	{
		bool		r;
		List	   *exprList;

		/* Deal with the special case of SCATTER RANDOMLY */
		if (list_length(parse->scatterClause) == 1 && linitial(parse->scatterClause) == NULL)
			exprList = NIL;
		else
			exprList = parse->scatterClause;

		/*
		 * Repartition the subquery plan based on our distribution
		 * requirements
		 */
		r = repartitionPlan(result_plan, false, false, exprList);
		if (!r)
		{
			/*
			 * This should not be possible, repartitionPlan should never fail
			 * when both stable and rescannable are false.
			 */
			elog(ERROR, "failure repartitioning plan");
		}
2156 2157
	}

2158
	Insist(result_plan->flow);
2159

2160 2161
	/*
	 * Deal with the RETURNING clause if any.  It's convenient to pass the
B
Bruce Momjian 已提交
2162 2163
	 * returningList through setrefs.c now rather than at top level (if we
	 * waited, handling inherited UPDATE/DELETE would be much harder).
2164 2165 2166
	 */
	if (parse->returningList)
	{
B
Bruce Momjian 已提交
2167
		List	   *rlist;
2168

2169 2170 2171
		Assert(parse->resultRelation);
		rlist = set_returning_clause_references(root->glob,
												parse->returningList,
2172
												result_plan,
2173
												parse->resultRelation);
2174
		root->returningLists = list_make1(rlist);
2175
	}
2176 2177
	else
		root->returningLists = NIL;
2178

2179 2180 2181 2182 2183
	/* Compute result-relations list if needed */
	if (parse->resultRelation)
		root->resultRelations = list_make1_int(parse->resultRelation);
	else
		root->resultRelations = NIL;
2184

2185
	/*
B
Bruce Momjian 已提交
2186 2187
	 * Return the actual output ordering in query_pathkeys for possible use by
	 * an outer query level.
2188
	 */
2189
	root->query_pathkeys = current_pathkeys;
2190

2191 2192 2193 2194
#ifdef USE_ASSERT_CHECKING
	grouping_planner_output_asserts(root, result_plan);
#endif

2195
	return result_plan;
2196 2197
}

2198
/*
2199 2200
 * Entry is through is_dummy_plan().
 *
2201 2202 2203
 * Detect whether a plan node is a "dummy" plan created when a relation
 * is deemed not to need scanning due to constraint exclusion.
 *
2204 2205 2206 2207 2208 2209
 * At bottom, such dummy plans are Result nodes with constant FALSE
 * filter quals.  However, we also recognize simple plans that are
 * known to return no rows because they contain a dummy.
 *
 * BTW The plan_tree_walker framework is overkill here, but it's good to 
 *     do things the standard way.
2210 2211
 */
static bool
2212
is_dummy_plan_walker(Node *node, bool *context)
2213
{
2214 2215 2216
	/*
	 * We are only interested in Plan nodes.
	 */
2217
	if (node == NULL || !is_plan_node(node))
2218
		return false;
2219

2220
	switch (nodeTag(node))
2221
	{
2222
		case T_Result:
2223

2224
			/*
2225 2226
			 * This tests the base case of a dummy plan which is a Result node
			 * with a constant FALSE filter quals.  (This is the case
2227 2228 2229 2230
			 * constructed as an empty Append path by set_plain_rel_pathlist
			 * in allpaths.c and made into a Result plan by create_append_plan
			 * in createplan.c.
			 */
2231
			{
2232 2233 2234
				List	   *rcqual = (List *) ((Result *) node)->resconstantqual;

				if (list_length(rcqual) == 1)
2235
				{
2236 2237 2238 2239 2240 2241 2242 2243 2244
					Const	   *constqual = (Const *) linitial(rcqual);

					if (constqual && IsA(constqual, Const))
					{
						if (!constqual->constisnull &&
							!DatumGetBool(constqual->constvalue))
							*context = true;
						return true;
					}
2245 2246 2247
				}
			}
			return false;
2248

2249
		case T_SubqueryScan:
2250 2251

			/*
2252 2253 2254
			 * A SubqueryScan is dummy, if its subplan is dummy.
			 */
			{
2255 2256 2257 2258 2259 2260 2261 2262 2263
				SubqueryScan *subqueryscan = (SubqueryScan *) node;
				Plan	   *subplan = subqueryscan->subplan;

				if (is_dummy_plan(subplan))
				{
					*context = true;
					return true;
				}
			}
2264
			return false;
2265

2266 2267 2268
		case T_NestLoop:
		case T_MergeJoin:
		case T_HashJoin:
2269

2270
			/*
2271
			 * Joins with dummy inner and/or outer plans are dummy or not
2272 2273 2274
			 * based on the type of join.
			 */
			{
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
				switch (((Join *) node)->jointype)
				{
					case JOIN_INNER:	/* either */
						*context = is_dummy_plan(innerPlan(node))
							|| is_dummy_plan(outerPlan(node));
						break;

					case JOIN_LEFT:
					case JOIN_FULL:
					case JOIN_RIGHT:	/* both */
						*context = is_dummy_plan(innerPlan(node))
							&& is_dummy_plan(outerPlan(node));
						break;

2289
					case JOIN_SEMI:
2290
					case JOIN_LASJ_NOTIN:
E
Ekta Khanna 已提交
2291
					case JOIN_ANTI:		/* outer */
2292 2293 2294 2295 2296 2297 2298 2299
						*context = is_dummy_plan(outerPlan(node));
						break;

					default:
						break;
				}

				return true;
2300
			}
2301 2302 2303 2304 2305 2306 2307

			/*
			 * It may seem that we should check for Append or SetOp nodes with
			 * all dummy branches, but that case should not occur.  It would
			 * cause big problems elsewhere in the code.
			 */

2308 2309 2310 2311
		case T_Hash:
		case T_Material:
		case T_Sort:
		case T_Unique:
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322

			/*
			 * Some node types are dummy, if their outer plan is dummy so we
			 * just recur.
			 *
			 * We don't include "tricky" nodes like Motion that might affect
			 * plan topology, even though we know they will return no rows
			 * from a dummy.
			 */
			return plan_tree_walker(node, is_dummy_plan_walker, context);

2323
		default:
2324 2325 2326 2327 2328

			/*
			 * Other node types are "opaque" so we choose a conservative
			 * course and terminate the walk.
			 */
2329
			return true;
2330
	}
2331
	/* not reached */
2332 2333 2334
}


2335
static bool
2336 2337
is_dummy_plan(Plan *plan)
{
2338 2339 2340 2341 2342
	bool		is_dummy = false;

	is_dummy_plan_walker((Node *) plan, &is_dummy);

	return is_dummy;
2343 2344
}

2345
/*
2346
 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2347
 *
2348
 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
B
Bruce Momjian 已提交
2349
 * results back in *count_est and *offset_est.	These variables are set to
2350 2351 2352 2353 2354 2355 2356 2357
 * 0 if the corresponding clause is not present, and -1 if it's present
 * but we couldn't estimate the value for it.  (The "0" convention is OK
 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
 * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
 * usual practice of never estimating less than one row.)  These values will
 * be passed to make_limit, which see if you change this code.
 *
 * The return value is the suitably adjusted tuple_fraction to use for
B
Bruce Momjian 已提交
2358
 * planning the query.	This adjustment is not overridable, since it reflects
2359 2360
 * plan actions that grouping_planner() will certainly take, not assumptions
 * about context.
2361 2362
 */
static double
2363
preprocess_limit(PlannerInfo *root, double tuple_fraction,
B
Bruce Momjian 已提交
2364
				 int64 *offset_est, int64 *count_est)
2365 2366
{
	Query	   *parse = root->parse;
2367 2368
	Node	   *est;
	double		limit_fraction;
2369

2370 2371
	/* Should not be called unless LIMIT or OFFSET */
	Assert(parse->limitCount || parse->limitOffset);
2372 2373

	/*
2374 2375
	 * Try to obtain the clause values.  We use estimate_expression_value
	 * primarily because it can sometimes do something useful with Params.
2376
	 */
2377
	if (parse->limitCount)
2378
	{
2379
		est = estimate_expression_value(root, parse->limitCount);
2380
		if (est && IsA(est, Const))
2381
		{
2382
			if (((Const *) est)->constisnull)
2383
			{
2384
				/* NULL indicates LIMIT ALL, ie, no limit */
B
Bruce Momjian 已提交
2385
				*count_est = 0; /* treat as not present */
2386 2387 2388
			}
			else
			{
2389
				if (((Const *) est)->consttype == INT4OID)
2390 2391 2392
					*count_est = DatumGetInt32(((Const *) est)->constvalue);
				else
					*count_est = DatumGetInt64(((Const *) est)->constvalue);
2393 2394
				if (*count_est <= 0)
					*count_est = 1;		/* force to at least 1 */
2395 2396
			}
		}
2397 2398
		else
			*count_est = -1;	/* can't estimate */
2399 2400
	}
	else
2401 2402 2403
		*count_est = 0;			/* not present */

	if (parse->limitOffset)
2404
	{
2405
		est = estimate_expression_value(root, parse->limitOffset);
2406 2407 2408 2409 2410
		if (est && IsA(est, Const))
		{
			if (((Const *) est)->constisnull)
			{
				/* Treat NULL as no offset; the executor will too */
B
Bruce Momjian 已提交
2411
				*offset_est = 0;	/* treat as not present */
2412 2413 2414
			}
			else
			{
2415
				if (((Const *) est)->consttype == INT4OID)
2416 2417
					*offset_est = DatumGetInt32(((Const *) est)->constvalue);
				else
2418
					*offset_est = DatumGetInt64(((Const *) est)->constvalue);
2419

2420 2421 2422 2423 2424 2425
				if (*offset_est < 0)
					*offset_est = 0;	/* less than 0 is same as 0 */
			}
		}
		else
			*offset_est = -1;	/* can't estimate */
2426
	}
2427 2428
	else
		*offset_est = 0;		/* not present */
2429

2430
	if (*count_est != 0)
2431
	{
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
		/*
		 * A LIMIT clause limits the absolute number of tuples returned.
		 * However, if it's not a constant LIMIT then we have to guess; for
		 * lack of a better idea, assume 10% of the plan's result is wanted.
		 */
		if (*count_est < 0 || *offset_est < 0)
		{
			/* LIMIT or OFFSET is an expression ... punt ... */
			limit_fraction = 0.10;
		}
		else
		{
			/* LIMIT (plus OFFSET, if any) is max number of tuples needed */
			limit_fraction = (double) *count_est + (double) *offset_est;
		}

2448 2449
		/*
		 * If we have absolute limits from both caller and LIMIT, use the
2450 2451 2452 2453
		 * smaller value; likewise if they are both fractional.  If one is
		 * fractional and the other absolute, we can't easily determine which
		 * is smaller, but we use the heuristic that the absolute will usually
		 * be smaller.
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
		 */
		if (tuple_fraction >= 1.0)
		{
			if (limit_fraction >= 1.0)
			{
				/* both absolute */
				tuple_fraction = Min(tuple_fraction, limit_fraction);
			}
			else
			{
2464
				/* caller absolute, limit fractional; use caller's value */
2465 2466 2467 2468 2469 2470
			}
		}
		else if (tuple_fraction > 0.0)
		{
			if (limit_fraction >= 1.0)
			{
2471 2472
				/* caller fractional, limit absolute; use limit */
				tuple_fraction = limit_fraction;
2473 2474 2475 2476
			}
			else
			{
				/* both fractional */
2477
				tuple_fraction = Min(tuple_fraction, limit_fraction);
2478 2479 2480 2481 2482 2483 2484 2485
			}
		}
		else
		{
			/* no info from caller, just use limit */
			tuple_fraction = limit_fraction;
		}
	}
2486 2487 2488
	else if (*offset_est != 0 && tuple_fraction > 0.0)
	{
		/*
B
Bruce Momjian 已提交
2489 2490 2491 2492 2493
		 * We have an OFFSET but no LIMIT.	This acts entirely differently
		 * from the LIMIT case: here, we need to increase rather than decrease
		 * the caller's tuple_fraction, because the OFFSET acts to cause more
		 * tuples to be fetched instead of fewer.  This only matters if we got
		 * a tuple_fraction > 0, however.
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
		 *
		 * As above, use 10% if OFFSET is present but unestimatable.
		 */
		if (*offset_est < 0)
			limit_fraction = 0.10;
		else
			limit_fraction = (double) *offset_est;

		/*
		 * If we have absolute counts from both caller and OFFSET, add them
B
Bruce Momjian 已提交
2504 2505 2506
		 * together; likewise if they are both fractional.	If one is
		 * fractional and the other absolute, we want to take the larger, and
		 * we heuristically assume that's the fractional one.
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
		 */
		if (tuple_fraction >= 1.0)
		{
			if (limit_fraction >= 1.0)
			{
				/* both absolute, so add them together */
				tuple_fraction += limit_fraction;
			}
			else
			{
				/* caller absolute, limit fractional; use limit */
				tuple_fraction = limit_fraction;
			}
		}
		else
		{
			if (limit_fraction >= 1.0)
			{
				/* caller fractional, limit absolute; use caller's value */
			}
			else
			{
				/* both fractional, so add them together */
				tuple_fraction += limit_fraction;
				if (tuple_fraction >= 1.0)
B
Bruce Momjian 已提交
2532
					tuple_fraction = 0.0;		/* assume fetch all */
2533 2534 2535
			}
		}
	}
2536 2537 2538 2539

	return tuple_fraction;
}

2540 2541 2542
/*
 * extract_grouping_ops - make an array of the equality operator OIDs
 *		for the GROUP BY clause
2543 2544 2545 2546
 *
 * In PostgreSQL, the returned array's size is always list_length(groupClause), but
 * in GPDB's GROUPING SETS implementation, that's not true. The size of the
 * returned array is returned in *numGroupCols.
2547
 */
2548
#ifdef NOT_USED
2549
static Oid *
2550
extract_grouping_ops(List *groupClause, int *numGroupOps)
2551
{
2552
	int			maxCols = list_length(groupClause);
2553 2554 2555 2556
	int			colno = 0;
	Oid		   *groupOperators;
	ListCell   *glitem;

2557
	groupOperators = (Oid *) palloc(maxCols * sizeof(Oid));
2558 2559 2560

	foreach(glitem, groupClause)
	{
2561
		Node	   *node = lfirst(glitem);
2562 2563 2564

		if (node == NULL)
			continue;
2565

2566
		if (IsA(node, GroupClause) ||IsA(node, SortClause))
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
		{
			GroupClause *groupcl = (GroupClause *) lfirst(glitem);

			if (colno == maxCols)
			{
				maxCols *= 2;
				groupOperators = (Oid *) repalloc(groupOperators,
												  maxCols * sizeof(Oid));
			}

			groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
			if (!OidIsValid(groupOperators[colno]))		/* shouldn't happen */
				elog(ERROR, "could not find equality operator for ordering operator %u",
					 groupcl->sortop);
			colno++;
		}
		else if (IsA(node, GroupingClause))
		{
			List	   *groupsets = ((GroupingClause *) node)->groupsets;
			Oid		   *subops;
			int			nsubops;

			subops = extract_grouping_ops(groupsets, &nsubops);
			while (colno + nsubops > maxCols)
			{
				maxCols *= 2;
				groupOperators = (Oid *) repalloc(groupOperators,
												  maxCols * sizeof(Oid));
			}
			memcpy(&groupOperators[colno], subops, nsubops * sizeof(Oid));
			colno += nsubops;
		}
2599 2600
	}

2601 2602
	*numGroupOps = colno;

2603 2604
	return groupOperators;
}
2605
#endif
2606

2607 2608 2609
/*
 * choose_hashed_grouping - should we use hashed grouping?
 */
2610
bool
2611 2612
choose_hashed_grouping(PlannerInfo *root,
					   double tuple_fraction, double limit_tuples,
2613
					   Path *cheapest_path, Path *sorted_path,
2614
					   Oid *groupOperators, int numGroupOps, double dNumGroups,
2615
					   AggClauseCounts *agg_counts)
2616
{
2617
	int			numGroupCols;
2618 2619
	double		cheapest_path_rows;
	int			cheapest_path_width;
2620
	double		hashentrysize;
2621 2622 2623
	List	   *current_pathkeys;
	Path		hashed_p;
	Path		sorted_p;
2624
	int			i;
2625

2626
	HashAggTableSizes hash_info;
2627 2628 2629
	bool		has_dqa = false;
	bool		hash_cheaper = false;

2630 2631
	/*
	 * Check can't-do-it conditions, including whether the grouping operators
2632
	 * are hashjoinable.  (We assume hashing is OK if they are marked
2633
	 * oprcanhash.  If there isn't actually a supporting hash function, the
B
Bruce Momjian 已提交
2634
	 * executor will complain at runtime.)
2635 2636 2637 2638 2639
	 *
	 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
	 * (Doing so would imply storing *all* the input values in the hash table,
	 * which seems like a certain loser.)
	 *
2640 2641 2642 2643
	 * CDB: The parallel grouping planner can use hashed aggregation with
	 * DISTINCT-qualified aggregates in some cases, so in case we don't choose
	 * hashed grouping here, we make note in agg_counts to indicate whether
	 * DQAs are the only reason.
2644 2645 2646 2647
	 */
	if (!root->config->enable_hashagg)
		goto hash_not_ok;
	has_dqa = agg_counts->numDistinctAggs != 0;
2648
	for (i = 0; i < numGroupOps; i++)
2649 2650
	{
		if (!op_hashjoinable(groupOperators[i]))
2651
			goto hash_not_ok;
2652
	}
2653 2654

	/*
2655 2656 2657
	 * CDB: The preliminary function is used to merge transient values during
	 * hash reloading (see execHHashagg.c). So hash agg is not allowed if one
	 * of the aggregates doesn't have its preliminary function.
2658
	 */
2659 2660
	if (agg_counts->missing_prelimfunc)
		goto hash_not_ok;
2661

2662
	/*
2663 2664
	 * CDB: The parallel grouping planner cannot use hashed aggregation for
	 * ordered aggregates.
2665 2666 2667
	 */
	if (agg_counts->aggOrder != NIL)
		goto hash_not_ok;
2668

2669 2670 2671 2672 2673 2674 2675 2676
	/*
	 * Don't do it if it doesn't look like the hashtable will fit into
	 * work_mem.
	 *
	 * Beware here of the possibility that cheapest_path->parent is NULL. This
	 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
	 */
	if (cheapest_path->parent)
2677
	{
2678 2679 2680 2681 2682 2683 2684 2685
		cheapest_path_rows = cdbpath_rows(root, cheapest_path);
		cheapest_path_width = cheapest_path->parent->width;
	}
	else
	{
		cheapest_path_rows = 1; /* assume non-set result */
		cheapest_path_width = 100;		/* arbitrary */
	}
2686

2687
	/* Estimate per-hash-entry space at tuple width... */
2688 2689 2690
	hashentrysize = agg_hash_entrywidth(agg_counts->numAggs,
							   sizeof(HeapTupleData) + sizeof(HeapTupleHeaderData) + cheapest_path_width,
							   agg_counts->transitionSpace);
2691 2692 2693

	if (!calcHashAggTableSizes(global_work_mem(root),
							   dNumGroups,
2694
							   hashentrysize,
2695 2696 2697 2698
							   false,
							   &hash_info))
	{
		goto hash_not_ok;
2699
	}
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716

	/*
	 * See if the estimated cost is no more than doing it the other way. While
	 * avoiding the need for sorted input is usually a win, the fact that the
	 * output won't be sorted may be a loss; so we need to do an actual cost
	 * comparison.
	 *
	 * We need to consider cheapest_path + hashagg [+ final sort] versus
	 * either cheapest_path [+ sort] + group or agg [+ final sort] or
	 * presorted_path + group or agg [+ final sort] where brackets indicate a
	 * step that may not be needed. We assume query_planner() will have
	 * returned a presorted path only if it's a winner compared to
	 * cheapest_path for this purpose.
	 *
	 * These path variables are dummies that just hold cost fields; we don't
	 * make actual Paths for these steps.
	 */
2717
	numGroupCols = num_distcols_in_grouplist(root->parse->groupClause);
2718 2719 2720 2721 2722 2723 2724 2725
	cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
			 numGroupCols, dNumGroups,
			 cheapest_path->startup_cost, cheapest_path->total_cost,
			 cheapest_path_rows, hash_info.workmem_per_entry,
			 hash_info.nbatches, hash_info.hashentry_width, false);
	/* Result of hashed agg is always unsorted */
	if (root->sort_pathkeys)
		cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2726
				  dNumGroups, cheapest_path_width, limit_tuples);
2727 2728 2729 2730 2731 2732 2733 2734

	if (sorted_path)
	{
		sorted_p.startup_cost = sorted_path->startup_cost;
		sorted_p.total_cost = sorted_path->total_cost;
		current_pathkeys = sorted_path->pathkeys;
	}
	else
2735
	{
2736 2737 2738 2739 2740 2741 2742
		sorted_p.startup_cost = cheapest_path->startup_cost;
		sorted_p.total_cost = cheapest_path->total_cost;
		current_pathkeys = cheapest_path->pathkeys;
	}
	if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
	{
		cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
2743
				  cheapest_path_rows, cheapest_path_width, -1.0);
2744 2745 2746 2747 2748
		current_pathkeys = root->group_pathkeys;
	}

	if (root->parse->hasAggs)
		cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
2749
				 numGroupCols, dNumGroups,
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
				 sorted_p.startup_cost, sorted_p.total_cost,
				 cheapest_path_rows, 0.0, 0.0, 0.0, false);
	else
		cost_group(&sorted_p, root, numGroupCols, dNumGroups,
				   sorted_p.startup_cost, sorted_p.total_cost,
				   cheapest_path_rows);
	/* The Agg or Group node will preserve ordering */
	if (root->sort_pathkeys &&
		!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
		cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2760
				  dNumGroups, cheapest_path_width, limit_tuples);
2761

2762 2763 2764 2765 2766 2767
	/*
	 * Now make the decision using the top-level tuple fraction.  First we
	 * have to convert an absolute count (LIMIT) into fractional form.
	 */
	if (tuple_fraction >= 1.0)
		tuple_fraction /= dNumGroups;
2768

2769 2770 2771 2772 2773 2774
	if (!root->config->enable_groupagg)
		hash_cheaper = true;
	else
		hash_cheaper = 0 > compare_fractional_path_costs(&hashed_p, 
														 &sorted_p, 
														 tuple_fraction);
2775

2776 2777 2778 2779 2780 2781
	agg_counts->canHashAgg = true; /* costing is wrong if there are DQAs */
	return !has_dqa && hash_cheaper;

hash_not_ok:
	agg_counts->canHashAgg = false;
	return false;
2782 2783
}

2784 2785
/*---------------
 * make_subplanTargetList
2786
 *	  Generate appropriate target list when grouping is required.
2787
 *
2788 2789
 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
 * above the result of query_planner, we typically want to pass a different
2790
 * target list to query_planner than the outer plan nodes should have.
2791
 * This routine generates the correct target list for the subplan.
2792 2793 2794 2795
 *
 * The initial target list passed from the parser already contains entries
 * for all ORDER BY and GROUP BY expressions, but it will not have entries
 * for variables used only in HAVING clauses; so we need to add those
2796 2797 2798 2799
 * variables to the subplan target list.  Also, we flatten all expressions
 * except GROUP BY items into their component variables; the other expressions
 * will be computed by the inserted nodes rather than by the subplan.
 * For example, given a query like
2800 2801
 *		SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
 * we want to pass this targetlist to the subplan:
2802
 *		a,b,c,d,a+b
2803
 * where the a+b target will be used by the Sort/Group steps, and the
2804
 * other targets will be used for computing the final results.	(In the
2805
 * above example we could theoretically suppress the a and b targets and
2806 2807 2808
 * pass down only c,d,a+b, but it's not really worth the trouble to
 * eliminate simple var references from the subplan.  We will avoid doing
 * the extra computation to recompute a+b at the outer level; see
2809
 * fix_upper_expr() in setrefs.c.)
2810
 *
2811 2812 2813 2814 2815
 * If we are grouping or aggregating, *and* there are no non-Var grouping
 * expressions, then the returned tlist is effectively dummy; we do not
 * need to force it to be evaluated, because all the Vars it contains
 * should be present in the output of query_planner anyway.
 *
2816
 * 'tlist' is the query's target list.
2817
 * 'groupColIdx' receives an array of column numbers for the GROUP BY
2818
 *			expressions (if there are any) in the subplan's target list.
2819 2820
 * 'groupOperators' receives an array of equality operators corresponding
 *			the GROUP BY expressions.
2821 2822
 * 'need_tlist_eval' is set true if we really need to evaluate the
 *			result tlist.
2823
 *
2824
 * The result is the targetlist to be passed to the subplan.
2825 2826 2827
 *---------------
 */
static List *
2828
make_subplanTargetList(PlannerInfo *root,
2829
					   List *tlist,
2830
					   AttrNumber **groupColIdx,
2831
					   Oid **groupOperators,
2832
					   bool *need_tlist_eval)
2833
{
2834
	Query	   *parse = root->parse;
2835
	List	   *sub_tlist;
2836
	List	   *extravars;
2837 2838 2839 2840
	int			numCols;

	*groupColIdx = NULL;

B
Bruce Momjian 已提交
2841
	/*
2842
	 * If we're not grouping or aggregating, there's nothing to do here;
2843 2844
	 * query_planner should receive the unmodified target list.
	 */
2845
	if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
2846 2847
	{
		*need_tlist_eval = true;
2848
		return tlist;
2849
	}
2850

B
Bruce Momjian 已提交
2851
	/*
2852
	 * Otherwise, start with a "flattened" tlist (having just the vars
B
Bruce Momjian 已提交
2853 2854
	 * mentioned in the targetlist and HAVING qual --- but not upper- level
	 * Vars; they will be replaced by Params later on).
2855
	 */
2856
	sub_tlist = flatten_tlist(tlist);
2857
	extravars = pull_var_clause(parse->havingQual, true);
2858
	sub_tlist = add_to_flat_tlist(sub_tlist, extravars, false /* resjunk */);
2859
	list_free(extravars);
2860

2861 2862
	/*
	 * XXX Set need_tlist_eval to true for group queries.
2863
	 *
2864 2865 2866 2867
	 * Reason: We are doing an aggregate on top.  No matter what we do, hash
	 * or sort, we may spill.  Every unnecessary columns means useless I/O,
	 * and heap_form/deform_tuple.  It is almost always better to to the
	 * projection.
2868
	 */
2869
	if (parse->groupClause)
2870 2871
		*need_tlist_eval = true;
	else
2872
		*need_tlist_eval = false;		/* only eval if not flat tlist */
2873 2874

	/*
2875
	 * If grouping, create sub_tlist entries for all GROUP BY expressions
B
Bruce Momjian 已提交
2876 2877
	 * (GROUP BY items that are simple Vars should be in the list already),
	 * and make an array showing where the group columns are in the sub_tlist.
2878
	 */
2879 2880
	numCols = num_distcols_in_grouplist(parse->groupClause);

2881
	if (numCols > 0)
2882 2883
	{
		int			keyno = 0;
2884
		AttrNumber *grpColIdx;
2885
		Oid		   *grpOperators;
2886
		List	   *grouptles;
2887 2888 2889
		List	   *groupops;
		ListCell   *lc_tle;
		ListCell   *lc_op;
2890 2891

		grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2892
		grpOperators = (Oid *) palloc(sizeof(Oid) * numCols);
2893
		*groupColIdx = grpColIdx;
2894
		*groupOperators = grpOperators;
2895

2896 2897 2898 2899
		get_sortgroupclauses_tles(parse->groupClause, tlist,
								  &grouptles, &groupops);
		Assert(numCols == list_length(grouptles) &&
			   numCols == list_length(groupops));
2900
		forboth(lc_tle, grouptles, lc_op, groupops)
2901
		{
2902 2903
			Node	   *groupexpr;
			TargetEntry *tle;
2904 2905 2906
			TargetEntry *sub_tle = NULL;
			ListCell   *sl = NULL;

2907 2908
			tle = (TargetEntry *) lfirst(lc_tle);
			groupexpr = (Node *) tle->expr;
2909

2910 2911
			/* Find or make a matching sub_tlist entry */
			foreach(sl, sub_tlist)
2912
			{
2913
				sub_tle = (TargetEntry *) lfirst(sl);
2914 2915
				if (equal(groupexpr, sub_tle->expr)
					&& (sub_tle->ressortgroupref == 0))
2916
					break;
2917
			}
2918
			if (!sl)
2919
			{
2920
				sub_tle = makeTargetEntry((Expr *) groupexpr,
2921 2922 2923
										  list_length(sub_tlist) + 1,
										  NULL,
										  false);
2924
				sub_tlist = lappend(sub_tlist, sub_tle);
B
Bruce Momjian 已提交
2925
				*need_tlist_eval = true;		/* it's not flat anymore */
2926 2927
			}

2928 2929
			/* Set its group reference and save its resno */
			sub_tle->ressortgroupref = tle->ressortgroupref;
2930 2931 2932 2933 2934 2935 2936
			grpColIdx[keyno] = sub_tle->resno;

			grpOperators[keyno] = get_equality_op_for_ordering_op(lfirst_oid(lc_op));
			if (!OidIsValid(grpOperators[keyno]))		/* shouldn't happen */
				elog(ERROR, "could not find equality operator for ordering operator %u",
					 lfirst_oid(lc_op));
			keyno++;
2937
		}
2938
		Assert(keyno == numCols);
2939 2940 2941 2942 2943
	}

	return sub_tlist;
}

2944 2945

/*
2946
 * Function: register_ordered_aggs
2947 2948 2949 2950 2951 2952
 *
 * Update the AggOrder nodes found in Aggref nodes of the given Query
 * node for a grouping/aggregating query to refer to targets in the
 * indirectly given subplan target list.  As a side-effect, new targets
 * may be added to he subplan target list.
 *
2953
 * The idea is that Aggref nodes from the input Query node specify
2954
 * ordering expressions corresponding to sort specifications that must
2955
 * refer (via sortgroupref values as usual) to the target list of the
2956 2957 2958 2959
 * node below them in the plan.  Initially they may not, so we must find
 * or add them to the indirectly given subplan targetlist and adjust the
 * AggOrder node to match.
 *
2960 2961
 * This may scribble on the Query!	(This isn't too bad since only the
 * tleSortGroupRef fields of SortClause nodes and the corresponding
2962 2963 2964 2965
 * ressortgroupref fields of TargetEntry nodes in the AggOrder node in
 * an Aggref change, and the interpretation of the list is the same
 * afterward.)
 */
2966 2967
List *
register_ordered_aggs(List *tlist, Node *havingqual, List *sub_tlist)
2968
{
2969
	ListCell   *lc;
2970
	register_ordered_aggs_context ctx;
2971 2972 2973 2974 2975 2976

	ctx.tlist = tlist;			/* aggregating target list */
	ctx.havingqual = havingqual;	/* aggregating HAVING qual */
	ctx.sub_tlist = sub_tlist;	/* input target list */
	ctx.last_sgr = 0;			/* 0 = unassigned */

2977
	/* There may be Aggrefs in the query's target list. */
2978
	foreach(lc, ctx.tlist)
2979
	{
2980 2981 2982
		TargetEntry *tle = (TargetEntry *) lfirst(lc);

		tle->expr = (Expr *) register_ordered_aggs_mutator((Node *) tle->expr, &ctx);
2983
	}
2984

2985 2986
	/* There may be Aggrefs in the query's having clause */
	ctx.havingqual = register_ordered_aggs_mutator(ctx.havingqual, &ctx);
2987

2988 2989 2990 2991 2992 2993 2994
	return ctx.sub_tlist;
}

/*
 * Function: register_ordered_aggs_mutator
 *
 * Update the AggOrder nodes found in Aggref nodes of the given expression
2995 2996
 * to refer to targets in the context's subplan target list.  New targets
 * may be added to he subplan target list as a side effect.
2997
 */
2998 2999 3000
Node *
register_ordered_aggs_mutator(Node *node,
							  register_ordered_aggs_context * context)
3001
{
3002
	if (node == NULL)
3003
		return NULL;
3004
	if (IsA(node, Aggref))
3005
	{
3006 3007 3008
		Aggref	   *aggref = (Aggref *) node;

		if (aggref->aggorder)
3009
		{
3010
			register_AggOrder(aggref->aggorder, context);
3011 3012
		}
	}
3013 3014 3015
	return expression_tree_mutator(node,
								   register_ordered_aggs_mutator,
								   (void *) context);
3016 3017 3018 3019
}


/*
3020
 * Function register_AggOrder
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
 *
 * Find or add the sort targets in the given AggOrder node to the
 * indirectly given subplan target list.  If we add a target, give
 * it a distinct sortgroupref value.  
 * 
 * Then update the AggOrder node to refer to the subplan target list.  
 * We need to update the target node too, so the sort specification 
 * continues to refer to its target in the AggOrder.  Note, however,
 * that we need to defer these updates to the end so that we don't
 * mess up the correspondence in the AggOrder before we're done
 * using it.
 */
typedef struct agg_order_update_spec
{
	SortClause *sort;
	TargetEntry *entry;
	Index sortgroupref;
}
agg_order_update_spec;

void register_AggOrder(AggOrder *aggorder, 
					   register_ordered_aggs_context *context)
{	
	ListCell *lc;
	List *updates = NIL;
	agg_order_update_spec *update;
	
	/* In the first release, targets and orders are 1:1.  This may
	 * change, but for now ... */
	Assert( list_length(aggorder->sortTargets) == 
		    list_length(aggorder->sortClause) );
	
	foreach (lc, aggorder->sortClause)
	{
		SortClause *sort;
		TargetEntry *sort_tle;
		TargetEntry *sub_tle;
		
		sort = (SortClause *)lfirst(lc);
		Assert(IsA(sort, SortClause));
		Assert( sort->tleSortGroupRef != 0 );
		sort_tle = get_sortgroupclause_tle(sort, aggorder->sortTargets);
		
		/* Find sort expression in the given target list, ... */
		sub_tle = tlist_member((Node*)sort_tle->expr, context->sub_tlist);
		
		/* ... or add it. */
		if ( !sub_tle )
		{
			sub_tle = makeTargetEntry(copyObject(sort_tle->expr),
									  list_length(context->sub_tlist) + 1,
									  NULL,
									  false);
			/* We fill in the sortgroupref below. */
			context->sub_tlist = lappend( context->sub_tlist, sub_tle );
		}
		
		if ( sub_tle->ressortgroupref == 0 )
		{
			/* Lazy initialize next sortgroupref value. */
			if ( context->last_sgr == 0 )
			{
				ListCell *c;
				/* Targets in sub_tlist and main tlist must not conflict. */
				foreach( c, context->tlist )
				{
					TargetEntry *tle = (TargetEntry*)lfirst(c);
					if ( context->last_sgr < tle->ressortgroupref )
						context->last_sgr = tle->ressortgroupref;
				}
				
				/* Might there be non-zero SGRs in sub_tlist? Don't see
				 * how, but be safe.
				 */
				foreach( c, context->sub_tlist )
				{
					TargetEntry *tle = (TargetEntry*)lfirst(c);
					if ( context->last_sgr < tle->ressortgroupref )
						context->last_sgr = tle->ressortgroupref;
				}
			}

			sub_tle->ressortgroupref = ++context->last_sgr;
		}
		
		/* Update AggOrder to agree with the tle in the target list. */
		update = (agg_order_update_spec*)palloc(sizeof(agg_order_update_spec));
		update->sort = sort;
		update->entry = sort_tle;
		update->sortgroupref = sub_tle->ressortgroupref;
		updates = lappend(updates, update);
	}
	
	foreach (lc, updates)
	{
		update = (agg_order_update_spec*)lfirst(lc);
		
		update->sort->tleSortGroupRef = update->sortgroupref;
		update->entry->ressortgroupref = update->sortgroupref;
	}
	list_free(updates);
}


3125 3126 3127 3128 3129
/*
 * locate_grouping_columns
 *		Locate grouping columns in the tlist chosen by query_planner.
 *
 * This is only needed if we don't use the sub_tlist chosen by
B
Bruce Momjian 已提交
3130
 * make_subplanTargetList.	We have to forget the column indexes found
3131 3132 3133
 * by that routine and re-locate the grouping vars in the real sub_tlist.
 */
static void
3134
locate_grouping_columns(PlannerInfo *root,
3135 3136 3137 3138 3139
						List *tlist,
						List *sub_tlist,
						AttrNumber *groupColIdx)
{
	int			keyno = 0;
3140 3141 3142
	List	   *grouptles;
	List	   *groupops;
	ListCell   *ge;
3143 3144 3145 3146

	/*
	 * No work unless grouping.
	 */
3147
	if (!root->parse->groupClause)
3148 3149 3150 3151 3152 3153
	{
		Assert(groupColIdx == NULL);
		return;
	}
	Assert(groupColIdx != NULL);

3154 3155
	get_sortgroupclauses_tles(root->parse->groupClause, tlist,
							  &grouptles, &groupops);
3156 3157

	foreach (ge, grouptles)
3158
	{
3159 3160 3161
		TargetEntry *groupte = (TargetEntry *)lfirst(ge);
		Node	*groupexpr;

B
Bruce Momjian 已提交
3162 3163
		TargetEntry *te = NULL;
		ListCell   *sl;
3164

3165 3166
		groupexpr = (Node *) groupte->expr;

3167 3168 3169 3170 3171 3172 3173
		foreach(sl, sub_tlist)
		{
			te = (TargetEntry *) lfirst(sl);
			if (equal(groupexpr, te->expr))
				break;
		}
		if (!sl)
3174
			elog(ERROR, "failed to locate grouping columns");
3175

3176
		groupColIdx[keyno++] = te->resno;
3177 3178 3179
	}
}

3180 3181 3182 3183 3184 3185 3186
/*
 * postprocess_setop_tlist
 *	  Fix up targetlist returned by plan_set_operations().
 *
 * We need to transpose sort key info from the orig_tlist into new_tlist.
 * NOTE: this would not be good enough if we supported resjunk sort keys
 * for results of set operations --- then, we'd need to project a whole
3187
 * new tlist to evaluate the resjunk columns.  For now, just ereport if we
3188 3189 3190 3191 3192
 * find any resjunk columns in orig_tlist.
 */
static List *
postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
{
3193 3194
	ListCell   *l;
	ListCell   *orig_tlist_item = list_head(orig_tlist);
3195

3196 3197 3198 3199
	/* empty orig has no effect on info in new (MPP-2655) */
	if (orig_tlist_item == NULL)
		return new_tlist;

3200 3201 3202 3203 3204 3205
	foreach(l, new_tlist)
	{
		TargetEntry *new_tle = (TargetEntry *) lfirst(l);
		TargetEntry *orig_tle;

		/* ignore resjunk columns in setop result */
3206
		if (new_tle->resjunk)
3207 3208
			continue;

3209 3210 3211
		Assert(orig_tlist_item != NULL);
		orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
		orig_tlist_item = lnext(orig_tlist_item);
B
Bruce Momjian 已提交
3212
		if (orig_tle->resjunk)	/* should not happen */
3213
			elog(ERROR, "resjunk output columns are not implemented");
3214 3215
		Assert(new_tle->resno == orig_tle->resno);
		new_tle->ressortgroupref = orig_tle->ressortgroupref;
3216
	}
3217
	if (orig_tlist_item != NULL)
3218
		elog(ERROR, "resjunk output columns are not implemented");
3219 3220
	return new_tlist;
}
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699

/*
 * Produce the canonical form of a GROUP BY clause given the parse
 * tree form.
 *
 * The result is a CanonicalGroupingSets, which contains a list of
 * Bitmapsets.  Each Bitmapset contains the sort-group reference
 * values of the attributes in one of the grouping sets specified in
 * the GROUP BY clause.  The number of list elements is the number of
 * grouping sets specified.
 */
static CanonicalGroupingSets *
make_canonical_groupingsets(List *groupClause)
{
	CanonicalGroupingSets *canonical_grpsets = 
		(CanonicalGroupingSets *) palloc0(sizeof(CanonicalGroupingSets));
	ListCell *lc;
	List *ord_grping = NIL; /* the ordinary grouping */
	List *rollups = NIL;    /* the grouping sets from ROLLUP */
	List *grpingsets = NIL; /* the grouping sets from GROUPING SETS */
	List *cubes = NIL;      /* the grouping sets from CUBE */
	Bitmapset *bms = NULL;
	List *final_grpingsets = NIL;
	List *list_grpingsets = NIL;
	int setno;
	int prev_setno = 0;

	if (groupClause == NIL)
		return canonical_grpsets;

	foreach (lc, groupClause)
	{
		GroupingClause *gc;

		Node *node = lfirst(lc);

		if (node == NULL)
			continue;

		/* Note that the top-level empty sets have been removed
		 * in the parser.
		 */
		Assert(IsA(node, GroupClause) ||
			   IsA(node, GroupingClause) ||
			   IsA(node, List));

		if (IsA(node, GroupClause) ||
			IsA(node, List))
		{
			ord_grping = lappend(ord_grping,
								 canonicalize_colref_list(node));
			continue;
		}

		gc = (GroupingClause *)node;
		switch (gc->groupType)
		{
			case GROUPINGTYPE_ROLLUP:
				rollups = lappend(rollups,
								  rollup_gs_list(canonicalize_gs_list(gc->groupsets, true)));
				break;
			case GROUPINGTYPE_CUBE:
				cubes = lappend(cubes,
								cube_gs_list(canonicalize_gs_list(gc->groupsets, true)));
				break;
			case GROUPINGTYPE_GROUPING_SETS:
				grpingsets = lappend(grpingsets,
									 canonicalize_gs_list(gc->groupsets, false));
				break;
			default:
				elog(ERROR, "invalid grouping set");
		}
	}

	/* Obtain the cartesian product of grouping sets generated for ordinary
	 * grouping sets, rollups, cubes, and grouping sets.
	 *
	 * We apply a small optimization here. We always append grouping sets
	 * generated for rollups, cubes and grouping sets to grouping sets for
	 * ordinary sets. This makes it easier to tell if there is a partial
	 * rollup. Consider the example of GROUP BY rollup(i,j),k. There are
	 * three grouping sets for rollup(i,j): (i,j), (i), (). If we append
	 * k after each grouping set for rollups, we get three sets:
	 * (i,j,k), (i,k) and (k). We can not easily tell that this is a partial
	 * rollup. However, if we append each grouping set after k, we get
	 * these three sets: (k,i,j), (k,i), (k), which is obviously a partial
	 * rollup.
	 */

	/* First, we bring all columns in ordinary grouping sets together into
	 * one list.
	 */
	foreach (lc, ord_grping)
	{
	    Bitmapset *sub_bms = (Bitmapset *)lfirst(lc);
		bms = bms_add_members(bms, sub_bms);
	}

	final_grpingsets = lappend(final_grpingsets, bms);

	/* Make the list of grouping sets */
	if (rollups)
		list_grpingsets = list_concat(list_grpingsets, rollups);
	if (cubes)
		list_grpingsets = list_concat(list_grpingsets, cubes);
	if (grpingsets)
		list_grpingsets = list_concat(list_grpingsets, grpingsets);

	/* Obtain the cartesian product of grouping sets generated from ordinary
	 * grouping sets, rollups, cubes, and grouping sets.
	 */
	foreach (lc, list_grpingsets)
	{
		List *bms_list = (List *)lfirst(lc);
		ListCell *tmp_lc;
		List *tmp_list;

		tmp_list = final_grpingsets;
		final_grpingsets = NIL;

		foreach (tmp_lc, tmp_list)
		{
			Bitmapset *tmp_bms = (Bitmapset *)lfirst(tmp_lc);
			ListCell *bms_lc;

			foreach (bms_lc, bms_list)
			{
				bms = bms_copy(tmp_bms);
				bms = bms_add_members(bms, (Bitmapset *)lfirst(bms_lc));
				final_grpingsets = lappend(final_grpingsets, bms);
			}
		}
	}

	/* Sort final_grpingsets */
	sort_canonical_gs_list(final_grpingsets,
						   &(canonical_grpsets->ngrpsets),
						   &(canonical_grpsets->grpsets));

	/* Combine duplicate grouping sets and set the counts for
	 * each grouping set.
	 */
	canonical_grpsets->grpset_counts =
		(int *)palloc0(canonical_grpsets->ngrpsets * sizeof(int));
	prev_setno = 0;
	canonical_grpsets->grpset_counts[0] = 1;
	for (setno = 1; setno<canonical_grpsets->ngrpsets; setno++)
	{
		if (bms_equal(canonical_grpsets->grpsets[setno],
					  canonical_grpsets->grpsets[prev_setno]))
		{
			canonical_grpsets->grpset_counts[prev_setno]++;
			if (canonical_grpsets->grpsets[setno])
				pfree(canonical_grpsets->grpsets[setno]);
		}

		else
		{
			prev_setno++;
			canonical_grpsets->grpsets[prev_setno] =
				canonical_grpsets->grpsets[setno];
			canonical_grpsets->grpset_counts[prev_setno]++;
		}
	}
	/* Reset ngrpsets to eliminate duplicate groupint sets */
	canonical_grpsets->ngrpsets = prev_setno + 1;

	/* Obtain the number of distinct columns appeared in these
	 * grouping sets.
	 */
	{
		Bitmapset *distcols = NULL;
		for (setno =0; setno < canonical_grpsets->ngrpsets; setno++)
			distcols =
				bms_add_members(distcols, canonical_grpsets->grpsets[setno]);
		
		canonical_grpsets->num_distcols = bms_num_members(distcols);
		bms_free(distcols);
	}
	

	/* Release spaces */
	list_free_deep(ord_grping);
	list_free_deep(list_grpingsets);
	list_free(final_grpingsets);
	
	return canonical_grpsets;
}

/* Produce the canonical representation of a column reference list.
 *
 * A column reference list (in SQL) is a comma-delimited list of
 * column references which are represented by the parser as a
 * List of GroupClauses.  No nesting is allowed in column reference 
 * lists.
 *
 * As a convenience, this function also recognizes a bare column
 * reference.
 *
 * The result is a Bitmapset of the sort-group-ref values in the list.
 */
static Bitmapset* canonicalize_colref_list(Node * node)
{
	ListCell *lc;
	GroupClause *gc;
	Bitmapset* gs = NULL;
	
	if ( node == NULL )
		elog(ERROR,"invalid column reference list");
	
	if ( IsA(node, GroupClause) )
	{
		gc = (GroupClause*)node;
		return bms_make_singleton(gc->tleSortGroupRef);
	}
	
	if ( !IsA(node, List) )
		elog(ERROR,"invalid column reference list");
	
	foreach (lc, (List*)node)
	{
		Node *cr = lfirst(lc);
		
		if ( cr == NULL )
			continue;
			
		if ( !IsA(cr, GroupClause) )
			elog(ERROR,"invalid column reference list");

		gc = (GroupClause*)cr;
		gs = bms_add_member(gs, gc->tleSortGroupRef);	
	}
	return gs;
}

/* Produce the list of canonical grouping sets corresponding to a
 * grouping set list or an ordinary grouping set list.
 * 
 * An ordinary grouping set list (in SQL) is a comma-delimited list 
 * of ordinary grouping sets.  
 * 
 * Each ordinary grouping set is either a grouping column reference 
 * or a parenthesized list of grouping column references.  No nesting 
 * is allowed.  
 *
 * A grouping set list (in SQL) is a comma-delimited list of grouping 
 * sets.  
 *
 * Each grouping set is either an ordinary grouping set, a rollup list, 
 * a cube list, the empty grouping set, or (recursively) a grouping set 
 * list.
 *
 * The parse tree form of an ordinary grouping set is a  list containing
 * GroupClauses and lists of GroupClauses (without nesting).  In the case
 * of a (general) grouping set, the parse tree list may also include
 * NULLs and GroupingClauses.
 *
 * The result is a list of bit map sets.
 */
static List *canonicalize_gs_list(List *gsl, bool ordinary)
{
	ListCell *lc;
	List *list = NIL;

	foreach (lc, gsl)
	{
		Node *node = lfirst(lc);

		if ( node == NULL )
		{
			if ( ordinary )
				elog(ERROR,"invalid ordinary grouping set");
			
			list = lappend(list, NIL); /* empty grouping set */
		}
		else if ( IsA(node, GroupClause) || IsA(node, List) )
		{
			/* ordinary grouping set */
			list = lappend(list, canonicalize_colref_list(node));
		}
		else if ( IsA(node, GroupingClause) )
		{	
			List *gs = NIL;
			GroupingClause *gc = (GroupingClause*)node;
			
			if ( ordinary )
				elog(ERROR,"invalid ordinary grouping set");
				
			switch ( gc->groupType )
			{
				case GROUPINGTYPE_ROLLUP:
					gs = rollup_gs_list(canonicalize_gs_list(gc->groupsets, true));
					break;
				case GROUPINGTYPE_CUBE:
					gs = cube_gs_list(canonicalize_gs_list(gc->groupsets, true));
					break;
				case GROUPINGTYPE_GROUPING_SETS:
					gs = canonicalize_gs_list(gc->groupsets, false);
					break;
				default:
					elog(ERROR,"invalid grouping set");
			}
			list = list_concat(list,gs);
		}
		else
		{
			elog(ERROR,"invalid grouping set list");
		}
	}
	return list;
}

/* Produce the list of N+1 canonical grouping sets corresponding
 * to the rollup of the given list of N canonical grouping sets.
 * These N+1 grouping sets are listed in the descending order
 * based on the number of columns.
 *
 * Argument and result are both a list of bit map sets.
 */
static List *rollup_gs_list(List *gsl)
{
	ListCell *lc;
	Bitmapset **bms;
	int i, n = list_length(gsl);
	
	if ( n == 0 )
		elog(ERROR,"invalid grouping ordinary grouping set list");
	
	if ( n > 1 )
	{
		/* Reverse the elements in gsl */
		List *new_gsl = NIL;
		foreach (lc, gsl)
		{
			new_gsl = lcons(lfirst(lc), new_gsl);
		}
		list_free(gsl);
		gsl = new_gsl;

		bms = (Bitmapset**)palloc(n*sizeof(Bitmapset*));
		i = 0;
		foreach (lc, gsl)
		{
			bms[i++] = (Bitmapset*)lfirst(lc);
		}
		for ( i = n-2; i >= 0; i-- )
		{
			bms[i] = bms_add_members(bms[i], bms[i+1]);
		}
		pfree(bms);
	}

	return lappend(gsl, NULL);
}

/* Subroutine for cube_gs_list. */
static List *add_gs_combinations(List *list, int n, int i,
								 Bitmapset **base, Bitmapset **work)
{
	if ( i < n )
	{
		work[i] = base[i];
		list = add_gs_combinations(list, n, i+1, base, work);
		work[i] = NULL;
		list = add_gs_combinations(list, n, i+1, base, work);	
	}
	else
	{
		Bitmapset *gs = NULL;
		int j;
		for ( j = 0; j < n; j++ )
		{
			gs = bms_add_members(gs, work[j]);
		}
		list = lappend(list,gs);
	}
	return list;
}

/* Produce the list of 2^N canonical grouping sets corresponding
 * to the cube of the given list of N canonical grouping sets.
 *
 * We could do this more efficiently, but the number of grouping
 * sets should be small, so don't bother.
 *
 * Argument and result are both a list of bit map sets.
 */
static List *cube_gs_list(List *gsl)
{
	ListCell *lc;
	Bitmapset **bms_base;
	Bitmapset **bms_work;
	int i, n = list_length(gsl);
	
	if ( n == 0 )
		elog(ERROR,"invalid grouping ordinary grouping set list");
	
	bms_base = (Bitmapset**)palloc(n*sizeof(Bitmapset*));
	bms_work = (Bitmapset**)palloc(n*sizeof(Bitmapset*));
	i = 0;
	foreach (lc, gsl)
	{
		bms_work[i] = NULL;
		bms_base[i++] = (Bitmapset*)lfirst(lc);
	}

	return add_gs_combinations(NIL, n, 0, bms_base, bms_work);
}

/* Subroutine for sort_canonical_gs_list. */
static int gs_compare(const void *a, const void*b)
{
	/* Put the larger grouping sets before smaller ones. */
	return (0-bms_compare(*(Bitmapset**)a, *(Bitmapset**)b));
}

/* Produce a sorted array of Bitmapsets from the given list of Bitmapsets in
 * descending order.
 */
static void sort_canonical_gs_list(List *gs, int *p_nsets, Bitmapset ***p_sets)
{
	ListCell *lc;
	int nsets = list_length(gs);
	Bitmapset **sets = palloc(nsets*sizeof(Bitmapset*));
	int i = 0;
	
	foreach (lc, gs)
	{
		sets[i++] =  (Bitmapset*)lfirst(lc);
	}
	
	qsort(sets, nsets, sizeof(Bitmapset*), gs_compare);
	
	Assert( p_nsets != NULL && p_sets != NULL );
	
	*p_nsets = nsets;
	*p_sets = sets;
}

/*
 * In any plan where we are doing multi-phase limit, the first phase needs
 * to take the offset into account.
 */
static Plan *
pushdown_preliminary_limit(Plan *plan, Node *limitCount, int64 count_est, Node *limitOffset, int64 offset_est)
{
	Node *precount = copyObject(limitCount);
	int64 precount_est = count_est;
	Plan *result_plan = plan;

	/*
	 * If we've specified an offset *and* a limit, we need to collect
	 * from tuples from 0 -> count + offset
	 *
	 * add offset to each QEs requested contribution. 
	 * ( MPP-1370: Do it even if no ORDER BY was specified) 
	 */	
	if (precount && limitOffset)
	{
		precount = (Node*)make_op(NULL,
								  list_make1(makeString(pstrdup("+"))),
								  copyObject(limitOffset),
								  precount,
								  -1);
		precount_est += offset_est;
	}
			
	if (precount != NULL)
	{
		/*
		 * Add a prelimary LIMIT on the partitioned results. This may
		 * reduce the amount of work done on the QEs.
		 */
		result_plan = (Plan *) make_limit(result_plan,
										  NULL,
										  precount,
										  0,
										  precount_est);

3700
		result_plan->flow = pull_up_Flow(result_plan, result_plan->lefttree);
3701 3702 3703 3704
	}

	return result_plan;
}
3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740


/*
 * isSimplyUpdatableQuery -
 *  determine whether a query is a simply updatable scan of a relation
 *
 * A query is simply updatable if, and only if, it...
 * - has no window clauses
 * - has no sort clauses
 * - has no grouping, having, distinct clauses, or simple aggregates
 * - has no subqueries
 * - has no LIMIT/OFFSET
 * - references only one range table (i.e. no joins, self-joins)
 *   - this range table must itself be updatable
 */
static bool
isSimplyUpdatableQuery(Query *query)
{
	if (query->commandType == CMD_SELECT &&
		query->windowClause == NIL &&
		query->sortClause == NIL &&
		query->groupClause == NIL &&
		query->havingQual == NULL &&
		query->distinctClause == NIL &&
		!query->hasAggs &&
		!query->hasSubLinks &&
		query->limitCount == NULL &&
		query->limitOffset == NULL &&
		list_length(query->rtable) == 1)
	{
		RangeTblEntry *rte = (RangeTblEntry *) linitial(query->rtable);
		if (isSimplyUpdatableRelation(rte->relid, true))
			return true;
	}
	return false;
}