planner.c 108.1 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * planner.c
4
 *	  The query optimizer external interface.
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  src/backend/optimizer/plan/planner.c
12 13 14
 *
 *-------------------------------------------------------------------------
 */
M
Marc G. Fournier 已提交
15

16 17
#include "postgres.h"

18 19
#include <limits.h>

20
#include "access/htup_details.h"
21
#include "executor/executor.h"
22
#include "executor/nodeAgg.h"
23
#include "miscadmin.h"
B
Bruce Momjian 已提交
24
#include "nodes/makefuncs.h"
25 26 27
#ifdef OPTIMIZER_DEBUG
#include "nodes/print.h"
#endif
B
Bruce Momjian 已提交
28
#include "optimizer/clauses.h"
29 30
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
31
#include "optimizer/paths.h"
32
#include "optimizer/plancat.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/tlist.h"
38
#include "parser/analyze.h"
39
#include "parser/parsetree.h"
40
#include "rewrite/rewriteManip.h"
41
#include "utils/rel.h"
42

43

44
/* GUC parameter */
45
double		cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
46

47 48 49 50
/* Hook for plugins to get control in planner() */
planner_hook_type planner_hook = NULL;


51
/* Expression kind codes for preprocess_expression */
52 53 54 55 56 57 58 59 60
#define EXPRKIND_QUAL			0
#define EXPRKIND_TARGET			1
#define EXPRKIND_RTFUNC			2
#define EXPRKIND_RTFUNC_LATERAL	3
#define EXPRKIND_VALUES			4
#define EXPRKIND_VALUES_LATERAL	5
#define EXPRKIND_LIMIT			6
#define EXPRKIND_APPINFO		7
#define EXPRKIND_PHV			8
61 62


63 64
static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
65
static Plan *inheritance_planner(PlannerInfo *root);
66
static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
67
static void preprocess_rowmarks(PlannerInfo *root);
68
static double preprocess_limit(PlannerInfo *root,
B
Bruce Momjian 已提交
69
				 double tuple_fraction,
B
Bruce Momjian 已提交
70
				 int64 *offset_est, int64 *count_est);
71
static void preprocess_groupclause(PlannerInfo *root);
72 73
static bool choose_hashed_grouping(PlannerInfo *root,
					   double tuple_fraction, double limit_tuples,
74
					   double path_rows, int path_width,
75
					   Path *cheapest_path, Path *sorted_path,
76
					   double dNumGroups, AggClauseCosts *agg_costs);
77 78
static bool choose_hashed_distinct(PlannerInfo *root,
					   double tuple_fraction, double limit_tuples,
79 80 81 82
					   double path_rows, int path_width,
					   Cost cheapest_startup_cost, Cost cheapest_total_cost,
					   Cost sorted_startup_cost, Cost sorted_total_cost,
					   List *sorted_pathkeys,
83
					   double dNumDistinctRows);
84
static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
85
					   AttrNumber **groupColIdx, bool *need_tlist_eval);
86
static int	get_grouping_column_index(Query *parse, TargetEntry *tle);
87
static void locate_grouping_columns(PlannerInfo *root,
B
Bruce Momjian 已提交
88 89 90
						List *tlist,
						List *sub_tlist,
						AttrNumber *groupColIdx);
91
static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
T
Tom Lane 已提交
92
static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
93 94
static List *make_windowInputTargetList(PlannerInfo *root,
						   List *tlist, List *activeWindows);
T
Tom Lane 已提交
95
static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
96
						 List *tlist, bool canonicalize);
T
Tom Lane 已提交
97
static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
98 99 100 101 102 103 104 105
						   List *tlist,
						   int numSortCols, AttrNumber *sortColIdx,
						   int *partNumCols,
						   AttrNumber **partColIdx,
						   Oid **partOperators,
						   int *ordNumCols,
						   AttrNumber **ordColIdx,
						   Oid **ordOperators);
106

107 108 109

/*****************************************************************************
 *
110 111
 *	   Query optimizer entry point
 *
112 113 114 115 116 117 118 119
 * 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.
 *
120
 *****************************************************************************/
121
PlannedStmt *
122
planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
123 124 125 126 127 128 129 130 131 132 133 134
{
	PlannedStmt *result;

	if (planner_hook)
		result = (*planner_hook) (parse, cursorOptions, boundParams);
	else
		result = standard_planner(parse, cursorOptions, boundParams);
	return result;
}

PlannedStmt *
standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
135
{
136
	PlannedStmt *result;
137
	PlannerGlobal *glob;
138
	double		tuple_fraction;
139 140
	PlannerInfo *root;
	Plan	   *top_plan;
141
	ListCell   *lp,
142
			   *lr;
143

144 145 146 147 148
	/* Cursor options may come from caller or from DECLARE CURSOR stmt */
	if (parse->utilityStmt &&
		IsA(parse->utilityStmt, DeclareCursorStmt))
		cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;

149
	/*
150 151 152 153
	 * 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.
154
	 */
155
	glob = makeNode(PlannerGlobal);
156

157
	glob->boundParams = boundParams;
158
	glob->subplans = NIL;
159
	glob->subroots = NIL;
160
	glob->rewindPlanIDs = NULL;
161
	glob->finalrtable = NIL;
162
	glob->finalrowmarks = NIL;
163
	glob->resultRelations = NIL;
164
	glob->relationOids = NIL;
165
	glob->invalItems = NIL;
166
	glob->nParamExec = 0;
167
	glob->lastPHId = 0;
168
	glob->lastRowMarkId = 0;
169
	glob->transientPlan = false;
170

171
	/* Determine what fraction of the plan is likely to be scanned */
172
	if (cursorOptions & CURSOR_OPT_FAST_PLAN)
173 174
	{
		/*
B
Bruce Momjian 已提交
175
		 * We have no real idea how many tuples the user will ultimately FETCH
176 177 178 179 180 181 182 183
		 * from a cursor, but it is often 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.
		 */
		tuple_fraction = cursor_tuple_fraction;

		/*
184 185 186
		 * 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.
187
		 */
188 189 190 191
		if (tuple_fraction >= 1.0)
			tuple_fraction = 0.0;
		else if (tuple_fraction <= 0.0)
			tuple_fraction = 1e-10;
192 193 194 195 196 197 198
	}
	else
	{
		/* Default assumption is we need all the tuples */
		tuple_fraction = 0.0;
	}

199
	/* primary planning entry point (may recurse for subqueries) */
200 201
	top_plan = subquery_planner(glob, parse, NULL,
								false, tuple_fraction, &root);
202

203
	/*
B
Bruce Momjian 已提交
204 205
	 * 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.
206
	 */
207
	if (cursorOptions & CURSOR_OPT_SCROLL)
208
	{
209 210
		if (!ExecSupportsBackwardScan(top_plan))
			top_plan = materialize_finished_plan(top_plan);
211 212
	}

213
	/* final cleanup of the plan */
214
	Assert(glob->finalrtable == NIL);
215
	Assert(glob->finalrowmarks == NIL);
216
	Assert(glob->resultRelations == NIL);
217
	top_plan = set_plan_references(root, top_plan);
218
	/* ... and the subplans (both regular subplans and initplans) */
219 220
	Assert(list_length(glob->subplans) == list_length(glob->subroots));
	forboth(lp, glob->subplans, lr, glob->subroots)
221
	{
B
Bruce Momjian 已提交
222
		Plan	   *subplan = (Plan *) lfirst(lp);
223
		PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
224

225
		lfirst(lp) = set_plan_references(subroot, subplan);
226
	}
227 228 229 230 231

	/* build the PlannedStmt result */
	result = makeNode(PlannedStmt);

	result->commandType = parse->commandType;
232
	result->queryId = parse->queryId;
233
	result->hasReturning = (parse->returningList != NIL);
234
	result->hasModifyingCTE = parse->hasModifyingCTE;
235
	result->canSetTag = parse->canSetTag;
236
	result->transientPlan = glob->transientPlan;
237
	result->planTree = top_plan;
238
	result->rtable = glob->finalrtable;
239
	result->resultRelations = glob->resultRelations;
240
	result->utilityStmt = parse->utilityStmt;
241
	result->subplans = glob->subplans;
242
	result->rewindPlanIDs = glob->rewindPlanIDs;
243
	result->rowMarks = glob->finalrowmarks;
244
	result->relationOids = glob->relationOids;
245
	result->invalItems = glob->invalItems;
246
	result->nParamExec = glob->nParamExec;
247 248

	return result;
249
}
250

251

252
/*--------------------
253 254 255
 * subquery_planner
 *	  Invokes the planner on a subquery.  We recurse to here for each
 *	  sub-SELECT found in the query tree.
256
 *
257
 * glob is the global state for the current planner run.
258
 * parse is the querytree produced by the parser & rewriter.
259 260
 * parent_root is the immediate parent Query's info (NULL at the top level).
 * hasRecursion is true if this is a recursive WITH query.
261
 * tuple_fraction is the fraction of tuples we expect will be retrieved.
262
 * tuple_fraction is interpreted as explained for grouping_planner, below.
263
 *
264 265
 * 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.
266
 *
267
 * Basically, this routine does the stuff that should only be done once
268 269 270 271 272
 * 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.
 *
273 274
 * subquery_planner will be called recursively to handle sub-Query nodes
 * found within the query's expressions and rangetable.
275
 *
276 277
 * Returns a query plan.
 *--------------------
278
 */
279
Plan *
280
subquery_planner(PlannerGlobal *glob, Query *parse,
281 282
				 PlannerInfo *parent_root,
				 bool hasRecursion, double tuple_fraction,
283
				 PlannerInfo **subroot)
284
{
285
	int			num_old_subplans = list_length(glob->subplans);
286
	PlannerInfo *root;
287
	Plan	   *plan;
288
	List	   *newHaving;
289
	bool		hasOuterJoins;
290
	ListCell   *l;
291

292 293 294
	/* Create a PlannerInfo data structure for this subquery */
	root = makeNode(PlannerInfo);
	root->parse = parse;
295
	root->glob = glob;
296 297
	root->query_level = parent_root ? parent_root->query_level + 1 : 1;
	root->parent_root = parent_root;
298
	root->plan_params = NIL;
299
	root->planner_cxt = CurrentMemoryContext;
300
	root->init_plans = NIL;
301
	root->cte_plan_ids = NIL;
302
	root->eq_classes = NIL;
303
	root->append_rel_list = NIL;
304
	root->rowMarks = NIL;
305
	root->hasInheritedTarget = false;
306

307 308
	root->hasRecursion = hasRecursion;
	if (hasRecursion)
309
		root->wt_param_id = SS_assign_special_param(root);
310 311 312 313 314
	else
		root->wt_param_id = -1;
	root->non_recursive_plan = NULL;

	/*
315 316
	 * If there is a WITH list, process each WITH query and build an initplan
	 * SubPlan structure for it.
317 318 319 320
	 */
	if (parse->cteList)
		SS_process_ctes(root);

321
	/*
322 323 324 325
	 * 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.
326 327
	 */
	if (parse->hasSubLinks)
328
		pull_up_sublinks(root);
329

330
	/*
331 332
	 * Scan the rangetable for set-returning functions, and inline them if
	 * possible (producing subqueries that might get pulled up next).
333
	 * Recursion issues here are handled in the same way as for SubLinks.
334 335 336
	 */
	inline_set_returning_functions(root);

337
	/*
338 339
	 * Check to see if any subqueries in the jointree can be merged into this
	 * query.
340 341
	 */
	parse->jointree = (FromExpr *)
342
		pull_up_subqueries(root, (Node *) parse->jointree);
B
Bruce Momjian 已提交
343

344
	/*
345 346 347
	 * If this is a simple UNION ALL query, flatten it into an appendrel. We
	 * do this now because it requires applying pull_up_subqueries to the leaf
	 * queries of the UNION ALL, which weren't touched above because they
348 349 350 351 352
	 * weren't referenced by the jointree (they will be after we do this).
	 */
	if (parse->setOperations)
		flatten_simple_union_all(root);

353
	/*
B
Bruce Momjian 已提交
354 355
	 * 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
356 357 358
	 * outer joins --- if none, we can skip reduce_outer_joins().  And check
	 * for LATERAL RTEs, too.  This must be done after we have done
	 * pull_up_subqueries(), of course.
359
	 */
360
	root->hasJoinRTEs = false;
361
	root->hasLateralRTEs = false;
362
	hasOuterJoins = false;
363
	foreach(l, parse->rtable)
364
	{
365
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
366 367 368

		if (rte->rtekind == RTE_JOIN)
		{
369
			root->hasJoinRTEs = true;
370
			if (IS_OUTER_JOIN(rte->jointype))
371
				hasOuterJoins = true;
372
		}
373 374
		if (rte->lateral)
			root->hasLateralRTEs = true;
375 376
	}

377
	/*
B
Bruce Momjian 已提交
378
	 * Preprocess RowMark information.	We need to do this after subquery
379 380 381
	 * pullup (so that all non-inherited RTEs are present) and before
	 * inheritance expansion (so that the info is available for
	 * expand_inherited_tables to examine and modify).
382
	 */
383
	preprocess_rowmarks(root);
384

385 386 387 388 389 390 391 392 393 394
	/*
	 * 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);

395 396
	/*
	 * Set hasHavingQual to remember if HAVING clause is present.  Needed
B
Bruce Momjian 已提交
397 398
	 * because preprocess_expression will reduce a constant-true condition to
	 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
399
	 */
400
	root->hasHavingQual = (parse->havingQual != NULL);
401

402 403 404
	/* Clear this flag; might get set in distribute_qual_to_rels */
	root->hasPseudoConstantQuals = false;

405
	/*
406 407 408 409
	 * Do expression preprocessing on targetlist and quals, as well as other
	 * random expressions in the querytree.  Note that we do not need to
	 * handle sort/group expressions explicitly, because they are actually
	 * part of the targetlist.
410
	 */
411
	parse->targetList = (List *)
412
		preprocess_expression(root, (Node *) parse->targetList,
413 414
							  EXPRKIND_TARGET);

415 416 417 418
	parse->returningList = (List *)
		preprocess_expression(root, (Node *) parse->returningList,
							  EXPRKIND_TARGET);

419
	preprocess_qual_conditions(root, (Node *) parse->jointree);
420

421
	parse->havingQual = preprocess_expression(root, parse->havingQual,
422 423
											  EXPRKIND_QUAL);

424 425 426 427 428 429 430 431 432 433 434
	foreach(l, parse->windowClause)
	{
		WindowClause *wc = (WindowClause *) lfirst(l);

		/* partitionClause/orderClause are sort/group expressions */
		wc->startOffset = preprocess_expression(root, wc->startOffset,
												EXPRKIND_LIMIT);
		wc->endOffset = preprocess_expression(root, wc->endOffset,
											  EXPRKIND_LIMIT);
	}

435
	parse->limitOffset = preprocess_expression(root, parse->limitOffset,
436
											   EXPRKIND_LIMIT);
437
	parse->limitCount = preprocess_expression(root, parse->limitCount,
438 439
											  EXPRKIND_LIMIT);

440 441
	root->append_rel_list = (List *)
		preprocess_expression(root, (Node *) root->append_rel_list,
442
							  EXPRKIND_APPINFO);
443

444
	/* Also need to preprocess expressions within RTEs */
445
	foreach(l, parse->rtable)
446
	{
447
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
448
		int			kind;
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
		if (rte->rtekind == RTE_SUBQUERY)
		{
			/*
			 * We don't want to do all preprocessing yet on the subquery's
			 * expressions, since that will happen when we plan it.  But if it
			 * contains any join aliases of our level, those have to get
			 * expanded now, because planning of the subquery won't do it.
			 * That's only possible if the subquery is LATERAL.
			 */
			if (rte->lateral && root->hasJoinRTEs)
				rte->subquery = (Query *)
					flatten_join_alias_vars(root, (Node *) rte->subquery);
		}
		else if (rte->rtekind == RTE_FUNCTION)
		{
			/* Preprocess the function expression fully */
			kind = rte->lateral ? EXPRKIND_RTFUNC_LATERAL : EXPRKIND_RTFUNC;
			rte->funcexpr = preprocess_expression(root, rte->funcexpr, kind);
		}
469
		else if (rte->rtekind == RTE_VALUES)
470 471 472
		{
			/* Preprocess the values lists fully */
			kind = rte->lateral ? EXPRKIND_VALUES_LATERAL : EXPRKIND_VALUES;
473
			rte->values_lists = (List *)
474 475
				preprocess_expression(root, (Node *) rte->values_lists, kind);
		}
476 477
	}

478
	/*
B
Bruce Momjian 已提交
479 480 481
	 * 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
482 483 484 485
	 * 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 已提交
486 487
	 * containing subplans are left in HAVING.	Otherwise, we move or copy the
	 * HAVING clause into WHERE, in hopes of eliminating tuples before
488 489
	 * aggregation instead of after.
	 *
490 491 492 493 494 495 496 497
	 * 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.)
498 499
	 *
	 * Note that both havingQual and parse->jointree->quals are in
B
Bruce Momjian 已提交
500 501
	 * implicitly-ANDed-list form at this point, even though they are declared
	 * as Node *.
502 503
	 */
	newHaving = NIL;
504
	foreach(l, (List *) parse->havingQual)
505
	{
506
		Node	   *havingclause = (Node *) lfirst(l);
507

508 509 510 511 512
		if (contain_agg_clause(havingclause) ||
			contain_volatile_functions(havingclause) ||
			contain_subplans(havingclause))
		{
			/* keep it in HAVING */
513
			newHaving = lappend(newHaving, havingclause);
514 515 516 517
		}
		else if (parse->groupClause)
		{
			/* move it to WHERE */
518 519
			parse->jointree->quals = (Node *)
				lappend((List *) parse->jointree->quals, havingclause);
520 521 522 523 524 525 526 527 528
		}
		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);
		}
