1 /*-------------------------------------------------------------------------
2  *
3  * pathnode.c
4  *	  Routines to manipulate pathlists and create path nodes
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/optimizer/util/pathnode.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <math.h>
18 
19 #include "miscadmin.h"
20 #include "nodes/nodeFuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/pathnode.h"
24 #include "optimizer/paths.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/restrictinfo.h"
27 #include "optimizer/var.h"
28 #include "parser/parsetree.h"
29 #include "utils/lsyscache.h"
30 #include "utils/selfuncs.h"
31 
32 
33 typedef enum
34 {
35 	COSTS_EQUAL,				/* path costs are fuzzily equal */
36 	COSTS_BETTER1,				/* first path is cheaper than second */
37 	COSTS_BETTER2,				/* second path is cheaper than first */
38 	COSTS_DIFFERENT				/* neither path dominates the other on cost */
39 } PathCostComparison;
40 
41 /*
42  * STD_FUZZ_FACTOR is the normal fuzz factor for compare_path_costs_fuzzily.
43  * XXX is it worth making this user-controllable?  It provides a tradeoff
44  * between planner runtime and the accuracy of path cost comparisons.
45  */
46 #define STD_FUZZ_FACTOR 1.01
47 
48 static List *translate_sub_tlist(List *tlist, int relid);
49 
50 
51 /*****************************************************************************
52  *		MISC. PATH UTILITIES
53  *****************************************************************************/
54 
55 /*
56  * compare_path_costs
57  *	  Return -1, 0, or +1 according as path1 is cheaper, the same cost,
58  *	  or more expensive than path2 for the specified criterion.
59  */
60 int
compare_path_costs(Path * path1,Path * path2,CostSelector criterion)61 compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
62 {
63 	if (criterion == STARTUP_COST)
64 	{
65 		if (path1->startup_cost < path2->startup_cost)
66 			return -1;
67 		if (path1->startup_cost > path2->startup_cost)
68 			return +1;
69 
70 		/*
71 		 * If paths have the same startup cost (not at all unlikely), order
72 		 * them by total cost.
73 		 */
74 		if (path1->total_cost < path2->total_cost)
75 			return -1;
76 		if (path1->total_cost > path2->total_cost)
77 			return +1;
78 	}
79 	else
80 	{
81 		if (path1->total_cost < path2->total_cost)
82 			return -1;
83 		if (path1->total_cost > path2->total_cost)
84 			return +1;
85 
86 		/*
87 		 * If paths have the same total cost, order them by startup cost.
88 		 */
89 		if (path1->startup_cost < path2->startup_cost)
90 			return -1;
91 		if (path1->startup_cost > path2->startup_cost)
92 			return +1;
93 	}
94 	return 0;
95 }
96 
97 /*
98  * compare_path_fractional_costs
99  *	  Return -1, 0, or +1 according as path1 is cheaper, the same cost,
100  *	  or more expensive than path2 for fetching the specified fraction
101  *	  of the total tuples.
102  *
103  * If fraction is <= 0 or > 1, we interpret it as 1, ie, we select the
104  * path with the cheaper total_cost.
105  */
106 int
compare_fractional_path_costs(Path * path1,Path * path2,double fraction)107 compare_fractional_path_costs(Path *path1, Path *path2,
108 							  double fraction)
109 {
110 	Cost		cost1,
111 				cost2;
112 
113 	if (fraction <= 0.0 || fraction >= 1.0)
114 		return compare_path_costs(path1, path2, TOTAL_COST);
115 	cost1 = path1->startup_cost +
116 		fraction * (path1->total_cost - path1->startup_cost);
117 	cost2 = path2->startup_cost +
118 		fraction * (path2->total_cost - path2->startup_cost);
119 	if (cost1 < cost2)
120 		return -1;
121 	if (cost1 > cost2)
122 		return +1;
123 	return 0;
124 }
125 
126 /*
127  * compare_path_costs_fuzzily
128  *	  Compare the costs of two paths to see if either can be said to
129  *	  dominate the other.
130  *
131  * We use fuzzy comparisons so that add_path() can avoid keeping both of
132  * a pair of paths that really have insignificantly different cost.
133  *
134  * The fuzz_factor argument must be 1.0 plus delta, where delta is the
135  * fraction of the smaller cost that is considered to be a significant
136  * difference.  For example, fuzz_factor = 1.01 makes the fuzziness limit
137  * be 1% of the smaller cost.
138  *
139  * The two paths are said to have "equal" costs if both startup and total
140  * costs are fuzzily the same.  Path1 is said to be better than path2 if
141  * it has fuzzily better startup cost and fuzzily no worse total cost,
142  * or if it has fuzzily better total cost and fuzzily no worse startup cost.
143  * Path2 is better than path1 if the reverse holds.  Finally, if one path
144  * is fuzzily better than the other on startup cost and fuzzily worse on
145  * total cost, we just say that their costs are "different", since neither
146  * dominates the other across the whole performance spectrum.
147  *
148  * This function also enforces a policy rule that paths for which the relevant
149  * one of parent->consider_startup and parent->consider_param_startup is false
150  * cannot survive comparisons solely on the grounds of good startup cost, so
151  * we never return COSTS_DIFFERENT when that is true for the total-cost loser.
152  * (But if total costs are fuzzily equal, we compare startup costs anyway,
153  * in hopes of eliminating one path or the other.)
154  */
155 static PathCostComparison
compare_path_costs_fuzzily(Path * path1,Path * path2,double fuzz_factor)156 compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
157 {
158 #define CONSIDER_PATH_STARTUP_COST(p)  \
159 	((p)->param_info == NULL ? (p)->parent->consider_startup : (p)->parent->consider_param_startup)
160 
161 	/*
162 	 * Check total cost first since it's more likely to be different; many
163 	 * paths have zero startup cost.
164 	 */
165 	if (path1->total_cost > path2->total_cost * fuzz_factor)
166 	{
167 		/* path1 fuzzily worse on total cost */
168 		if (CONSIDER_PATH_STARTUP_COST(path1) &&
169 			path2->startup_cost > path1->startup_cost * fuzz_factor)
170 		{
171 			/* ... but path2 fuzzily worse on startup, so DIFFERENT */
172 			return COSTS_DIFFERENT;
173 		}
174 		/* else path2 dominates */
175 		return COSTS_BETTER2;
176 	}
177 	if (path2->total_cost > path1->total_cost * fuzz_factor)
178 	{
179 		/* path2 fuzzily worse on total cost */
180 		if (CONSIDER_PATH_STARTUP_COST(path2) &&
181 			path1->startup_cost > path2->startup_cost * fuzz_factor)
182 		{
183 			/* ... but path1 fuzzily worse on startup, so DIFFERENT */
184 			return COSTS_DIFFERENT;
185 		}
186 		/* else path1 dominates */
187 		return COSTS_BETTER1;
188 	}
189 	/* fuzzily the same on total cost ... */
190 	if (path1->startup_cost > path2->startup_cost * fuzz_factor)
191 	{
192 		/* ... but path1 fuzzily worse on startup, so path2 wins */
193 		return COSTS_BETTER2;
194 	}
195 	if (path2->startup_cost > path1->startup_cost * fuzz_factor)
196 	{
197 		/* ... but path2 fuzzily worse on startup, so path1 wins */
198 		return COSTS_BETTER1;
199 	}
200 	/* fuzzily the same on both costs */
201 	return COSTS_EQUAL;
202 
203 #undef CONSIDER_PATH_STARTUP_COST
204 }
205 
206 /*
207  * set_cheapest
208  *	  Find the minimum-cost paths from among a relation's paths,
209  *	  and save them in the rel's cheapest-path fields.
210  *
211  * cheapest_total_path is normally the cheapest-total-cost unparameterized
212  * path; but if there are no unparameterized paths, we assign it to be the
213  * best (cheapest least-parameterized) parameterized path.  However, only
214  * unparameterized paths are considered candidates for cheapest_startup_path,
215  * so that will be NULL if there are no unparameterized paths.
216  *
217  * The cheapest_parameterized_paths list collects all parameterized paths
218  * that have survived the add_path() tournament for this relation.  (Since
219  * add_path ignores pathkeys for a parameterized path, these will be paths
220  * that have best cost or best row count for their parameterization.  We
221  * may also have both a parallel-safe and a non-parallel-safe path in some
222  * cases for the same parameterization in some cases, but this should be
223  * relatively rare since, most typically, all paths for the same relation
224  * will be parallel-safe or none of them will.)
225  *
226  * cheapest_parameterized_paths always includes the cheapest-total
227  * unparameterized path, too, if there is one; the users of that list find
228  * it more convenient if that's included.
229  *
230  * This is normally called only after we've finished constructing the path
231  * list for the rel node.
232  */
233 void
set_cheapest(RelOptInfo * parent_rel)234 set_cheapest(RelOptInfo *parent_rel)
235 {
236 	Path	   *cheapest_startup_path;
237 	Path	   *cheapest_total_path;
238 	Path	   *best_param_path;
239 	List	   *parameterized_paths;
240 	ListCell   *p;
241 
242 	Assert(IsA(parent_rel, RelOptInfo));
243 
244 	if (parent_rel->pathlist == NIL)
245 		elog(ERROR, "could not devise a query plan for the given query");
246 
247 	cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
248 	parameterized_paths = NIL;
249 
250 	foreach(p, parent_rel->pathlist)
251 	{
252 		Path	   *path = (Path *) lfirst(p);
253 		int			cmp;
254 
255 		if (path->param_info)
256 		{
257 			/* Parameterized path, so add it to parameterized_paths */
258 			parameterized_paths = lappend(parameterized_paths, path);
259 
260 			/*
261 			 * If we have an unparameterized cheapest-total, we no longer care
262 			 * about finding the best parameterized path, so move on.
263 			 */
264 			if (cheapest_total_path)
265 				continue;
266 
267 			/*
268 			 * Otherwise, track the best parameterized path, which is the one
269 			 * with least total cost among those of the minimum
270 			 * parameterization.
271 			 */
272 			if (best_param_path == NULL)
273 				best_param_path = path;
274 			else
275 			{
276 				switch (bms_subset_compare(PATH_REQ_OUTER(path),
277 										   PATH_REQ_OUTER(best_param_path)))
278 				{
279 					case BMS_EQUAL:
280 						/* keep the cheaper one */
281 						if (compare_path_costs(path, best_param_path,
282 											   TOTAL_COST) < 0)
283 							best_param_path = path;
284 						break;
285 					case BMS_SUBSET1:
286 						/* new path is less-parameterized */
287 						best_param_path = path;
288 						break;
289 					case BMS_SUBSET2:
290 						/* old path is less-parameterized, keep it */
291 						break;
292 					case BMS_DIFFERENT:
293 
294 						/*
295 						 * This means that neither path has the least possible
296 						 * parameterization for the rel.  We'll sit on the old
297 						 * path until something better comes along.
298 						 */
299 						break;
300 				}
301 			}
302 		}
303 		else
304 		{
305 			/* Unparameterized path, so consider it for cheapest slots */
306 			if (cheapest_total_path == NULL)
307 			{
308 				cheapest_startup_path = cheapest_total_path = path;
309 				continue;
310 			}
311 
312 			/*
313 			 * If we find two paths of identical costs, try to keep the
314 			 * better-sorted one.  The paths might have unrelated sort
315 			 * orderings, in which case we can only guess which might be
316 			 * better to keep, but if one is superior then we definitely
317 			 * should keep that one.
318 			 */
319 			cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
320 			if (cmp > 0 ||
321 				(cmp == 0 &&
322 				 compare_pathkeys(cheapest_startup_path->pathkeys,
323 								  path->pathkeys) == PATHKEYS_BETTER2))
324 				cheapest_startup_path = path;
325 
326 			cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
327 			if (cmp > 0 ||
328 				(cmp == 0 &&
329 				 compare_pathkeys(cheapest_total_path->pathkeys,
330 								  path->pathkeys) == PATHKEYS_BETTER2))
331 				cheapest_total_path = path;
332 		}
333 	}
334 
335 	/* Add cheapest unparameterized path, if any, to parameterized_paths */
336 	if (cheapest_total_path)
337 		parameterized_paths = lcons(cheapest_total_path, parameterized_paths);
338 
339 	/*
340 	 * If there is no unparameterized path, use the best parameterized path as
341 	 * cheapest_total_path (but not as cheapest_startup_path).
342 	 */
343 	if (cheapest_total_path == NULL)
344 		cheapest_total_path = best_param_path;
345 	Assert(cheapest_total_path != NULL);
346 
347 	parent_rel->cheapest_startup_path = cheapest_startup_path;
348 	parent_rel->cheapest_total_path = cheapest_total_path;
349 	parent_rel->cheapest_unique_path = NULL;	/* computed only if needed */
350 	parent_rel->cheapest_parameterized_paths = parameterized_paths;
351 }
352 
353 /*
354  * add_path
355  *	  Consider a potential implementation path for the specified parent rel,
356  *	  and add it to the rel's pathlist if it is worthy of consideration.
357  *	  A path is worthy if it has a better sort order (better pathkeys) or
358  *	  cheaper cost (on either dimension), or generates fewer rows, than any
359  *	  existing path that has the same or superset parameterization rels.
360  *	  We also consider parallel-safe paths more worthy than others.
361  *
362  *	  We also remove from the rel's pathlist any old paths that are dominated
363  *	  by new_path --- that is, new_path is cheaper, at least as well ordered,
364  *	  generates no more rows, requires no outer rels not required by the old
365  *	  path, and is no less parallel-safe.
366  *
367  *	  In most cases, a path with a superset parameterization will generate
368  *	  fewer rows (since it has more join clauses to apply), so that those two
369  *	  figures of merit move in opposite directions; this means that a path of
370  *	  one parameterization can seldom dominate a path of another.  But such
371  *	  cases do arise, so we make the full set of checks anyway.
372  *
373  *	  There are two policy decisions embedded in this function, along with
374  *	  its sibling add_path_precheck.  First, we treat all parameterized paths
375  *	  as having NIL pathkeys, so that they cannot win comparisons on the
376  *	  basis of sort order.  This is to reduce the number of parameterized
377  *	  paths that are kept; see discussion in src/backend/optimizer/README.
378  *
379  *	  Second, we only consider cheap startup cost to be interesting if
380  *	  parent_rel->consider_startup is true for an unparameterized path, or
381  *	  parent_rel->consider_param_startup is true for a parameterized one.
382  *	  Again, this allows discarding useless paths sooner.
383  *
384  *	  The pathlist is kept sorted by total_cost, with cheaper paths
385  *	  at the front.  Within this routine, that's simply a speed hack:
386  *	  doing it that way makes it more likely that we will reject an inferior
387  *	  path after a few comparisons, rather than many comparisons.
388  *	  However, add_path_precheck relies on this ordering to exit early
389  *	  when possible.
390  *
391  *	  NOTE: discarded Path objects are immediately pfree'd to reduce planner
392  *	  memory consumption.  We dare not try to free the substructure of a Path,
393  *	  since much of it may be shared with other Paths or the query tree itself;
394  *	  but just recycling discarded Path nodes is a very useful savings in
395  *	  a large join tree.  We can recycle the List nodes of pathlist, too.
396  *
397  *	  As noted in optimizer/README, deleting a previously-accepted Path is
398  *	  safe because we know that Paths of this rel cannot yet be referenced
399  *	  from any other rel, such as a higher-level join.  However, in some cases
400  *	  it is possible that a Path is referenced by another Path for its own
401  *	  rel; we must not delete such a Path, even if it is dominated by the new
402  *	  Path.  Currently this occurs only for IndexPath objects, which may be
403  *	  referenced as children of BitmapHeapPaths as well as being paths in
404  *	  their own right.  Hence, we don't pfree IndexPaths when rejecting them.
405  *
406  * 'parent_rel' is the relation entry to which the path corresponds.
407  * 'new_path' is a potential path for parent_rel.
408  *
409  * Returns nothing, but modifies parent_rel->pathlist.
410  */
411 void
add_path(RelOptInfo * parent_rel,Path * new_path)412 add_path(RelOptInfo *parent_rel, Path *new_path)
413 {
414 	bool		accept_new = true;		/* unless we find a superior old path */
415 	ListCell   *insert_after = NULL;	/* where to insert new item */
416 	List	   *new_path_pathkeys;
417 	ListCell   *p1;
418 	ListCell   *p1_prev;
419 	ListCell   *p1_next;
420 
421 	/*
422 	 * This is a convenient place to check for query cancel --- no part of the
423 	 * planner goes very long without calling add_path().
424 	 */
425 	CHECK_FOR_INTERRUPTS();
426 
427 	/* Pretend parameterized paths have no pathkeys, per comment above */
428 	new_path_pathkeys = new_path->param_info ? NIL : new_path->pathkeys;
429 
430 	/*
431 	 * Loop to check proposed new path against old paths.  Note it is possible
432 	 * for more than one old path to be tossed out because new_path dominates
433 	 * it.
434 	 *
435 	 * We can't use foreach here because the loop body may delete the current
436 	 * list cell.
437 	 */
438 	p1_prev = NULL;
439 	for (p1 = list_head(parent_rel->pathlist); p1 != NULL; p1 = p1_next)
440 	{
441 		Path	   *old_path = (Path *) lfirst(p1);
442 		bool		remove_old = false; /* unless new proves superior */
443 		PathCostComparison costcmp;
444 		PathKeysComparison keyscmp;
445 		BMS_Comparison outercmp;
446 
447 		p1_next = lnext(p1);
448 
449 		/*
450 		 * Do a fuzzy cost comparison with standard fuzziness limit.
451 		 */
452 		costcmp = compare_path_costs_fuzzily(new_path, old_path,
453 											 STD_FUZZ_FACTOR);
454 
455 		/*
456 		 * If the two paths compare differently for startup and total cost,
457 		 * then we want to keep both, and we can skip comparing pathkeys and
458 		 * required_outer rels.  If they compare the same, proceed with the
459 		 * other comparisons.  Row count is checked last.  (We make the tests
460 		 * in this order because the cost comparison is most likely to turn
461 		 * out "different", and the pathkeys comparison next most likely.  As
462 		 * explained above, row count very seldom makes a difference, so even
463 		 * though it's cheap to compare there's not much point in checking it
464 		 * earlier.)
465 		 */
466 		if (costcmp != COSTS_DIFFERENT)
467 		{
468 			/* Similarly check to see if either dominates on pathkeys */
469 			List	   *old_path_pathkeys;
470 
471 			old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
472 			keyscmp = compare_pathkeys(new_path_pathkeys,
473 									   old_path_pathkeys);
474 			if (keyscmp != PATHKEYS_DIFFERENT)
475 			{
476 				switch (costcmp)
477 				{
478 					case COSTS_EQUAL:
479 						outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
480 												   PATH_REQ_OUTER(old_path));
481 						if (keyscmp == PATHKEYS_BETTER1)
482 						{
483 							if ((outercmp == BMS_EQUAL ||
484 								 outercmp == BMS_SUBSET1) &&
485 								new_path->rows <= old_path->rows &&
486 								new_path->parallel_safe >= old_path->parallel_safe)
487 								remove_old = true;		/* new dominates old */
488 						}
489 						else if (keyscmp == PATHKEYS_BETTER2)
490 						{
491 							if ((outercmp == BMS_EQUAL ||
492 								 outercmp == BMS_SUBSET2) &&
493 								new_path->rows >= old_path->rows &&
494 								new_path->parallel_safe <= old_path->parallel_safe)
495 								accept_new = false;		/* old dominates new */
496 						}
497 						else	/* keyscmp == PATHKEYS_EQUAL */
498 						{
499 							if (outercmp == BMS_EQUAL)
500 							{
501 								/*
502 								 * Same pathkeys and outer rels, and fuzzily
503 								 * the same cost, so keep just one; to decide
504 								 * which, first check parallel-safety, then
505 								 * rows, then do a fuzzy cost comparison with
506 								 * very small fuzz limit.  (We used to do an
507 								 * exact cost comparison, but that results in
508 								 * annoying platform-specific plan variations
509 								 * due to roundoff in the cost estimates.)	If
510 								 * things are still tied, arbitrarily keep
511 								 * only the old path.  Notice that we will
512 								 * keep only the old path even if the
513 								 * less-fuzzy comparison decides the startup
514 								 * and total costs compare differently.
515 								 */
516 								if (new_path->parallel_safe >
517 									old_path->parallel_safe)
518 									remove_old = true;	/* new dominates old */
519 								else if (new_path->parallel_safe <
520 										 old_path->parallel_safe)
521 									accept_new = false; /* old dominates new */
522 								else if (new_path->rows < old_path->rows)
523 									remove_old = true;	/* new dominates old */
524 								else if (new_path->rows > old_path->rows)
525 									accept_new = false; /* old dominates new */
526 								else if (compare_path_costs_fuzzily(new_path,
527 																	old_path,
528 											  1.0000000001) == COSTS_BETTER1)
529 									remove_old = true;	/* new dominates old */
530 								else
531 									accept_new = false; /* old equals or
532 														 * dominates new */
533 							}
534 							else if (outercmp == BMS_SUBSET1 &&
535 									 new_path->rows <= old_path->rows &&
536 									 new_path->parallel_safe >= old_path->parallel_safe)
537 								remove_old = true;		/* new dominates old */
538 							else if (outercmp == BMS_SUBSET2 &&
539 									 new_path->rows >= old_path->rows &&
540 									 new_path->parallel_safe <= old_path->parallel_safe)
541 								accept_new = false;		/* old dominates new */
542 							/* else different parameterizations, keep both */
543 						}
544 						break;
545 					case COSTS_BETTER1:
546 						if (keyscmp != PATHKEYS_BETTER2)
547 						{
548 							outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
549 												   PATH_REQ_OUTER(old_path));
550 							if ((outercmp == BMS_EQUAL ||
551 								 outercmp == BMS_SUBSET1) &&
552 								new_path->rows <= old_path->rows &&
553 								new_path->parallel_safe >= old_path->parallel_safe)
554 								remove_old = true;		/* new dominates old */
555 						}
556 						break;
557 					case COSTS_BETTER2:
558 						if (keyscmp != PATHKEYS_BETTER1)
559 						{
560 							outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
561 												   PATH_REQ_OUTER(old_path));
562 							if ((outercmp == BMS_EQUAL ||
563 								 outercmp == BMS_SUBSET2) &&
564 								new_path->rows >= old_path->rows &&
565 								new_path->parallel_safe <= old_path->parallel_safe)
566 								accept_new = false;		/* old dominates new */
567 						}
568 						break;
569 					case COSTS_DIFFERENT:
570 
571 						/*
572 						 * can't get here, but keep this case to keep compiler
573 						 * quiet
574 						 */
575 						break;
576 				}
577 			}
578 		}
579 
580 		/*
581 		 * Remove current element from pathlist if dominated by new.
582 		 */
583 		if (remove_old)
584 		{
585 			parent_rel->pathlist = list_delete_cell(parent_rel->pathlist,
586 													p1, p1_prev);
587 
588 			/*
589 			 * Delete the data pointed-to by the deleted cell, if possible
590 			 */
591 			if (!IsA(old_path, IndexPath))
592 				pfree(old_path);
593 			/* p1_prev does not advance */
594 		}
595 		else
596 		{
597 			/* new belongs after this old path if it has cost >= old's */
598 			if (new_path->total_cost >= old_path->total_cost)
599 				insert_after = p1;
600 			/* p1_prev advances */
601 			p1_prev = p1;
602 		}
603 
604 		/*
605 		 * If we found an old path that dominates new_path, we can quit
606 		 * scanning the pathlist; we will not add new_path, and we assume
607 		 * new_path cannot dominate any other elements of the pathlist.
608 		 */
609 		if (!accept_new)
610 			break;
611 	}
612 
613 	if (accept_new)
614 	{
615 		/* Accept the new path: insert it at proper place in pathlist */
616 		if (insert_after)
617 			lappend_cell(parent_rel->pathlist, insert_after, new_path);
618 		else
619 			parent_rel->pathlist = lcons(new_path, parent_rel->pathlist);
620 	}
621 	else
622 	{
623 		/* Reject and recycle the new path */
624 		if (!IsA(new_path, IndexPath))
625 			pfree(new_path);
626 	}
627 }
628 
629 /*
630  * add_path_precheck
631  *	  Check whether a proposed new path could possibly get accepted.
632  *	  We assume we know the path's pathkeys and parameterization accurately,
633  *	  and have lower bounds for its costs.
634  *
635  * Note that we do not know the path's rowcount, since getting an estimate for
636  * that is too expensive to do before prechecking.  We assume here that paths
637  * of a superset parameterization will generate fewer rows; if that holds,
638  * then paths with different parameterizations cannot dominate each other
639  * and so we can simply ignore existing paths of another parameterization.
640  * (In the infrequent cases where that rule of thumb fails, add_path will
641  * get rid of the inferior path.)
642  *
643  * At the time this is called, we haven't actually built a Path structure,
644  * so the required information has to be passed piecemeal.
645  */
646 bool
add_path_precheck(RelOptInfo * parent_rel,Cost startup_cost,Cost total_cost,List * pathkeys,Relids required_outer)647 add_path_precheck(RelOptInfo *parent_rel,
648 				  Cost startup_cost, Cost total_cost,
649 				  List *pathkeys, Relids required_outer)
650 {
651 	List	   *new_path_pathkeys;
652 	bool		consider_startup;
653 	ListCell   *p1;
654 
655 	/* Pretend parameterized paths have no pathkeys, per add_path policy */
656 	new_path_pathkeys = required_outer ? NIL : pathkeys;
657 
658 	/* Decide whether new path's startup cost is interesting */
659 	consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
660 
661 	foreach(p1, parent_rel->pathlist)
662 	{
663 		Path	   *old_path = (Path *) lfirst(p1);
664 		PathKeysComparison keyscmp;
665 
666 		/*
667 		 * We are looking for an old_path with the same parameterization (and
668 		 * by assumption the same rowcount) that dominates the new path on
669 		 * pathkeys as well as both cost metrics.  If we find one, we can
670 		 * reject the new path.
671 		 *
672 		 * Cost comparisons here should match compare_path_costs_fuzzily.
673 		 */
674 		if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
675 		{
676 			/* new path can win on startup cost only if consider_startup */
677 			if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
678 				!consider_startup)
679 			{
680 				/* new path loses on cost, so check pathkeys... */
681 				List	   *old_path_pathkeys;
682 
683 				old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
684 				keyscmp = compare_pathkeys(new_path_pathkeys,
685 										   old_path_pathkeys);
686 				if (keyscmp == PATHKEYS_EQUAL ||
687 					keyscmp == PATHKEYS_BETTER2)
688 				{
689 					/* new path does not win on pathkeys... */
690 					if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
691 					{
692 						/* Found an old path that dominates the new one */
693 						return false;
694 					}
695 				}
696 			}
697 		}
698 		else
699 		{
700 			/*
701 			 * Since the pathlist is sorted by total_cost, we can stop looking
702 			 * once we reach a path with a total_cost larger than the new
703 			 * path's.
704 			 */
705 			break;
706 		}
707 	}
708 
709 	return true;
710 }
711 
712 /*
713  * add_partial_path
714  *	  Like add_path, our goal here is to consider whether a path is worthy
715  *	  of being kept around, but the considerations here are a bit different.
716  *	  A partial path is one which can be executed in any number of workers in
717  *	  parallel such that each worker will generate a subset of the path's
718  *	  overall result.
719  *
720  *	  As in add_path, the partial_pathlist is kept sorted with the cheapest
721  *	  total path in front.  This is depended on by multiple places, which
722  *	  just take the front entry as the cheapest path without searching.
723  *
724  *	  We don't generate parameterized partial paths for several reasons.  Most
725  *	  importantly, they're not safe to execute, because there's nothing to
726  *	  make sure that a parallel scan within the parameterized portion of the
727  *	  plan is running with the same value in every worker at the same time.
728  *	  Fortunately, it seems unlikely to be worthwhile anyway, because having
729  *	  each worker scan the entire outer relation and a subset of the inner
730  *	  relation will generally be a terrible plan.  The inner (parameterized)
731  *	  side of the plan will be small anyway.  There could be rare cases where
732  *	  this wins big - e.g. if join order constraints put a 1-row relation on
733  *	  the outer side of the topmost join with a parameterized plan on the inner
734  *	  side - but we'll have to be content not to handle such cases until
735  *	  somebody builds an executor infrastructure that can cope with them.
736  *
737  *	  Because we don't consider parameterized paths here, we also don't
738  *	  need to consider the row counts as a measure of quality: every path will
739  *	  produce the same number of rows.  Neither do we need to consider startup
740  *	  costs: parallelism is only used for plans that will be run to completion.
741  *	  Therefore, this routine is much simpler than add_path: it needs to
742  *	  consider only pathkeys and total cost.
743  *
744  *	  As with add_path, we pfree paths that are found to be dominated by
745  *	  another partial path; this requires that there be no other references to
746  *	  such paths yet.  Hence, GatherPaths must not be created for a rel until
747  *	  we're done creating all partial paths for it.  We do not currently build
748  *	  partial indexscan paths, so there is no need for an exception for
749  *	  IndexPaths here; for safety, we instead Assert that a path to be freed
750  *	  isn't an IndexPath.
751  */
752 void
add_partial_path(RelOptInfo * parent_rel,Path * new_path)753 add_partial_path(RelOptInfo *parent_rel, Path *new_path)
754 {
755 	bool		accept_new = true;		/* unless we find a superior old path */
756 	ListCell   *insert_after = NULL;	/* where to insert new item */
757 	ListCell   *p1;
758 	ListCell   *p1_prev;
759 	ListCell   *p1_next;
760 
761 	/* Check for query cancel. */
762 	CHECK_FOR_INTERRUPTS();
763 
764 	/*
765 	 * As in add_path, throw out any paths which are dominated by the new
766 	 * path, but throw out the new path if some existing path dominates it.
767 	 */
768 	p1_prev = NULL;
769 	for (p1 = list_head(parent_rel->partial_pathlist); p1 != NULL;
770 		 p1 = p1_next)
771 	{
772 		Path	   *old_path = (Path *) lfirst(p1);
773 		bool		remove_old = false; /* unless new proves superior */
774 		PathKeysComparison keyscmp;
775 
776 		p1_next = lnext(p1);
777 
778 		/* Compare pathkeys. */
779 		keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
780 
781 		/* Unless pathkeys are incompable, keep just one of the two paths. */
782 		if (keyscmp != PATHKEYS_DIFFERENT)
783 		{
784 			if (new_path->total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
785 			{
786 				/* New path costs more; keep it only if pathkeys are better. */
787 				if (keyscmp != PATHKEYS_BETTER1)
788 					accept_new = false;
789 			}
790 			else if (old_path->total_cost > new_path->total_cost
791 					 * STD_FUZZ_FACTOR)
792 			{
793 				/* Old path costs more; keep it only if pathkeys are better. */
794 				if (keyscmp != PATHKEYS_BETTER2)
795 					remove_old = true;
796 			}
797 			else if (keyscmp == PATHKEYS_BETTER1)
798 			{
799 				/* Costs are about the same, new path has better pathkeys. */
800 				remove_old = true;
801 			}
802 			else if (keyscmp == PATHKEYS_BETTER2)
803 			{
804 				/* Costs are about the same, old path has better pathkeys. */
805 				accept_new = false;
806 			}
807 			else if (old_path->total_cost > new_path->total_cost * 1.0000000001)
808 			{
809 				/* Pathkeys are the same, and the old path costs more. */
810 				remove_old = true;
811 			}
812 			else
813 			{
814 				/*
815 				 * Pathkeys are the same, and new path isn't materially
816 				 * cheaper.
817 				 */
818 				accept_new = false;
819 			}
820 		}
821 
822 		/*
823 		 * Remove current element from partial_pathlist if dominated by new.
824 		 */
825 		if (remove_old)
826 		{
827 			parent_rel->partial_pathlist =
828 				list_delete_cell(parent_rel->partial_pathlist, p1, p1_prev);
829 			/* we should not see IndexPaths here, so always safe to delete */
830 			Assert(!IsA(old_path, IndexPath));
831 			pfree(old_path);
832 			/* p1_prev does not advance */
833 		}
834 		else
835 		{
836 			/* new belongs after this old path if it has cost >= old's */
837 			if (new_path->total_cost >= old_path->total_cost)
838 				insert_after = p1;
839 			/* p1_prev advances */
840 			p1_prev = p1;
841 		}
842 
843 		/*
844 		 * If we found an old path that dominates new_path, we can quit
845 		 * scanning the partial_pathlist; we will not add new_path, and we
846 		 * assume new_path cannot dominate any later path.
847 		 */
848 		if (!accept_new)
849 			break;
850 	}
851 
852 	if (accept_new)
853 	{
854 		/* Accept the new path: insert it at proper place */
855 		if (insert_after)
856 			lappend_cell(parent_rel->partial_pathlist, insert_after, new_path);
857 		else
858 			parent_rel->partial_pathlist =
859 				lcons(new_path, parent_rel->partial_pathlist);
860 	}
861 	else
862 	{
863 		/* we should not see IndexPaths here, so always safe to delete */
864 		Assert(!IsA(new_path, IndexPath));
865 		/* Reject and recycle the new path */
866 		pfree(new_path);
867 	}
868 }
869 
870 /*
871  * add_partial_path_precheck
872  *	  Check whether a proposed new partial path could possibly get accepted.
873  *
874  * Unlike add_path_precheck, we can ignore startup cost and parameterization,
875  * since they don't matter for partial paths (see add_partial_path).  But
876  * we do want to make sure we don't add a partial path if there's already
877  * a complete path that dominates it, since in that case the proposed path
878  * is surely a loser.
879  */
880 bool
add_partial_path_precheck(RelOptInfo * parent_rel,Cost total_cost,List * pathkeys)881 add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost,
882 						  List *pathkeys)
883 {
884 	ListCell   *p1;
885 
886 	/*
887 	 * Our goal here is twofold.  First, we want to find out whether this path
888 	 * is clearly inferior to some existing partial path.  If so, we want to
889 	 * reject it immediately.  Second, we want to find out whether this path
890 	 * is clearly superior to some existing partial path -- at least, modulo
891 	 * final cost computations.  If so, we definitely want to consider it.
892 	 *
893 	 * Unlike add_path(), we always compare pathkeys here.  This is because we
894 	 * expect partial_pathlist to be very short, and getting a definitive
895 	 * answer at this stage avoids the need to call add_path_precheck.
896 	 */
897 	foreach(p1, parent_rel->partial_pathlist)
898 	{
899 		Path	   *old_path = (Path *) lfirst(p1);
900 		PathKeysComparison keyscmp;
901 
902 		keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
903 		if (keyscmp != PATHKEYS_DIFFERENT)
904 		{
905 			if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
906 				keyscmp != PATHKEYS_BETTER1)
907 				return false;
908 			if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
909 				keyscmp != PATHKEYS_BETTER2)
910 				return true;
911 		}
912 	}
913 
914 	/*
915 	 * This path is neither clearly inferior to an existing partial path nor
916 	 * clearly good enough that it might replace one.  Compare it to
917 	 * non-parallel plans.  If it loses even before accounting for the cost of
918 	 * the Gather node, we should definitely reject it.
919 	 *
920 	 * Note that we pass the total_cost to add_path_precheck twice.  This is
921 	 * because it's never advantageous to consider the startup cost of a
922 	 * partial path; the resulting plans, if run in parallel, will be run to
923 	 * completion.
924 	 */
925 	if (!add_path_precheck(parent_rel, total_cost, total_cost, pathkeys,
926 						   NULL))
927 		return false;
928 
929 	return true;
930 }
931 
932 
933 /*****************************************************************************
934  *		PATH NODE CREATION ROUTINES
935  *****************************************************************************/
936 
937 /*
938  * create_seqscan_path
939  *	  Creates a path corresponding to a sequential scan, returning the
940  *	  pathnode.
941  */
942 Path *
create_seqscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer,int parallel_workers)943 create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
944 					Relids required_outer, int parallel_workers)
945 {
946 	Path	   *pathnode = makeNode(Path);
947 
948 	pathnode->pathtype = T_SeqScan;
949 	pathnode->parent = rel;
950 	pathnode->pathtarget = rel->reltarget;
951 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
952 													 required_outer);
953 	pathnode->parallel_aware = parallel_workers > 0 ? true : false;
954 	pathnode->parallel_safe = rel->consider_parallel;
955 	pathnode->parallel_workers = parallel_workers;
956 	pathnode->pathkeys = NIL;	/* seqscan has unordered result */
957 
958 	cost_seqscan(pathnode, root, rel, pathnode->param_info);
959 
960 	return pathnode;
961 }
962 
963 /*
964  * create_samplescan_path
965  *	  Creates a path node for a sampled table scan.
966  */
967 Path *
create_samplescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)968 create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
969 {
970 	Path	   *pathnode = makeNode(Path);
971 
972 	pathnode->pathtype = T_SampleScan;
973 	pathnode->parent = rel;
974 	pathnode->pathtarget = rel->reltarget;
975 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
976 													 required_outer);
977 	pathnode->parallel_aware = false;
978 	pathnode->parallel_safe = rel->consider_parallel;
979 	pathnode->parallel_workers = 0;
980 	pathnode->pathkeys = NIL;	/* samplescan has unordered result */
981 
982 	cost_samplescan(pathnode, root, rel, pathnode->param_info);
983 
984 	return pathnode;
985 }
986 
987 /*
988  * create_index_path
989  *	  Creates a path node for an index scan.
990  *
991  * 'index' is a usable index.
992  * 'indexclauses' is a list of RestrictInfo nodes representing clauses
993  *			to be used as index qual conditions in the scan.
994  * 'indexclausecols' is an integer list of index column numbers (zero based)
995  *			the indexclauses can be used with.
996  * 'indexorderbys' is a list of bare expressions (no RestrictInfos)
997  *			to be used as index ordering operators in the scan.
998  * 'indexorderbycols' is an integer list of index column numbers (zero based)
999  *			the ordering operators can be used with.
1000  * 'pathkeys' describes the ordering of the path.
1001  * 'indexscandir' is ForwardScanDirection or BackwardScanDirection
1002  *			for an ordered index, or NoMovementScanDirection for
1003  *			an unordered index.
1004  * 'indexonly' is true if an index-only scan is wanted.
1005  * 'required_outer' is the set of outer relids for a parameterized path.
1006  * 'loop_count' is the number of repetitions of the indexscan to factor into
1007  *		estimates of caching behavior.
1008  *
1009  * Returns the new path node.
1010  */
1011 IndexPath *
create_index_path(PlannerInfo * root,IndexOptInfo * index,List * indexclauses,List * indexclausecols,List * indexorderbys,List * indexorderbycols,List * pathkeys,ScanDirection indexscandir,bool indexonly,Relids required_outer,double loop_count)1012 create_index_path(PlannerInfo *root,
1013 				  IndexOptInfo *index,
1014 				  List *indexclauses,
1015 				  List *indexclausecols,
1016 				  List *indexorderbys,
1017 				  List *indexorderbycols,
1018 				  List *pathkeys,
1019 				  ScanDirection indexscandir,
1020 				  bool indexonly,
1021 				  Relids required_outer,
1022 				  double loop_count)
1023 {
1024 	IndexPath  *pathnode = makeNode(IndexPath);
1025 	RelOptInfo *rel = index->rel;
1026 	List	   *indexquals,
1027 			   *indexqualcols;
1028 
1029 	pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1030 	pathnode->path.parent = rel;
1031 	pathnode->path.pathtarget = rel->reltarget;
1032 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1033 														  required_outer);
1034 	pathnode->path.parallel_aware = false;
1035 	pathnode->path.parallel_safe = rel->consider_parallel;
1036 	pathnode->path.parallel_workers = 0;
1037 	pathnode->path.pathkeys = pathkeys;
1038 
1039 	/* Convert clauses to indexquals the executor can handle */
1040 	expand_indexqual_conditions(index, indexclauses, indexclausecols,
1041 								&indexquals, &indexqualcols);
1042 
1043 	/* Fill in the pathnode */
1044 	pathnode->indexinfo = index;
1045 	pathnode->indexclauses = indexclauses;
1046 	pathnode->indexquals = indexquals;
1047 	pathnode->indexqualcols = indexqualcols;
1048 	pathnode->indexorderbys = indexorderbys;
1049 	pathnode->indexorderbycols = indexorderbycols;
1050 	pathnode->indexscandir = indexscandir;
1051 
1052 	cost_index(pathnode, root, loop_count);
1053 
1054 	return pathnode;
1055 }
1056 
1057 /*
1058  * create_bitmap_heap_path
1059  *	  Creates a path node for a bitmap scan.
1060  *
1061  * 'bitmapqual' is a tree of IndexPath, BitmapAndPath, and BitmapOrPath nodes.
1062  * 'required_outer' is the set of outer relids for a parameterized path.
1063  * 'loop_count' is the number of repetitions of the indexscan to factor into
1064  *		estimates of caching behavior.
1065  *
1066  * loop_count should match the value used when creating the component
1067  * IndexPaths.
1068  */
1069 BitmapHeapPath *
create_bitmap_heap_path(PlannerInfo * root,RelOptInfo * rel,Path * bitmapqual,Relids required_outer,double loop_count)1070 create_bitmap_heap_path(PlannerInfo *root,
1071 						RelOptInfo *rel,
1072 						Path *bitmapqual,
1073 						Relids required_outer,
1074 						double loop_count)
1075 {
1076 	BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1077 
1078 	pathnode->path.pathtype = T_BitmapHeapScan;
1079 	pathnode->path.parent = rel;
1080 	pathnode->path.pathtarget = rel->reltarget;
1081 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1082 														  required_outer);
1083 	pathnode->path.parallel_aware = false;
1084 	pathnode->path.parallel_safe = rel->consider_parallel;
1085 	pathnode->path.parallel_workers = 0;
1086 	pathnode->path.pathkeys = NIL;		/* always unordered */
1087 
1088 	pathnode->bitmapqual = bitmapqual;
1089 
1090 	cost_bitmap_heap_scan(&pathnode->path, root, rel,
1091 						  pathnode->path.param_info,
1092 						  bitmapqual, loop_count);
1093 
1094 	return pathnode;
1095 }
1096 
1097 /*
1098  * create_bitmap_and_path
1099  *	  Creates a path node representing a BitmapAnd.
1100  */
1101 BitmapAndPath *
create_bitmap_and_path(PlannerInfo * root,RelOptInfo * rel,List * bitmapquals)1102 create_bitmap_and_path(PlannerInfo *root,
1103 					   RelOptInfo *rel,
1104 					   List *bitmapquals)
1105 {
1106 	BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1107 
1108 	pathnode->path.pathtype = T_BitmapAnd;
1109 	pathnode->path.parent = rel;
1110 	pathnode->path.pathtarget = rel->reltarget;
1111 	pathnode->path.param_info = NULL;	/* not used in bitmap trees */
1112 
1113 	/*
1114 	 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1115 	 * parallel-safe if and only if rel->consider_parallel is set.  So, we can
1116 	 * set the flag for this path based only on the relation-level flag,
1117 	 * without actually iterating over the list of children.
1118 	 */
1119 	pathnode->path.parallel_aware = false;
1120 	pathnode->path.parallel_safe = rel->consider_parallel;
1121 	pathnode->path.parallel_workers = 0;
1122 
1123 	pathnode->path.pathkeys = NIL;		/* always unordered */
1124 
1125 	pathnode->bitmapquals = bitmapquals;
1126 
1127 	/* this sets bitmapselectivity as well as the regular cost fields: */
1128 	cost_bitmap_and_node(pathnode, root);
1129 
1130 	return pathnode;
1131 }
1132 
1133 /*
1134  * create_bitmap_or_path
1135  *	  Creates a path node representing a BitmapOr.
1136  */
1137 BitmapOrPath *
create_bitmap_or_path(PlannerInfo * root,RelOptInfo * rel,List * bitmapquals)1138 create_bitmap_or_path(PlannerInfo *root,
1139 					  RelOptInfo *rel,
1140 					  List *bitmapquals)
1141 {
1142 	BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1143 
1144 	pathnode->path.pathtype = T_BitmapOr;
1145 	pathnode->path.parent = rel;
1146 	pathnode->path.pathtarget = rel->reltarget;
1147 	pathnode->path.param_info = NULL;	/* not used in bitmap trees */
1148 
1149 	/*
1150 	 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1151 	 * parallel-safe if and only if rel->consider_parallel is set.  So, we can
1152 	 * set the flag for this path based only on the relation-level flag,
1153 	 * without actually iterating over the list of children.
1154 	 */
1155 	pathnode->path.parallel_aware = false;
1156 	pathnode->path.parallel_safe = rel->consider_parallel;
1157 	pathnode->path.parallel_workers = 0;
1158 
1159 	pathnode->path.pathkeys = NIL;		/* always unordered */
1160 
1161 	pathnode->bitmapquals = bitmapquals;
1162 
1163 	/* this sets bitmapselectivity as well as the regular cost fields: */
1164 	cost_bitmap_or_node(pathnode, root);
1165 
1166 	return pathnode;
1167 }
1168 
1169 /*
1170  * create_tidscan_path
1171  *	  Creates a path corresponding to a scan by TID, returning the pathnode.
1172  */
1173 TidPath *
create_tidscan_path(PlannerInfo * root,RelOptInfo * rel,List * tidquals,Relids required_outer)1174 create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals,
1175 					Relids required_outer)
1176 {
1177 	TidPath    *pathnode = makeNode(TidPath);
1178 
1179 	pathnode->path.pathtype = T_TidScan;
1180 	pathnode->path.parent = rel;
1181 	pathnode->path.pathtarget = rel->reltarget;
1182 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1183 														  required_outer);
1184 	pathnode->path.parallel_aware = false;
1185 	pathnode->path.parallel_safe = rel->consider_parallel;
1186 	pathnode->path.parallel_workers = 0;
1187 	pathnode->path.pathkeys = NIL;		/* always unordered */
1188 
1189 	pathnode->tidquals = tidquals;
1190 
1191 	cost_tidscan(&pathnode->path, root, rel, tidquals,
1192 				 pathnode->path.param_info);
1193 
1194 	return pathnode;
1195 }
1196 
1197 /*
1198  * create_append_path
1199  *	  Creates a path corresponding to an Append plan, returning the
1200  *	  pathnode.
1201  *
1202  * Note that we must handle subpaths = NIL, representing a dummy access path.
1203  */
1204 AppendPath *
create_append_path(RelOptInfo * rel,List * subpaths,Relids required_outer,int parallel_workers)1205 create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer,
1206 				   int parallel_workers)
1207 {
1208 	AppendPath *pathnode = makeNode(AppendPath);
1209 	ListCell   *l;
1210 
1211 	pathnode->path.pathtype = T_Append;
1212 	pathnode->path.parent = rel;
1213 	pathnode->path.pathtarget = rel->reltarget;
1214 	pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1215 															required_outer);
1216 	pathnode->path.parallel_aware = false;
1217 	pathnode->path.parallel_safe = rel->consider_parallel;
1218 	pathnode->path.parallel_workers = parallel_workers;
1219 	pathnode->path.pathkeys = NIL;		/* result is always considered
1220 										 * unsorted */
1221 	pathnode->subpaths = subpaths;
1222 
1223 	/*
1224 	 * We don't bother with inventing a cost_append(), but just do it here.
1225 	 *
1226 	 * Compute rows and costs as sums of subplan rows and costs.  We charge
1227 	 * nothing extra for the Append itself, which perhaps is too optimistic,
1228 	 * but since it doesn't do any selection or projection, it is a pretty
1229 	 * cheap node.
1230 	 */
1231 	pathnode->path.rows = 0;
1232 	pathnode->path.startup_cost = 0;
1233 	pathnode->path.total_cost = 0;
1234 	foreach(l, subpaths)
1235 	{
1236 		Path	   *subpath = (Path *) lfirst(l);
1237 
1238 		pathnode->path.rows += subpath->rows;
1239 
1240 		if (l == list_head(subpaths))	/* first node? */
1241 			pathnode->path.startup_cost = subpath->startup_cost;
1242 		pathnode->path.total_cost += subpath->total_cost;
1243 		pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1244 			subpath->parallel_safe;
1245 
1246 		/* All child paths must have same parameterization */
1247 		Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1248 	}
1249 
1250 	return pathnode;
1251 }
1252 
1253 /*
1254  * create_merge_append_path
1255  *	  Creates a path corresponding to a MergeAppend plan, returning the
1256  *	  pathnode.
1257  */
1258 MergeAppendPath *
create_merge_append_path(PlannerInfo * root,RelOptInfo * rel,List * subpaths,List * pathkeys,Relids required_outer)1259 create_merge_append_path(PlannerInfo *root,
1260 						 RelOptInfo *rel,
1261 						 List *subpaths,
1262 						 List *pathkeys,
1263 						 Relids required_outer)
1264 {
1265 	MergeAppendPath *pathnode = makeNode(MergeAppendPath);
1266 	Cost		input_startup_cost;
1267 	Cost		input_total_cost;
1268 	ListCell   *l;
1269 
1270 	pathnode->path.pathtype = T_MergeAppend;
1271 	pathnode->path.parent = rel;
1272 	pathnode->path.pathtarget = rel->reltarget;
1273 	pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1274 															required_outer);
1275 	pathnode->path.parallel_aware = false;
1276 	pathnode->path.parallel_safe = rel->consider_parallel;
1277 	pathnode->path.parallel_workers = 0;
1278 	pathnode->path.pathkeys = pathkeys;
1279 	pathnode->subpaths = subpaths;
1280 
1281 	/*
1282 	 * Apply query-wide LIMIT if known and path is for sole base relation.
1283 	 * (Handling this at this low level is a bit klugy.)
1284 	 */
1285 	if (bms_equal(rel->relids, root->all_baserels))
1286 		pathnode->limit_tuples = root->limit_tuples;
1287 	else
1288 		pathnode->limit_tuples = -1.0;
1289 
1290 	/*
1291 	 * Add up the sizes and costs of the input paths.
1292 	 */
1293 	pathnode->path.rows = 0;
1294 	input_startup_cost = 0;
1295 	input_total_cost = 0;
1296 	foreach(l, subpaths)
1297 	{
1298 		Path	   *subpath = (Path *) lfirst(l);
1299 
1300 		pathnode->path.rows += subpath->rows;
1301 		pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1302 			subpath->parallel_safe;
1303 
1304 		if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1305 		{
1306 			/* Subpath is adequately ordered, we won't need to sort it */
1307 			input_startup_cost += subpath->startup_cost;
1308 			input_total_cost += subpath->total_cost;
1309 		}
1310 		else
1311 		{
1312 			/* We'll need to insert a Sort node, so include cost for that */
1313 			Path		sort_path;		/* dummy for result of cost_sort */
1314 
1315 			cost_sort(&sort_path,
1316 					  root,
1317 					  pathkeys,
1318 					  subpath->total_cost,
1319 					  subpath->parent->tuples,
1320 					  subpath->pathtarget->width,
1321 					  0.0,
1322 					  work_mem,
1323 					  pathnode->limit_tuples);
1324 			input_startup_cost += sort_path.startup_cost;
1325 			input_total_cost += sort_path.total_cost;
1326 		}
1327 
1328 		/* All child paths must have same parameterization */
1329 		Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1330 	}
1331 
1332 	/* Now we can compute total costs of the MergeAppend */
1333 	cost_merge_append(&pathnode->path, root,
1334 					  pathkeys, list_length(subpaths),
1335 					  input_startup_cost, input_total_cost,
1336 					  rel->tuples);
1337 
1338 	return pathnode;
1339 }
1340 
1341 /*
1342  * create_result_path
1343  *	  Creates a path representing a Result-and-nothing-else plan.
1344  *
1345  * This is only used for degenerate cases, such as a query with an empty
1346  * jointree.
1347  */
1348 ResultPath *
create_result_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,List * resconstantqual)1349 create_result_path(PlannerInfo *root, RelOptInfo *rel,
1350 				   PathTarget *target, List *resconstantqual)
1351 {
1352 	ResultPath *pathnode = makeNode(ResultPath);
1353 
1354 	pathnode->path.pathtype = T_Result;
1355 	pathnode->path.parent = rel;
1356 	pathnode->path.pathtarget = target;
1357 	pathnode->path.param_info = NULL;	/* there are no other rels... */
1358 	pathnode->path.parallel_aware = false;
1359 	pathnode->path.parallel_safe = rel->consider_parallel;
1360 	pathnode->path.parallel_workers = 0;
1361 	pathnode->path.pathkeys = NIL;
1362 	pathnode->quals = resconstantqual;
1363 
1364 	/* Hardly worth defining a cost_result() function ... just do it */
1365 	pathnode->path.rows = 1;
1366 	pathnode->path.startup_cost = target->cost.startup;
1367 	pathnode->path.total_cost = target->cost.startup +
1368 		cpu_tuple_cost + target->cost.per_tuple;
1369 	if (resconstantqual)
1370 	{
1371 		QualCost	qual_cost;
1372 
1373 		cost_qual_eval(&qual_cost, resconstantqual, root);
1374 		/* resconstantqual is evaluated once at startup */
1375 		pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1376 		pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1377 	}
1378 
1379 	return pathnode;
1380 }
1381 
1382 /*
1383  * create_material_path
1384  *	  Creates a path corresponding to a Material plan, returning the
1385  *	  pathnode.
1386  */
1387 MaterialPath *
create_material_path(RelOptInfo * rel,Path * subpath)1388 create_material_path(RelOptInfo *rel, Path *subpath)
1389 {
1390 	MaterialPath *pathnode = makeNode(MaterialPath);
1391 
1392 	Assert(subpath->parent == rel);
1393 
1394 	pathnode->path.pathtype = T_Material;
1395 	pathnode->path.parent = rel;
1396 	pathnode->path.pathtarget = rel->reltarget;
1397 	pathnode->path.param_info = subpath->param_info;
1398 	pathnode->path.parallel_aware = false;
1399 	pathnode->path.parallel_safe = rel->consider_parallel &&
1400 		subpath->parallel_safe;
1401 	pathnode->path.parallel_workers = subpath->parallel_workers;
1402 	pathnode->path.pathkeys = subpath->pathkeys;
1403 
1404 	pathnode->subpath = subpath;
1405 
1406 	cost_material(&pathnode->path,
1407 				  subpath->startup_cost,
1408 				  subpath->total_cost,
1409 				  subpath->rows,
1410 				  subpath->pathtarget->width);
1411 
1412 	return pathnode;
1413 }
1414 
1415 /*
1416  * create_unique_path
1417  *	  Creates a path representing elimination of distinct rows from the
1418  *	  input data.  Distinct-ness is defined according to the needs of the
1419  *	  semijoin represented by sjinfo.  If it is not possible to identify
1420  *	  how to make the data unique, NULL is returned.
1421  *
1422  * If used at all, this is likely to be called repeatedly on the same rel;
1423  * and the input subpath should always be the same (the cheapest_total path
1424  * for the rel).  So we cache the result.
1425  */
1426 UniquePath *
create_unique_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,SpecialJoinInfo * sjinfo)1427 create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1428 				   SpecialJoinInfo *sjinfo)
1429 {
1430 	UniquePath *pathnode;
1431 	Path		sort_path;		/* dummy for result of cost_sort */
1432 	Path		agg_path;		/* dummy for result of cost_agg */
1433 	MemoryContext oldcontext;
1434 	int			numCols;
1435 
1436 	/* Caller made a mistake if subpath isn't cheapest_total ... */
1437 	Assert(subpath == rel->cheapest_total_path);
1438 	Assert(subpath->parent == rel);
1439 	/* ... or if SpecialJoinInfo is the wrong one */
1440 	Assert(sjinfo->jointype == JOIN_SEMI);
1441 	Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
1442 
1443 	/* If result already cached, return it */
1444 	if (rel->cheapest_unique_path)
1445 		return (UniquePath *) rel->cheapest_unique_path;
1446 
1447 	/* If it's not possible to unique-ify, return NULL */
1448 	if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
1449 		return NULL;
1450 
1451 	/*
1452 	 * We must ensure path struct and subsidiary data are allocated in main
1453 	 * planning context; otherwise GEQO memory management causes trouble.
1454 	 */
1455 	oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1456 
1457 	pathnode = makeNode(UniquePath);
1458 
1459 	pathnode->path.pathtype = T_Unique;
1460 	pathnode->path.parent = rel;
1461 	pathnode->path.pathtarget = rel->reltarget;
1462 	pathnode->path.param_info = subpath->param_info;
1463 	pathnode->path.parallel_aware = false;
1464 	pathnode->path.parallel_safe = rel->consider_parallel &&
1465 		subpath->parallel_safe;
1466 	pathnode->path.parallel_workers = subpath->parallel_workers;
1467 
1468 	/*
1469 	 * Assume the output is unsorted, since we don't necessarily have pathkeys
1470 	 * to represent it.  (This might get overridden below.)
1471 	 */
1472 	pathnode->path.pathkeys = NIL;
1473 
1474 	pathnode->subpath = subpath;
1475 	pathnode->in_operators = sjinfo->semi_operators;
1476 	pathnode->uniq_exprs = sjinfo->semi_rhs_exprs;
1477 
1478 	/*
1479 	 * If the input is a relation and it has a unique index that proves the
1480 	 * semi_rhs_exprs are unique, then we don't need to do anything.  Note
1481 	 * that relation_has_unique_index_for automatically considers restriction
1482 	 * clauses for the rel, as well.
1483 	 */
1484 	if (rel->rtekind == RTE_RELATION && sjinfo->semi_can_btree &&
1485 		relation_has_unique_index_for(root, rel, NIL,
1486 									  sjinfo->semi_rhs_exprs,
1487 									  sjinfo->semi_operators))
1488 	{
1489 		pathnode->umethod = UNIQUE_PATH_NOOP;
1490 		pathnode->path.rows = rel->rows;
1491 		pathnode->path.startup_cost = subpath->startup_cost;
1492 		pathnode->path.total_cost = subpath->total_cost;
1493 		pathnode->path.pathkeys = subpath->pathkeys;
1494 
1495 		rel->cheapest_unique_path = (Path *) pathnode;
1496 
1497 		MemoryContextSwitchTo(oldcontext);
1498 
1499 		return pathnode;
1500 	}
1501 
1502 	/*
1503 	 * If the input is a subquery whose output must be unique already, then we
1504 	 * don't need to do anything.  The test for uniqueness has to consider
1505 	 * exactly which columns we are extracting; for example "SELECT DISTINCT
1506 	 * x,y" doesn't guarantee that x alone is distinct. So we cannot check for
1507 	 * this optimization unless semi_rhs_exprs consists only of simple Vars
1508 	 * referencing subquery outputs.  (Possibly we could do something with
1509 	 * expressions in the subquery outputs, too, but for now keep it simple.)
1510 	 */
1511 	if (rel->rtekind == RTE_SUBQUERY)
1512 	{
1513 		RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1514 
1515 		if (query_supports_distinctness(rte->subquery))
1516 		{
1517 			List	   *sub_tlist_colnos;
1518 
1519 			sub_tlist_colnos = translate_sub_tlist(sjinfo->semi_rhs_exprs,
1520 												   rel->relid);
1521 
1522 			if (sub_tlist_colnos &&
1523 				query_is_distinct_for(rte->subquery,
1524 									  sub_tlist_colnos,
1525 									  sjinfo->semi_operators))
1526 			{
1527 				pathnode->umethod = UNIQUE_PATH_NOOP;
1528 				pathnode->path.rows = rel->rows;
1529 				pathnode->path.startup_cost = subpath->startup_cost;
1530 				pathnode->path.total_cost = subpath->total_cost;
1531 				pathnode->path.pathkeys = subpath->pathkeys;
1532 
1533 				rel->cheapest_unique_path = (Path *) pathnode;
1534 
1535 				MemoryContextSwitchTo(oldcontext);
1536 
1537 				return pathnode;
1538 			}
1539 		}
1540 	}
1541 
1542 	/* Estimate number of output rows */
1543 	pathnode->path.rows = estimate_num_groups(root,
1544 											  sjinfo->semi_rhs_exprs,
1545 											  rel->rows,
1546 											  NULL);
1547 	numCols = list_length(sjinfo->semi_rhs_exprs);
1548 
1549 	if (sjinfo->semi_can_btree)
1550 	{
1551 		/*
1552 		 * Estimate cost for sort+unique implementation
1553 		 */
1554 		cost_sort(&sort_path, root, NIL,
1555 				  subpath->total_cost,
1556 				  rel->rows,
1557 				  subpath->pathtarget->width,
1558 				  0.0,
1559 				  work_mem,
1560 				  -1.0);
1561 
1562 		/*
1563 		 * Charge one cpu_operator_cost per comparison per input tuple. We
1564 		 * assume all columns get compared at most of the tuples. (XXX
1565 		 * probably this is an overestimate.)  This should agree with
1566 		 * create_upper_unique_path.
1567 		 */
1568 		sort_path.total_cost += cpu_operator_cost * rel->rows * numCols;
1569 	}
1570 
1571 	if (sjinfo->semi_can_hash)
1572 	{
1573 		/*
1574 		 * Estimate the overhead per hashtable entry at 64 bytes (same as in
1575 		 * planner.c).
1576 		 */
1577 		int			hashentrysize = subpath->pathtarget->width + 64;
1578 
1579 		if (hashentrysize * pathnode->path.rows > work_mem * 1024L)
1580 		{
1581 			/*
1582 			 * We should not try to hash.  Hack the SpecialJoinInfo to
1583 			 * remember this, in case we come through here again.
1584 			 */
1585 			sjinfo->semi_can_hash = false;
1586 		}
1587 		else
1588 			cost_agg(&agg_path, root,
1589 					 AGG_HASHED, NULL,
1590 					 numCols, pathnode->path.rows,
1591 					 subpath->startup_cost,
1592 					 subpath->total_cost,
1593 					 rel->rows);
1594 	}
1595 
1596 	if (sjinfo->semi_can_btree && sjinfo->semi_can_hash)
1597 	{
1598 		if (agg_path.total_cost < sort_path.total_cost)
1599 			pathnode->umethod = UNIQUE_PATH_HASH;
1600 		else
1601 			pathnode->umethod = UNIQUE_PATH_SORT;
1602 	}
1603 	else if (sjinfo->semi_can_btree)
1604 		pathnode->umethod = UNIQUE_PATH_SORT;
1605 	else if (sjinfo->semi_can_hash)
1606 		pathnode->umethod = UNIQUE_PATH_HASH;
1607 	else
1608 	{
1609 		/* we can get here only if we abandoned hashing above */
1610 		MemoryContextSwitchTo(oldcontext);
1611 		return NULL;
1612 	}
1613 
1614 	if (pathnode->umethod == UNIQUE_PATH_HASH)
1615 	{
1616 		pathnode->path.startup_cost = agg_path.startup_cost;
1617 		pathnode->path.total_cost = agg_path.total_cost;
1618 	}
1619 	else
1620 	{
1621 		pathnode->path.startup_cost = sort_path.startup_cost;
1622 		pathnode->path.total_cost = sort_path.total_cost;
1623 	}
1624 
1625 	rel->cheapest_unique_path = (Path *) pathnode;
1626 
1627 	MemoryContextSwitchTo(oldcontext);
1628 
1629 	return pathnode;
1630 }
1631 
1632 /*
1633  * translate_sub_tlist - get subquery column numbers represented by tlist
1634  *
1635  * The given targetlist usually contains only Vars referencing the given relid.
1636  * Extract their varattnos (ie, the column numbers of the subquery) and return
1637  * as an integer List.
1638  *
1639  * If any of the tlist items is not a simple Var, we cannot determine whether
1640  * the subquery's uniqueness condition (if any) matches ours, so punt and
1641  * return NIL.
1642  */
1643 static List *
translate_sub_tlist(List * tlist,int relid)1644 translate_sub_tlist(List *tlist, int relid)
1645 {
1646 	List	   *result = NIL;
1647 	ListCell   *l;
1648 
1649 	foreach(l, tlist)
1650 	{
1651 		Var		   *var = (Var *) lfirst(l);
1652 
1653 		if (!var || !IsA(var, Var) ||
1654 			var->varno != relid)
1655 			return NIL;			/* punt */
1656 
1657 		result = lappend_int(result, var->varattno);
1658 	}
1659 	return result;
1660 }
1661 
1662 /*
1663  * create_gather_path
1664  *	  Creates a path corresponding to a gather scan, returning the
1665  *	  pathnode.
1666  *
1667  * 'rows' may optionally be set to override row estimates from other sources.
1668  */
1669 GatherPath *
create_gather_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,Relids required_outer,double * rows)1670 create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1671 				   PathTarget *target, Relids required_outer, double *rows)
1672 {
1673 	GatherPath *pathnode = makeNode(GatherPath);
1674 
1675 	Assert(subpath->parallel_safe);
1676 
1677 	pathnode->path.pathtype = T_Gather;
1678 	pathnode->path.parent = rel;
1679 	pathnode->path.pathtarget = target;
1680 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1681 														  required_outer);
1682 	pathnode->path.parallel_aware = false;
1683 	pathnode->path.parallel_safe = false;
1684 	pathnode->path.parallel_workers = 0;
1685 	pathnode->path.pathkeys = NIL;		/* Gather has unordered result */
1686 
1687 	pathnode->subpath = subpath;
1688 	pathnode->num_workers = subpath->parallel_workers;
1689 	pathnode->single_copy = false;
1690 
1691 	if (pathnode->num_workers == 0)
1692 	{
1693 		pathnode->path.pathkeys = subpath->pathkeys;
1694 		pathnode->num_workers = 1;
1695 		pathnode->single_copy = true;
1696 	}
1697 
1698 	cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1699 
1700 	return pathnode;
1701 }
1702 
1703 /*
1704  * create_subqueryscan_path
1705  *	  Creates a path corresponding to a scan of a subquery,
1706  *	  returning the pathnode.
1707  */
1708 SubqueryScanPath *
create_subqueryscan_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * pathkeys,Relids required_outer)1709 create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1710 						 List *pathkeys, Relids required_outer)
1711 {
1712 	SubqueryScanPath *pathnode = makeNode(SubqueryScanPath);
1713 
1714 	pathnode->path.pathtype = T_SubqueryScan;
1715 	pathnode->path.parent = rel;
1716 	pathnode->path.pathtarget = rel->reltarget;
1717 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1718 														  required_outer);
1719 	pathnode->path.parallel_aware = false;
1720 	pathnode->path.parallel_safe = rel->consider_parallel &&
1721 		subpath->parallel_safe;
1722 	pathnode->path.parallel_workers = subpath->parallel_workers;
1723 	pathnode->path.pathkeys = pathkeys;
1724 	pathnode->subpath = subpath;
1725 
1726 	cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info);
1727 
1728 	return pathnode;
1729 }
1730 
1731 /*
1732  * create_functionscan_path
1733  *	  Creates a path corresponding to a sequential scan of a function,
1734  *	  returning the pathnode.
1735  */
1736 Path *
create_functionscan_path(PlannerInfo * root,RelOptInfo * rel,List * pathkeys,Relids required_outer)1737 create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
1738 						 List *pathkeys, Relids required_outer)
1739 {
1740 	Path	   *pathnode = makeNode(Path);
1741 
1742 	pathnode->pathtype = T_FunctionScan;
1743 	pathnode->parent = rel;
1744 	pathnode->pathtarget = rel->reltarget;
1745 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
1746 													 required_outer);
1747 	pathnode->parallel_aware = false;
1748 	pathnode->parallel_safe = rel->consider_parallel;
1749 	pathnode->parallel_workers = 0;
1750 	pathnode->pathkeys = pathkeys;
1751 
1752 	cost_functionscan(pathnode, root, rel, pathnode->param_info);
1753 
1754 	return pathnode;
1755 }
1756 
1757 /*
1758  * create_valuesscan_path
1759  *	  Creates a path corresponding to a scan of a VALUES list,
1760  *	  returning the pathnode.
1761  */
1762 Path *
create_valuesscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)1763 create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
1764 					   Relids required_outer)
1765 {
1766 	Path	   *pathnode = makeNode(Path);
1767 
1768 	pathnode->pathtype = T_ValuesScan;
1769 	pathnode->parent = rel;
1770 	pathnode->pathtarget = rel->reltarget;
1771 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
1772 													 required_outer);
1773 	pathnode->parallel_aware = false;
1774 	pathnode->parallel_safe = rel->consider_parallel;
1775 	pathnode->parallel_workers = 0;
1776 	pathnode->pathkeys = NIL;	/* result is always unordered */
1777 
1778 	cost_valuesscan(pathnode, root, rel, pathnode->param_info);
1779 
1780 	return pathnode;
1781 }
1782 
1783 /*
1784  * create_ctescan_path
1785  *	  Creates a path corresponding to a scan of a non-self-reference CTE,
1786  *	  returning the pathnode.
1787  */
1788 Path *
create_ctescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)1789 create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
1790 {
1791 	Path	   *pathnode = makeNode(Path);
1792 
1793 	pathnode->pathtype = T_CteScan;
1794 	pathnode->parent = rel;
1795 	pathnode->pathtarget = rel->reltarget;
1796 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
1797 													 required_outer);
1798 	pathnode->parallel_aware = false;
1799 	pathnode->parallel_safe = rel->consider_parallel;
1800 	pathnode->parallel_workers = 0;
1801 	pathnode->pathkeys = NIL;	/* XXX for now, result is always unordered */
1802 
1803 	cost_ctescan(pathnode, root, rel, pathnode->param_info);
1804 
1805 	return pathnode;
1806 }
1807 
1808 /*
1809  * create_worktablescan_path
1810  *	  Creates a path corresponding to a scan of a self-reference CTE,
1811  *	  returning the pathnode.
1812  */
1813 Path *
create_worktablescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)1814 create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
1815 						  Relids required_outer)
1816 {
1817 	Path	   *pathnode = makeNode(Path);
1818 
1819 	pathnode->pathtype = T_WorkTableScan;
1820 	pathnode->parent = rel;
1821 	pathnode->pathtarget = rel->reltarget;
1822 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
1823 													 required_outer);
1824 	pathnode->parallel_aware = false;
1825 	pathnode->parallel_safe = rel->consider_parallel;
1826 	pathnode->parallel_workers = 0;
1827 	pathnode->pathkeys = NIL;	/* result is always unordered */
1828 
1829 	/* Cost is the same as for a regular CTE scan */
1830 	cost_ctescan(pathnode, root, rel, pathnode->param_info);
1831 
1832 	return pathnode;
1833 }
1834 
1835 /*
1836  * create_foreignscan_path
1837  *	  Creates a path corresponding to a scan of a foreign table, foreign join,
1838  *	  or foreign upper-relation processing, returning the pathnode.
1839  *
1840  * This function is never called from core Postgres; rather, it's expected
1841  * to be called by the GetForeignPaths, GetForeignJoinPaths, or
1842  * GetForeignUpperPaths function of a foreign data wrapper.  We make the FDW
1843  * supply all fields of the path, since we do not have any way to calculate
1844  * them in core.  However, there is a usually-sane default for the pathtarget
1845  * (rel->reltarget), so we let a NULL for "target" select that.
1846  */
1847 ForeignPath *
create_foreignscan_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,double rows,Cost startup_cost,Cost total_cost,List * pathkeys,Relids required_outer,Path * fdw_outerpath,List * fdw_private)1848 create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
1849 						PathTarget *target,
1850 						double rows, Cost startup_cost, Cost total_cost,
1851 						List *pathkeys,
1852 						Relids required_outer,
1853 						Path *fdw_outerpath,
1854 						List *fdw_private)
1855 {
1856 	ForeignPath *pathnode = makeNode(ForeignPath);
1857 
1858 	/*
1859 	 * Since the path's required_outer should always include all the rel's
1860 	 * lateral_relids, forcibly add those if necessary.  This is a bit of a
1861 	 * hack, but up till early 2019 the contrib FDWs failed to ensure that,
1862 	 * and it's likely that the same error has propagated into many external
1863 	 * FDWs.  Don't risk modifying the passed-in relid set here.
1864 	 */
1865 	if (rel->lateral_relids && !bms_is_subset(rel->lateral_relids,
1866 											  required_outer))
1867 		required_outer = bms_union(required_outer, rel->lateral_relids);
1868 
1869 	/*
1870 	 * Although this function is only designed to be used for scans of
1871 	 * baserels, before v12 postgres_fdw abused it to make paths for join and
1872 	 * upper rels.  It will work for such cases as long as required_outer is
1873 	 * empty (otherwise get_baserel_parampathinfo does the wrong thing), which
1874 	 * fortunately is the expected case for now.
1875 	 */
1876 	if (!bms_is_empty(required_outer) &&
1877 		!(rel->reloptkind == RELOPT_BASEREL ||
1878 		  rel->reloptkind == RELOPT_OTHER_MEMBER_REL))
1879 		elog(ERROR, "parameterized foreign joins are not supported yet");
1880 
1881 	pathnode->path.pathtype = T_ForeignScan;
1882 	pathnode->path.parent = rel;
1883 	pathnode->path.pathtarget = target ? target : rel->reltarget;
1884 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1885 														  required_outer);
1886 	pathnode->path.parallel_aware = false;
1887 	pathnode->path.parallel_safe = rel->consider_parallel;
1888 	pathnode->path.parallel_workers = 0;
1889 	pathnode->path.rows = rows;
1890 	pathnode->path.startup_cost = startup_cost;
1891 	pathnode->path.total_cost = total_cost;
1892 	pathnode->path.pathkeys = pathkeys;
1893 
1894 	pathnode->fdw_outerpath = fdw_outerpath;
1895 	pathnode->fdw_private = fdw_private;
1896 
1897 	return pathnode;
1898 }
1899 
1900 /*
1901  * calc_nestloop_required_outer
1902  *	  Compute the required_outer set for a nestloop join path
1903  *
1904  * Note: result must not share storage with either input
1905  */
1906 Relids
calc_nestloop_required_outer(Path * outer_path,Path * inner_path)1907 calc_nestloop_required_outer(Path *outer_path, Path *inner_path)
1908 {
1909 	Relids		outer_paramrels = PATH_REQ_OUTER(outer_path);
1910 	Relids		inner_paramrels = PATH_REQ_OUTER(inner_path);
1911 	Relids		required_outer;
1912 
1913 	/* inner_path can require rels from outer path, but not vice versa */
1914 	Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
1915 	/* easy case if inner path is not parameterized */
1916 	if (!inner_paramrels)
1917 		return bms_copy(outer_paramrels);
1918 	/* else, form the union ... */
1919 	required_outer = bms_union(outer_paramrels, inner_paramrels);
1920 	/* ... and remove any mention of now-satisfied outer rels */
1921 	required_outer = bms_del_members(required_outer,
1922 									 outer_path->parent->relids);
1923 	/* maintain invariant that required_outer is exactly NULL if empty */
1924 	if (bms_is_empty(required_outer))
1925 	{
1926 		bms_free(required_outer);
1927 		required_outer = NULL;
1928 	}
1929 	return required_outer;
1930 }
1931 
1932 /*
1933  * calc_non_nestloop_required_outer
1934  *	  Compute the required_outer set for a merge or hash join path
1935  *
1936  * Note: result must not share storage with either input
1937  */
1938 Relids
calc_non_nestloop_required_outer(Path * outer_path,Path * inner_path)1939 calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
1940 {
1941 	Relids		outer_paramrels = PATH_REQ_OUTER(outer_path);
1942 	Relids		inner_paramrels = PATH_REQ_OUTER(inner_path);
1943 	Relids		required_outer;
1944 
1945 	/* neither path can require rels from the other */
1946 	Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
1947 	Assert(!bms_overlap(inner_paramrels, outer_path->parent->relids));
1948 	/* form the union ... */
1949 	required_outer = bms_union(outer_paramrels, inner_paramrels);
1950 	/* we do not need an explicit test for empty; bms_union gets it right */
1951 	return required_outer;
1952 }
1953 
1954 /*
1955  * create_nestloop_path
1956  *	  Creates a pathnode corresponding to a nestloop join between two
1957  *	  relations.
1958  *
1959  * 'joinrel' is the join relation.
1960  * 'jointype' is the type of join required
1961  * 'workspace' is the result from initial_cost_nestloop
1962  * 'sjinfo' is extra info about the join for selectivity estimation
1963  * 'semifactors' contains valid data if jointype is SEMI or ANTI
1964  * 'outer_path' is the outer path
1965  * 'inner_path' is the inner path
1966  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
1967  * 'pathkeys' are the path keys of the new join path
1968  * 'required_outer' is the set of required outer rels
1969  *
1970  * Returns the resulting path node.
1971  */
1972 NestPath *
create_nestloop_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,SpecialJoinInfo * sjinfo,SemiAntiJoinFactors * semifactors,Path * outer_path,Path * inner_path,List * restrict_clauses,List * pathkeys,Relids required_outer)1973 create_nestloop_path(PlannerInfo *root,
1974 					 RelOptInfo *joinrel,
1975 					 JoinType jointype,
1976 					 JoinCostWorkspace *workspace,
1977 					 SpecialJoinInfo *sjinfo,
1978 					 SemiAntiJoinFactors *semifactors,
1979 					 Path *outer_path,
1980 					 Path *inner_path,
1981 					 List *restrict_clauses,
1982 					 List *pathkeys,
1983 					 Relids required_outer)
1984 {
1985 	NestPath   *pathnode = makeNode(NestPath);
1986 	Relids		inner_req_outer = PATH_REQ_OUTER(inner_path);
1987 
1988 	/*
1989 	 * If the inner path is parameterized by the outer, we must drop any
1990 	 * restrict_clauses that are due to be moved into the inner path.  We have
1991 	 * to do this now, rather than postpone the work till createplan time,
1992 	 * because the restrict_clauses list can affect the size and cost
1993 	 * estimates for this path.
1994 	 */
1995 	if (bms_overlap(inner_req_outer, outer_path->parent->relids))
1996 	{
1997 		Relids		inner_and_outer = bms_union(inner_path->parent->relids,
1998 												inner_req_outer);
1999 		List	   *jclauses = NIL;
2000 		ListCell   *lc;
2001 
2002 		foreach(lc, restrict_clauses)
2003 		{
2004 			RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2005 
2006 			if (!join_clause_is_movable_into(rinfo,
2007 											 inner_path->parent->relids,
2008 											 inner_and_outer))
2009 				jclauses = lappend(jclauses, rinfo);
2010 		}
2011 		restrict_clauses = jclauses;
2012 	}
2013 
2014 	pathnode->path.pathtype = T_NestLoop;
2015 	pathnode->path.parent = joinrel;
2016 	pathnode->path.pathtarget = joinrel->reltarget;
2017 	pathnode->path.param_info =
2018 		get_joinrel_parampathinfo(root,
2019 								  joinrel,
2020 								  outer_path,
2021 								  inner_path,
2022 								  sjinfo,
2023 								  required_outer,
2024 								  &restrict_clauses);
2025 	pathnode->path.parallel_aware = false;
2026 	pathnode->path.parallel_safe = joinrel->consider_parallel &&
2027 		outer_path->parallel_safe && inner_path->parallel_safe;
2028 	/* This is a foolish way to estimate parallel_workers, but for now... */
2029 	pathnode->path.parallel_workers = outer_path->parallel_workers;
2030 	pathnode->path.pathkeys = pathkeys;
2031 	pathnode->jointype = jointype;
2032 	pathnode->outerjoinpath = outer_path;
2033 	pathnode->innerjoinpath = inner_path;
2034 	pathnode->joinrestrictinfo = restrict_clauses;
2035 
2036 	final_cost_nestloop(root, pathnode, workspace, sjinfo, semifactors);
2037 
2038 	return pathnode;
2039 }
2040 
2041 /*
2042  * create_mergejoin_path
2043  *	  Creates a pathnode corresponding to a mergejoin join between
2044  *	  two relations
2045  *
2046  * 'joinrel' is the join relation
2047  * 'jointype' is the type of join required
2048  * 'workspace' is the result from initial_cost_mergejoin
2049  * 'sjinfo' is extra info about the join for selectivity estimation
2050  * 'outer_path' is the outer path
2051  * 'inner_path' is the inner path
2052  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2053  * 'pathkeys' are the path keys of the new join path
2054  * 'required_outer' is the set of required outer rels
2055  * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2056  *		(this should be a subset of the restrict_clauses list)
2057  * 'outersortkeys' are the sort varkeys for the outer relation
2058  * 'innersortkeys' are the sort varkeys for the inner relation
2059  */
2060 MergePath *
create_mergejoin_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,SpecialJoinInfo * sjinfo,Path * outer_path,Path * inner_path,List * restrict_clauses,List * pathkeys,Relids required_outer,List * mergeclauses,List * outersortkeys,List * innersortkeys)2061 create_mergejoin_path(PlannerInfo *root,
2062 					  RelOptInfo *joinrel,
2063 					  JoinType jointype,
2064 					  JoinCostWorkspace *workspace,
2065 					  SpecialJoinInfo *sjinfo,
2066 					  Path *outer_path,
2067 					  Path *inner_path,
2068 					  List *restrict_clauses,
2069 					  List *pathkeys,
2070 					  Relids required_outer,
2071 					  List *mergeclauses,
2072 					  List *outersortkeys,
2073 					  List *innersortkeys)
2074 {
2075 	MergePath  *pathnode = makeNode(MergePath);
2076 
2077 	pathnode->jpath.path.pathtype = T_MergeJoin;
2078 	pathnode->jpath.path.parent = joinrel;
2079 	pathnode->jpath.path.pathtarget = joinrel->reltarget;
2080 	pathnode->jpath.path.param_info =
2081 		get_joinrel_parampathinfo(root,
2082 								  joinrel,
2083 								  outer_path,
2084 								  inner_path,
2085 								  sjinfo,
2086 								  required_outer,
2087 								  &restrict_clauses);
2088 	pathnode->jpath.path.parallel_aware = false;
2089 	pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2090 		outer_path->parallel_safe && inner_path->parallel_safe;
2091 	/* This is a foolish way to estimate parallel_workers, but for now... */
2092 	pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2093 	pathnode->jpath.path.pathkeys = pathkeys;
2094 	pathnode->jpath.jointype = jointype;
2095 	pathnode->jpath.outerjoinpath = outer_path;
2096 	pathnode->jpath.innerjoinpath = inner_path;
2097 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
2098 	pathnode->path_mergeclauses = mergeclauses;
2099 	pathnode->outersortkeys = outersortkeys;
2100 	pathnode->innersortkeys = innersortkeys;
2101 	/* pathnode->materialize_inner will be set by final_cost_mergejoin */
2102 
2103 	final_cost_mergejoin(root, pathnode, workspace, sjinfo);
2104 
2105 	return pathnode;
2106 }
2107 
2108 /*
2109  * create_hashjoin_path
2110  *	  Creates a pathnode corresponding to a hash join between two relations.
2111  *
2112  * 'joinrel' is the join relation
2113  * 'jointype' is the type of join required
2114  * 'workspace' is the result from initial_cost_hashjoin
2115  * 'sjinfo' is extra info about the join for selectivity estimation
2116  * 'semifactors' contains valid data if jointype is SEMI or ANTI
2117  * 'outer_path' is the cheapest outer path
2118  * 'inner_path' is the cheapest inner path
2119  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2120  * 'required_outer' is the set of required outer rels
2121  * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2122  *		(this should be a subset of the restrict_clauses list)
2123  */
2124 HashPath *
create_hashjoin_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,SpecialJoinInfo * sjinfo,SemiAntiJoinFactors * semifactors,Path * outer_path,Path * inner_path,List * restrict_clauses,Relids required_outer,List * hashclauses)2125 create_hashjoin_path(PlannerInfo *root,
2126 					 RelOptInfo *joinrel,
2127 					 JoinType jointype,
2128 					 JoinCostWorkspace *workspace,
2129 					 SpecialJoinInfo *sjinfo,
2130 					 SemiAntiJoinFactors *semifactors,
2131 					 Path *outer_path,
2132 					 Path *inner_path,
2133 					 List *restrict_clauses,
2134 					 Relids required_outer,
2135 					 List *hashclauses)
2136 {
2137 	HashPath   *pathnode = makeNode(HashPath);
2138 
2139 	pathnode->jpath.path.pathtype = T_HashJoin;
2140 	pathnode->jpath.path.parent = joinrel;
2141 	pathnode->jpath.path.pathtarget = joinrel->reltarget;
2142 	pathnode->jpath.path.param_info =
2143 		get_joinrel_parampathinfo(root,
2144 								  joinrel,
2145 								  outer_path,
2146 								  inner_path,
2147 								  sjinfo,
2148 								  required_outer,
2149 								  &restrict_clauses);
2150 	pathnode->jpath.path.parallel_aware = false;
2151 	pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2152 		outer_path->parallel_safe && inner_path->parallel_safe;
2153 	/* This is a foolish way to estimate parallel_workers, but for now... */
2154 	pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2155 
2156 	/*
2157 	 * A hashjoin never has pathkeys, since its output ordering is
2158 	 * unpredictable due to possible batching.  XXX If the inner relation is
2159 	 * small enough, we could instruct the executor that it must not batch,
2160 	 * and then we could assume that the output inherits the outer relation's
2161 	 * ordering, which might save a sort step.  However there is considerable
2162 	 * downside if our estimate of the inner relation size is badly off. For
2163 	 * the moment we don't risk it.  (Note also that if we wanted to take this
2164 	 * seriously, joinpath.c would have to consider many more paths for the
2165 	 * outer rel than it does now.)
2166 	 */
2167 	pathnode->jpath.path.pathkeys = NIL;
2168 	pathnode->jpath.jointype = jointype;
2169 	pathnode->jpath.outerjoinpath = outer_path;
2170 	pathnode->jpath.innerjoinpath = inner_path;
2171 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
2172 	pathnode->path_hashclauses = hashclauses;
2173 	/* final_cost_hashjoin will fill in pathnode->num_batches */
2174 
2175 	final_cost_hashjoin(root, pathnode, workspace, sjinfo, semifactors);
2176 
2177 	return pathnode;
2178 }
2179 
2180 /*
2181  * create_projection_path
2182  *	  Creates a pathnode that represents performing a projection.
2183  *
2184  * 'rel' is the parent relation associated with the result
2185  * 'subpath' is the path representing the source of data
2186  * 'target' is the PathTarget to be computed
2187  */
2188 ProjectionPath *
create_projection_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target)2189 create_projection_path(PlannerInfo *root,
2190 					   RelOptInfo *rel,
2191 					   Path *subpath,
2192 					   PathTarget *target)
2193 {
2194 	ProjectionPath *pathnode = makeNode(ProjectionPath);
2195 	PathTarget *oldtarget = subpath->pathtarget;
2196 
2197 	pathnode->path.pathtype = T_Result;
2198 	pathnode->path.parent = rel;
2199 	pathnode->path.pathtarget = target;
2200 	/* For now, assume we are above any joins, so no parameterization */
2201 	pathnode->path.param_info = NULL;
2202 	pathnode->path.parallel_aware = false;
2203 	pathnode->path.parallel_safe = rel->consider_parallel &&
2204 		subpath->parallel_safe &&
2205 		!has_parallel_hazard((Node *) target->exprs, false);
2206 	pathnode->path.parallel_workers = subpath->parallel_workers;
2207 	/* Projection does not change the sort order */
2208 	pathnode->path.pathkeys = subpath->pathkeys;
2209 
2210 	pathnode->subpath = subpath;
2211 
2212 	/*
2213 	 * We might not need a separate Result node.  If the input plan node type
2214 	 * can project, we can just tell it to project something else.  Or, if it
2215 	 * can't project but the desired target has the same expression list as
2216 	 * what the input will produce anyway, we can still give it the desired
2217 	 * tlist (possibly changing its ressortgroupref labels, but nothing else).
2218 	 * Note: in the latter case, create_projection_plan has to recheck our
2219 	 * conclusion; see comments therein.
2220 	 */
2221 	if (is_projection_capable_path(subpath) ||
2222 		equal(oldtarget->exprs, target->exprs))
2223 	{
2224 		/* No separate Result node needed */
2225 		pathnode->dummypp = true;
2226 
2227 		/*
2228 		 * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2229 		 */
2230 		pathnode->path.rows = subpath->rows;
2231 		pathnode->path.startup_cost = subpath->startup_cost +
2232 			(target->cost.startup - oldtarget->cost.startup);
2233 		pathnode->path.total_cost = subpath->total_cost +
2234 			(target->cost.startup - oldtarget->cost.startup) +
2235 			(target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2236 	}
2237 	else
2238 	{
2239 		/* We really do need the Result node */
2240 		pathnode->dummypp = false;
2241 
2242 		/*
2243 		 * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2244 		 * evaluating the tlist.  There is no qual to worry about.
2245 		 */
2246 		pathnode->path.rows = subpath->rows;
2247 		pathnode->path.startup_cost = subpath->startup_cost +
2248 			target->cost.startup;
2249 		pathnode->path.total_cost = subpath->total_cost +
2250 			target->cost.startup +
2251 			(cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2252 	}
2253 
2254 	return pathnode;
2255 }
2256 
2257 /*
2258  * apply_projection_to_path
2259  *	  Add a projection step, or just apply the target directly to given path.
2260  *
2261  * This has the same net effect as create_projection_path(), except that if
2262  * a separate Result plan node isn't needed, we just replace the given path's
2263  * pathtarget with the desired one.  This must be used only when the caller
2264  * knows that the given path isn't referenced elsewhere and so can be modified
2265  * in-place.
2266  *
2267  * If the input path is a GatherPath, we try to push the new target down to
2268  * its input as well; this is a yet more invasive modification of the input
2269  * path, which create_projection_path() can't do.
2270  *
2271  * Note that we mustn't change the source path's parent link; so when it is
2272  * add_path'd to "rel" things will be a bit inconsistent.  So far that has
2273  * not caused any trouble.
2274  *
2275  * 'rel' is the parent relation associated with the result
2276  * 'path' is the path representing the source of data
2277  * 'target' is the PathTarget to be computed
2278  */
2279 Path *
apply_projection_to_path(PlannerInfo * root,RelOptInfo * rel,Path * path,PathTarget * target)2280 apply_projection_to_path(PlannerInfo *root,
2281 						 RelOptInfo *rel,
2282 						 Path *path,
2283 						 PathTarget *target)
2284 {
2285 	QualCost	oldcost;
2286 
2287 	/*
2288 	 * If given path can't project, we might need a Result node, so make a
2289 	 * separate ProjectionPath.
2290 	 */
2291 	if (!is_projection_capable_path(path))
2292 		return (Path *) create_projection_path(root, rel, path, target);
2293 
2294 	/*
2295 	 * We can just jam the desired tlist into the existing path, being sure to
2296 	 * update its cost estimates appropriately.
2297 	 */
2298 	oldcost = path->pathtarget->cost;
2299 	path->pathtarget = target;
2300 
2301 	path->startup_cost += target->cost.startup - oldcost.startup;
2302 	path->total_cost += target->cost.startup - oldcost.startup +
2303 		(target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2304 
2305 	/*
2306 	 * If the path happens to be a Gather path, we'd like to arrange for the
2307 	 * subpath to return the required target list so that workers can help
2308 	 * project.  But if there is something that is not parallel-safe in the
2309 	 * target expressions, then we can't.
2310 	 */
2311 	if (IsA(path, GatherPath) &&
2312 		!has_parallel_hazard((Node *) target->exprs, false))
2313 	{
2314 		GatherPath *gpath = (GatherPath *) path;
2315 
2316 		/*
2317 		 * We always use create_projection_path here, even if the subpath is
2318 		 * projection-capable, so as to avoid modifying the subpath in place.
2319 		 * It seems unlikely at present that there could be any other
2320 		 * references to the subpath, but better safe than sorry.
2321 		 *
2322 		 * Note that we don't change the GatherPath's cost estimates; it might
2323 		 * be appropriate to do so, to reflect the fact that the bulk of the
2324 		 * target evaluation will happen in workers.
2325 		 */
2326 		gpath->subpath = (Path *)
2327 			create_projection_path(root,
2328 								   gpath->subpath->parent,
2329 								   gpath->subpath,
2330 								   target);
2331 	}
2332 	else if (path->parallel_safe &&
2333 			 has_parallel_hazard((Node *) target->exprs, false))
2334 	{
2335 		/*
2336 		 * We're inserting a parallel-restricted target list into a path
2337 		 * currently marked parallel-safe, so we have to mark it as no longer
2338 		 * safe.
2339 		 */
2340 		path->parallel_safe = false;
2341 	}
2342 
2343 	return path;
2344 }
2345 
2346 /*
2347  * create_sort_path
2348  *	  Creates a pathnode that represents performing an explicit sort.
2349  *
2350  * 'rel' is the parent relation associated with the result
2351  * 'subpath' is the path representing the source of data
2352  * 'pathkeys' represents the desired sort order
2353  * 'limit_tuples' is the estimated bound on the number of output tuples,
2354  *		or -1 if no LIMIT or couldn't estimate
2355  */
2356 SortPath *
create_sort_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * pathkeys,double limit_tuples)2357 create_sort_path(PlannerInfo *root,
2358 				 RelOptInfo *rel,
2359 				 Path *subpath,
2360 				 List *pathkeys,
2361 				 double limit_tuples)
2362 {
2363 	SortPath   *pathnode = makeNode(SortPath);
2364 
2365 	pathnode->path.pathtype = T_Sort;
2366 	pathnode->path.parent = rel;
2367 	/* Sort doesn't project, so use source path's pathtarget */
2368 	pathnode->path.pathtarget = subpath->pathtarget;
2369 	/* For now, assume we are above any joins, so no parameterization */
2370 	pathnode->path.param_info = NULL;
2371 	pathnode->path.parallel_aware = false;
2372 	pathnode->path.parallel_safe = rel->consider_parallel &&
2373 		subpath->parallel_safe;
2374 	pathnode->path.parallel_workers = subpath->parallel_workers;
2375 	pathnode->path.pathkeys = pathkeys;
2376 
2377 	pathnode->subpath = subpath;
2378 
2379 	cost_sort(&pathnode->path, root, pathkeys,
2380 			  subpath->total_cost,
2381 			  subpath->rows,
2382 			  subpath->pathtarget->width,
2383 			  0.0,				/* XXX comparison_cost shouldn't be 0? */
2384 			  work_mem, limit_tuples);
2385 
2386 	return pathnode;
2387 }
2388 
2389 /*
2390  * create_group_path
2391  *	  Creates a pathnode that represents performing grouping of presorted input
2392  *
2393  * 'rel' is the parent relation associated with the result
2394  * 'subpath' is the path representing the source of data
2395  * 'target' is the PathTarget to be computed
2396  * 'groupClause' is a list of SortGroupClause's representing the grouping
2397  * 'qual' is the HAVING quals if any
2398  * 'numGroups' is the estimated number of groups
2399  */
2400 GroupPath *
create_group_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,List * groupClause,List * qual,double numGroups)2401 create_group_path(PlannerInfo *root,
2402 				  RelOptInfo *rel,
2403 				  Path *subpath,
2404 				  PathTarget *target,
2405 				  List *groupClause,
2406 				  List *qual,
2407 				  double numGroups)
2408 {
2409 	GroupPath  *pathnode = makeNode(GroupPath);
2410 
2411 	pathnode->path.pathtype = T_Group;
2412 	pathnode->path.parent = rel;
2413 	pathnode->path.pathtarget = target;
2414 	/* For now, assume we are above any joins, so no parameterization */
2415 	pathnode->path.param_info = NULL;
2416 	pathnode->path.parallel_aware = false;
2417 	pathnode->path.parallel_safe = rel->consider_parallel &&
2418 		subpath->parallel_safe;
2419 	pathnode->path.parallel_workers = subpath->parallel_workers;
2420 	/* Group doesn't change sort ordering */
2421 	pathnode->path.pathkeys = subpath->pathkeys;
2422 
2423 	pathnode->subpath = subpath;
2424 
2425 	pathnode->groupClause = groupClause;
2426 	pathnode->qual = qual;
2427 
2428 	cost_group(&pathnode->path, root,
2429 			   list_length(groupClause),
2430 			   numGroups,
2431 			   subpath->startup_cost, subpath->total_cost,
2432 			   subpath->rows);
2433 
2434 	/* add tlist eval cost for each output row */
2435 	pathnode->path.startup_cost += target->cost.startup;
2436 	pathnode->path.total_cost += target->cost.startup +
2437 		target->cost.per_tuple * pathnode->path.rows;
2438 
2439 	return pathnode;
2440 }
2441 
2442 /*
2443  * create_upper_unique_path
2444  *	  Creates a pathnode that represents performing an explicit Unique step
2445  *	  on presorted input.
2446  *
2447  * This produces a Unique plan node, but the use-case is so different from
2448  * create_unique_path that it doesn't seem worth trying to merge the two.
2449  *
2450  * 'rel' is the parent relation associated with the result
2451  * 'subpath' is the path representing the source of data
2452  * 'numCols' is the number of grouping columns
2453  * 'numGroups' is the estimated number of groups
2454  *
2455  * The input path must be sorted on the grouping columns, plus possibly
2456  * additional columns; so the first numCols pathkeys are the grouping columns
2457  */
2458 UpperUniquePath *
create_upper_unique_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,int numCols,double numGroups)2459 create_upper_unique_path(PlannerInfo *root,
2460 						 RelOptInfo *rel,
2461 						 Path *subpath,
2462 						 int numCols,
2463 						 double numGroups)
2464 {
2465 	UpperUniquePath *pathnode = makeNode(UpperUniquePath);
2466 
2467 	pathnode->path.pathtype = T_Unique;
2468 	pathnode->path.parent = rel;
2469 	/* Unique doesn't project, so use source path's pathtarget */
2470 	pathnode->path.pathtarget = subpath->pathtarget;
2471 	/* For now, assume we are above any joins, so no parameterization */
2472 	pathnode->path.param_info = NULL;
2473 	pathnode->path.parallel_aware = false;
2474 	pathnode->path.parallel_safe = rel->consider_parallel &&
2475 		subpath->parallel_safe;
2476 	pathnode->path.parallel_workers = subpath->parallel_workers;
2477 	/* Unique doesn't change the input ordering */
2478 	pathnode->path.pathkeys = subpath->pathkeys;
2479 
2480 	pathnode->subpath = subpath;
2481 	pathnode->numkeys = numCols;
2482 
2483 	/*
2484 	 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2485 	 * all columns get compared at most of the tuples.  (XXX probably this is
2486 	 * an overestimate.)
2487 	 */
2488 	pathnode->path.startup_cost = subpath->startup_cost;
2489 	pathnode->path.total_cost = subpath->total_cost +
2490 		cpu_operator_cost * subpath->rows * numCols;
2491 	pathnode->path.rows = numGroups;
2492 
2493 	return pathnode;
2494 }
2495 
2496 /*
2497  * create_agg_path
2498  *	  Creates a pathnode that represents performing aggregation/grouping
2499  *
2500  * 'rel' is the parent relation associated with the result
2501  * 'subpath' is the path representing the source of data
2502  * 'target' is the PathTarget to be computed
2503  * 'aggstrategy' is the Agg node's basic implementation strategy
2504  * 'aggsplit' is the Agg node's aggregate-splitting mode
2505  * 'groupClause' is a list of SortGroupClause's representing the grouping
2506  * 'qual' is the HAVING quals if any
2507  * 'aggcosts' contains cost info about the aggregate functions to be computed
2508  * 'numGroups' is the estimated number of groups (1 if not grouping)
2509  */
2510 AggPath *
create_agg_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,AggStrategy aggstrategy,AggSplit aggsplit,List * groupClause,List * qual,const AggClauseCosts * aggcosts,double numGroups)2511 create_agg_path(PlannerInfo *root,
2512 				RelOptInfo *rel,
2513 				Path *subpath,
2514 				PathTarget *target,
2515 				AggStrategy aggstrategy,
2516 				AggSplit aggsplit,
2517 				List *groupClause,
2518 				List *qual,
2519 				const AggClauseCosts *aggcosts,
2520 				double numGroups)
2521 {
2522 	AggPath    *pathnode = makeNode(AggPath);
2523 
2524 	pathnode->path.pathtype = T_Agg;
2525 	pathnode->path.parent = rel;
2526 	pathnode->path.pathtarget = target;
2527 	/* For now, assume we are above any joins, so no parameterization */
2528 	pathnode->path.param_info = NULL;
2529 	pathnode->path.parallel_aware = false;
2530 	pathnode->path.parallel_safe = rel->consider_parallel &&
2531 		subpath->parallel_safe;
2532 	pathnode->path.parallel_workers = subpath->parallel_workers;
2533 	if (aggstrategy == AGG_SORTED)
2534 		pathnode->path.pathkeys = subpath->pathkeys;	/* preserves order */
2535 	else
2536 		pathnode->path.pathkeys = NIL;	/* output is unordered */
2537 	pathnode->subpath = subpath;
2538 
2539 	pathnode->aggstrategy = aggstrategy;
2540 	pathnode->aggsplit = aggsplit;
2541 	pathnode->numGroups = numGroups;
2542 	pathnode->groupClause = groupClause;
2543 	pathnode->qual = qual;
2544 
2545 	cost_agg(&pathnode->path, root,
2546 			 aggstrategy, aggcosts,
2547 			 list_length(groupClause), numGroups,
2548 			 subpath->startup_cost, subpath->total_cost,
2549 			 subpath->rows);
2550 
2551 	/* add tlist eval cost for each output row */
2552 	pathnode->path.startup_cost += target->cost.startup;
2553 	pathnode->path.total_cost += target->cost.startup +
2554 		target->cost.per_tuple * pathnode->path.rows;
2555 
2556 	return pathnode;
2557 }
2558 
2559 /*
2560  * create_groupingsets_path
2561  *	  Creates a pathnode that represents performing GROUPING SETS aggregation
2562  *
2563  * GroupingSetsPath represents sorted grouping with one or more grouping sets.
2564  * The input path's result must be sorted to match the last entry in
2565  * rollup_groupclauses.
2566  *
2567  * 'rel' is the parent relation associated with the result
2568  * 'subpath' is the path representing the source of data
2569  * 'target' is the PathTarget to be computed
2570  * 'having_qual' is the HAVING quals if any
2571  * 'rollup_lists' is a list of grouping sets
2572  * 'rollup_groupclauses' is a list of grouping clauses for grouping sets
2573  * 'agg_costs' contains cost info about the aggregate functions to be computed
2574  * 'numGroups' is the estimated number of groups
2575  */
2576 GroupingSetsPath *
create_groupingsets_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,List * having_qual,List * rollup_lists,List * rollup_groupclauses,const AggClauseCosts * agg_costs,double numGroups)2577 create_groupingsets_path(PlannerInfo *root,
2578 						 RelOptInfo *rel,
2579 						 Path *subpath,
2580 						 PathTarget *target,
2581 						 List *having_qual,
2582 						 List *rollup_lists,
2583 						 List *rollup_groupclauses,
2584 						 const AggClauseCosts *agg_costs,
2585 						 double numGroups)
2586 {
2587 	GroupingSetsPath *pathnode = makeNode(GroupingSetsPath);
2588 	int			numGroupCols;
2589 
2590 	/* The topmost generated Plan node will be an Agg */
2591 	pathnode->path.pathtype = T_Agg;
2592 	pathnode->path.parent = rel;
2593 	pathnode->path.pathtarget = target;
2594 	pathnode->path.param_info = subpath->param_info;
2595 	pathnode->path.parallel_aware = false;
2596 	pathnode->path.parallel_safe = rel->consider_parallel &&
2597 		subpath->parallel_safe;
2598 	pathnode->path.parallel_workers = subpath->parallel_workers;
2599 	pathnode->subpath = subpath;
2600 
2601 	/*
2602 	 * Output will be in sorted order by group_pathkeys if, and only if, there
2603 	 * is a single rollup operation on a non-empty list of grouping
2604 	 * expressions.
2605 	 */
2606 	if (list_length(rollup_groupclauses) == 1 &&
2607 		((List *) linitial(rollup_groupclauses)) != NIL)
2608 		pathnode->path.pathkeys = root->group_pathkeys;
2609 	else
2610 		pathnode->path.pathkeys = NIL;
2611 
2612 	pathnode->rollup_groupclauses = rollup_groupclauses;
2613 	pathnode->rollup_lists = rollup_lists;
2614 	pathnode->qual = having_qual;
2615 
2616 	Assert(rollup_lists != NIL);
2617 	Assert(list_length(rollup_lists) == list_length(rollup_groupclauses));
2618 
2619 	/* Account for cost of the topmost Agg node */
2620 	numGroupCols = list_length((List *) linitial((List *) llast(rollup_lists)));
2621 
2622 	cost_agg(&pathnode->path, root,
2623 			 (numGroupCols > 0) ? AGG_SORTED : AGG_PLAIN,
2624 			 agg_costs,
2625 			 numGroupCols,
2626 			 numGroups,
2627 			 subpath->startup_cost,
2628 			 subpath->total_cost,
2629 			 subpath->rows);
2630 
2631 	/*
2632 	 * Add in the costs and output rows of the additional sorting/aggregation
2633 	 * steps, if any.  Only total costs count, since the extra sorts aren't
2634 	 * run on startup.
2635 	 */
2636 	if (list_length(rollup_lists) > 1)
2637 	{
2638 		ListCell   *lc;
2639 
2640 		foreach(lc, rollup_lists)
2641 		{
2642 			List	   *gsets = (List *) lfirst(lc);
2643 			Path		sort_path;		/* dummy for result of cost_sort */
2644 			Path		agg_path;		/* dummy for result of cost_agg */
2645 
2646 			/* We must iterate over all but the last rollup_lists element */
2647 			if (lnext(lc) == NULL)
2648 				break;
2649 
2650 			/* Account for cost of sort, but don't charge input cost again */
2651 			cost_sort(&sort_path, root, NIL,
2652 					  0.0,
2653 					  subpath->rows,
2654 					  subpath->pathtarget->width,
2655 					  0.0,
2656 					  work_mem,
2657 					  -1.0);
2658 
2659 			/* Account for cost of aggregation */
2660 			numGroupCols = list_length((List *) linitial(gsets));
2661 
2662 			cost_agg(&agg_path, root,
2663 					 AGG_SORTED,
2664 					 agg_costs,
2665 					 numGroupCols,
2666 					 numGroups, /* XXX surely not right for all steps? */
2667 					 sort_path.startup_cost,
2668 					 sort_path.total_cost,
2669 					 sort_path.rows);
2670 
2671 			pathnode->path.total_cost += agg_path.total_cost;
2672 			pathnode->path.rows += agg_path.rows;
2673 		}
2674 	}
2675 
2676 	/* add tlist eval cost for each output row */
2677 	pathnode->path.startup_cost += target->cost.startup;
2678 	pathnode->path.total_cost += target->cost.startup +
2679 		target->cost.per_tuple * pathnode->path.rows;
2680 
2681 	return pathnode;
2682 }
2683 
2684 /*
2685  * create_minmaxagg_path
2686  *	  Creates a pathnode that represents computation of MIN/MAX aggregates
2687  *
2688  * 'rel' is the parent relation associated with the result
2689  * 'target' is the PathTarget to be computed
2690  * 'mmaggregates' is a list of MinMaxAggInfo structs
2691  * 'quals' is the HAVING quals if any
2692  */
2693 MinMaxAggPath *
create_minmaxagg_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,List * mmaggregates,List * quals)2694 create_minmaxagg_path(PlannerInfo *root,
2695 					  RelOptInfo *rel,
2696 					  PathTarget *target,
2697 					  List *mmaggregates,
2698 					  List *quals)
2699 {
2700 	MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
2701 	Cost		initplan_cost;
2702 	ListCell   *lc;
2703 
2704 	/* The topmost generated Plan node will be a Result */
2705 	pathnode->path.pathtype = T_Result;
2706 	pathnode->path.parent = rel;
2707 	pathnode->path.pathtarget = target;
2708 	/* For now, assume we are above any joins, so no parameterization */
2709 	pathnode->path.param_info = NULL;
2710 	pathnode->path.parallel_aware = false;
2711 	/* A MinMaxAggPath implies use of subplans, so cannot be parallel-safe */
2712 	pathnode->path.parallel_safe = false;
2713 	pathnode->path.parallel_workers = 0;
2714 	/* Result is one unordered row */
2715 	pathnode->path.rows = 1;
2716 	pathnode->path.pathkeys = NIL;
2717 
2718 	pathnode->mmaggregates = mmaggregates;
2719 	pathnode->quals = quals;
2720 
2721 	/* Calculate cost of all the initplans ... */
2722 	initplan_cost = 0;
2723 	foreach(lc, mmaggregates)
2724 	{
2725 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2726 
2727 		initplan_cost += mminfo->pathcost;
2728 	}
2729 
2730 	/* add tlist eval cost for each output row, plus cpu_tuple_cost */
2731 	pathnode->path.startup_cost = initplan_cost + target->cost.startup;
2732 	pathnode->path.total_cost = initplan_cost + target->cost.startup +
2733 		target->cost.per_tuple + cpu_tuple_cost;
2734 
2735 	return pathnode;
2736 }
2737 
2738 /*
2739  * create_windowagg_path
2740  *	  Creates a pathnode that represents computation of window functions
2741  *
2742  * 'rel' is the parent relation associated with the result
2743  * 'subpath' is the path representing the source of data
2744  * 'target' is the PathTarget to be computed
2745  * 'windowFuncs' is a list of WindowFunc structs
2746  * 'winclause' is a WindowClause that is common to all the WindowFuncs
2747  * 'winpathkeys' is the pathkeys for the PARTITION keys + ORDER keys
2748  *
2749  * The actual sort order of the input must match winpathkeys, but might
2750  * have additional keys after those.
2751  */
2752 WindowAggPath *
create_windowagg_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,List * windowFuncs,WindowClause * winclause,List * winpathkeys)2753 create_windowagg_path(PlannerInfo *root,
2754 					  RelOptInfo *rel,
2755 					  Path *subpath,
2756 					  PathTarget *target,
2757 					  List *windowFuncs,
2758 					  WindowClause *winclause,
2759 					  List *winpathkeys)
2760 {
2761 	WindowAggPath *pathnode = makeNode(WindowAggPath);
2762 
2763 	pathnode->path.pathtype = T_WindowAgg;
2764 	pathnode->path.parent = rel;
2765 	pathnode->path.pathtarget = target;
2766 	/* For now, assume we are above any joins, so no parameterization */
2767 	pathnode->path.param_info = NULL;
2768 	pathnode->path.parallel_aware = false;
2769 	pathnode->path.parallel_safe = rel->consider_parallel &&
2770 		subpath->parallel_safe;
2771 	pathnode->path.parallel_workers = subpath->parallel_workers;
2772 	/* WindowAgg preserves the input sort order */
2773 	pathnode->path.pathkeys = subpath->pathkeys;
2774 
2775 	pathnode->subpath = subpath;
2776 	pathnode->winclause = winclause;
2777 	pathnode->winpathkeys = winpathkeys;
2778 
2779 	/*
2780 	 * For costing purposes, assume that there are no redundant partitioning
2781 	 * or ordering columns; it's not worth the trouble to deal with that
2782 	 * corner case here.  So we just pass the unmodified list lengths to
2783 	 * cost_windowagg.
2784 	 */
2785 	cost_windowagg(&pathnode->path, root,
2786 				   windowFuncs,
2787 				   list_length(winclause->partitionClause),
2788 				   list_length(winclause->orderClause),
2789 				   subpath->startup_cost,
2790 				   subpath->total_cost,
2791 				   subpath->rows);
2792 
2793 	/* add tlist eval cost for each output row */
2794 	pathnode->path.startup_cost += target->cost.startup;
2795 	pathnode->path.total_cost += target->cost.startup +
2796 		target->cost.per_tuple * pathnode->path.rows;
2797 
2798 	return pathnode;
2799 }
2800 
2801 /*
2802  * create_setop_path
2803  *	  Creates a pathnode that represents computation of INTERSECT or EXCEPT
2804  *
2805  * 'rel' is the parent relation associated with the result
2806  * 'subpath' is the path representing the source of data
2807  * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
2808  * 'strategy' is the implementation strategy (sorted or hashed)
2809  * 'distinctList' is a list of SortGroupClause's representing the grouping
2810  * 'flagColIdx' is the column number where the flag column will be, if any
2811  * 'firstFlag' is the flag value for the first input relation when hashing;
2812  *		or -1 when sorting
2813  * 'numGroups' is the estimated number of distinct groups
2814  * 'outputRows' is the estimated number of output rows
2815  */
2816 SetOpPath *
create_setop_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,SetOpCmd cmd,SetOpStrategy strategy,List * distinctList,AttrNumber flagColIdx,int firstFlag,double numGroups,double outputRows)2817 create_setop_path(PlannerInfo *root,
2818 				  RelOptInfo *rel,
2819 				  Path *subpath,
2820 				  SetOpCmd cmd,
2821 				  SetOpStrategy strategy,
2822 				  List *distinctList,
2823 				  AttrNumber flagColIdx,
2824 				  int firstFlag,
2825 				  double numGroups,
2826 				  double outputRows)
2827 {
2828 	SetOpPath  *pathnode = makeNode(SetOpPath);
2829 
2830 	pathnode->path.pathtype = T_SetOp;
2831 	pathnode->path.parent = rel;
2832 	/* SetOp doesn't project, so use source path's pathtarget */
2833 	pathnode->path.pathtarget = subpath->pathtarget;
2834 	/* For now, assume we are above any joins, so no parameterization */
2835 	pathnode->path.param_info = NULL;
2836 	pathnode->path.parallel_aware = false;
2837 	pathnode->path.parallel_safe = rel->consider_parallel &&
2838 		subpath->parallel_safe;
2839 	pathnode->path.parallel_workers = subpath->parallel_workers;
2840 	/* SetOp preserves the input sort order if in sort mode */
2841 	pathnode->path.pathkeys =
2842 		(strategy == SETOP_SORTED) ? subpath->pathkeys : NIL;
2843 
2844 	pathnode->subpath = subpath;
2845 	pathnode->cmd = cmd;
2846 	pathnode->strategy = strategy;
2847 	pathnode->distinctList = distinctList;
2848 	pathnode->flagColIdx = flagColIdx;
2849 	pathnode->firstFlag = firstFlag;
2850 	pathnode->numGroups = numGroups;
2851 
2852 	/*
2853 	 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2854 	 * all columns get compared at most of the tuples.
2855 	 */
2856 	pathnode->path.startup_cost = subpath->startup_cost;
2857 	pathnode->path.total_cost = subpath->total_cost +
2858 		cpu_operator_cost * subpath->rows * list_length(distinctList);
2859 	pathnode->path.rows = outputRows;
2860 
2861 	return pathnode;
2862 }
2863 
2864 /*
2865  * create_recursiveunion_path
2866  *	  Creates a pathnode that represents a recursive UNION node
2867  *
2868  * 'rel' is the parent relation associated with the result
2869  * 'leftpath' is the source of data for the non-recursive term
2870  * 'rightpath' is the source of data for the recursive term
2871  * 'target' is the PathTarget to be computed
2872  * 'distinctList' is a list of SortGroupClause's representing the grouping
2873  * 'wtParam' is the ID of Param representing work table
2874  * 'numGroups' is the estimated number of groups
2875  *
2876  * For recursive UNION ALL, distinctList is empty and numGroups is zero
2877  */
2878 RecursiveUnionPath *
create_recursiveunion_path(PlannerInfo * root,RelOptInfo * rel,Path * leftpath,Path * rightpath,PathTarget * target,List * distinctList,int wtParam,double numGroups)2879 create_recursiveunion_path(PlannerInfo *root,
2880 						   RelOptInfo *rel,
2881 						   Path *leftpath,
2882 						   Path *rightpath,
2883 						   PathTarget *target,
2884 						   List *distinctList,
2885 						   int wtParam,
2886 						   double numGroups)
2887 {
2888 	RecursiveUnionPath *pathnode = makeNode(RecursiveUnionPath);
2889 
2890 	pathnode->path.pathtype = T_RecursiveUnion;
2891 	pathnode->path.parent = rel;
2892 	pathnode->path.pathtarget = target;
2893 	/* For now, assume we are above any joins, so no parameterization */
2894 	pathnode->path.param_info = NULL;
2895 	pathnode->path.parallel_aware = false;
2896 	pathnode->path.parallel_safe = rel->consider_parallel &&
2897 		leftpath->parallel_safe && rightpath->parallel_safe;
2898 	/* Foolish, but we'll do it like joins for now: */
2899 	pathnode->path.parallel_workers = leftpath->parallel_workers;
2900 	/* RecursiveUnion result is always unsorted */
2901 	pathnode->path.pathkeys = NIL;
2902 
2903 	pathnode->leftpath = leftpath;
2904 	pathnode->rightpath = rightpath;
2905 	pathnode->distinctList = distinctList;
2906 	pathnode->wtParam = wtParam;
2907 	pathnode->numGroups = numGroups;
2908 
2909 	cost_recursive_union(&pathnode->path, leftpath, rightpath);
2910 
2911 	return pathnode;
2912 }
2913 
2914 /*
2915  * create_lockrows_path
2916  *	  Creates a pathnode that represents acquiring row locks
2917  *
2918  * 'rel' is the parent relation associated with the result
2919  * 'subpath' is the path representing the source of data
2920  * 'rowMarks' is a list of PlanRowMark's
2921  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
2922  */
2923 LockRowsPath *
create_lockrows_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * rowMarks,int epqParam)2924 create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
2925 					 Path *subpath, List *rowMarks, int epqParam)
2926 {
2927 	LockRowsPath *pathnode = makeNode(LockRowsPath);
2928 
2929 	pathnode->path.pathtype = T_LockRows;
2930 	pathnode->path.parent = rel;
2931 	/* LockRows doesn't project, so use source path's pathtarget */
2932 	pathnode->path.pathtarget = subpath->pathtarget;
2933 	/* For now, assume we are above any joins, so no parameterization */
2934 	pathnode->path.param_info = NULL;
2935 	pathnode->path.parallel_aware = false;
2936 	pathnode->path.parallel_safe = false;
2937 	pathnode->path.parallel_workers = 0;
2938 	pathnode->path.rows = subpath->rows;
2939 
2940 	/*
2941 	 * The result cannot be assumed sorted, since locking might cause the sort
2942 	 * key columns to be replaced with new values.
2943 	 */
2944 	pathnode->path.pathkeys = NIL;
2945 
2946 	pathnode->subpath = subpath;
2947 	pathnode->rowMarks = rowMarks;
2948 	pathnode->epqParam = epqParam;
2949 
2950 	/*
2951 	 * We should charge something extra for the costs of row locking and
2952 	 * possible refetches, but it's hard to say how much.  For now, use
2953 	 * cpu_tuple_cost per row.
2954 	 */
2955 	pathnode->path.startup_cost = subpath->startup_cost;
2956 	pathnode->path.total_cost = subpath->total_cost +
2957 		cpu_tuple_cost * subpath->rows;
2958 
2959 	return pathnode;
2960 }
2961 
2962 /*
2963  * create_modifytable_path
2964  *	  Creates a pathnode that represents performing INSERT/UPDATE/DELETE mods
2965  *
2966  * 'rel' is the parent relation associated with the result
2967  * 'operation' is the operation type
2968  * 'canSetTag' is true if we set the command tag/es_processed
2969  * 'nominalRelation' is the parent RT index for use of EXPLAIN
2970  * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
2971  * 'subpaths' is a list of Path(s) producing source data (one per rel)
2972  * 'subroots' is a list of PlannerInfo structs (one per rel)
2973  * 'withCheckOptionLists' is a list of WCO lists (one per rel)
2974  * 'returningLists' is a list of RETURNING tlists (one per rel)
2975  * 'rowMarks' is a list of PlanRowMarks (non-locking only)
2976  * 'onconflict' is the ON CONFLICT clause, or NULL
2977  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
2978  */
2979 ModifyTablePath *
create_modifytable_path(PlannerInfo * root,RelOptInfo * rel,CmdType operation,bool canSetTag,Index nominalRelation,List * resultRelations,List * subpaths,List * subroots,List * withCheckOptionLists,List * returningLists,List * rowMarks,OnConflictExpr * onconflict,int epqParam)2980 create_modifytable_path(PlannerInfo *root, RelOptInfo *rel,
2981 						CmdType operation, bool canSetTag,
2982 						Index nominalRelation,
2983 						List *resultRelations, List *subpaths,
2984 						List *subroots,
2985 						List *withCheckOptionLists, List *returningLists,
2986 						List *rowMarks, OnConflictExpr *onconflict,
2987 						int epqParam)
2988 {
2989 	ModifyTablePath *pathnode = makeNode(ModifyTablePath);
2990 	double		total_size;
2991 	ListCell   *lc;
2992 
2993 	Assert(list_length(resultRelations) == list_length(subpaths));
2994 	Assert(list_length(resultRelations) == list_length(subroots));
2995 	Assert(withCheckOptionLists == NIL ||
2996 		   list_length(resultRelations) == list_length(withCheckOptionLists));
2997 	Assert(returningLists == NIL ||
2998 		   list_length(resultRelations) == list_length(returningLists));
2999 
3000 	pathnode->path.pathtype = T_ModifyTable;
3001 	pathnode->path.parent = rel;
3002 	/* pathtarget is not interesting, just make it minimally valid */
3003 	pathnode->path.pathtarget = rel->reltarget;
3004 	/* For now, assume we are above any joins, so no parameterization */
3005 	pathnode->path.param_info = NULL;
3006 	pathnode->path.parallel_aware = false;
3007 	pathnode->path.parallel_safe = false;
3008 	pathnode->path.parallel_workers = 0;
3009 	pathnode->path.pathkeys = NIL;
3010 
3011 	/*
3012 	 * Compute cost & rowcount as sum of subpath costs & rowcounts.
3013 	 *
3014 	 * Currently, we don't charge anything extra for the actual table
3015 	 * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3016 	 * expressions if any.  It would only be window dressing, since
3017 	 * ModifyTable is always a top-level node and there is no way for the
3018 	 * costs to change any higher-level planning choices.  But we might want
3019 	 * to make it look better sometime.
3020 	 */
3021 	pathnode->path.startup_cost = 0;
3022 	pathnode->path.total_cost = 0;
3023 	pathnode->path.rows = 0;
3024 	total_size = 0;
3025 	foreach(lc, subpaths)
3026 	{
3027 		Path	   *subpath = (Path *) lfirst(lc);
3028 
3029 		if (lc == list_head(subpaths))	/* first node? */
3030 			pathnode->path.startup_cost = subpath->startup_cost;
3031 		pathnode->path.total_cost += subpath->total_cost;
3032 		pathnode->path.rows += subpath->rows;
3033 		total_size += subpath->pathtarget->width * subpath->rows;
3034 	}
3035 
3036 	/*
3037 	 * Set width to the average width of the subpath outputs.  XXX this is
3038 	 * totally wrong: we should report zero if no RETURNING, else an average
3039 	 * of the RETURNING tlist widths.  But it's what happened historically,
3040 	 * and improving it is a task for another day.
3041 	 */
3042 	if (pathnode->path.rows > 0)
3043 		total_size /= pathnode->path.rows;
3044 	pathnode->path.pathtarget->width = rint(total_size);
3045 
3046 	pathnode->operation = operation;
3047 	pathnode->canSetTag = canSetTag;
3048 	pathnode->nominalRelation = nominalRelation;
3049 	pathnode->resultRelations = resultRelations;
3050 	pathnode->subpaths = subpaths;
3051 	pathnode->subroots = subroots;
3052 	pathnode->withCheckOptionLists = withCheckOptionLists;
3053 	pathnode->returningLists = returningLists;
3054 	pathnode->rowMarks = rowMarks;
3055 	pathnode->onconflict = onconflict;
3056 	pathnode->epqParam = epqParam;
3057 
3058 	return pathnode;
3059 }
3060 
3061 /*
3062  * create_limit_path
3063  *	  Creates a pathnode that represents performing LIMIT/OFFSET
3064  *
3065  * In addition to providing the actual OFFSET and LIMIT expressions,
3066  * the caller must provide estimates of their values for costing purposes.
3067  * The estimates are as computed by preprocess_limit(), ie, 0 represents
3068  * the clause not being present, and -1 means it's present but we could
3069  * not estimate its value.
3070  *
3071  * 'rel' is the parent relation associated with the result
3072  * 'subpath' is the path representing the source of data
3073  * 'limitOffset' is the actual OFFSET expression, or NULL
3074  * 'limitCount' is the actual LIMIT expression, or NULL
3075  * 'offset_est' is the estimated value of the OFFSET expression
3076  * 'count_est' is the estimated value of the LIMIT expression
3077  */
3078 LimitPath *
create_limit_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,Node * limitOffset,Node * limitCount,int64 offset_est,int64 count_est)3079 create_limit_path(PlannerInfo *root, RelOptInfo *rel,
3080 				  Path *subpath,
3081 				  Node *limitOffset, Node *limitCount,
3082 				  int64 offset_est, int64 count_est)
3083 {
3084 	LimitPath  *pathnode = makeNode(LimitPath);
3085 
3086 	pathnode->path.pathtype = T_Limit;
3087 	pathnode->path.parent = rel;
3088 	/* Limit doesn't project, so use source path's pathtarget */
3089 	pathnode->path.pathtarget = subpath->pathtarget;
3090 	/* For now, assume we are above any joins, so no parameterization */
3091 	pathnode->path.param_info = NULL;
3092 	pathnode->path.parallel_aware = false;
3093 	pathnode->path.parallel_safe = rel->consider_parallel &&
3094 		subpath->parallel_safe;
3095 	pathnode->path.parallel_workers = subpath->parallel_workers;
3096 	pathnode->path.rows = subpath->rows;
3097 	pathnode->path.startup_cost = subpath->startup_cost;
3098 	pathnode->path.total_cost = subpath->total_cost;
3099 	pathnode->path.pathkeys = subpath->pathkeys;
3100 	pathnode->subpath = subpath;
3101 	pathnode->limitOffset = limitOffset;
3102 	pathnode->limitCount = limitCount;
3103 
3104 	/*
3105 	 * Adjust the output rows count and costs according to the offset/limit.
3106 	 * This is only a cosmetic issue if we are at top level, but if we are
3107 	 * building a subquery then it's important to report correct info to the
3108 	 * outer planner.
3109 	 *
3110 	 * When the offset or count couldn't be estimated, use 10% of the
3111 	 * estimated number of rows emitted from the subpath.
3112 	 *
3113 	 * XXX we don't bother to add eval costs of the offset/limit expressions
3114 	 * themselves to the path costs.  In theory we should, but in most cases
3115 	 * those expressions are trivial and it's just not worth the trouble.
3116 	 */
3117 	if (offset_est != 0)
3118 	{
3119 		double		offset_rows;
3120 
3121 		if (offset_est > 0)
3122 			offset_rows = (double) offset_est;
3123 		else
3124 			offset_rows = clamp_row_est(subpath->rows * 0.10);
3125 		if (offset_rows > pathnode->path.rows)
3126 			offset_rows = pathnode->path.rows;
3127 		if (subpath->rows > 0)
3128 			pathnode->path.startup_cost +=
3129 				(subpath->total_cost - subpath->startup_cost)
3130 				* offset_rows / subpath->rows;
3131 		pathnode->path.rows -= offset_rows;
3132 		if (pathnode->path.rows < 1)
3133 			pathnode->path.rows = 1;
3134 	}
3135 
3136 	if (count_est != 0)
3137 	{
3138 		double		count_rows;
3139 
3140 		if (count_est > 0)
3141 			count_rows = (double) count_est;
3142 		else
3143 			count_rows = clamp_row_est(subpath->rows * 0.10);
3144 		if (count_rows > pathnode->path.rows)
3145 			count_rows = pathnode->path.rows;
3146 		if (subpath->rows > 0)
3147 			pathnode->path.total_cost = pathnode->path.startup_cost +
3148 				(subpath->total_cost - subpath->startup_cost)
3149 				* count_rows / subpath->rows;
3150 		pathnode->path.rows = count_rows;
3151 		if (pathnode->path.rows < 1)
3152 			pathnode->path.rows = 1;
3153 	}
3154 
3155 	return pathnode;
3156 }
3157 
3158 
3159 /*
3160  * reparameterize_path
3161  *		Attempt to modify a Path to have greater parameterization
3162  *
3163  * We use this to attempt to bring all child paths of an appendrel to the
3164  * same parameterization level, ensuring that they all enforce the same set
3165  * of join quals (and thus that that parameterization can be attributed to
3166  * an append path built from such paths).  Currently, only a few path types
3167  * are supported here, though more could be added at need.  We return NULL
3168  * if we can't reparameterize the given path.
3169  *
3170  * Note: we intentionally do not pass created paths to add_path(); it would
3171  * possibly try to delete them on the grounds of being cost-inferior to the
3172  * paths they were made from, and we don't want that.  Paths made here are
3173  * not necessarily of general-purpose usefulness, but they can be useful
3174  * as members of an append path.
3175  */
3176 Path *
reparameterize_path(PlannerInfo * root,Path * path,Relids required_outer,double loop_count)3177 reparameterize_path(PlannerInfo *root, Path *path,
3178 					Relids required_outer,
3179 					double loop_count)
3180 {
3181 	RelOptInfo *rel = path->parent;
3182 
3183 	/* Can only increase, not decrease, path's parameterization */
3184 	if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3185 		return NULL;
3186 	switch (path->pathtype)
3187 	{
3188 		case T_SeqScan:
3189 			return create_seqscan_path(root, rel, required_outer, 0);
3190 		case T_SampleScan:
3191 			return (Path *) create_samplescan_path(root, rel, required_outer);
3192 		case T_IndexScan:
3193 		case T_IndexOnlyScan:
3194 			{
3195 				IndexPath  *ipath = (IndexPath *) path;
3196 				IndexPath  *newpath = makeNode(IndexPath);
3197 
3198 				/*
3199 				 * We can't use create_index_path directly, and would not want
3200 				 * to because it would re-compute the indexqual conditions
3201 				 * which is wasted effort.  Instead we hack things a bit:
3202 				 * flat-copy the path node, revise its param_info, and redo
3203 				 * the cost estimate.
3204 				 */
3205 				memcpy(newpath, ipath, sizeof(IndexPath));
3206 				newpath->path.param_info =
3207 					get_baserel_parampathinfo(root, rel, required_outer);
3208 				cost_index(newpath, root, loop_count);
3209 				return (Path *) newpath;
3210 			}
3211 		case T_BitmapHeapScan:
3212 			{
3213 				BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3214 
3215 				return (Path *) create_bitmap_heap_path(root,
3216 														rel,
3217 														bpath->bitmapqual,
3218 														required_outer,
3219 														loop_count);
3220 			}
3221 		case T_SubqueryScan:
3222 			{
3223 				SubqueryScanPath *spath = (SubqueryScanPath *) path;
3224 
3225 				return (Path *) create_subqueryscan_path(root,
3226 														 rel,
3227 														 spath->subpath,
3228 														 spath->path.pathkeys,
3229 														 required_outer);
3230 			}
3231 		case T_Append:
3232 			{
3233 				AppendPath *apath = (AppendPath *) path;
3234 				List	   *childpaths = NIL;
3235 				ListCell   *lc;
3236 
3237 				/* Reparameterize the children */
3238 				foreach(lc, apath->subpaths)
3239 				{
3240 					Path	   *spath = (Path *) lfirst(lc);
3241 
3242 					spath = reparameterize_path(root, spath,
3243 												required_outer,
3244 												loop_count);
3245 					if (spath == NULL)
3246 						return NULL;
3247 					childpaths = lappend(childpaths, spath);
3248 				}
3249 				return (Path *)
3250 					create_append_path(rel, childpaths,
3251 									   required_outer,
3252 									   apath->path.parallel_workers);
3253 			}
3254 		default:
3255 			break;
3256 	}
3257 	return NULL;
3258 }
3259