529 530 531
	}
	parse->havingQual = (Node *) newHaving;

532
	/*
B
Bruce Momjian 已提交
533 534
	 * 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 已提交
535
	 * preprocessing.
536
	 */
537
	if (hasOuterJoins)
538
		reduce_outer_joins(root);
539

540
	/*
B
Bruce Momjian 已提交
541 542
	 * Do the main planning.  If we have an inherited target relation, that
	 * needs special processing, else go straight to grouping_planner.
543
	 */
544
	if (parse->resultRelation &&
545 546
		rt_fetch(parse->resultRelation, parse->rtable)->inh)
		plan = inheritance_planner(root);
547
	else
548
	{
549
		plan = grouping_planner(root, tuple_fraction);
550 551 552
		/* If it's not SELECT, we need a ModifyTable node */
		if (parse->commandType != CMD_SELECT)
		{
B
Bruce Momjian 已提交
553 554
			List	   *returningLists;
			List	   *rowMarks;
555

556
			/*
557
			 * Set up the RETURNING list-of-lists, if needed.
558 559
			 */
			if (parse->returningList)
560
				returningLists = list_make1(parse->returningList);
561 562 563
			else
				returningLists = NIL;

564
			/*
565
			 * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node will
566 567 568 569 570 571 572 573
			 * have dealt with fetching non-locked marked rows, else we need
			 * to have ModifyTable do that.
			 */
			if (parse->rowMarks)
				rowMarks = NIL;
			else
				rowMarks = root->rowMarks;

574
			plan = (Plan *) make_modifytable(parse->commandType,
575
											 parse->canSetTag,
576
									   list_make1_int(parse->resultRelation),
577
											 list_make1(plan),
578 579 580
											 returningLists,
											 rowMarks,
											 SS_assign_special_param(root));
581 582
		}
	}
583 584

	/*
585 586 587
	 * If any subplans were generated, or if there are any parameters to worry
	 * about, build initPlan list and extParam/allParam sets for plan nodes,
	 * and attach the initPlans to the top plan node.
588
	 */
589
	if (list_length(glob->subplans) != num_old_subplans ||
590
		root->glob->nParamExec > 0)
591
		SS_finalize_plan(root, plan, true);
B
Bruce Momjian 已提交
592

593 594 595
	/* Return internal info if caller wants it */
	if (subroot)
		*subroot = root;
596

597
	return plan;
598
}
599

600 601 602 603
/*
 * preprocess_expression
 *		Do subquery_planner's preprocessing work for an expression,
 *		which can be a targetlist, a WHERE clause (including JOIN/ON
604
 *		conditions), a HAVING clause, or a few other things.
605 606
 */
static Node *
607
preprocess_expression(PlannerInfo *root, Node *expr, int kind)
608
{
609
	/*
B
Bruce Momjian 已提交
610 611 612
	 * 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.
613 614 615 616
	 */
	if (expr == NULL)
		return NULL;

617 618
	/*
	 * If the query has any join RTEs, replace join alias variables with
619 620 621 622
	 * base-relation variables.  We must do this before sublink processing,
	 * else sublinks expanded out from join aliases would not get processed.
	 * We can skip it in non-lateral RTE functions and VALUES lists, however,
	 * since they can't contain any Vars of the current query level.
623
	 */
624 625
	if (root->hasJoinRTEs &&
		!(kind == EXPRKIND_RTFUNC || kind == EXPRKIND_VALUES))
626
		expr = flatten_join_alias_vars(root, expr);
627

628
	/*
629
	 * Simplify constant expressions.
630
	 *
631
	 * Note: an essential effect of this is to convert named-argument function
B
Bruce Momjian 已提交
632 633 634 635 636
	 * calls to positional notation and 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.
637
	 *
638 639 640 641 642
	 * 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.
	 */
643
	expr = eval_const_expressions(root, expr);
644 645 646

	/*
	 * If it's a qual or havingQual, canonicalize it.
647
	 */
648
	if (kind == EXPRKIND_QUAL)
649
	{
650
		expr = (Node *) canonicalize_qual((Expr *) expr);
651 652 653 654 655 656

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

658
	/* Expand SubLinks to SubPlans */
659
	if (root->parse->hasSubLinks)
660
		expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
661

662
	/*
B
Bruce Momjian 已提交
663 664
	 * XXX do not insert anything here unless you have grokked the comments in
	 * SS_replace_correlation_vars ...
665 666
	 */

667
	/* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
668 669
	if (root->query_level > 1)
		expr = SS_replace_correlation_vars(root, expr);
670

671
	/*
B
Bruce Momjian 已提交
672 673 674
	 * 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,
675
	 * SS_process_sublinks expects explicit-AND format.)
676 677 678 679
	 */
	if (kind == EXPRKIND_QUAL)
		expr = (Node *) make_ands_implicit((Expr *) expr);

680 681 682 683 684 685 686 687 688
	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
689
preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
690 691 692 693 694 695 696 697 698 699
{
	if (jtnode == NULL)
		return;
	if (IsA(jtnode, RangeTblRef))
	{
		/* nothing to do here */
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
700
		ListCell   *l;
701

702
		foreach(l, f->fromlist)
703
			preprocess_qual_conditions(root, lfirst(l));
704

705
		f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
706 707 708 709 710
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

711 712
		preprocess_qual_conditions(root, j->larg);
		preprocess_qual_conditions(root, j->rarg);
713

714
		j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
715 716
	}
	else
717 718
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
719
}
720

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
/*
 * preprocess_phv_expression
 *	  Do preprocessing on a PlaceHolderVar expression that's been pulled up.
 *
 * If a LATERAL subquery references an output of another subquery, and that
 * output must be wrapped in a PlaceHolderVar because of an intermediate outer
 * join, then we'll push the PlaceHolderVar expression down into the subquery
 * and later pull it back up during find_lateral_references, which runs after
 * subquery_planner has preprocessed all the expressions that were in the
 * current query level to start with.  So we need to preprocess it then.
 */
Expr *
preprocess_phv_expression(PlannerInfo *root, Expr *expr)
{
	return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
}

738
/*
739 740 741 742
 * inheritance_planner
 *	  Generate a plan in the case where the result relation is an
 *	  inheritance set.
 *
743 744 745 746
 * 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
747
 * different targetlist matching its own column set.  Fortunately,
748 749
 * the UPDATE/DELETE target can never be the nullable side of an outer join,
 * so it's OK to generate the plan this way.
750 751 752 753
 *
 * Returns a query plan.
 */
static Plan *
754
inheritance_planner(PlannerInfo *root)
755
{
756
	Query	   *parse = root->parse;
757
	int			parentRTindex = parse->resultRelation;
758 759 760
	List	   *final_rtable = NIL;
	int			save_rel_array_size = 0;
	RelOptInfo **save_rel_array = NULL;
761
	List	   *subplans = NIL;
762 763
	List	   *resultRelations = NIL;
	List	   *returningLists = NIL;
764
	List	   *rowMarks;
765
	ListCell   *lc;
766

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
	/*
	 * We generate a modified instance of the original Query for each target
	 * relation, plan that, and put all the plans into a list that will be
	 * controlled by a single ModifyTable node.  All the instances share the
	 * same rangetable, but each instance must have its own set of subquery
	 * RTEs within the finished rangetable because (1) they are likely to get
	 * scribbled on during planning, and (2) it's not inconceivable that
	 * subqueries could get planned differently in different cases.  We need
	 * not create duplicate copies of other RTE kinds, in particular not the
	 * target relations, because they don't have either of those issues.  Not
	 * having to duplicate the target relations is important because doing so
	 * (1) would result in a rangetable of length O(N^2) for N targets, with
	 * at least O(N^3) work expended here; and (2) would greatly complicate
	 * management of the rowMarks list.
	 */
	foreach(lc, root->append_rel_list)
783
	{
784 785
		AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
		PlannerInfo subroot;
B
Bruce Momjian 已提交
786
		Plan	   *subplan;
787
		Index		rti;
788

789 790 791 792
		/* append_rel_list contains all append rels; ignore others */
		if (appinfo->parent_relid != parentRTindex)
			continue;

793
		/*
794 795
		 * We need a working copy of the PlannerInfo so that we can control
		 * propagation of information back to the main copy.
796 797
		 */
		memcpy(&subroot, root, sizeof(PlannerInfo));
798 799 800 801 802 803 804

		/*
		 * Generate modified query with this rel as target.  We first apply
		 * adjust_appendrel_attrs, which copies the Query and changes
		 * references to the parent RTE to refer to the current child RTE,
		 * then fool around with subquery RTEs.
		 */
805
		subroot.parse = (Query *)
806 807
			adjust_appendrel_attrs(root,
								   (Node *) parse,
808
								   appinfo);
809 810 811

		/*
		 * The rowMarks list might contain references to subquery RTEs, so
812 813 814
		 * make a copy that we can apply ChangeVarNodes to.  (Fortunately, the
		 * executor doesn't need to see the modified copies --- we can just
		 * pass it the original rowMarks list.)
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
		 */
		subroot.rowMarks = (List *) copyObject(root->rowMarks);

		/*
		 * Add placeholders to the child Query's rangetable list to fill the
		 * RT indexes already reserved for subqueries in previous children.
		 * These won't be referenced, so there's no need to make them very
		 * valid-looking.
		 */
		while (list_length(subroot.parse->rtable) < list_length(final_rtable))
			subroot.parse->rtable = lappend(subroot.parse->rtable,
											makeNode(RangeTblEntry));

		/*
		 * If this isn't the first child Query, generate duplicates of all
830 831 832 833 834
		 * subquery RTEs, and adjust Var numbering to reference the
		 * duplicates. To simplify the loop logic, we scan the original rtable
		 * not the copy just made by adjust_appendrel_attrs; that should be OK
		 * since subquery RTEs couldn't contain any references to the target
		 * rel.
835 836 837 838 839 840 841 842 843 844 845 846
		 */
		if (final_rtable != NIL)
		{
			ListCell   *lr;

			rti = 1;
			foreach(lr, parse->rtable)
			{
				RangeTblEntry *rte = (RangeTblEntry *) lfirst(lr);

				if (rte->rtekind == RTE_SUBQUERY)
				{
847
					Index		newrti;
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865

					/*
					 * The RTE can't contain any references to its own RT
					 * index, so we can save a few cycles by applying
					 * ChangeVarNodes before we append the RTE to the
					 * rangetable.
					 */
					newrti = list_length(subroot.parse->rtable) + 1;
					ChangeVarNodes((Node *) subroot.parse, rti, newrti, 0);
					ChangeVarNodes((Node *) subroot.rowMarks, rti, newrti, 0);
					rte = copyObject(rte);
					subroot.parse->rtable = lappend(subroot.parse->rtable,
													rte);
				}
				rti++;
			}
		}

866
		/* We needn't modify the child's append_rel_list */
867
		/* There shouldn't be any OJ or LATERAL info to translate, as yet */
868
		Assert(subroot.join_info_list == NIL);
869
		Assert(subroot.lateral_info_list == NIL);
870 871
		/* and we haven't created PlaceHolderInfos, either */
		Assert(subroot.placeholder_list == NIL);
872 873
		/* hack to mark target relation as an inheritance partition */
		subroot.hasInheritedTarget = true;
874

875
		/* Generate plan */
876 877
		subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );

878
		/*
B
Bruce Momjian 已提交
879
		 * If this child rel was excluded by constraint exclusion, exclude it
880
		 * from the result plan.
881 882 883
		 */
		if (is_dummy_plan(subplan))
			continue;
B
Bruce Momjian 已提交
884

885 886
		subplans = lappend(subplans, subplan);

887 888 889 890 891 892 893 894 895 896
		/*
		 * If this is the first non-excluded child, its post-planning rtable
		 * becomes the initial contents of final_rtable; otherwise, append
		 * just its modified subquery RTEs to final_rtable.
		 */
		if (final_rtable == NIL)
			final_rtable = subroot.parse->rtable;
		else
			final_rtable = list_concat(final_rtable,
									   list_copy_tail(subroot.parse->rtable,
897
												 list_length(final_rtable)));
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

		/*
		 * We need to collect all the RelOptInfos from all child plans into
		 * the main PlannerInfo, since setrefs.c will need them.  We use the
		 * last child's simple_rel_array (previous ones are too short), so we
		 * have to propagate forward the RelOptInfos that were already built
		 * in previous children.
		 */
		Assert(subroot.simple_rel_array_size >= save_rel_array_size);
		for (rti = 1; rti < save_rel_array_size; rti++)
		{
			RelOptInfo *brel = save_rel_array[rti];

			if (brel)
				subroot.simple_rel_array[rti] = brel;
		}
		save_rel_array_size = subroot.simple_rel_array_size;
		save_rel_array = subroot.simple_rel_array;

917
		/* Make sure any initplans from this rel get into the outer list */
918
		root->init_plans = subroot.init_plans;
919

920
		/* Build list of target-relation RT indexes */
921 922 923 924
		resultRelations = lappend_int(resultRelations, appinfo->child_relid);

		/* Build list of per-relation RETURNING targetlists */
		if (parse->returningList)
925 926
			returningLists = lappend(returningLists,
									 subroot.parse->returningList);
927 928
	}

929 930 931 932
	/* Mark result as unordered (probably unnecessary) */
	root->query_pathkeys = NIL;

	/*
B
Bruce Momjian 已提交
933 934
	 * If we managed to exclude every child rel, return a dummy plan; it
	 * doesn't even need a ModifyTable node.
935 936
	 */
	if (subplans == NIL)
937 938
	{
		/* although dummy, it must have a valid tlist for executor */
939 940
		List	   *tlist;

941
		tlist = preprocess_targetlist(root, parse->targetList);
942 943
		return (Plan *) make_result(root,
									tlist,
944 945 946
									(Node *) list_make1(makeBoolConst(false,
																	  false)),
									NULL);
947
	}
948

949
	/*
950
	 * Put back the final adjusted rtable into the master copy of the Query.
951
	 */
952 953 954
	parse->rtable = final_rtable;
	root->simple_rel_array_size = save_rel_array_size;
	root->simple_rel_array = save_rel_array;
955

956
	/*
957
	 * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node will have
B
Bruce Momjian 已提交
958 959
	 * dealt with fetching non-locked marked rows, else we need to have
	 * ModifyTable do that.
960 961 962 963 964 965
	 */
	if (parse->rowMarks)
		rowMarks = NIL;
	else
		rowMarks = root->rowMarks;

966 967
	/* And last, tack on a ModifyTable node to do the UPDATE/DELETE work */
	return (Plan *) make_modifytable(parse->commandType,
968 969
									 parse->canSetTag,
									 resultRelations,
B
Bruce Momjian 已提交
970
									 subplans,
971 972 973
									 returningLists,
									 rowMarks,
									 SS_assign_special_param(root));
974 975 976 977 978 979 980
}

/*--------------------
 * 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.
981 982 983 984
 *
 * tuple_fraction is the fraction of tuples we expect will be retrieved
 *
 * tuple_fraction is interpreted as follows:
985
 *	  0: expect all tuples to be retrieved (normal case)
986 987 988 989 990
 *	  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)
 *
991
 * Returns a query plan.  Also, root->query_pathkeys is returned as the
992
 * actual output ordering of the plan (in pathkey format).
993 994
 *--------------------
 */
995
static Plan *
996
grouping_planner(PlannerInfo *root, double tuple_fraction)
997
{
998
	Query	   *parse = root->parse;
999
	List	   *tlist = parse->targetList;
B
Bruce Momjian 已提交
1000 1001
	int64		offset_est = 0;
	int64		count_est = 0;
1002
	double		limit_tuples = -1.0;
1003 1004
	Plan	   *result_plan;
	List	   *current_pathkeys;
1005
	double		dNumGroups = 0;
1006 1007
	bool		use_hashed_distinct = false;
	bool		tested_hashed_distinct = false;
1008

1009 1010
	/* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
	if (parse->limitCount || parse->limitOffset)
1011
	{
1012 1013
		tuple_fraction = preprocess_limit(root, tuple_fraction,
										  &offset_est, &count_est);
B
Bruce Momjian 已提交
1014

1015
		/*
B
Bruce Momjian 已提交
1016 1017
		 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
		 * estimate the effects of using a bounded sort.
1018 1019 1020 1021
		 */
		if (count_est > 0 && offset_est >= 0)
			limit_tuples = (double) count_est + (double) offset_est;
	}
1022

1023
	if (parse->setOperations)
B
Bruce Momjian 已提交
1024
	{
B
Bruce Momjian 已提交
1025
		List	   *set_sortclauses;
1026

1027
		/*
B
Bruce Momjian 已提交
1028
		 * If there's a top-level ORDER BY, assume we have to fetch all the
1029
		 * tuples.	This might be too simplistic given all the hackery below
1030 1031
		 * to possibly avoid the sort; but the odds of accurate estimates here
		 * are pretty low anyway.
1032 1033 1034 1035
		 */
		if (parse->sortClause)
			tuple_fraction = 0.0;

1036
		/*
B
Bruce Momjian 已提交
1037
		 * Construct the plan for set operations.  The result will not need
1038 1039 1040
		 * 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.
1041
		 */
1042
		result_plan = plan_set_operations(root, tuple_fraction,
1043 1044 1045
										  &set_sortclauses);

		/*
B
Bruce Momjian 已提交
1046 1047 1048
		 * 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...
1049
		 */
1050 1051
		current_pathkeys = make_pathkeys_for_sortclauses(root,
														 set_sortclauses,
B
Bruce Momjian 已提交
1052
													 result_plan->targetlist,
1053
														 true);
1054 1055

		/*
B
Bruce Momjian 已提交
1056 1057 1058 1059 1060
		 * 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.
1061 1062
		 */
		Assert(parse->commandType == CMD_SELECT);
1063

1064 1065
		tlist = postprocess_setop_tlist(copyObject(result_plan->targetlist),
										tlist);
1066

1067
		/*
1068
		 * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have checked
B
Bruce Momjian 已提交
1069
		 * already, but let's make sure).
1070 1071
		 */
		if (parse->rowMarks)
1072 1073
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
A
Alvaro Herrera 已提交
1074
					 errmsg("row-level locks are not allowed with UNION/INTERSECT/EXCEPT")));
1075

1076
		/*
1077
		 * Calculate pathkeys that represent result ordering requirements
1078
		 */
1079
		Assert(parse->distinctClause == NIL);
1080 1081 1082 1083
		root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
															parse->sortClause,
															tlist,
															true);
B
Bruce Momjian 已提交
1084
	}
1085
	else
1086
	{
1087
		/* No set operations, do regular planning */
B
Bruce Momjian 已提交
1088
		List	   *sub_tlist;
1089
		double		sub_limit_tuples;
1090
		AttrNumber *groupColIdx = NULL;
1091
		bool		need_tlist_eval = true;
1092 1093
		Path	   *cheapest_path;
		Path	   *sorted_path;
1094
		Path	   *best_path;
1095
		long		numGroups = 0;
1096
		AggClauseCosts agg_costs;
1097
		int			numGroupCols;
1098 1099
		double		path_rows;
		int			path_width;
1100
		bool		use_hashed_grouping = false;
T
Tom Lane 已提交
1101 1102
		WindowFuncLists *wflists = NULL;
		List	   *activeWindows = NIL;
1103

1104
		MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
1105

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

1109 1110 1111 1112 1113
		/* Preprocess GROUP BY clause, if any */
		if (parse->groupClause)
			preprocess_groupclause(root);
		numGroupCols = list_length(parse->groupClause);

1114
		/* Preprocess targetlist */
1115
		tlist = preprocess_targetlist(root, tlist);
B
Bruce Momjian 已提交
1116

T
Tom Lane 已提交
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
		/*
		 * Locate any window functions in the tlist.  (We don't need to look
		 * anywhere else, since expressions used in ORDER BY will be in there
		 * too.)  Note that they could all have been eliminated by constant
		 * folding, in which case we don't need to do any more work.
		 */
		if (parse->hasWindowFuncs)
		{
			wflists = find_window_functions((Node *) tlist,
											list_length(parse->windowClause));
			if (wflists->numWindowFuncs > 0)
				activeWindows = select_active_windows(root, wflists);
			else
				parse->hasWindowFuncs = false;
		}

1133
		/*
B
Bruce Momjian 已提交
1134 1135
		 * Generate appropriate target list for subplan; may be different from
		 * tlist if grouping or aggregation is needed.
1136
		 */
1137
		sub_tlist = make_subplanTargetList(root, tlist,
B
Bruce Momjian 已提交
1138
										   &groupColIdx, &need_tlist_eval);
1139

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
		/*
		 * Do aggregate preprocessing, if the query has any aggs.
		 *
		 * Note: think not that we can turn off hasAggs if we find no aggs. It
		 * is possible for constant-expression simplification to remove all
		 * explicit references to aggs, but we still have to follow the
		 * aggregate semantics (eg, producing only one output row).
		 */
		if (parse->hasAggs)
		{
			/*
B
Bruce Momjian 已提交
1151 1152
			 * Collect statistics about aggregates for estimating costs. Note:
			 * we do not attempt to detect duplicate aggregates here; a
1153
			 * somewhat-overestimated cost is okay for our present purposes.
1154
			 */
1155 1156
			count_agg_clauses(root, (Node *) tlist, &agg_costs);
			count_agg_clauses(root, parse->havingQual, &agg_costs);
1157 1158

			/*
1159 1160 1161 1162
			 * Preprocess MIN/MAX aggregates, if any.  Note: be careful about
			 * adding logic between here and the optimize_minmax_aggregates
			 * call.  Anything that is needed in MIN/MAX-optimizable cases
			 * will have to be duplicated in planagg.c.
1163 1164 1165 1166
			 */
			preprocess_minmax_aggregates(root, tlist);
		}

1167
		/*
1168 1169
		 * Calculate pathkeys that represent grouping/ordering requirements.
		 * Stash them in PlannerInfo so that query_planner can canonicalize
1170 1171 1172
		 * them after EquivalenceClasses have been formed.	The sortClause is
		 * certainly sort-able, but GROUP BY and DISTINCT might not be, in
		 * which case we just leave their pathkeys empty.
1173
		 */
1174 1175
		if (parse->groupClause &&
			grouping_is_sortable(parse->groupClause))
1176 1177 1178 1179 1180 1181 1182 1183
			root->group_pathkeys =
				make_pathkeys_for_sortclauses(root,
											  parse->groupClause,
											  tlist,
											  false);
		else
			root->group_pathkeys = NIL;

T
Tom Lane 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
		/* We consider only the first (bottom) window in pathkeys logic */
		if (activeWindows != NIL)
		{
			WindowClause *wc = (WindowClause *) linitial(activeWindows);

			root->window_pathkeys = make_pathkeys_for_window(root,
															 wc,
															 tlist,
															 false);
		}
		else
			root->window_pathkeys = NIL;

1197 1198 1199
		if (parse->distinctClause &&
			grouping_is_sortable(parse->distinctClause))
			root->distinct_pathkeys =
1200 1201 1202 1203 1204
				make_pathkeys_for_sortclauses(root,
											  parse->distinctClause,
											  tlist,
											  false);
		else
1205 1206 1207 1208 1209 1210 1211
			root->distinct_pathkeys = NIL;

		root->sort_pathkeys =
			make_pathkeys_for_sortclauses(root,
										  parse->sortClause,
										  tlist,
										  false);
1212

1213
		/*
1214
		 * Figure out whether we want a sorted result from query_planner.
1215
		 *
1216
		 * If we have a sortable GROUP BY clause, then we want a result sorted
T
Tom Lane 已提交
1217 1218 1219 1220 1221 1222
		 * properly for grouping.  Otherwise, if we have window functions to
		 * evaluate, we try to sort for the first window.  Otherwise, if
		 * there's a sortable DISTINCT clause that's more rigorous than the
		 * ORDER BY clause, we try to produce output that's sufficiently well
		 * sorted for the DISTINCT.  Otherwise, if there is an ORDER BY
		 * clause, we want to sort by the ORDER BY clause.
1223 1224 1225 1226
		 *
		 * Note: if we have both ORDER BY and GROUP BY, 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
1227
		 * sort order at all.  Needs more thought.	The choice for DISTINCT
1228 1229
		 * versus ORDER BY is much easier, since we know that the parser
		 * ensured that one is a superset of the other.
1230
		 */
1231
		if (root->group_pathkeys)
1232
			root->query_pathkeys = root->group_pathkeys;
T
Tom Lane 已提交
1233 1234
		else if (root->window_pathkeys)
			root->query_pathkeys = root->window_pathkeys;
1235 1236 1237
		else if (list_length(root->distinct_pathkeys) >
				 list_length(root->sort_pathkeys))
			root->query_pathkeys = root->distinct_pathkeys;
1238
		else if (root->sort_pathkeys)
1239
			root->query_pathkeys = root->sort_pathkeys;
1240
		else
1241
			root->query_pathkeys = NIL;
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
		/*
		 * Figure out whether there's a hard limit on the number of rows that
		 * query_planner's result subplan needs to return.  Even if we know a
		 * hard limit overall, it doesn't apply if the query has any
		 * grouping/aggregation operations.
		 */
		if (parse->groupClause ||
			parse->distinctClause ||
			parse->hasAggs ||
			parse->hasWindowFuncs ||
			root->hasHavingQual)
			sub_limit_tuples = -1.0;
		else
			sub_limit_tuples = limit_tuples;

1258
		/*
B
Bruce Momjian 已提交
1259 1260 1261 1262
		 * 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.
1263
		 */
1264
		query_planner(root, sub_tlist, tuple_fraction, sub_limit_tuples,
1265
					  &cheapest_path, &sorted_path, &dNumGroups);
1266

1267
		/*
1268 1269 1270
		 * Extract rowcount and width estimates for possible use in grouping
		 * decisions.  Beware here of the possibility that
		 * cheapest_path->parent is NULL (ie, there is no FROM clause).
1271
		 */
1272 1273 1274 1275 1276 1277
		if (cheapest_path->parent)
		{
			path_rows = cheapest_path->parent->rows;
			path_width = cheapest_path->parent->width;
		}
		else
1278
		{
B
Bruce Momjian 已提交
1279 1280
			path_rows = 1;		/* assume non-set result */
			path_width = 100;	/* arbitrary */
1281
		}
1282

1283 1284
		if (parse->groupClause)
		{
1285
			/*
1286
			 * If grouping, decide whether to use sorted or hashed grouping.
1287
			 */
1288 1289 1290 1291 1292
			use_hashed_grouping =
				choose_hashed_grouping(root,
									   tuple_fraction, limit_tuples,
									   path_rows, path_width,
									   cheapest_path, sorted_path,
1293
									   dNumGroups, &agg_costs);
1294 1295
			/* Also convert # groups to long int --- but 'ware overflow! */
			numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1296
		}
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
		else if (parse->distinctClause && sorted_path &&
				 !root->hasHavingQual && !parse->hasAggs && !activeWindows)
		{
			/*
			 * We'll reach the DISTINCT stage without any intermediate
			 * processing, so figure out whether we will want to hash or not
			 * so we can choose whether to use cheapest or sorted path.
			 */
			use_hashed_distinct =
				choose_hashed_distinct(root,
									   tuple_fraction, limit_tuples,
									   path_rows, path_width,
									   cheapest_path->startup_cost,
									   cheapest_path->total_cost,
									   sorted_path->startup_cost,
									   sorted_path->total_cost,
									   sorted_path->pathkeys,
									   dNumGroups);
			tested_hashed_distinct = true;
		}
1317

B
Bruce Momjian 已提交
1318
		/*
1319
		 * Select the best path.  If we are doing hashed grouping, we will
B
Bruce Momjian 已提交
1320 1321
		 * always read all the input tuples, so use the cheapest-total path.
		 * Otherwise, trust query_planner's decision about which to use.
1322
		 */
1323
		if (use_hashed_grouping || use_hashed_distinct || !sorted_path)
1324
			best_path = cheapest_path;
1325
		else
1326
			best_path = sorted_path;
1327

1328
		/*
B
Bruce Momjian 已提交
1329 1330 1331 1332
		 * 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.
1333
		 */
1334
		result_plan = optimize_minmax_aggregates(root,
1335
												 tlist,
1336
												 &agg_costs,
1337 1338 1339 1340
												 best_path);
		if (result_plan != NULL)
		{
			/*
B
Bruce Momjian 已提交
1341 1342
			 * optimize_minmax_aggregates generated the full plan, with the
			 * right tlist, and it has no sort order.
1343 1344 1345 1346
			 */
			current_pathkeys = NIL;
		}
		else
1347
		{
1348
			/*
1349 1350
			 * Normal case --- create a plan according to query_planner's
			 * results.
1351
			 */
1352
			bool		need_sort_for_grouping = false;
1353

1354
			result_plan = create_plan(root, best_path);
1355 1356
			current_pathkeys = best_path->pathkeys;

1357 1358
			/* Detect if we'll need an explicit sort for grouping */
			if (parse->groupClause && !use_hashed_grouping &&
1359
			  !pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1360 1361
			{
				need_sort_for_grouping = true;
1362

1363
				/*
1364 1365
				 * Always override create_plan's tlist, so that we don't sort
				 * useless data from a "physical" tlist.
1366 1367 1368 1369
				 */
				need_tlist_eval = true;
			}

1370
			/*
1371 1372 1373 1374
			 * 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 create_plan chose to return will be good enough.
1375 1376
			 */
			if (need_tlist_eval)
1377
			{
1378 1379 1380 1381 1382 1383 1384
				/*
				 * If the top-level plan node is one that cannot do expression
				 * evaluation, we must insert a Result node to project the
				 * desired tlist.
				 */
				if (!is_projection_capable_plan(result_plan))
				{
1385 1386 1387
					result_plan = (Plan *) make_result(root,
													   sub_tlist,
													   NULL,
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
													   result_plan);
				}
				else
				{
					/*
					 * Otherwise, just replace the subplan's flat tlist with
					 * the desired tlist.
					 */
					result_plan->targetlist = sub_tlist;
				}

				/*
				 * Also, account for the cost of evaluation of the sub_tlist.
1401
				 * See comments for add_tlist_costs_to_plan() for more info.
1402
				 */
1403
				add_tlist_costs_to_plan(root, result_plan, sub_tlist);
1404 1405 1406 1407
			}
			else
			{
				/*
1408
				 * Since we're using create_plan's tlist and not the one
1409 1410
				 * make_subplanTargetList calculated, we have to refigure any
				 * grouping-column indexes make_subplanTargetList computed.
1411
				 */
1412
				locate_grouping_columns(root, tlist, result_plan->targetlist,
1413
										groupColIdx);
1414
			}
B
Bruce Momjian 已提交
1415

1416
			/*
1417 1418
			 * Insert AGG or GROUP node if needed, plus an explicit sort step
			 * if necessary.
1419
			 *
1420
			 * HAVING clause, if any, becomes qual of the Agg or Group node.
1421
			 */
1422 1423 1424
			if (use_hashed_grouping)
			{
				/* Hashed aggregate plan --- no sort needed */
1425
				result_plan = (Plan *) make_agg(root,
1426 1427 1428
												tlist,
												(List *) parse->havingQual,
												AGG_HASHED,
1429
												&agg_costs,
1430 1431
												numGroupCols,
												groupColIdx,
1432
									extract_grouping_ops(parse->groupClause),
1433 1434 1435 1436 1437 1438 1439 1440 1441
												numGroups,
												result_plan);
				/* Hashed aggregation produces randomly-ordered results */
				current_pathkeys = NIL;
			}
			else if (parse->hasAggs)
			{
				/* Plain aggregate plan --- sort if needed */
				AggStrategy aggstrategy;
1442

1443 1444
				if (parse->groupClause)
				{
1445
					if (need_sort_for_grouping)
1446 1447
					{
						result_plan = (Plan *)
1448
							make_sort_from_groupcols(root,
1449 1450 1451
													 parse->groupClause,
													 groupColIdx,
													 result_plan);
1452
						current_pathkeys = root->group_pathkeys;
1453 1454
					}
					aggstrategy = AGG_SORTED;
1455

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
					/*
					 * The AGG node will not change the sort ordering of its
					 * groups, so current_pathkeys describes the result too.
					 */
				}
				else
				{
					aggstrategy = AGG_PLAIN;
					/* Result will be only one row anyway; no sort order */
					current_pathkeys = NIL;
				}

1468
				result_plan = (Plan *) make_agg(root,
1469 1470 1471
												tlist,
												(List *) parse->havingQual,
												aggstrategy,
1472
												&agg_costs,
1473 1474
												numGroupCols,
												groupColIdx,
1475
									extract_grouping_ops(parse->groupClause),
1476 1477 1478 1479
												numGroups,
												result_plan);
			}
			else if (parse->groupClause)
1480
			{
1481 1482 1483 1484
				/*
				 * GROUP BY without aggregation, so insert a group node (plus
				 * the appropriate sort node, if necessary).
				 *
1485 1486
				 * Add an explicit sort if we couldn't make the path come out
				 * the way the GROUP node needs it.
1487
				 */
1488
				if (need_sort_for_grouping)
1489
				{
1490
					result_plan = (Plan *)
1491
						make_sort_from_groupcols(root,
1492 1493 1494
												 parse->groupClause,
												 groupColIdx,
												 result_plan);
1495
					current_pathkeys = root->group_pathkeys;
1496
				}
B
Bruce Momjian 已提交
1497

1498
				result_plan = (Plan *) make_group(root,
1499 1500 1501 1502
												  tlist,
												  (List *) parse->havingQual,
												  numGroupCols,
												  groupColIdx,
1503
									extract_grouping_ops(parse->groupClause),
1504 1505 1506
												  dNumGroups,
												  result_plan);
				/* The Group node won't change sort ordering */
1507
			}
1508
			else if (root->hasHavingQual)
1509
			{
1510 1511 1512 1513 1514
				/*
				 * 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 已提交
1515 1516 1517 1518 1519 1520
				 * 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.
1521
				 */
1522 1523
				result_plan = (Plan *) make_result(root,
												   tlist,
1524 1525
												   parse->havingQual,
												   NULL);
1526
			}
1527
		}						/* end of non-minmax-aggregate case */
T
Tom Lane 已提交
1528 1529

		/*
1530 1531 1532
		 * Since each window function could require a different sort order, we
		 * stack up a WindowAgg node for each window, with sort steps between
		 * them as needed.
T
Tom Lane 已提交
1533 1534 1535 1536 1537 1538 1539 1540
		 */
		if (activeWindows)
		{
			List	   *window_tlist;
			ListCell   *l;

			/*
			 * If the top-level plan node is one that cannot do expression
1541 1542 1543 1544 1545 1546
			 * evaluation, we must insert a Result node to project the desired
			 * tlist.  (In some cases this might not really be required, but
			 * it's not worth trying to avoid it.)  Note that on second and
			 * subsequent passes through the following loop, the top-level
			 * node will be a WindowAgg which we know can project; so we only
			 * need to check once.
T
Tom Lane 已提交
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
			 */
			if (!is_projection_capable_plan(result_plan))
			{
				result_plan = (Plan *) make_result(root,
												   NIL,
												   NULL,
												   result_plan);
			}

			/*
1557
			 * The "base" targetlist for all steps of the windowing process is
1558
			 * a flat tlist of all Vars and Aggs needed in the result.  (In
1559 1560 1561
			 * some cases we wouldn't need to propagate all of these all the
			 * way to the top, since they might only be needed as inputs to
			 * WindowFuncs.  It's probably not worth trying to optimize that
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
			 * though.)  We also add window partitioning and sorting
			 * expressions to the base tlist, to ensure they're computed only
			 * once at the bottom of the stack (that's critical for volatile
			 * functions).  As we climb up the stack, we'll add outputs for
			 * the WindowFuncs computed at each level.
			 */
			window_tlist = make_windowInputTargetList(root,
													  tlist,
													  activeWindows);

			/*
			 * The copyObject steps here are needed to ensure that each plan
			 * node has a separately modifiable tlist.  (XXX wouldn't a
			 * shallow list copy do for that?)
T
Tom Lane 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
			 */
			result_plan->targetlist = (List *) copyObject(window_tlist);

			foreach(l, activeWindows)
			{
				WindowClause *wc = (WindowClause *) lfirst(l);
				List	   *window_pathkeys;
				int			partNumCols;
				AttrNumber *partColIdx;
				Oid		   *partOperators;
				int			ordNumCols;
				AttrNumber *ordColIdx;
				Oid		   *ordOperators;

				window_pathkeys = make_pathkeys_for_window(root,
														   wc,
														   tlist,
														   true);

				/*
				 * This is a bit tricky: we build a sort node even if we don't
				 * really have to sort.  Even when no explicit sort is needed,
				 * we need to have suitable resjunk items added to the input
				 * plan's tlist for any partitioning or ordering columns that
1600 1601 1602 1603 1604
				 * aren't plain Vars.  (In theory, make_windowInputTargetList
				 * should have provided all such columns, but let's not assume
				 * that here.)  Furthermore, this way we can use existing
				 * infrastructure to identify which input columns are the
				 * interesting ones.
T
Tom Lane 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
				 */
				if (window_pathkeys)
				{
					Sort	   *sort_plan;

					sort_plan = make_sort_from_pathkeys(root,
														result_plan,
														window_pathkeys,
														-1.0);
					if (!pathkeys_contained_in(window_pathkeys,
											   current_pathkeys))
					{
						/* we do indeed need to sort */
						result_plan = (Plan *) sort_plan;
						current_pathkeys = window_pathkeys;
					}
					/* In either case, extract the per-column information */
					get_column_info_for_window(root, wc, tlist,
											   sort_plan->numCols,
											   sort_plan->sortColIdx,
											   &partNumCols,
											   &partColIdx,
											   &partOperators,
											   &ordNumCols,
											   &ordColIdx,
											   &ordOperators);
				}
				else
				{
					/* empty window specification, nothing to sort */
					partNumCols = 0;
					partColIdx = NULL;
					partOperators = NULL;
					ordNumCols = 0;
					ordColIdx = NULL;
					ordOperators = NULL;
				}

				if (lnext(l))
				{
					/* Add the current WindowFuncs to the running tlist */
					window_tlist = add_to_flat_tlist(window_tlist,
1647
										   wflists->windowFuncs[wc->winref]);
T
Tom Lane 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
				}
				else
				{
					/* Install the original tlist in the topmost WindowAgg */
					window_tlist = tlist;
				}

				/* ... and make the WindowAgg plan node */
				result_plan = (Plan *)
					make_windowagg(root,
								   (List *) copyObject(window_tlist),
1659
								   wflists->windowFuncs[wc->winref],
1660
								   wc->winref,
T
Tom Lane 已提交
1661 1662 1663 1664 1665 1666
								   partNumCols,
								   partColIdx,
								   partOperators,
								   ordNumCols,
								   ordColIdx,
								   ordOperators,
1667
								   wc->frameOptions,
1668 1669
								   wc->startOffset,
								   wc->endOffset,
T
Tom Lane 已提交
1670 1671 1672
								   result_plan);
			}
		}
B
Bruce Momjian 已提交
1673
	}							/* end of if (setOperations) */
1674

1675
	/*
1676
	 * If there is a DISTINCT clause, add the necessary node(s).
1677
	 */
1678
	if (parse->distinctClause)
1679
	{
1680 1681
		double		dNumDistinctRows;
		long		numDistinctRows;
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696

		/*
		 * If there was grouping or aggregation, use the current number of
		 * rows as the estimated number of DISTINCT rows (ie, assume the
		 * result was already mostly unique).  If not, use the number of
		 * distinct-groups calculated by query_planner.
		 */
		if (parse->groupClause || root->hasHavingQual || parse->hasAggs)
			dNumDistinctRows = result_plan->plan_rows;
		else
			dNumDistinctRows = dNumGroups;

		/* Also convert to long int --- but 'ware overflow! */
		numDistinctRows = (long) Min(dNumDistinctRows, (double) LONG_MAX);

1697 1698
		/* Choose implementation method if we didn't already */
		if (!tested_hashed_distinct)
1699
		{
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
			/*
			 * At this point, either hashed or sorted grouping will have to
			 * work from result_plan, so we pass that as both "cheapest" and
			 * "sorted".
			 */
			use_hashed_distinct =
				choose_hashed_distinct(root,
									   tuple_fraction, limit_tuples,
									   result_plan->plan_rows,
									   result_plan->plan_width,
									   result_plan->startup_cost,
									   result_plan->total_cost,
									   result_plan->startup_cost,
									   result_plan->total_cost,
									   current_pathkeys,
									   dNumDistinctRows);
1716 1717 1718 1719 1720 1721 1722 1723 1724
		}

		if (use_hashed_distinct)
		{
			/* Hashed aggregate plan --- no sort needed */
			result_plan = (Plan *) make_agg(root,
											result_plan->targetlist,
											NIL,
											AGG_HASHED,
1725
											NULL,
1726 1727 1728 1729
										  list_length(parse->distinctClause),
								 extract_grouping_cols(parse->distinctClause,
													result_plan->targetlist),
								 extract_grouping_ops(parse->distinctClause),
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
											numDistinctRows,
											result_plan);
			/* Hashed aggregation produces randomly-ordered results */
			current_pathkeys = NIL;
		}
		else
		{
			/*
			 * Use a Unique node to implement DISTINCT.  Add an explicit sort
			 * if we couldn't make the path come out the way the Unique node
1740 1741 1742 1743
			 * needs it.  If we do have to sort, always sort by the more
			 * rigorous of DISTINCT and ORDER BY, to avoid a second sort
			 * below.  However, for regular DISTINCT, don't sort now if we
			 * don't have to --- sorting afterwards will likely be cheaper,
1744 1745 1746
			 * and also has the possibility of optimizing via LIMIT.  But for
			 * DISTINCT ON, we *must* force the final sort now, else it won't
			 * have the desired behavior.
1747
			 */
1748
			List	   *needed_pathkeys;
1749 1750 1751 1752 1753 1754 1755 1756 1757

			if (parse->hasDistinctOn &&
				list_length(root->distinct_pathkeys) <
				list_length(root->sort_pathkeys))
				needed_pathkeys = root->sort_pathkeys;
			else
				needed_pathkeys = root->distinct_pathkeys;

			if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
			{
				if (list_length(root->distinct_pathkeys) >=
					list_length(root->sort_pathkeys))
					current_pathkeys = root->distinct_pathkeys;
				else
				{
					current_pathkeys = root->sort_pathkeys;
					/* Assert checks that parser didn't mess up... */
					Assert(pathkeys_contained_in(root->distinct_pathkeys,
												 current_pathkeys));
				}

				result_plan = (Plan *) make_sort_from_pathkeys(root,
															   result_plan,
1772
															current_pathkeys,
1773 1774 1775 1776 1777 1778 1779
															   -1.0);
			}

			result_plan = (Plan *) make_unique(result_plan,
											   parse->distinctClause);
			result_plan->plan_rows = dNumDistinctRows;
			/* The Unique node won't change sort ordering */
1780
		}
1781
	}
1782 1783

	/*
1784 1785
	 * If ORDER BY was given and we were not able to make the plan come out in
	 * the right order, add an explicit sort step.
1786
	 */
1787
	if (parse->sortClause)
1788
	{
1789 1790 1791 1792
		if (!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
		{
			result_plan = (Plan *) make_sort_from_pathkeys(root,
														   result_plan,
1793
														 root->sort_pathkeys,
1794 1795 1796
														   limit_tuples);
			current_pathkeys = root->sort_pathkeys;
		}
1797
	}
1798

1799
	/*
1800
	 * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node. (Note: we
B
Bruce Momjian 已提交
1801 1802 1803
	 * intentionally test parse->rowMarks not root->rowMarks here. If there
	 * are only non-locking rowmarks, they should be handled by the
	 * ModifyTable node instead.)
1804 1805 1806 1807
	 */
	if (parse->rowMarks)
	{
		result_plan = (Plan *) make_lockrows(result_plan,
1808 1809
											 root->rowMarks,
											 SS_assign_special_param(root));
B
Bruce Momjian 已提交
1810

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
		/*
		 * The result can no longer be assumed sorted, since locking might
		 * cause the sort key columns to be replaced with new values.
		 */
		current_pathkeys = NIL;
	}

	/*
	 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
	 */
	if (parse->limitCount || parse->limitOffset)
	{
		result_plan = (Plan *) make_limit(result_plan,
										  parse->limitOffset,
										  parse->limitCount,
										  offset_est,
										  count_est);
1828 1829
	}

1830
	/*
B
Bruce Momjian 已提交
1831 1832
	 * Return the actual output ordering in query_pathkeys for possible use by
	 * an outer query level.
1833
	 */
1834
	root->query_pathkeys = current_pathkeys;
1835

1836
	return result_plan;
1837 1838
}

1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
/*
 * add_tlist_costs_to_plan
 *
 * Estimate the execution costs associated with evaluating the targetlist
 * expressions, and add them to the cost estimates for the Plan node.
 *
 * If the tlist contains set-returning functions, also inflate the Plan's cost
 * and plan_rows estimates accordingly.  (Hence, this must be called *after*
 * any logic that uses plan_rows to, eg, estimate qual evaluation costs.)
 *
 * Note: during initial stages of planning, we mostly consider plan nodes 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 once we apply a
 * tlist that might contain actual operators, sub-selects, etc, we'd better
 * account for its cost.  Any set-returning functions in the tlist must also
 * affect the estimated rowcount.
 *
 * Once grouping_planner() has applied a general tlist to the topmost
 * scan/join plan node, any tlist eval cost for added-on nodes should be
1860
 * accounted for as we create those nodes.	Presently, of the node types we
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
 * can add on later, only Agg, WindowAgg, and Group project new tlists (the
 * rest just copy their input tuples) --- so make_agg(), make_windowagg() and
 * make_group() are responsible for calling this function to account for their
 * tlist costs.
 */
void
add_tlist_costs_to_plan(PlannerInfo *root, Plan *plan, List *tlist)
{
	QualCost	tlist_cost;
	double		tlist_rows;

	cost_qual_eval(&tlist_cost, tlist, root);
	plan->startup_cost += tlist_cost.startup;
	plan->total_cost += tlist_cost.startup +
		tlist_cost.per_tuple * plan->plan_rows;

	tlist_rows = tlist_returns_set_rows(tlist);
	if (tlist_rows > 1)
	{
		/*
		 * We assume that execution costs of the tlist proper were all
		 * accounted for by cost_qual_eval.  However, it still seems
		 * appropriate to charge something more for the executor's general
		 * costs of processing the added tuples.  The cost is probably less
		 * than cpu_tuple_cost, though, so we arbitrarily use half of that.
		 */
		plan->total_cost += plan->plan_rows * (tlist_rows - 1) *
			cpu_tuple_cost / 2;

		plan->plan_rows *= tlist_rows;
	}
}

1894 1895 1896 1897 1898
/*
 * Detect whether a plan node is a "dummy" plan created when a relation
 * is deemed not to need scanning due to constraint exclusion.
 *
 * Currently, such dummy plans are Result nodes with constant FALSE
1899 1900 1901
 * filter quals (see set_dummy_rel_pathlist and create_append_plan).
 *
 * XXX this probably ought to be somewhere else, but not clear where.
1902
 */
1903
bool
1904 1905 1906 1907
is_dummy_plan(Plan *plan)
{
	if (IsA(plan, Result))
	{
B
Bruce Momjian 已提交
1908
		List	   *rcqual = (List *) ((Result *) plan)->resconstantqual;
1909 1910 1911

		if (list_length(rcqual) == 1)
		{
B
Bruce Momjian 已提交
1912
			Const	   *constqual = (Const *) linitial(rcqual);
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

			if (constqual && IsA(constqual, Const))
			{
				if (!constqual->constisnull &&
					!DatumGetBool(constqual->constvalue))
					return true;
			}
		}
	}
	return false;
}

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
/*
 * Create a bitmapset of the RT indexes of live base relations
 *
 * Helper for preprocess_rowmarks ... at this point in the proceedings,
 * the only good way to distinguish baserels from appendrel children
 * is to see what is in the join tree.
 */
static Bitmapset *
get_base_rel_indexes(Node *jtnode)
{
	Bitmapset  *result;

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

		result = bms_make_singleton(varno);
	}
	else if (IsA(jtnode, FromExpr))
	{
		FromExpr   *f = (FromExpr *) jtnode;
		ListCell   *l;

		result = NULL;
		foreach(l, f->fromlist)
			result = bms_join(result,
							  get_base_rel_indexes(lfirst(l)));
	}
	else if (IsA(jtnode, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) jtnode;

		result = bms_join(get_base_rel_indexes(j->larg),
						  get_base_rel_indexes(j->rarg));
	}
	else
	{
		elog(ERROR, "unrecognized node type: %d",
			 (int) nodeTag(jtnode));
		result = NULL;			/* keep compiler quiet */
	}
	return result;
}

/*
 * preprocess_rowmarks - set up PlanRowMarks if needed
 */
static void
preprocess_rowmarks(PlannerInfo *root)
{
	Query	   *parse = root->parse;
	Bitmapset  *rels;
	List	   *prowmarks;
	ListCell   *l;
	int			i;

	if (parse->rowMarks)
	{
		/*
1986
		 * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside grouping,
1987 1988 1989 1990 1991 1992 1993 1994 1995
		 * since grouping renders a reference to individual tuple CTIDs
		 * invalid.  This is also checked at parse time, but that's
		 * insufficient because of rule substitution, query pullup, etc.
		 */
		CheckSelectLocking(parse);
	}
	else
	{
		/*
1996
		 * We only need rowmarks for UPDATE, DELETE, or FOR [KEY] UPDATE/SHARE.
1997 1998 1999 2000 2001 2002 2003
		 */
		if (parse->commandType != CMD_UPDATE &&
			parse->commandType != CMD_DELETE)
			return;
	}

	/*
B
Bruce Momjian 已提交
2004 2005
	 * We need to have rowmarks for all base relations except the target. We
	 * make a bitmapset of all base rels and then remove the items we don't
2006
	 * need or have FOR [KEY] UPDATE/SHARE marks for.
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
	 */
	rels = get_base_rel_indexes((Node *) parse->jointree);
	if (parse->resultRelation)
		rels = bms_del_member(rels, parse->resultRelation);

	/*
	 * Convert RowMarkClauses to PlanRowMark representation.
	 */
	prowmarks = NIL;
	foreach(l, parse->rowMarks)
	{
		RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2019 2020
		RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
		PlanRowMark *newrc;
2021

2022
		/*
2023
		 * Currently, it is syntactically impossible to have FOR UPDATE et al
B
Bruce Momjian 已提交
2024
		 * applied to an update/delete target rel.	If that ever becomes
2025 2026
		 * possible, we should drop the target from the PlanRowMark list.
		 */
2027
		Assert(rc->rti != parse->resultRelation);
2028 2029

		/*
B
Bruce Momjian 已提交
2030 2031 2032 2033
		 * Ignore RowMarkClauses for subqueries; they aren't real tables and
		 * can't support true locking.  Subqueries that got flattened into the
		 * main query should be ignored completely.  Any that didn't will get
		 * ROW_MARK_COPY items in the next loop.
2034 2035 2036 2037
		 */
		if (rte->rtekind != RTE_RELATION)
			continue;

2038 2039
		rels = bms_del_member(rels, rc->rti);

2040
		newrc = makeNode(PlanRowMark);
2041
		newrc->rti = newrc->prti = rc->rti;
2042
		newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
		switch (rc->strength)
		{
			case LCS_FORUPDATE:
				newrc->markType = ROW_MARK_EXCLUSIVE;
				break;
			case LCS_FORNOKEYUPDATE:
				newrc->markType = ROW_MARK_NOKEYEXCLUSIVE;
				break;
			case LCS_FORSHARE:
				newrc->markType = ROW_MARK_SHARE;
				break;
			case LCS_FORKEYSHARE:
				newrc->markType = ROW_MARK_KEYSHARE;
				break;
		}
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
		newrc->noWait = rc->noWait;
		newrc->isParent = false;

		prowmarks = lappend(prowmarks, newrc);
	}

	/*
	 * Now, add rowmarks for any non-target, non-locked base relations.
	 */
	i = 0;
	foreach(l, parse->rtable)
	{
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
		PlanRowMark *newrc;

		i++;
		if (!bms_is_member(i, rels))
			continue;

		newrc = makeNode(PlanRowMark);
		newrc->rti = newrc->prti = i;
2079
		newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2080
		/* real tables support REFERENCE, anything else needs COPY */
2081
		if (rte->rtekind == RTE_RELATION &&
2082
			rte->relkind != RELKIND_FOREIGN_TABLE)
2083 2084 2085
			newrc->markType = ROW_MARK_REFERENCE;
		else
			newrc->markType = ROW_MARK_COPY;
B
Bruce Momjian 已提交
2086
		newrc->noWait = false;	/* doesn't matter */
2087 2088 2089 2090 2091 2092 2093 2094
		newrc->isParent = false;

		prowmarks = lappend(prowmarks, newrc);
	}

	root->rowMarks = prowmarks;
}

2095
/*
2096
 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2097
 *
2098
 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
B
Bruce Momjian 已提交
2099
 * results back in *count_est and *offset_est.	These variables are set to
2100 2101 2102 2103 2104 2105 2106 2107
 * 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 已提交
2108
 * planning the query.	This adjustment is not overridable, since it reflects
2109 2110
 * plan actions that grouping_planner() will certainly take, not assumptions
 * about context.
2111 2112
 */
static double
2113
preprocess_limit(PlannerInfo *root, double tuple_fraction,
B
Bruce Momjian 已提交
2114
				 int64 *offset_est, int64 *count_est)
2115 2116
{
	Query	   *parse = root->parse;
2117 2118
	Node	   *est;
	double		limit_fraction;
2119

2120 2121
	/* Should not be called unless LIMIT or OFFSET */
	Assert(parse->limitCount || parse->limitOffset);
2122 2123

	/*
2124 2125
	 * Try to obtain the clause values.  We use estimate_expression_value
	 * primarily because it can sometimes do something useful with Params.
2126
	 */
2127
	if (parse->limitCount)
2128
	{
2129
		est = estimate_expression_value(root, parse->limitCount);
2130
		if (est && IsA(est, Const))
2131
		{
2132
			if (((Const *) est)->constisnull)
2133
			{
2134
				/* NULL indicates LIMIT ALL, ie, no limit */
B
Bruce Momjian 已提交
2135
				*count_est = 0; /* treat as not present */
2136 2137 2138
			}
			else
			{
B
Bruce Momjian 已提交
2139
				*count_est = DatumGetInt64(((Const *) est)->constvalue);
2140 2141
				if (*count_est <= 0)
					*count_est = 1;		/* force to at least 1 */
2142 2143
			}
		}
2144 2145
		else
			*count_est = -1;	/* can't estimate */
2146 2147
	}
	else
2148 2149 2150
		*count_est = 0;			/* not present */

	if (parse->limitOffset)
2151
	{
2152
		est = estimate_expression_value(root, parse->limitOffset);
2153 2154 2155 2156 2157
		if (est && IsA(est, Const))
		{
			if (((Const *) est)->constisnull)
			{
				/* Treat NULL as no offset; the executor will too */
B
Bruce Momjian 已提交
2158
				*offset_est = 0;	/* treat as not present */
2159 2160 2161
			}
			else
			{
B
Bruce Momjian 已提交
2162
				*offset_est = DatumGetInt64(((Const *) est)->constvalue);
2163 2164 2165 2166 2167 2168
				if (*offset_est < 0)
					*offset_est = 0;	/* less than 0 is same as 0 */
			}
		}
		else
			*offset_est = -1;	/* can't estimate */
2169
	}
2170 2171
	else
		*offset_est = 0;		/* not present */
2172

2173
	if (*count_est != 0)
2174
	{
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
		/*
		 * 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;
		}

2191 2192
		/*
		 * If we have absolute limits from both caller and LIMIT, use the
2193 2194 2195 2196
		 * 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.
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
		 */
		if (tuple_fraction >= 1.0)
		{
			if (limit_fraction >= 1.0)
			{
				/* both absolute */
				tuple_fraction = Min(tuple_fraction, limit_fraction);
			}
			else
			{
2207
				/* caller absolute, limit fractional; use caller's value */
2208 2209 2210 2211 2212 2213
			}
		}
		else if (tuple_fraction > 0.0)
		{
			if (limit_fraction >= 1.0)
			{
2214 2215
				/* caller fractional, limit absolute; use limit */
				tuple_fraction = limit_fraction;
2216 2217 2218 2219
			}
			else
			{
				/* both fractional */
2220
				tuple_fraction = Min(tuple_fraction, limit_fraction);
2221 2222 2223 2224 2225 2226 2227 2228
			}
		}
		else
		{
			/* no info from caller, just use limit */
			tuple_fraction = limit_fraction;
		}
	}
2229 2230 2231
	else if (*offset_est != 0 && tuple_fraction > 0.0)
	{
		/*
B
Bruce Momjian 已提交
2232 2233 2234 2235 2236
		 * 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.
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
		 *
		 * 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 已提交
2247 2248 2249
		 * 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.
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
		 */
		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 已提交
2275
					tuple_fraction = 0.0;		/* assume fetch all */
2276 2277 2278
			}
		}
	}
2279 2280 2281 2282

	return tuple_fraction;
}

2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295

/*
 * preprocess_groupclause - do preparatory work on GROUP BY clause
 *
 * The idea here is to adjust the ordering of the GROUP BY elements
 * (which in itself is semantically insignificant) to match ORDER BY,
 * thereby allowing a single sort operation to both implement the ORDER BY
 * requirement and set up for a Unique step that implements GROUP BY.
 *
 * In principle it might be interesting to consider other orderings of the
 * GROUP BY elements, which could match the sort ordering of other
 * possible plans (eg an indexscan) and thereby reduce cost.  We don't
 * bother with that, though.  Hashed grouping will frequently win anyway.
2296 2297 2298
 *
 * Note: we need no comparable processing of the distinctClause because
 * the parser already enforced that that matches ORDER BY.
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
 */
static void
preprocess_groupclause(PlannerInfo *root)
{
	Query	   *parse = root->parse;
	List	   *new_groupclause;
	bool		partial_match;
	ListCell   *sl;
	ListCell   *gl;

2309
	/* If no ORDER BY, nothing useful to do here */
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
	if (parse->sortClause == NIL)
		return;

	/*
	 * Scan the ORDER BY clause and construct a list of matching GROUP BY
	 * items, but only as far as we can make a matching prefix.
	 *
	 * This code assumes that the sortClause contains no duplicate items.
	 */
	new_groupclause = NIL;
	foreach(sl, parse->sortClause)
	{
		SortGroupClause *sc = (SortGroupClause *) lfirst(sl);

		foreach(gl, parse->groupClause)
		{
			SortGroupClause *gc = (SortGroupClause *) lfirst(gl);

			if (equal(gc, sc))
			{
				new_groupclause = lappend(new_groupclause, gc);
				break;
			}
		}
		if (gl == NULL)
			break;				/* no match, so stop scanning */
	}

	/* Did we match all of the ORDER BY list, or just some of it? */
	partial_match = (sl != NULL);

	/* If no match at all, no point in reordering GROUP BY */
	if (new_groupclause == NIL)
		return;

	/*
2346 2347 2348 2349 2350 2351
	 * Add any remaining GROUP BY items to the new list, but only if we were
	 * able to make a complete match.  In other words, we only rearrange the
	 * GROUP BY list if the result is that one list is a prefix of the other
	 * --- otherwise there's no possibility of a common sort.  Also, give up
	 * if there are any non-sortable GROUP BY items, since then there's no
	 * hope anyway.
2352 2353 2354 2355 2356 2357 2358 2359 2360
	 */
	foreach(gl, parse->groupClause)
	{
		SortGroupClause *gc = (SortGroupClause *) lfirst(gl);

		if (list_member_ptr(new_groupclause, gc))
			continue;			/* it matched an ORDER BY item */
		if (partial_match)
			return;				/* give up, no common sort possible */
2361 2362
		if (!OidIsValid(gc->sortop))
			return;				/* give up, GROUP BY can't be sorted */
2363 2364 2365 2366 2367 2368 2369 2370
		new_groupclause = lappend(new_groupclause, gc);
	}

	/* Success --- install the rearranged GROUP BY list */
	Assert(list_length(parse->groupClause) == list_length(new_groupclause));
	parse->groupClause = new_groupclause;
}

2371 2372
/*
 * choose_hashed_grouping - should we use hashed grouping?
2373
 *
2374
 * Returns TRUE to select hashing, FALSE to select sorting.
2375 2376
 */
static bool
2377 2378
choose_hashed_grouping(PlannerInfo *root,
					   double tuple_fraction, double limit_tuples,
2379
					   double path_rows, int path_width,
2380
					   Path *cheapest_path, Path *sorted_path,
2381
					   double dNumGroups, AggClauseCosts *agg_costs)
2382
{
2383 2384 2385 2386
	Query	   *parse = root->parse;
	int			numGroupCols = list_length(parse->groupClause);
	bool		can_hash;
	bool		can_sort;
2387
	Size		hashentrysize;
2388
	List	   *target_pathkeys;
2389 2390 2391 2392
	List	   *current_pathkeys;
	Path		hashed_p;
	Path		sorted_p;

2393 2394
	/*
	 * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
B
Bruce Momjian 已提交
2395
	 * aggregates.	(Doing so would imply storing *all* the input values in
2396 2397 2398
	 * the hash table, and/or running many sorts in parallel, either of which
	 * seems like a certain loser.)
	 */
2399
	can_hash = (agg_costs->numOrderedAggs == 0 &&
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
				grouping_is_hashable(parse->groupClause));
	can_sort = grouping_is_sortable(parse->groupClause);

	/* Quick out if only one choice is workable */
	if (!(can_hash && can_sort))
	{
		if (can_hash)
			return true;
		else if (can_sort)
			return false;
		else
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("could not implement GROUP BY"),
					 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
	}

2417
	/* Prefer sorting when enable_hashagg is off */
2418 2419 2420 2421 2422 2423 2424 2425 2426
	if (!enable_hashagg)
		return false;

	/*
	 * Don't do it if it doesn't look like the hashtable will fit into
	 * work_mem.
	 */

	/* Estimate per-hash-entry space at tuple width... */
2427
	hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2428
	/* plus space for pass-by-ref transition values... */
2429
	hashentrysize += agg_costs->transitionSpace;
2430
	/* plus the per-hash-entry overhead */
2431
	hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
2432 2433 2434 2435

	if (hashentrysize * dNumGroups > work_mem * 1024L)
		return false;

2436 2437
	/*
	 * When we have both GROUP BY and DISTINCT, use the more-rigorous of
2438 2439 2440 2441
	 * DISTINCT and ORDER BY as the assumed required output sort order. This
	 * is an oversimplification because the DISTINCT might get implemented via
	 * hashing, but it's not clear that the case is common enough (or that our
	 * estimates are good enough) to justify trying to solve it exactly.
2442 2443 2444 2445 2446 2447 2448
	 */
	if (list_length(root->distinct_pathkeys) >
		list_length(root->sort_pathkeys))
		target_pathkeys = root->distinct_pathkeys;
	else
		target_pathkeys = root->sort_pathkeys;

2449
	/*
B
Bruce Momjian 已提交
2450 2451 2452 2453
	 * 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.
2454
	 *
2455 2456 2457 2458 2459 2460
	 * 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.
2461
	 *
2462 2463
	 * These path variables are dummies that just hold cost fields; we don't
	 * make actual Paths for these steps.
2464
	 */
2465
	cost_agg(&hashed_p, root, AGG_HASHED, agg_costs,
2466 2467
			 numGroupCols, dNumGroups,
			 cheapest_path->startup_cost, cheapest_path->total_cost,
2468
			 path_rows);
2469
	/* Result of hashed agg is always unsorted */
2470 2471
	if (target_pathkeys)
		cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
2472 2473
				  dNumGroups, path_width,
				  0.0, work_mem, limit_tuples);
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486

	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
	{
		sorted_p.startup_cost = cheapest_path->startup_cost;
		sorted_p.total_cost = cheapest_path->total_cost;
		current_pathkeys = cheapest_path->pathkeys;
	}
2487
	if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
2488
	{
2489
		cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
2490 2491
				  path_rows, path_width,
				  0.0, work_mem, -1.0);
2492
		current_pathkeys = root->group_pathkeys;
2493 2494
	}

2495
	if (parse->hasAggs)
2496
		cost_agg(&sorted_p, root, AGG_SORTED, agg_costs,
2497 2498
				 numGroupCols, dNumGroups,
				 sorted_p.startup_cost, sorted_p.total_cost,
2499
				 path_rows);
2500
	else
2501
		cost_group(&sorted_p, root, numGroupCols, dNumGroups,
2502
				   sorted_p.startup_cost, sorted_p.total_cost,
2503
				   path_rows);
2504
	/* The Agg or Group node will preserve ordering */
2505 2506 2507
	if (target_pathkeys &&
		!pathkeys_contained_in(target_pathkeys, current_pathkeys))
		cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
2508 2509
				  dNumGroups, path_width,
				  0.0, work_mem, limit_tuples);
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526

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

	if (compare_fractional_path_costs(&hashed_p, &sorted_p,
									  tuple_fraction) < 0)
	{
		/* Hashed is cheaper, so use it */
		return true;
	}
	return false;
}

2527 2528 2529 2530 2531
/*
 * choose_hashed_distinct - should we use hashing for DISTINCT?
 *
 * This is fairly similar to choose_hashed_grouping, but there are enough
 * differences that it doesn't seem worth trying to unify the two functions.
2532 2533 2534
 * (One difference is that we sometimes apply this after forming a Plan,
 * so the input alternatives can't be represented as Paths --- instead we
 * pass in the costs as individual variables.)
2535 2536
 *
 * But note that making the two choices independently is a bit bogus in
2537
 * itself.	If the two could be combined into a single choice operation
2538 2539 2540 2541 2542 2543
 * it'd probably be better, but that seems far too unwieldy to be practical,
 * especially considering that the combination of GROUP BY and DISTINCT
 * isn't very common in real queries.  By separating them, we are giving
 * extra preference to using a sorting implementation when a common sort key
 * is available ... and that's not necessarily wrong anyway.
 *
2544
 * Returns TRUE to select hashing, FALSE to select sorting.
2545 2546 2547 2548
 */
static bool
choose_hashed_distinct(PlannerInfo *root,
					   double tuple_fraction, double limit_tuples,
2549 2550 2551 2552
					   double path_rows, int path_width,
					   Cost cheapest_startup_cost, Cost cheapest_total_cost,
					   Cost sorted_startup_cost, Cost sorted_total_cost,
					   List *sorted_pathkeys,
2553 2554
					   double dNumDistinctRows)
{
2555 2556 2557 2558
	Query	   *parse = root->parse;
	int			numDistinctCols = list_length(parse->distinctClause);
	bool		can_sort;
	bool		can_hash;
2559 2560
	Size		hashentrysize;
	List	   *current_pathkeys;
2561
	List	   *needed_pathkeys;
2562 2563 2564
	Path		hashed_p;
	Path		sorted_p;

2565
	/*
B
Bruce Momjian 已提交
2566 2567
	 * If we have a sortable DISTINCT ON clause, we always use sorting. This
	 * enforces the expected behavior of DISTINCT ON.
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
	 */
	can_sort = grouping_is_sortable(parse->distinctClause);
	if (can_sort && parse->hasDistinctOn)
		return false;

	can_hash = grouping_is_hashable(parse->distinctClause);

	/* Quick out if only one choice is workable */
	if (!(can_hash && can_sort))
	{
		if (can_hash)
			return true;
		else if (can_sort)
			return false;
		else
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("could not implement DISTINCT"),
					 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
	}

2589 2590 2591 2592 2593 2594 2595 2596
	/* Prefer sorting when enable_hashagg is off */
	if (!enable_hashagg)
		return false;

	/*
	 * Don't do it if it doesn't look like the hashtable will fit into
	 * work_mem.
	 */
2597
	hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607

	if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
		return false;

	/*
	 * 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.
	 *
2608 2609
	 * We need to consider cheapest_path + hashagg [+ final sort] versus
	 * sorted_path [+ sort] + group [+ final sort] where brackets indicate a
2610
	 * step that may not be needed.
2611 2612 2613 2614
	 *
	 * These path variables are dummies that just hold cost fields; we don't
	 * make actual Paths for these steps.
	 */
2615
	cost_agg(&hashed_p, root, AGG_HASHED, NULL,
2616
			 numDistinctCols, dNumDistinctRows,
2617 2618
			 cheapest_startup_cost, cheapest_total_cost,
			 path_rows);
2619

2620
	/*
2621 2622
	 * Result of hashed agg is always unsorted, so if ORDER BY is present we
	 * need to charge for the final sort.
2623
	 */
2624
	if (parse->sortClause)
2625
		cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2626 2627
				  dNumDistinctRows, path_width,
				  0.0, work_mem, limit_tuples);
2628

2629
	/*
2630
	 * Now for the GROUP case.	See comments in grouping_planner about the
2631 2632
	 * sorting choices here --- this code should match that code.
	 */
2633 2634 2635 2636
	sorted_p.startup_cost = sorted_startup_cost;
	sorted_p.total_cost = sorted_total_cost;
	current_pathkeys = sorted_pathkeys;
	if (parse->hasDistinctOn &&
2637 2638 2639 2640 2641 2642
		list_length(root->distinct_pathkeys) <
		list_length(root->sort_pathkeys))
		needed_pathkeys = root->sort_pathkeys;
	else
		needed_pathkeys = root->distinct_pathkeys;
	if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
2643 2644 2645 2646 2647 2648 2649
	{
		if (list_length(root->distinct_pathkeys) >=
			list_length(root->sort_pathkeys))
			current_pathkeys = root->distinct_pathkeys;
		else
			current_pathkeys = root->sort_pathkeys;
		cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
2650 2651
				  path_rows, path_width,
				  0.0, work_mem, -1.0);
2652 2653 2654
	}
	cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
			   sorted_p.startup_cost, sorted_p.total_cost,
2655 2656
			   path_rows);
	if (parse->sortClause &&
2657 2658
		!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
		cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2659 2660
				  dNumDistinctRows, path_width,
				  0.0, work_mem, limit_tuples);
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677

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

	if (compare_fractional_path_costs(&hashed_p, &sorted_p,
									  tuple_fraction) < 0)
	{
		/* Hashed is cheaper, so use it */
		return true;
	}
	return false;
}

2678
/*
2679
 * make_subplanTargetList
2680
 *	  Generate appropriate target list when grouping is required.
2681
 *
2682 2683 2684 2685 2686
 * When grouping_planner inserts grouping or aggregation plan nodes
 * above the scan/join plan constructed by query_planner+create_plan,
 * we typically want the scan/join plan to emit a different target list
 * than the outer plan nodes should have.  This routine generates the
 * correct target list for the scan/join subplan.
2687 2688 2689 2690
 *
 * 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
2691 2692 2693 2694
 * 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
2695 2696
 *		SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
 * we want to pass this targetlist to the subplan:
2697
 *		a+b,c,d
2698
 * where the a+b target will be used by the Sort/Group steps, and the
2699
 * other targets will be used for computing the final results.
2700
 *
2701 2702 2703
 * 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
2704 2705 2706 2707
 * should be present in the "flat" tlist generated by create_plan, though
 * possibly in a different order.  In that case we'll use create_plan's tlist,
 * and the tlist made here is only needed as input to query_planner to tell
 * it which Vars are needed in the output of the scan/join plan.
2708
 *
2709
 * 'tlist' is the query's target list.
2710
 * 'groupColIdx' receives an array of column numbers for the GROUP BY
2711
 *			expressions (if there are any) in the returned target list.
2712
 * 'need_tlist_eval' is set true if we really need to evaluate the
2713
 *			returned tlist as-is.
2714
 *
2715
 * The result is the targetlist to be passed to query_planner.
2716 2717
 */
static List *
2718
make_subplanTargetList(PlannerInfo *root,
2719
					   List *tlist,
2720 2721
					   AttrNumber **groupColIdx,
					   bool *need_tlist_eval)
2722
{
2723
	Query	   *parse = root->parse;
2724
	List	   *sub_tlist;
2725 2726
	List	   *non_group_cols;
	List	   *non_group_vars;
2727 2728 2729 2730
	int			numCols;

	*groupColIdx = NULL;

B
Bruce Momjian 已提交
2731
	/*
2732
	 * If we're not grouping or aggregating, there's nothing to do here;
2733 2734
	 * query_planner should receive the unmodified target list.
	 */
T
Tom Lane 已提交
2735 2736
	if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual &&
		!parse->hasWindowFuncs)
2737 2738
	{
		*need_tlist_eval = true;
2739
		return tlist;
2740
	}
2741

B
Bruce Momjian 已提交
2742
	/*
2743 2744
	 * Otherwise, we must build a tlist containing all grouping columns, plus
	 * any other Vars mentioned in the targetlist and HAVING qual.
2745
	 */
2746 2747
	sub_tlist = NIL;
	non_group_cols = NIL;
2748
	*need_tlist_eval = false;	/* only eval if not flat tlist */
2749

2750
	numCols = list_length(parse->groupClause);
2751
	if (numCols > 0)
2752
	{
2753 2754 2755 2756 2757 2758 2759
		/*
		 * If grouping, create sub_tlist entries for all GROUP BY columns, and
		 * make an array showing where the group columns are in the sub_tlist.
		 *
		 * Note: with this implementation, the array entries will always be
		 * 1..N, but we don't want callers to assume that.
		 */
2760
		AttrNumber *grpColIdx;
2761
		ListCell   *tl;
2762

2763
		grpColIdx = (AttrNumber *) palloc0(sizeof(AttrNumber) * numCols);
2764
		*groupColIdx = grpColIdx;
2765

2766
		foreach(tl, tlist)
2767
		{
2768 2769
			TargetEntry *tle = (TargetEntry *) lfirst(tl);
			int			colno;
2770

2771 2772 2773 2774 2775 2776 2777 2778
			colno = get_grouping_column_index(parse, tle);
			if (colno >= 0)
			{
				/*
				 * It's a grouping column, so add it to the result tlist and
				 * remember its resno in grpColIdx[].
				 */
				TargetEntry *newtle;
2779

2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
				newtle = makeTargetEntry(tle->expr,
										 list_length(sub_tlist) + 1,
										 NULL,
										 false);
				sub_tlist = lappend(sub_tlist, newtle);

				Assert(grpColIdx[colno] == 0);	/* no dups expected */
				grpColIdx[colno] = newtle->resno;

				if (!(newtle->expr && IsA(newtle->expr, Var)))
					*need_tlist_eval = true;	/* tlist contains non Vars */
			}
			else
2793
			{
2794
				/*
2795 2796
				 * Non-grouping column, so just remember the expression for
				 * later call to pull_var_clause.  There's no need for
2797 2798 2799
				 * pull_var_clause to examine the TargetEntry node itself.
				 */
				non_group_cols = lappend(non_group_cols, tle->expr);
2800 2801 2802
			}
		}
	}
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
	else
	{
		/*
		 * With no grouping columns, just pass whole tlist to pull_var_clause.
		 * Need (shallow) copy to avoid damaging input tlist below.
		 */
		non_group_cols = list_copy(tlist);
	}

	/*
	 * If there's a HAVING clause, we'll need the Vars it uses, too.
	 */
	if (parse->havingQual)
		non_group_cols = lappend(non_group_cols, parse->havingQual);

	/*
	 * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
	 * add them to the result tlist if not already present.  (A Var used
	 * directly as a GROUP BY item will be present already.)  Note this
	 * includes Vars used in resjunk items, so we are covering the needs of
2823
	 * ORDER BY and window specifications.	Vars used within Aggrefs will be
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
	 * pulled out here, too.
	 */
	non_group_vars = pull_var_clause((Node *) non_group_cols,
									 PVC_RECURSE_AGGREGATES,
									 PVC_INCLUDE_PLACEHOLDERS);
	sub_tlist = add_to_flat_tlist(sub_tlist, non_group_vars);

	/* clean up cruft */
	list_free(non_group_vars);
	list_free(non_group_cols);
2834 2835 2836 2837

	return sub_tlist;
}

2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
/*
 * get_grouping_column_index
 *		Get the GROUP BY column position, if any, of a targetlist entry.
 *
 * Returns the index (counting from 0) of the TLE in the GROUP BY list, or -1
 * if it's not a grouping column.  Note: the result is unique because the
 * parser won't make multiple groupClause entries for the same TLE.
 */
static int
get_grouping_column_index(Query *parse, TargetEntry *tle)
{
	int			colno = 0;
	Index		ressortgroupref = tle->ressortgroupref;
	ListCell   *gl;

	/* No need to search groupClause if TLE hasn't got a sortgroupref */
	if (ressortgroupref == 0)
		return -1;

	foreach(gl, parse->groupClause)
	{
		SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);

		if (grpcl->tleSortGroupRef == ressortgroupref)
			return colno;
		colno++;
	}

	return -1;
}

2869 2870
/*
 * locate_grouping_columns
2871
 *		Locate grouping columns in the tlist chosen by create_plan.
2872 2873
 *
 * This is only needed if we don't use the sub_tlist chosen by
B
Bruce Momjian 已提交
2874
 * make_subplanTargetList.	We have to forget the column indexes found
T
Tom Lane 已提交
2875
 * by that routine and re-locate the grouping exprs in the real sub_tlist.
2876 2877
 */
static void
2878
locate_grouping_columns(PlannerInfo *root,
2879 2880 2881 2882 2883
						List *tlist,
						List *sub_tlist,
						AttrNumber *groupColIdx)
{
	int			keyno = 0;
2884
	ListCell   *gl;
2885 2886 2887 2888

	/*
	 * No work unless grouping.
	 */
2889
	if (!root->parse->groupClause)
2890 2891 2892 2893 2894 2895
	{
		Assert(groupColIdx == NULL);
		return;
	}
	Assert(groupColIdx != NULL);

2896
	foreach(gl, root->parse->groupClause)
2897
	{
2898
		SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
B
Bruce Momjian 已提交
2899
		Node	   *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
T
Tom Lane 已提交
2900
		TargetEntry *te = tlist_member(groupexpr, sub_tlist);
2901

T
Tom Lane 已提交
2902
		if (!te)
2903
			elog(ERROR, "failed to locate grouping columns");
2904
		groupColIdx[keyno++] = te->resno;
2905 2906 2907
	}
}

2908 2909 2910 2911 2912 2913 2914
/*
 * 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
2915
 * new tlist to evaluate the resjunk columns.  For now, just ereport if we
2916 2917 2918 2919 2920
 * find any resjunk columns in orig_tlist.
 */
static List *
postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
{
2921 2922
	ListCell   *l;
	ListCell   *orig_tlist_item = list_head(orig_tlist);
2923 2924 2925 2926 2927 2928 2929

	foreach(l, new_tlist)
	{
		TargetEntry *new_tle = (TargetEntry *) lfirst(l);
		TargetEntry *orig_tle;

		/* ignore resjunk columns in setop result */
2930
		if (new_tle->resjunk)
2931 2932
			continue;

2933 2934 2935
		Assert(orig_tlist_item != NULL);
		orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
		orig_tlist_item = lnext(orig_tlist_item);
B
Bruce Momjian 已提交
2936
		if (orig_tle->resjunk)	/* should not happen */
2937
			elog(ERROR, "resjunk output columns are not implemented");
2938 2939
		Assert(new_tle->resno == orig_tle->resno);
		new_tle->ressortgroupref = orig_tle->ressortgroupref;
2940
	}
2941
	if (orig_tlist_item != NULL)
2942
		elog(ERROR, "resjunk output columns are not implemented");
2943 2944
	return new_tlist;
}
T
Tom Lane 已提交
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976

/*
 * select_active_windows
 *		Create a list of the "active" window clauses (ie, those referenced
 *		by non-deleted WindowFuncs) in the order they are to be executed.
 */
static List *
select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
{
	List	   *result;
	List	   *actives;
	ListCell   *lc;

	/* First, make a list of the active windows */
	actives = NIL;
	foreach(lc, root->parse->windowClause)
	{
		WindowClause *wc = (WindowClause *) lfirst(lc);

		/* It's only active if wflists shows some related WindowFuncs */
		Assert(wc->winref <= wflists->maxWinRef);
		if (wflists->windowFuncs[wc->winref] != NIL)
			actives = lappend(actives, wc);
	}

	/*
	 * Now, ensure that windows with identical partitioning/ordering clauses
	 * are adjacent in the list.  This is required by the SQL standard, which
	 * says that only one sort is to be used for such windows, even if they
	 * are otherwise distinct (eg, different names or framing clauses).
	 *
	 * There is room to be much smarter here, for example detecting whether
2977 2978 2979 2980
	 * one window's sort keys are a prefix of another's (so that sorting for
	 * the latter would do for the former), or putting windows first that
	 * match a sort order available for the underlying query.  For the moment
	 * we are content with meeting the spec.
T
Tom Lane 已提交
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
	 */
	result = NIL;
	while (actives != NIL)
	{
		WindowClause *wc = (WindowClause *) linitial(actives);
		ListCell   *prev;
		ListCell   *next;

		/* Move wc from actives to result */
		actives = list_delete_first(actives);
		result = lappend(result, wc);

		/* Now move any matching windows from actives to result */
		prev = NULL;
		for (lc = list_head(actives); lc; lc = next)
		{
			WindowClause *wc2 = (WindowClause *) lfirst(lc);

			next = lnext(lc);
3000
			/* framing options are NOT to be compared here! */
T
Tom Lane 已提交
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
			if (equal(wc->partitionClause, wc2->partitionClause) &&
				equal(wc->orderClause, wc2->orderClause))
			{
				actives = list_delete_cell(actives, lc, prev);
				result = lappend(result, wc2);
			}
			else
				prev = lc;
		}
	}

	return result;
}

3015
/*
3016 3017 3018 3019 3020 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
 * make_windowInputTargetList
 *	  Generate appropriate target list for initial input to WindowAgg nodes.
 *
 * When grouping_planner inserts one or more WindowAgg nodes into the plan,
 * this function computes the initial target list to be computed by the node
 * just below the first WindowAgg.  This list must contain all values needed
 * to evaluate the window functions, compute the final target list, and
 * perform any required final sort step.  If multiple WindowAggs are needed,
 * each intermediate one adds its window function results onto this tlist;
 * only the topmost WindowAgg computes the actual desired target list.
 *
 * This function is much like make_subplanTargetList, though not quite enough
 * like it to share code.  As in that function, we flatten most expressions
 * into their component variables.  But we do not want to flatten window
 * PARTITION BY/ORDER BY clauses, since that might result in multiple
 * evaluations of them, which would be bad (possibly even resulting in
 * inconsistent answers, if they contain volatile functions).  Also, we must
 * not flatten GROUP BY clauses that were left unflattened by
 * make_subplanTargetList, because we may no longer have access to the
 * individual Vars in them.
 *
 * Another key difference from make_subplanTargetList is that we don't flatten
 * Aggref expressions, since those are to be computed below the window
 * functions and just referenced like Vars above that.
 *
 * 'tlist' is the query's final target list.
 * 'activeWindows' is the list of active windows previously identified by
 *			select_active_windows.
 *
 * The result is the targetlist to be computed by the plan node immediately
 * below the first WindowAgg node.
3047 3048
 */
static List *
3049 3050 3051
make_windowInputTargetList(PlannerInfo *root,
						   List *tlist,
						   List *activeWindows)
3052
{
3053 3054 3055 3056 3057
	Query	   *parse = root->parse;
	Bitmapset  *sgrefs;
	List	   *new_tlist;
	List	   *flattenable_cols;
	List	   *flattenable_vars;
3058 3059
	ListCell   *lc;

3060 3061 3062 3063 3064 3065 3066
	Assert(parse->hasWindowFuncs);

	/*
	 * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
	 * into a bitmapset for convenient reference below.
	 */
	sgrefs = NULL;
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
	foreach(lc, activeWindows)
	{
		WindowClause *wc = (WindowClause *) lfirst(lc);
		ListCell   *lc2;

		foreach(lc2, wc->partitionClause)
		{
			SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);

			sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
		}
		foreach(lc2, wc->orderClause)
		{
			SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);

			sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
		}
	}

3086 3087 3088 3089 3090 3091 3092 3093
	/* Add in sortgroupref numbers of GROUP BY clauses, too */
	foreach(lc, parse->groupClause)
	{
		SortGroupClause *grpcl = (SortGroupClause *) lfirst(lc);

		sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
	}

3094
	/*
3095 3096
	 * Construct a tlist containing all the non-flattenable tlist items, and
	 * save aside the others for a moment.
3097
	 */
3098 3099 3100
	new_tlist = NIL;
	flattenable_cols = NIL;

3101 3102 3103 3104
	foreach(lc, tlist)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(lc);

3105 3106 3107 3108 3109
		/*
		 * Don't want to deconstruct window clauses or GROUP BY items.  (Note
		 * that such items can't contain window functions, so it's okay to
		 * compute them below the WindowAgg nodes.)
		 */
3110
		if (tle->ressortgroupref != 0 &&
3111
			bms_is_member(tle->ressortgroupref, sgrefs))
3112
		{
3113
			/* Don't want to deconstruct this value, so add to new_tlist */
3114 3115 3116
			TargetEntry *newtle;

			newtle = makeTargetEntry(tle->expr,
3117
									 list_length(new_tlist) + 1,
3118 3119
									 NULL,
									 false);
3120
			/* Preserve its sortgroupref marking, in case it's volatile */
3121
			newtle->ressortgroupref = tle->ressortgroupref;
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
			new_tlist = lappend(new_tlist, newtle);
		}
		else
		{
			/*
			 * Column is to be flattened, so just remember the expression for
			 * later call to pull_var_clause.  There's no need for
			 * pull_var_clause to examine the TargetEntry node itself.
			 */
			flattenable_cols = lappend(flattenable_cols, tle->expr);
3132 3133 3134
		}
	}

3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
	/*
	 * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
	 * add them to the result tlist if not already present.  (Some might be
	 * there already because they're used directly as window/group clauses.)
	 *
	 * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that the
	 * Aggrefs are placed in the Agg node's tlist and not left to be computed
	 * at higher levels.
	 */
	flattenable_vars = pull_var_clause((Node *) flattenable_cols,
									   PVC_INCLUDE_AGGREGATES,
									   PVC_INCLUDE_PLACEHOLDERS);
	new_tlist = add_to_flat_tlist(new_tlist, flattenable_vars);

	/* clean up cruft */
	list_free(flattenable_vars);
	list_free(flattenable_cols);

	return new_tlist;
3154 3155
}

T
Tom Lane 已提交
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
/*
 * make_pathkeys_for_window
 *		Create a pathkeys list describing the required input ordering
 *		for the given WindowClause.
 *
 * The required ordering is first the PARTITION keys, then the ORDER keys.
 * In the future we might try to implement windowing using hashing, in which
 * case the ordering could be relaxed, but for now we always sort.
 */
static List *
make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
						 List *tlist, bool canonicalize)
{
	List	   *window_pathkeys;
	List	   *window_sortclauses;

	/* Throw error if can't sort */
	if (!grouping_is_sortable(wc->partitionClause))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("could not implement window PARTITION BY"),
				 errdetail("Window partitioning columns must be of sortable datatypes.")));
	if (!grouping_is_sortable(wc->orderClause))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("could not implement window ORDER BY"),
3182
		errdetail("Window ordering columns must be of sortable datatypes.")));
T
Tom Lane 已提交
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202

	/* Okay, make the combined pathkeys */
	window_sortclauses = list_concat(list_copy(wc->partitionClause),
									 list_copy(wc->orderClause));
	window_pathkeys = make_pathkeys_for_sortclauses(root,
													window_sortclauses,
													tlist,
													canonicalize);
	list_free(window_sortclauses);
	return window_pathkeys;
}

/*----------
 * get_column_info_for_window
 *		Get the partitioning/ordering column numbers and equality operators
 *		for a WindowAgg node.
 *
 * This depends on the behavior of make_pathkeys_for_window()!
 *
 * We are given the target WindowClause and an array of the input column
3203
 * numbers associated with the resulting pathkeys.	In the easy case, there
T
Tom Lane 已提交
3204 3205 3206 3207 3208 3209 3210
 * are the same number of pathkey columns as partitioning + ordering columns
 * and we just have to copy some data around.  However, it's possible that
 * some of the original partitioning + ordering columns were eliminated as
 * redundant during the transformation to pathkeys.  (This can happen even
 * though the parser gets rid of obvious duplicates.  A typical scenario is a
 * window specification "PARTITION BY x ORDER BY y" coupled with a clause
 * "WHERE x = y" that causes the two sort columns to be recognized as
3211
 * redundant.)	In that unusual case, we have to work a lot harder to
T
Tom Lane 已提交
3212 3213 3214
 * determine which keys are significant.
 *
 * The method used here is a bit brute-force: add the sort columns to a list
3215
 * one at a time and note when the resulting pathkey list gets longer.	But
T
Tom Lane 已提交
3216 3217 3218 3219 3220 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
 * it's a sufficiently uncommon case that a faster way doesn't seem worth
 * the amount of code refactoring that'd be needed.
 *----------
 */
static void
get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
						   int numSortCols, AttrNumber *sortColIdx,
						   int *partNumCols,
						   AttrNumber **partColIdx,
						   Oid **partOperators,
						   int *ordNumCols,
						   AttrNumber **ordColIdx,
						   Oid **ordOperators)
{
	int			numPart = list_length(wc->partitionClause);
	int			numOrder = list_length(wc->orderClause);

	if (numSortCols == numPart + numOrder)
	{
		/* easy case */
		*partNumCols = numPart;
		*partColIdx = sortColIdx;
		*partOperators = extract_grouping_ops(wc->partitionClause);
		*ordNumCols = numOrder;
		*ordColIdx = sortColIdx + numPart;
		*ordOperators = extract_grouping_ops(wc->orderClause);
	}
	else
	{
		List	   *sortclauses;
		List	   *pathkeys;
		int			scidx;
		ListCell   *lc;

		/* first, allocate what's certainly enough space for the arrays */
		*partNumCols = 0;
		*partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
		*partOperators = (Oid *) palloc(numPart * sizeof(Oid));
		*ordNumCols = 0;
		*ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
		*ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
		sortclauses = NIL;
		pathkeys = NIL;
		scidx = 0;
		foreach(lc, wc->partitionClause)
		{
			SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
			List	   *new_pathkeys;

			sortclauses = lappend(sortclauses, sgc);
			new_pathkeys = make_pathkeys_for_sortclauses(root,
														 sortclauses,
														 tlist,
														 true);
			if (list_length(new_pathkeys) > list_length(pathkeys))
			{
				/* this sort clause is actually significant */
3273 3274
				(*partColIdx)[*partNumCols] = sortColIdx[scidx++];
				(*partOperators)[*partNumCols] = sgc->eqop;
T
Tom Lane 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
				(*partNumCols)++;
				pathkeys = new_pathkeys;
			}
		}
		foreach(lc, wc->orderClause)
		{
			SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
			List	   *new_pathkeys;

			sortclauses = lappend(sortclauses, sgc);
			new_pathkeys = make_pathkeys_for_sortclauses(root,
														 sortclauses,
														 tlist,
														 true);
			if (list_length(new_pathkeys) > list_length(pathkeys))
			{
				/* this sort clause is actually significant */
3292 3293
				(*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
				(*ordOperators)[*ordNumCols] = sgc->eqop;
T
Tom Lane 已提交
3294 3295 3296 3297 3298 3299 3300 3301 3302
				(*ordNumCols)++;
				pathkeys = new_pathkeys;
			}
		}
		/* complain if we didn't eat exactly the right number of sort cols */
		if (scidx != numSortCols)
			elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
	}
}
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316


/*
 * expression_planner
 *		Perform planner's transformations on a standalone expression.
 *
 * Various utility commands need to evaluate expressions that are not part
 * of a plannable query.  They can do so using the executor's regular
 * expression-execution machinery, but first the expression has to be fed
 * through here to transform it from parser output to something executable.
 *
 * Currently, we disallow sublinks in standalone expressions, so there's no
 * real "planning" involved here.  (That might not always be true though.)
 * What we must do is run eval_const_expressions to ensure that any function
3317 3318 3319 3320
 * calls are converted to positional notation and function default arguments
 * get inserted.  The fact that constant subexpressions get simplified is a
 * side-effect that is useful when the expression will get evaluated more than
 * once.  Also, we must fix operator function IDs.
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
 *
 * Note: this must not make any damaging changes to the passed-in expression
 * tree.  (It would actually be okay to apply fix_opfuncids to it, but since
 * we first do an expression_tree_mutator-based walk, what is returned will
 * be a new node tree.)
 */
Expr *
expression_planner(Expr *expr)
{
	Node	   *result;

3332 3333 3334 3335
	/*
	 * Convert named-argument function calls, insert default arguments and
	 * simplify constant subexprs
	 */
3336 3337 3338 3339 3340 3341 3342
	result = eval_const_expressions(NULL, (Node *) expr);

	/* Fill in opfuncid values if missing */
	fix_opfuncids(result);

	return (Expr *) result;
}
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


/*
 * plan_cluster_use_sort
 *		Use the planner to decide how CLUSTER should implement sorting
 *
 * tableOid is the OID of a table to be clustered on its index indexOid
 * (which is already known to be a btree index).  Decide whether it's
 * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
 * Return TRUE to use sorting, FALSE to use an indexscan.
 *
 * Note: caller had better already hold some type of lock on the table.
 */
bool
plan_cluster_use_sort(Oid tableOid, Oid indexOid)
{
	PlannerInfo *root;
	Query	   *query;
	PlannerGlobal *glob;
	RangeTblEntry *rte;
	RelOptInfo *rel;
	IndexOptInfo *indexInfo;
	QualCost	indexExprCost;
	Cost		comparisonCost;
	Path	   *seqScanPath;
	Path		seqScanAndSortPath;
	IndexPath  *indexScanPath;
	ListCell   *lc;

	/* Set up mostly-dummy planner state */
	query = makeNode(Query);
	query->commandType = CMD_SELECT;

	glob = makeNode(PlannerGlobal);

	root = makeNode(PlannerInfo);
	root->parse = query;
	root->glob = glob;
	root->query_level = 1;
	root->planner_cxt = CurrentMemoryContext;
	root->wt_param_id = -1;

	/* Build a minimal RTE for the rel */
	rte = makeNode(RangeTblEntry);
	rte->rtekind = RTE_RELATION;
	rte->relid = tableOid;
3389
	rte->relkind = RELKIND_RELATION;
3390
	rte->lateral = false;
3391 3392 3393 3394
	rte->inh = false;
	rte->inFromCl = true;
	query->rtable = list_make1(rte);

3395 3396
	/* Set up RTE/RelOptInfo arrays */
	setup_simple_rel_arrays(root);
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408

	/* Build RelOptInfo */
	rel = build_simple_rel(root, 1, RELOPT_BASEREL);

	/* Locate IndexOptInfo for the target index */
	indexInfo = NULL;
	foreach(lc, rel->indexlist)
	{
		indexInfo = (IndexOptInfo *) lfirst(lc);
		if (indexInfo->indexoid == indexOid)
			break;
	}
3409 3410 3411 3412 3413 3414 3415 3416

	/*
	 * It's possible that get_relation_info did not generate an IndexOptInfo
	 * for the desired index; this could happen if it's not yet reached its
	 * indcheckxmin usability horizon, or if it's a system index and we're
	 * ignoring system indexes.  In such cases we should tell CLUSTER to not
	 * trust the index contents but use seqscan-and-sort.
	 */
3417
	if (lc == NULL)				/* not in the list? */
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
		return true;			/* use sort */

	/*
	 * Rather than doing all the pushups that would be needed to use
	 * set_baserel_size_estimates, just do a quick hack for rows and width.
	 */
	rel->rows = rel->tuples;
	rel->width = get_relation_data_width(tableOid, NULL);

	root->total_table_pages = rel->pages;
3428 3429 3430

	/*
	 * Determine eval cost of the index expressions, if any.  We need to
3431 3432 3433
	 * charge twice that amount for each tuple comparison that happens during
	 * the sort, since tuplesort.c will have to re-evaluate the index
	 * expressions each time.  (XXX that's pretty inefficient...)
3434 3435 3436 3437 3438
	 */
	cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
	comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);

	/* Estimate the cost of seq scan + sort */
3439
	seqScanPath = create_seqscan_path(root, rel, NULL);
3440 3441 3442 3443 3444 3445
	cost_sort(&seqScanAndSortPath, root, NIL,
			  seqScanPath->total_cost, rel->tuples, rel->width,
			  comparisonCost, maintenance_work_mem, -1.0);

	/* Estimate the cost of index scan */
	indexScanPath = create_index_path(root, indexInfo,
3446
									  NIL, NIL, NIL, NIL, NIL,
3447 3448
									  ForwardScanDirection, false,
									  NULL, 1.0);
3449 3450 3451

	return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
}