1 /*-------------------------------------------------------------------------
2  *
3  * pathnode.c
4  *	  Routines to manipulate pathlists and create path nodes
5  *
6  * Portions Copyright (c) 1996-2019, 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 "foreign/fdwapi.h"
21 #include "nodes/extensible.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/appendinfo.h"
24 #include "optimizer/clauses.h"
25 #include "optimizer/cost.h"
26 #include "optimizer/optimizer.h"
27 #include "optimizer/pathnode.h"
28 #include "optimizer/paths.h"
29 #include "optimizer/planmain.h"
30 #include "optimizer/prep.h"
31 #include "optimizer/restrictinfo.h"
32 #include "optimizer/tlist.h"
33 #include "parser/parsetree.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/selfuncs.h"
37 
38 
39 typedef enum
40 {
41 	COSTS_EQUAL,				/* path costs are fuzzily equal */
42 	COSTS_BETTER1,				/* first path is cheaper than second */
43 	COSTS_BETTER2,				/* second path is cheaper than first */
44 	COSTS_DIFFERENT				/* neither path dominates the other on cost */
45 } PathCostComparison;
46 
47 /*
48  * STD_FUZZ_FACTOR is the normal fuzz factor for compare_path_costs_fuzzily.
49  * XXX is it worth making this user-controllable?  It provides a tradeoff
50  * between planner runtime and the accuracy of path cost comparisons.
51  */
52 #define STD_FUZZ_FACTOR 1.01
53 
54 static List *translate_sub_tlist(List *tlist, int relid);
55 static int	append_total_cost_compare(const void *a, const void *b);
56 static int	append_startup_cost_compare(const void *a, const void *b);
57 static List *reparameterize_pathlist_by_child(PlannerInfo *root,
58 											  List *pathlist,
59 											  RelOptInfo *child_rel);
60 
61 
62 /*****************************************************************************
63  *		MISC. PATH UTILITIES
64  *****************************************************************************/
65 
66 /*
67  * compare_path_costs
68  *	  Return -1, 0, or +1 according as path1 is cheaper, the same cost,
69  *	  or more expensive than path2 for the specified criterion.
70  */
71 int
compare_path_costs(Path * path1,Path * path2,CostSelector criterion)72 compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
73 {
74 	if (criterion == STARTUP_COST)
75 	{
76 		if (path1->startup_cost < path2->startup_cost)
77 			return -1;
78 		if (path1->startup_cost > path2->startup_cost)
79 			return +1;
80 
81 		/*
82 		 * If paths have the same startup cost (not at all unlikely), order
83 		 * them by total cost.
84 		 */
85 		if (path1->total_cost < path2->total_cost)
86 			return -1;
87 		if (path1->total_cost > path2->total_cost)
88 			return +1;
89 	}
90 	else
91 	{
92 		if (path1->total_cost < path2->total_cost)
93 			return -1;
94 		if (path1->total_cost > path2->total_cost)
95 			return +1;
96 
97 		/*
98 		 * If paths have the same total cost, order them by startup cost.
99 		 */
100 		if (path1->startup_cost < path2->startup_cost)
101 			return -1;
102 		if (path1->startup_cost > path2->startup_cost)
103 			return +1;
104 	}
105 	return 0;
106 }
107 
108 /*
109  * compare_path_fractional_costs
110  *	  Return -1, 0, or +1 according as path1 is cheaper, the same cost,
111  *	  or more expensive than path2 for fetching the specified fraction
112  *	  of the total tuples.
113  *
114  * If fraction is <= 0 or > 1, we interpret it as 1, ie, we select the
115  * path with the cheaper total_cost.
116  */
117 int
compare_fractional_path_costs(Path * path1,Path * path2,double fraction)118 compare_fractional_path_costs(Path *path1, Path *path2,
119 							  double fraction)
120 {
121 	Cost		cost1,
122 				cost2;
123 
124 	if (fraction <= 0.0 || fraction >= 1.0)
125 		return compare_path_costs(path1, path2, TOTAL_COST);
126 	cost1 = path1->startup_cost +
127 		fraction * (path1->total_cost - path1->startup_cost);
128 	cost2 = path2->startup_cost +
129 		fraction * (path2->total_cost - path2->startup_cost);
130 	if (cost1 < cost2)
131 		return -1;
132 	if (cost1 > cost2)
133 		return +1;
134 	return 0;
135 }
136 
137 /*
138  * compare_path_costs_fuzzily
139  *	  Compare the costs of two paths to see if either can be said to
140  *	  dominate the other.
141  *
142  * We use fuzzy comparisons so that add_path() can avoid keeping both of
143  * a pair of paths that really have insignificantly different cost.
144  *
145  * The fuzz_factor argument must be 1.0 plus delta, where delta is the
146  * fraction of the smaller cost that is considered to be a significant
147  * difference.  For example, fuzz_factor = 1.01 makes the fuzziness limit
148  * be 1% of the smaller cost.
149  *
150  * The two paths are said to have "equal" costs if both startup and total
151  * costs are fuzzily the same.  Path1 is said to be better than path2 if
152  * it has fuzzily better startup cost and fuzzily no worse total cost,
153  * or if it has fuzzily better total cost and fuzzily no worse startup cost.
154  * Path2 is better than path1 if the reverse holds.  Finally, if one path
155  * is fuzzily better than the other on startup cost and fuzzily worse on
156  * total cost, we just say that their costs are "different", since neither
157  * dominates the other across the whole performance spectrum.
158  *
159  * This function also enforces a policy rule that paths for which the relevant
160  * one of parent->consider_startup and parent->consider_param_startup is false
161  * cannot survive comparisons solely on the grounds of good startup cost, so
162  * we never return COSTS_DIFFERENT when that is true for the total-cost loser.
163  * (But if total costs are fuzzily equal, we compare startup costs anyway,
164  * in hopes of eliminating one path or the other.)
165  */
166 static PathCostComparison
compare_path_costs_fuzzily(Path * path1,Path * path2,double fuzz_factor)167 compare_path_costs_fuzzily(Path *path1, Path *path2, double fuzz_factor)
168 {
169 #define CONSIDER_PATH_STARTUP_COST(p)  \
170 	((p)->param_info == NULL ? (p)->parent->consider_startup : (p)->parent->consider_param_startup)
171 
172 	/*
173 	 * Check total cost first since it's more likely to be different; many
174 	 * paths have zero startup cost.
175 	 */
176 	if (path1->total_cost > path2->total_cost * fuzz_factor)
177 	{
178 		/* path1 fuzzily worse on total cost */
179 		if (CONSIDER_PATH_STARTUP_COST(path1) &&
180 			path2->startup_cost > path1->startup_cost * fuzz_factor)
181 		{
182 			/* ... but path2 fuzzily worse on startup, so DIFFERENT */
183 			return COSTS_DIFFERENT;
184 		}
185 		/* else path2 dominates */
186 		return COSTS_BETTER2;
187 	}
188 	if (path2->total_cost > path1->total_cost * fuzz_factor)
189 	{
190 		/* path2 fuzzily worse on total cost */
191 		if (CONSIDER_PATH_STARTUP_COST(path2) &&
192 			path1->startup_cost > path2->startup_cost * fuzz_factor)
193 		{
194 			/* ... but path1 fuzzily worse on startup, so DIFFERENT */
195 			return COSTS_DIFFERENT;
196 		}
197 		/* else path1 dominates */
198 		return COSTS_BETTER1;
199 	}
200 	/* fuzzily the same on total cost ... */
201 	if (path1->startup_cost > path2->startup_cost * fuzz_factor)
202 	{
203 		/* ... but path1 fuzzily worse on startup, so path2 wins */
204 		return COSTS_BETTER2;
205 	}
206 	if (path2->startup_cost > path1->startup_cost * fuzz_factor)
207 	{
208 		/* ... but path2 fuzzily worse on startup, so path1 wins */
209 		return COSTS_BETTER1;
210 	}
211 	/* fuzzily the same on both costs */
212 	return COSTS_EQUAL;
213 
214 #undef CONSIDER_PATH_STARTUP_COST
215 }
216 
217 /*
218  * set_cheapest
219  *	  Find the minimum-cost paths from among a relation's paths,
220  *	  and save them in the rel's cheapest-path fields.
221  *
222  * cheapest_total_path is normally the cheapest-total-cost unparameterized
223  * path; but if there are no unparameterized paths, we assign it to be the
224  * best (cheapest least-parameterized) parameterized path.  However, only
225  * unparameterized paths are considered candidates for cheapest_startup_path,
226  * so that will be NULL if there are no unparameterized paths.
227  *
228  * The cheapest_parameterized_paths list collects all parameterized paths
229  * that have survived the add_path() tournament for this relation.  (Since
230  * add_path ignores pathkeys for a parameterized path, these will be paths
231  * that have best cost or best row count for their parameterization.  We
232  * may also have both a parallel-safe and a non-parallel-safe path in some
233  * cases for the same parameterization in some cases, but this should be
234  * relatively rare since, most typically, all paths for the same relation
235  * will be parallel-safe or none of them will.)
236  *
237  * cheapest_parameterized_paths always includes the cheapest-total
238  * unparameterized path, too, if there is one; the users of that list find
239  * it more convenient if that's included.
240  *
241  * This is normally called only after we've finished constructing the path
242  * list for the rel node.
243  */
244 void
set_cheapest(RelOptInfo * parent_rel)245 set_cheapest(RelOptInfo *parent_rel)
246 {
247 	Path	   *cheapest_startup_path;
248 	Path	   *cheapest_total_path;
249 	Path	   *best_param_path;
250 	List	   *parameterized_paths;
251 	ListCell   *p;
252 
253 	Assert(IsA(parent_rel, RelOptInfo));
254 
255 	if (parent_rel->pathlist == NIL)
256 		elog(ERROR, "could not devise a query plan for the given query");
257 
258 	cheapest_startup_path = cheapest_total_path = best_param_path = NULL;
259 	parameterized_paths = NIL;
260 
261 	foreach(p, parent_rel->pathlist)
262 	{
263 		Path	   *path = (Path *) lfirst(p);
264 		int			cmp;
265 
266 		if (path->param_info)
267 		{
268 			/* Parameterized path, so add it to parameterized_paths */
269 			parameterized_paths = lappend(parameterized_paths, path);
270 
271 			/*
272 			 * If we have an unparameterized cheapest-total, we no longer care
273 			 * about finding the best parameterized path, so move on.
274 			 */
275 			if (cheapest_total_path)
276 				continue;
277 
278 			/*
279 			 * Otherwise, track the best parameterized path, which is the one
280 			 * with least total cost among those of the minimum
281 			 * parameterization.
282 			 */
283 			if (best_param_path == NULL)
284 				best_param_path = path;
285 			else
286 			{
287 				switch (bms_subset_compare(PATH_REQ_OUTER(path),
288 										   PATH_REQ_OUTER(best_param_path)))
289 				{
290 					case BMS_EQUAL:
291 						/* keep the cheaper one */
292 						if (compare_path_costs(path, best_param_path,
293 											   TOTAL_COST) < 0)
294 							best_param_path = path;
295 						break;
296 					case BMS_SUBSET1:
297 						/* new path is less-parameterized */
298 						best_param_path = path;
299 						break;
300 					case BMS_SUBSET2:
301 						/* old path is less-parameterized, keep it */
302 						break;
303 					case BMS_DIFFERENT:
304 
305 						/*
306 						 * This means that neither path has the least possible
307 						 * parameterization for the rel.  We'll sit on the old
308 						 * path until something better comes along.
309 						 */
310 						break;
311 				}
312 			}
313 		}
314 		else
315 		{
316 			/* Unparameterized path, so consider it for cheapest slots */
317 			if (cheapest_total_path == NULL)
318 			{
319 				cheapest_startup_path = cheapest_total_path = path;
320 				continue;
321 			}
322 
323 			/*
324 			 * If we find two paths of identical costs, try to keep the
325 			 * better-sorted one.  The paths might have unrelated sort
326 			 * orderings, in which case we can only guess which might be
327 			 * better to keep, but if one is superior then we definitely
328 			 * should keep that one.
329 			 */
330 			cmp = compare_path_costs(cheapest_startup_path, path, STARTUP_COST);
331 			if (cmp > 0 ||
332 				(cmp == 0 &&
333 				 compare_pathkeys(cheapest_startup_path->pathkeys,
334 								  path->pathkeys) == PATHKEYS_BETTER2))
335 				cheapest_startup_path = path;
336 
337 			cmp = compare_path_costs(cheapest_total_path, path, TOTAL_COST);
338 			if (cmp > 0 ||
339 				(cmp == 0 &&
340 				 compare_pathkeys(cheapest_total_path->pathkeys,
341 								  path->pathkeys) == PATHKEYS_BETTER2))
342 				cheapest_total_path = path;
343 		}
344 	}
345 
346 	/* Add cheapest unparameterized path, if any, to parameterized_paths */
347 	if (cheapest_total_path)
348 		parameterized_paths = lcons(cheapest_total_path, parameterized_paths);
349 
350 	/*
351 	 * If there is no unparameterized path, use the best parameterized path as
352 	 * cheapest_total_path (but not as cheapest_startup_path).
353 	 */
354 	if (cheapest_total_path == NULL)
355 		cheapest_total_path = best_param_path;
356 	Assert(cheapest_total_path != NULL);
357 
358 	parent_rel->cheapest_startup_path = cheapest_startup_path;
359 	parent_rel->cheapest_total_path = cheapest_total_path;
360 	parent_rel->cheapest_unique_path = NULL;	/* computed only if needed */
361 	parent_rel->cheapest_parameterized_paths = parameterized_paths;
362 }
363 
364 /*
365  * add_path
366  *	  Consider a potential implementation path for the specified parent rel,
367  *	  and add it to the rel's pathlist if it is worthy of consideration.
368  *	  A path is worthy if it has a better sort order (better pathkeys) or
369  *	  cheaper cost (on either dimension), or generates fewer rows, than any
370  *	  existing path that has the same or superset parameterization rels.
371  *	  We also consider parallel-safe paths more worthy than others.
372  *
373  *	  We also remove from the rel's pathlist any old paths that are dominated
374  *	  by new_path --- that is, new_path is cheaper, at least as well ordered,
375  *	  generates no more rows, requires no outer rels not required by the old
376  *	  path, and is no less parallel-safe.
377  *
378  *	  In most cases, a path with a superset parameterization will generate
379  *	  fewer rows (since it has more join clauses to apply), so that those two
380  *	  figures of merit move in opposite directions; this means that a path of
381  *	  one parameterization can seldom dominate a path of another.  But such
382  *	  cases do arise, so we make the full set of checks anyway.
383  *
384  *	  There are two policy decisions embedded in this function, along with
385  *	  its sibling add_path_precheck.  First, we treat all parameterized paths
386  *	  as having NIL pathkeys, so that they cannot win comparisons on the
387  *	  basis of sort order.  This is to reduce the number of parameterized
388  *	  paths that are kept; see discussion in src/backend/optimizer/README.
389  *
390  *	  Second, we only consider cheap startup cost to be interesting if
391  *	  parent_rel->consider_startup is true for an unparameterized path, or
392  *	  parent_rel->consider_param_startup is true for a parameterized one.
393  *	  Again, this allows discarding useless paths sooner.
394  *
395  *	  The pathlist is kept sorted by total_cost, with cheaper paths
396  *	  at the front.  Within this routine, that's simply a speed hack:
397  *	  doing it that way makes it more likely that we will reject an inferior
398  *	  path after a few comparisons, rather than many comparisons.
399  *	  However, add_path_precheck relies on this ordering to exit early
400  *	  when possible.
401  *
402  *	  NOTE: discarded Path objects are immediately pfree'd to reduce planner
403  *	  memory consumption.  We dare not try to free the substructure of a Path,
404  *	  since much of it may be shared with other Paths or the query tree itself;
405  *	  but just recycling discarded Path nodes is a very useful savings in
406  *	  a large join tree.  We can recycle the List nodes of pathlist, too.
407  *
408  *	  As noted in optimizer/README, deleting a previously-accepted Path is
409  *	  safe because we know that Paths of this rel cannot yet be referenced
410  *	  from any other rel, such as a higher-level join.  However, in some cases
411  *	  it is possible that a Path is referenced by another Path for its own
412  *	  rel; we must not delete such a Path, even if it is dominated by the new
413  *	  Path.  Currently this occurs only for IndexPath objects, which may be
414  *	  referenced as children of BitmapHeapPaths as well as being paths in
415  *	  their own right.  Hence, we don't pfree IndexPaths when rejecting them.
416  *
417  * 'parent_rel' is the relation entry to which the path corresponds.
418  * 'new_path' is a potential path for parent_rel.
419  *
420  * Returns nothing, but modifies parent_rel->pathlist.
421  */
422 void
add_path(RelOptInfo * parent_rel,Path * new_path)423 add_path(RelOptInfo *parent_rel, Path *new_path)
424 {
425 	bool		accept_new = true;	/* unless we find a superior old path */
426 	ListCell   *insert_after = NULL;	/* where to insert new item */
427 	List	   *new_path_pathkeys;
428 	ListCell   *p1;
429 	ListCell   *p1_prev;
430 	ListCell   *p1_next;
431 
432 	/*
433 	 * This is a convenient place to check for query cancel --- no part of the
434 	 * planner goes very long without calling add_path().
435 	 */
436 	CHECK_FOR_INTERRUPTS();
437 
438 	/* Pretend parameterized paths have no pathkeys, per comment above */
439 	new_path_pathkeys = new_path->param_info ? NIL : new_path->pathkeys;
440 
441 	/*
442 	 * Loop to check proposed new path against old paths.  Note it is possible
443 	 * for more than one old path to be tossed out because new_path dominates
444 	 * it.
445 	 *
446 	 * We can't use foreach here because the loop body may delete the current
447 	 * list cell.
448 	 */
449 	p1_prev = NULL;
450 	for (p1 = list_head(parent_rel->pathlist); p1 != NULL; p1 = p1_next)
451 	{
452 		Path	   *old_path = (Path *) lfirst(p1);
453 		bool		remove_old = false; /* unless new proves superior */
454 		PathCostComparison costcmp;
455 		PathKeysComparison keyscmp;
456 		BMS_Comparison outercmp;
457 
458 		p1_next = lnext(p1);
459 
460 		/*
461 		 * Do a fuzzy cost comparison with standard fuzziness limit.
462 		 */
463 		costcmp = compare_path_costs_fuzzily(new_path, old_path,
464 											 STD_FUZZ_FACTOR);
465 
466 		/*
467 		 * If the two paths compare differently for startup and total cost,
468 		 * then we want to keep both, and we can skip comparing pathkeys and
469 		 * required_outer rels.  If they compare the same, proceed with the
470 		 * other comparisons.  Row count is checked last.  (We make the tests
471 		 * in this order because the cost comparison is most likely to turn
472 		 * out "different", and the pathkeys comparison next most likely.  As
473 		 * explained above, row count very seldom makes a difference, so even
474 		 * though it's cheap to compare there's not much point in checking it
475 		 * earlier.)
476 		 */
477 		if (costcmp != COSTS_DIFFERENT)
478 		{
479 			/* Similarly check to see if either dominates on pathkeys */
480 			List	   *old_path_pathkeys;
481 
482 			old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
483 			keyscmp = compare_pathkeys(new_path_pathkeys,
484 									   old_path_pathkeys);
485 			if (keyscmp != PATHKEYS_DIFFERENT)
486 			{
487 				switch (costcmp)
488 				{
489 					case COSTS_EQUAL:
490 						outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
491 													  PATH_REQ_OUTER(old_path));
492 						if (keyscmp == PATHKEYS_BETTER1)
493 						{
494 							if ((outercmp == BMS_EQUAL ||
495 								 outercmp == BMS_SUBSET1) &&
496 								new_path->rows <= old_path->rows &&
497 								new_path->parallel_safe >= old_path->parallel_safe)
498 								remove_old = true;	/* new dominates old */
499 						}
500 						else if (keyscmp == PATHKEYS_BETTER2)
501 						{
502 							if ((outercmp == BMS_EQUAL ||
503 								 outercmp == BMS_SUBSET2) &&
504 								new_path->rows >= old_path->rows &&
505 								new_path->parallel_safe <= old_path->parallel_safe)
506 								accept_new = false; /* old dominates new */
507 						}
508 						else	/* keyscmp == PATHKEYS_EQUAL */
509 						{
510 							if (outercmp == BMS_EQUAL)
511 							{
512 								/*
513 								 * Same pathkeys and outer rels, and fuzzily
514 								 * the same cost, so keep just one; to decide
515 								 * which, first check parallel-safety, then
516 								 * rows, then do a fuzzy cost comparison with
517 								 * very small fuzz limit.  (We used to do an
518 								 * exact cost comparison, but that results in
519 								 * annoying platform-specific plan variations
520 								 * due to roundoff in the cost estimates.)	If
521 								 * things are still tied, arbitrarily keep
522 								 * only the old path.  Notice that we will
523 								 * keep only the old path even if the
524 								 * less-fuzzy comparison decides the startup
525 								 * and total costs compare differently.
526 								 */
527 								if (new_path->parallel_safe >
528 									old_path->parallel_safe)
529 									remove_old = true;	/* new dominates old */
530 								else if (new_path->parallel_safe <
531 										 old_path->parallel_safe)
532 									accept_new = false; /* old dominates new */
533 								else if (new_path->rows < old_path->rows)
534 									remove_old = true;	/* new dominates old */
535 								else if (new_path->rows > old_path->rows)
536 									accept_new = false; /* old dominates new */
537 								else if (compare_path_costs_fuzzily(new_path,
538 																	old_path,
539 																	1.0000000001) == COSTS_BETTER1)
540 									remove_old = true;	/* new dominates old */
541 								else
542 									accept_new = false; /* old equals or
543 														 * dominates new */
544 							}
545 							else if (outercmp == BMS_SUBSET1 &&
546 									 new_path->rows <= old_path->rows &&
547 									 new_path->parallel_safe >= old_path->parallel_safe)
548 								remove_old = true;	/* new dominates old */
549 							else if (outercmp == BMS_SUBSET2 &&
550 									 new_path->rows >= old_path->rows &&
551 									 new_path->parallel_safe <= old_path->parallel_safe)
552 								accept_new = false; /* old dominates new */
553 							/* else different parameterizations, keep both */
554 						}
555 						break;
556 					case COSTS_BETTER1:
557 						if (keyscmp != PATHKEYS_BETTER2)
558 						{
559 							outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
560 														  PATH_REQ_OUTER(old_path));
561 							if ((outercmp == BMS_EQUAL ||
562 								 outercmp == BMS_SUBSET1) &&
563 								new_path->rows <= old_path->rows &&
564 								new_path->parallel_safe >= old_path->parallel_safe)
565 								remove_old = true;	/* new dominates old */
566 						}
567 						break;
568 					case COSTS_BETTER2:
569 						if (keyscmp != PATHKEYS_BETTER1)
570 						{
571 							outercmp = bms_subset_compare(PATH_REQ_OUTER(new_path),
572 														  PATH_REQ_OUTER(old_path));
573 							if ((outercmp == BMS_EQUAL ||
574 								 outercmp == BMS_SUBSET2) &&
575 								new_path->rows >= old_path->rows &&
576 								new_path->parallel_safe <= old_path->parallel_safe)
577 								accept_new = false; /* old dominates new */
578 						}
579 						break;
580 					case COSTS_DIFFERENT:
581 
582 						/*
583 						 * can't get here, but keep this case to keep compiler
584 						 * quiet
585 						 */
586 						break;
587 				}
588 			}
589 		}
590 
591 		/*
592 		 * Remove current element from pathlist if dominated by new.
593 		 */
594 		if (remove_old)
595 		{
596 			parent_rel->pathlist = list_delete_cell(parent_rel->pathlist,
597 													p1, p1_prev);
598 
599 			/*
600 			 * Delete the data pointed-to by the deleted cell, if possible
601 			 */
602 			if (!IsA(old_path, IndexPath))
603 				pfree(old_path);
604 			/* p1_prev does not advance */
605 		}
606 		else
607 		{
608 			/* new belongs after this old path if it has cost >= old's */
609 			if (new_path->total_cost >= old_path->total_cost)
610 				insert_after = p1;
611 			/* p1_prev advances */
612 			p1_prev = p1;
613 		}
614 
615 		/*
616 		 * If we found an old path that dominates new_path, we can quit
617 		 * scanning the pathlist; we will not add new_path, and we assume
618 		 * new_path cannot dominate any other elements of the pathlist.
619 		 */
620 		if (!accept_new)
621 			break;
622 	}
623 
624 	if (accept_new)
625 	{
626 		/* Accept the new path: insert it at proper place in pathlist */
627 		if (insert_after)
628 			lappend_cell(parent_rel->pathlist, insert_after, new_path);
629 		else
630 			parent_rel->pathlist = lcons(new_path, parent_rel->pathlist);
631 	}
632 	else
633 	{
634 		/* Reject and recycle the new path */
635 		if (!IsA(new_path, IndexPath))
636 			pfree(new_path);
637 	}
638 }
639 
640 /*
641  * add_path_precheck
642  *	  Check whether a proposed new path could possibly get accepted.
643  *	  We assume we know the path's pathkeys and parameterization accurately,
644  *	  and have lower bounds for its costs.
645  *
646  * Note that we do not know the path's rowcount, since getting an estimate for
647  * that is too expensive to do before prechecking.  We assume here that paths
648  * of a superset parameterization will generate fewer rows; if that holds,
649  * then paths with different parameterizations cannot dominate each other
650  * and so we can simply ignore existing paths of another parameterization.
651  * (In the infrequent cases where that rule of thumb fails, add_path will
652  * get rid of the inferior path.)
653  *
654  * At the time this is called, we haven't actually built a Path structure,
655  * so the required information has to be passed piecemeal.
656  */
657 bool
add_path_precheck(RelOptInfo * parent_rel,Cost startup_cost,Cost total_cost,List * pathkeys,Relids required_outer)658 add_path_precheck(RelOptInfo *parent_rel,
659 				  Cost startup_cost, Cost total_cost,
660 				  List *pathkeys, Relids required_outer)
661 {
662 	List	   *new_path_pathkeys;
663 	bool		consider_startup;
664 	ListCell   *p1;
665 
666 	/* Pretend parameterized paths have no pathkeys, per add_path policy */
667 	new_path_pathkeys = required_outer ? NIL : pathkeys;
668 
669 	/* Decide whether new path's startup cost is interesting */
670 	consider_startup = required_outer ? parent_rel->consider_param_startup : parent_rel->consider_startup;
671 
672 	foreach(p1, parent_rel->pathlist)
673 	{
674 		Path	   *old_path = (Path *) lfirst(p1);
675 		PathKeysComparison keyscmp;
676 
677 		/*
678 		 * We are looking for an old_path with the same parameterization (and
679 		 * by assumption the same rowcount) that dominates the new path on
680 		 * pathkeys as well as both cost metrics.  If we find one, we can
681 		 * reject the new path.
682 		 *
683 		 * Cost comparisons here should match compare_path_costs_fuzzily.
684 		 */
685 		if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
686 		{
687 			/* new path can win on startup cost only if consider_startup */
688 			if (startup_cost > old_path->startup_cost * STD_FUZZ_FACTOR ||
689 				!consider_startup)
690 			{
691 				/* new path loses on cost, so check pathkeys... */
692 				List	   *old_path_pathkeys;
693 
694 				old_path_pathkeys = old_path->param_info ? NIL : old_path->pathkeys;
695 				keyscmp = compare_pathkeys(new_path_pathkeys,
696 										   old_path_pathkeys);
697 				if (keyscmp == PATHKEYS_EQUAL ||
698 					keyscmp == PATHKEYS_BETTER2)
699 				{
700 					/* new path does not win on pathkeys... */
701 					if (bms_equal(required_outer, PATH_REQ_OUTER(old_path)))
702 					{
703 						/* Found an old path that dominates the new one */
704 						return false;
705 					}
706 				}
707 			}
708 		}
709 		else
710 		{
711 			/*
712 			 * Since the pathlist is sorted by total_cost, we can stop looking
713 			 * once we reach a path with a total_cost larger than the new
714 			 * path's.
715 			 */
716 			break;
717 		}
718 	}
719 
720 	return true;
721 }
722 
723 /*
724  * add_partial_path
725  *	  Like add_path, our goal here is to consider whether a path is worthy
726  *	  of being kept around, but the considerations here are a bit different.
727  *	  A partial path is one which can be executed in any number of workers in
728  *	  parallel such that each worker will generate a subset of the path's
729  *	  overall result.
730  *
731  *	  As in add_path, the partial_pathlist is kept sorted with the cheapest
732  *	  total path in front.  This is depended on by multiple places, which
733  *	  just take the front entry as the cheapest path without searching.
734  *
735  *	  We don't generate parameterized partial paths for several reasons.  Most
736  *	  importantly, they're not safe to execute, because there's nothing to
737  *	  make sure that a parallel scan within the parameterized portion of the
738  *	  plan is running with the same value in every worker at the same time.
739  *	  Fortunately, it seems unlikely to be worthwhile anyway, because having
740  *	  each worker scan the entire outer relation and a subset of the inner
741  *	  relation will generally be a terrible plan.  The inner (parameterized)
742  *	  side of the plan will be small anyway.  There could be rare cases where
743  *	  this wins big - e.g. if join order constraints put a 1-row relation on
744  *	  the outer side of the topmost join with a parameterized plan on the inner
745  *	  side - but we'll have to be content not to handle such cases until
746  *	  somebody builds an executor infrastructure that can cope with them.
747  *
748  *	  Because we don't consider parameterized paths here, we also don't
749  *	  need to consider the row counts as a measure of quality: every path will
750  *	  produce the same number of rows.  Neither do we need to consider startup
751  *	  costs: parallelism is only used for plans that will be run to completion.
752  *	  Therefore, this routine is much simpler than add_path: it needs to
753  *	  consider only pathkeys and total cost.
754  *
755  *	  As with add_path, we pfree paths that are found to be dominated by
756  *	  another partial path; this requires that there be no other references to
757  *	  such paths yet.  Hence, GatherPaths must not be created for a rel until
758  *	  we're done creating all partial paths for it.  Unlike add_path, we don't
759  *	  take an exception for IndexPaths as partial index paths won't be
760  *	  referenced by partial BitmapHeapPaths.
761  */
762 void
add_partial_path(RelOptInfo * parent_rel,Path * new_path)763 add_partial_path(RelOptInfo *parent_rel, Path *new_path)
764 {
765 	bool		accept_new = true;	/* unless we find a superior old path */
766 	ListCell   *insert_after = NULL;	/* where to insert new item */
767 	ListCell   *p1;
768 	ListCell   *p1_prev;
769 	ListCell   *p1_next;
770 
771 	/* Check for query cancel. */
772 	CHECK_FOR_INTERRUPTS();
773 
774 	/* Path to be added must be parallel safe. */
775 	Assert(new_path->parallel_safe);
776 
777 	/* Relation should be OK for parallelism, too. */
778 	Assert(parent_rel->consider_parallel);
779 
780 	/*
781 	 * As in add_path, throw out any paths which are dominated by the new
782 	 * path, but throw out the new path if some existing path dominates it.
783 	 */
784 	p1_prev = NULL;
785 	for (p1 = list_head(parent_rel->partial_pathlist); p1 != NULL;
786 		 p1 = p1_next)
787 	{
788 		Path	   *old_path = (Path *) lfirst(p1);
789 		bool		remove_old = false; /* unless new proves superior */
790 		PathKeysComparison keyscmp;
791 
792 		p1_next = lnext(p1);
793 
794 		/* Compare pathkeys. */
795 		keyscmp = compare_pathkeys(new_path->pathkeys, old_path->pathkeys);
796 
797 		/* Unless pathkeys are incompable, keep just one of the two paths. */
798 		if (keyscmp != PATHKEYS_DIFFERENT)
799 		{
800 			if (new_path->total_cost > old_path->total_cost * STD_FUZZ_FACTOR)
801 			{
802 				/* New path costs more; keep it only if pathkeys are better. */
803 				if (keyscmp != PATHKEYS_BETTER1)
804 					accept_new = false;
805 			}
806 			else if (old_path->total_cost > new_path->total_cost
807 					 * STD_FUZZ_FACTOR)
808 			{
809 				/* Old path costs more; keep it only if pathkeys are better. */
810 				if (keyscmp != PATHKEYS_BETTER2)
811 					remove_old = true;
812 			}
813 			else if (keyscmp == PATHKEYS_BETTER1)
814 			{
815 				/* Costs are about the same, new path has better pathkeys. */
816 				remove_old = true;
817 			}
818 			else if (keyscmp == PATHKEYS_BETTER2)
819 			{
820 				/* Costs are about the same, old path has better pathkeys. */
821 				accept_new = false;
822 			}
823 			else if (old_path->total_cost > new_path->total_cost * 1.0000000001)
824 			{
825 				/* Pathkeys are the same, and the old path costs more. */
826 				remove_old = true;
827 			}
828 			else
829 			{
830 				/*
831 				 * Pathkeys are the same, and new path isn't materially
832 				 * cheaper.
833 				 */
834 				accept_new = false;
835 			}
836 		}
837 
838 		/*
839 		 * Remove current element from partial_pathlist if dominated by new.
840 		 */
841 		if (remove_old)
842 		{
843 			parent_rel->partial_pathlist =
844 				list_delete_cell(parent_rel->partial_pathlist, p1, p1_prev);
845 			pfree(old_path);
846 			/* p1_prev does not advance */
847 		}
848 		else
849 		{
850 			/* new belongs after this old path if it has cost >= old's */
851 			if (new_path->total_cost >= old_path->total_cost)
852 				insert_after = p1;
853 			/* p1_prev advances */
854 			p1_prev = p1;
855 		}
856 
857 		/*
858 		 * If we found an old path that dominates new_path, we can quit
859 		 * scanning the partial_pathlist; we will not add new_path, and we
860 		 * assume new_path cannot dominate any later path.
861 		 */
862 		if (!accept_new)
863 			break;
864 	}
865 
866 	if (accept_new)
867 	{
868 		/* Accept the new path: insert it at proper place */
869 		if (insert_after)
870 			lappend_cell(parent_rel->partial_pathlist, insert_after, new_path);
871 		else
872 			parent_rel->partial_pathlist =
873 				lcons(new_path, parent_rel->partial_pathlist);
874 	}
875 	else
876 	{
877 		/* Reject and recycle the new path */
878 		pfree(new_path);
879 	}
880 }
881 
882 /*
883  * add_partial_path_precheck
884  *	  Check whether a proposed new partial path could possibly get accepted.
885  *
886  * Unlike add_path_precheck, we can ignore startup cost and parameterization,
887  * since they don't matter for partial paths (see add_partial_path).  But
888  * we do want to make sure we don't add a partial path if there's already
889  * a complete path that dominates it, since in that case the proposed path
890  * is surely a loser.
891  */
892 bool
add_partial_path_precheck(RelOptInfo * parent_rel,Cost total_cost,List * pathkeys)893 add_partial_path_precheck(RelOptInfo *parent_rel, Cost total_cost,
894 						  List *pathkeys)
895 {
896 	ListCell   *p1;
897 
898 	/*
899 	 * Our goal here is twofold.  First, we want to find out whether this path
900 	 * is clearly inferior to some existing partial path.  If so, we want to
901 	 * reject it immediately.  Second, we want to find out whether this path
902 	 * is clearly superior to some existing partial path -- at least, modulo
903 	 * final cost computations.  If so, we definitely want to consider it.
904 	 *
905 	 * Unlike add_path(), we always compare pathkeys here.  This is because we
906 	 * expect partial_pathlist to be very short, and getting a definitive
907 	 * answer at this stage avoids the need to call add_path_precheck.
908 	 */
909 	foreach(p1, parent_rel->partial_pathlist)
910 	{
911 		Path	   *old_path = (Path *) lfirst(p1);
912 		PathKeysComparison keyscmp;
913 
914 		keyscmp = compare_pathkeys(pathkeys, old_path->pathkeys);
915 		if (keyscmp != PATHKEYS_DIFFERENT)
916 		{
917 			if (total_cost > old_path->total_cost * STD_FUZZ_FACTOR &&
918 				keyscmp != PATHKEYS_BETTER1)
919 				return false;
920 			if (old_path->total_cost > total_cost * STD_FUZZ_FACTOR &&
921 				keyscmp != PATHKEYS_BETTER2)
922 				return true;
923 		}
924 	}
925 
926 	/*
927 	 * This path is neither clearly inferior to an existing partial path nor
928 	 * clearly good enough that it might replace one.  Compare it to
929 	 * non-parallel plans.  If it loses even before accounting for the cost of
930 	 * the Gather node, we should definitely reject it.
931 	 *
932 	 * Note that we pass the total_cost to add_path_precheck twice.  This is
933 	 * because it's never advantageous to consider the startup cost of a
934 	 * partial path; the resulting plans, if run in parallel, will be run to
935 	 * completion.
936 	 */
937 	if (!add_path_precheck(parent_rel, total_cost, total_cost, pathkeys,
938 						   NULL))
939 		return false;
940 
941 	return true;
942 }
943 
944 
945 /*****************************************************************************
946  *		PATH NODE CREATION ROUTINES
947  *****************************************************************************/
948 
949 /*
950  * create_seqscan_path
951  *	  Creates a path corresponding to a sequential scan, returning the
952  *	  pathnode.
953  */
954 Path *
create_seqscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer,int parallel_workers)955 create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
956 					Relids required_outer, int parallel_workers)
957 {
958 	Path	   *pathnode = makeNode(Path);
959 
960 	pathnode->pathtype = T_SeqScan;
961 	pathnode->parent = rel;
962 	pathnode->pathtarget = rel->reltarget;
963 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
964 													 required_outer);
965 	pathnode->parallel_aware = parallel_workers > 0 ? true : false;
966 	pathnode->parallel_safe = rel->consider_parallel;
967 	pathnode->parallel_workers = parallel_workers;
968 	pathnode->pathkeys = NIL;	/* seqscan has unordered result */
969 
970 	cost_seqscan(pathnode, root, rel, pathnode->param_info);
971 
972 	return pathnode;
973 }
974 
975 /*
976  * create_samplescan_path
977  *	  Creates a path node for a sampled table scan.
978  */
979 Path *
create_samplescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)980 create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
981 {
982 	Path	   *pathnode = makeNode(Path);
983 
984 	pathnode->pathtype = T_SampleScan;
985 	pathnode->parent = rel;
986 	pathnode->pathtarget = rel->reltarget;
987 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
988 													 required_outer);
989 	pathnode->parallel_aware = false;
990 	pathnode->parallel_safe = rel->consider_parallel;
991 	pathnode->parallel_workers = 0;
992 	pathnode->pathkeys = NIL;	/* samplescan has unordered result */
993 
994 	cost_samplescan(pathnode, root, rel, pathnode->param_info);
995 
996 	return pathnode;
997 }
998 
999 /*
1000  * create_index_path
1001  *	  Creates a path node for an index scan.
1002  *
1003  * 'index' is a usable index.
1004  * 'indexclauses' is a list of IndexClause nodes representing clauses
1005  *			to be enforced as qual conditions in the scan.
1006  * 'indexorderbys' is a list of bare expressions (no RestrictInfos)
1007  *			to be used as index ordering operators in the scan.
1008  * 'indexorderbycols' is an integer list of index column numbers (zero based)
1009  *			the ordering operators can be used with.
1010  * 'pathkeys' describes the ordering of the path.
1011  * 'indexscandir' is ForwardScanDirection or BackwardScanDirection
1012  *			for an ordered index, or NoMovementScanDirection for
1013  *			an unordered index.
1014  * 'indexonly' is true if an index-only scan is wanted.
1015  * 'required_outer' is the set of outer relids for a parameterized path.
1016  * 'loop_count' is the number of repetitions of the indexscan to factor into
1017  *		estimates of caching behavior.
1018  * 'partial_path' is true if constructing a parallel index scan path.
1019  *
1020  * Returns the new path node.
1021  */
1022 IndexPath *
create_index_path(PlannerInfo * root,IndexOptInfo * index,List * indexclauses,List * indexorderbys,List * indexorderbycols,List * pathkeys,ScanDirection indexscandir,bool indexonly,Relids required_outer,double loop_count,bool partial_path)1023 create_index_path(PlannerInfo *root,
1024 				  IndexOptInfo *index,
1025 				  List *indexclauses,
1026 				  List *indexorderbys,
1027 				  List *indexorderbycols,
1028 				  List *pathkeys,
1029 				  ScanDirection indexscandir,
1030 				  bool indexonly,
1031 				  Relids required_outer,
1032 				  double loop_count,
1033 				  bool partial_path)
1034 {
1035 	IndexPath  *pathnode = makeNode(IndexPath);
1036 	RelOptInfo *rel = index->rel;
1037 
1038 	pathnode->path.pathtype = indexonly ? T_IndexOnlyScan : T_IndexScan;
1039 	pathnode->path.parent = rel;
1040 	pathnode->path.pathtarget = rel->reltarget;
1041 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1042 														  required_outer);
1043 	pathnode->path.parallel_aware = false;
1044 	pathnode->path.parallel_safe = rel->consider_parallel;
1045 	pathnode->path.parallel_workers = 0;
1046 	pathnode->path.pathkeys = pathkeys;
1047 
1048 	pathnode->indexinfo = index;
1049 	pathnode->indexclauses = indexclauses;
1050 	pathnode->indexorderbys = indexorderbys;
1051 	pathnode->indexorderbycols = indexorderbycols;
1052 	pathnode->indexscandir = indexscandir;
1053 
1054 	cost_index(pathnode, root, loop_count, partial_path);
1055 
1056 	return pathnode;
1057 }
1058 
1059 /*
1060  * create_bitmap_heap_path
1061  *	  Creates a path node for a bitmap scan.
1062  *
1063  * 'bitmapqual' is a tree of IndexPath, BitmapAndPath, and BitmapOrPath nodes.
1064  * 'required_outer' is the set of outer relids for a parameterized path.
1065  * 'loop_count' is the number of repetitions of the indexscan to factor into
1066  *		estimates of caching behavior.
1067  *
1068  * loop_count should match the value used when creating the component
1069  * IndexPaths.
1070  */
1071 BitmapHeapPath *
create_bitmap_heap_path(PlannerInfo * root,RelOptInfo * rel,Path * bitmapqual,Relids required_outer,double loop_count,int parallel_degree)1072 create_bitmap_heap_path(PlannerInfo *root,
1073 						RelOptInfo *rel,
1074 						Path *bitmapqual,
1075 						Relids required_outer,
1076 						double loop_count,
1077 						int parallel_degree)
1078 {
1079 	BitmapHeapPath *pathnode = makeNode(BitmapHeapPath);
1080 
1081 	pathnode->path.pathtype = T_BitmapHeapScan;
1082 	pathnode->path.parent = rel;
1083 	pathnode->path.pathtarget = rel->reltarget;
1084 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1085 														  required_outer);
1086 	pathnode->path.parallel_aware = parallel_degree > 0 ? true : false;
1087 	pathnode->path.parallel_safe = rel->consider_parallel;
1088 	pathnode->path.parallel_workers = parallel_degree;
1089 	pathnode->path.pathkeys = NIL;	/* always unordered */
1090 
1091 	pathnode->bitmapqual = bitmapqual;
1092 
1093 	cost_bitmap_heap_scan(&pathnode->path, root, rel,
1094 						  pathnode->path.param_info,
1095 						  bitmapqual, loop_count);
1096 
1097 	return pathnode;
1098 }
1099 
1100 /*
1101  * create_bitmap_and_path
1102  *	  Creates a path node representing a BitmapAnd.
1103  */
1104 BitmapAndPath *
create_bitmap_and_path(PlannerInfo * root,RelOptInfo * rel,List * bitmapquals)1105 create_bitmap_and_path(PlannerInfo *root,
1106 					   RelOptInfo *rel,
1107 					   List *bitmapquals)
1108 {
1109 	BitmapAndPath *pathnode = makeNode(BitmapAndPath);
1110 	Relids		required_outer = NULL;
1111 	ListCell   *lc;
1112 
1113 	pathnode->path.pathtype = T_BitmapAnd;
1114 	pathnode->path.parent = rel;
1115 	pathnode->path.pathtarget = rel->reltarget;
1116 
1117 	/*
1118 	 * Identify the required outer rels as the union of what the child paths
1119 	 * depend on.  (Alternatively, we could insist that the caller pass this
1120 	 * in, but it's more convenient and reliable to compute it here.)
1121 	 */
1122 	foreach(lc, bitmapquals)
1123 	{
1124 		Path	   *bitmapqual = (Path *) lfirst(lc);
1125 
1126 		required_outer = bms_add_members(required_outer,
1127 										 PATH_REQ_OUTER(bitmapqual));
1128 	}
1129 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1130 														  required_outer);
1131 
1132 	/*
1133 	 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1134 	 * parallel-safe if and only if rel->consider_parallel is set.  So, we can
1135 	 * set the flag for this path based only on the relation-level flag,
1136 	 * without actually iterating over the list of children.
1137 	 */
1138 	pathnode->path.parallel_aware = false;
1139 	pathnode->path.parallel_safe = rel->consider_parallel;
1140 	pathnode->path.parallel_workers = 0;
1141 
1142 	pathnode->path.pathkeys = NIL;	/* always unordered */
1143 
1144 	pathnode->bitmapquals = bitmapquals;
1145 
1146 	/* this sets bitmapselectivity as well as the regular cost fields: */
1147 	cost_bitmap_and_node(pathnode, root);
1148 
1149 	return pathnode;
1150 }
1151 
1152 /*
1153  * create_bitmap_or_path
1154  *	  Creates a path node representing a BitmapOr.
1155  */
1156 BitmapOrPath *
create_bitmap_or_path(PlannerInfo * root,RelOptInfo * rel,List * bitmapquals)1157 create_bitmap_or_path(PlannerInfo *root,
1158 					  RelOptInfo *rel,
1159 					  List *bitmapquals)
1160 {
1161 	BitmapOrPath *pathnode = makeNode(BitmapOrPath);
1162 	Relids		required_outer = NULL;
1163 	ListCell   *lc;
1164 
1165 	pathnode->path.pathtype = T_BitmapOr;
1166 	pathnode->path.parent = rel;
1167 	pathnode->path.pathtarget = rel->reltarget;
1168 
1169 	/*
1170 	 * Identify the required outer rels as the union of what the child paths
1171 	 * depend on.  (Alternatively, we could insist that the caller pass this
1172 	 * in, but it's more convenient and reliable to compute it here.)
1173 	 */
1174 	foreach(lc, bitmapquals)
1175 	{
1176 		Path	   *bitmapqual = (Path *) lfirst(lc);
1177 
1178 		required_outer = bms_add_members(required_outer,
1179 										 PATH_REQ_OUTER(bitmapqual));
1180 	}
1181 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1182 														  required_outer);
1183 
1184 	/*
1185 	 * Currently, a BitmapHeapPath, BitmapAndPath, or BitmapOrPath will be
1186 	 * parallel-safe if and only if rel->consider_parallel is set.  So, we can
1187 	 * set the flag for this path based only on the relation-level flag,
1188 	 * without actually iterating over the list of children.
1189 	 */
1190 	pathnode->path.parallel_aware = false;
1191 	pathnode->path.parallel_safe = rel->consider_parallel;
1192 	pathnode->path.parallel_workers = 0;
1193 
1194 	pathnode->path.pathkeys = NIL;	/* always unordered */
1195 
1196 	pathnode->bitmapquals = bitmapquals;
1197 
1198 	/* this sets bitmapselectivity as well as the regular cost fields: */
1199 	cost_bitmap_or_node(pathnode, root);
1200 
1201 	return pathnode;
1202 }
1203 
1204 /*
1205  * create_tidscan_path
1206  *	  Creates a path corresponding to a scan by TID, returning the pathnode.
1207  */
1208 TidPath *
create_tidscan_path(PlannerInfo * root,RelOptInfo * rel,List * tidquals,Relids required_outer)1209 create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals,
1210 					Relids required_outer)
1211 {
1212 	TidPath    *pathnode = makeNode(TidPath);
1213 
1214 	pathnode->path.pathtype = T_TidScan;
1215 	pathnode->path.parent = rel;
1216 	pathnode->path.pathtarget = rel->reltarget;
1217 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1218 														  required_outer);
1219 	pathnode->path.parallel_aware = false;
1220 	pathnode->path.parallel_safe = rel->consider_parallel;
1221 	pathnode->path.parallel_workers = 0;
1222 	pathnode->path.pathkeys = NIL;	/* always unordered */
1223 
1224 	pathnode->tidquals = tidquals;
1225 
1226 	cost_tidscan(&pathnode->path, root, rel, tidquals,
1227 				 pathnode->path.param_info);
1228 
1229 	return pathnode;
1230 }
1231 
1232 /*
1233  * create_append_path
1234  *	  Creates a path corresponding to an Append plan, returning the
1235  *	  pathnode.
1236  *
1237  * Note that we must handle subpaths = NIL, representing a dummy access path.
1238  * Also, there are callers that pass root = NULL.
1239  */
1240 AppendPath *
create_append_path(PlannerInfo * root,RelOptInfo * rel,List * subpaths,List * partial_subpaths,List * pathkeys,Relids required_outer,int parallel_workers,bool parallel_aware,List * partitioned_rels,double rows)1241 create_append_path(PlannerInfo *root,
1242 				   RelOptInfo *rel,
1243 				   List *subpaths, List *partial_subpaths,
1244 				   List *pathkeys, Relids required_outer,
1245 				   int parallel_workers, bool parallel_aware,
1246 				   List *partitioned_rels, double rows)
1247 {
1248 	AppendPath *pathnode = makeNode(AppendPath);
1249 	ListCell   *l;
1250 
1251 	Assert(!parallel_aware || parallel_workers > 0);
1252 
1253 	pathnode->path.pathtype = T_Append;
1254 	pathnode->path.parent = rel;
1255 	pathnode->path.pathtarget = rel->reltarget;
1256 
1257 	/*
1258 	 * When generating an Append path for a partitioned table, there may be
1259 	 * parameters that are useful so we can eliminate certain partitions
1260 	 * during execution.  Here we'll go all the way and fully populate the
1261 	 * parameter info data as we do for normal base relations.  However, we
1262 	 * need only bother doing this for RELOPT_BASEREL rels, as
1263 	 * RELOPT_OTHER_MEMBER_REL's Append paths are merged into the base rel's
1264 	 * Append subpaths.  It would do no harm to do this, we just avoid it to
1265 	 * save wasting effort.
1266 	 */
1267 	if (partitioned_rels != NIL && root && rel->reloptkind == RELOPT_BASEREL)
1268 		pathnode->path.param_info = get_baserel_parampathinfo(root,
1269 															  rel,
1270 															  required_outer);
1271 	else
1272 		pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1273 																required_outer);
1274 
1275 	pathnode->path.parallel_aware = parallel_aware;
1276 	pathnode->path.parallel_safe = rel->consider_parallel;
1277 	pathnode->path.parallel_workers = parallel_workers;
1278 	pathnode->path.pathkeys = pathkeys;
1279 	pathnode->partitioned_rels = list_copy(partitioned_rels);
1280 
1281 	/*
1282 	 * For parallel append, non-partial paths are sorted by descending total
1283 	 * costs. That way, the total time to finish all non-partial paths is
1284 	 * minimized.  Also, the partial paths are sorted by descending startup
1285 	 * costs.  There may be some paths that require to do startup work by a
1286 	 * single worker.  In such case, it's better for workers to choose the
1287 	 * expensive ones first, whereas the leader should choose the cheapest
1288 	 * startup plan.
1289 	 */
1290 	if (pathnode->path.parallel_aware)
1291 	{
1292 		/*
1293 		 * We mustn't fiddle with the order of subpaths when the Append has
1294 		 * pathkeys.  The order they're listed in is critical to keeping the
1295 		 * pathkeys valid.
1296 		 */
1297 		Assert(pathkeys == NIL);
1298 
1299 		subpaths = list_qsort(subpaths, append_total_cost_compare);
1300 		partial_subpaths = list_qsort(partial_subpaths,
1301 									  append_startup_cost_compare);
1302 	}
1303 	pathnode->first_partial_path = list_length(subpaths);
1304 	pathnode->subpaths = list_concat(subpaths, partial_subpaths);
1305 
1306 	/*
1307 	 * Apply query-wide LIMIT if known and path is for sole base relation.
1308 	 * (Handling this at this low level is a bit klugy.)
1309 	 */
1310 	if (root != NULL && bms_equal(rel->relids, root->all_baserels))
1311 		pathnode->limit_tuples = root->limit_tuples;
1312 	else
1313 		pathnode->limit_tuples = -1.0;
1314 
1315 	foreach(l, pathnode->subpaths)
1316 	{
1317 		Path	   *subpath = (Path *) lfirst(l);
1318 
1319 		pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1320 			subpath->parallel_safe;
1321 
1322 		/* All child paths must have same parameterization */
1323 		Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1324 	}
1325 
1326 	Assert(!parallel_aware || pathnode->path.parallel_safe);
1327 
1328 	/*
1329 	 * If there's exactly one child path, the Append is a no-op and will be
1330 	 * discarded later (in setrefs.c); therefore, we can inherit the child's
1331 	 * size and cost, as well as its pathkeys if any (overriding whatever the
1332 	 * caller might've said).  Otherwise, we must do the normal costsize
1333 	 * calculation.
1334 	 */
1335 	if (list_length(pathnode->subpaths) == 1)
1336 	{
1337 		Path	   *child = (Path *) linitial(pathnode->subpaths);
1338 
1339 		pathnode->path.rows = child->rows;
1340 		pathnode->path.startup_cost = child->startup_cost;
1341 		pathnode->path.total_cost = child->total_cost;
1342 		pathnode->path.pathkeys = child->pathkeys;
1343 	}
1344 	else
1345 		cost_append(pathnode);
1346 
1347 	/* If the caller provided a row estimate, override the computed value. */
1348 	if (rows >= 0)
1349 		pathnode->path.rows = rows;
1350 
1351 	return pathnode;
1352 }
1353 
1354 /*
1355  * append_total_cost_compare
1356  *	  qsort comparator for sorting append child paths by total_cost descending
1357  *
1358  * For equal total costs, we fall back to comparing startup costs; if those
1359  * are equal too, break ties using bms_compare on the paths' relids.
1360  * (This is to avoid getting unpredictable results from qsort.)
1361  */
1362 static int
append_total_cost_compare(const void * a,const void * b)1363 append_total_cost_compare(const void *a, const void *b)
1364 {
1365 	Path	   *path1 = (Path *) lfirst(*(ListCell **) a);
1366 	Path	   *path2 = (Path *) lfirst(*(ListCell **) b);
1367 	int			cmp;
1368 
1369 	cmp = compare_path_costs(path1, path2, TOTAL_COST);
1370 	if (cmp != 0)
1371 		return -cmp;
1372 	return bms_compare(path1->parent->relids, path2->parent->relids);
1373 }
1374 
1375 /*
1376  * append_startup_cost_compare
1377  *	  qsort comparator for sorting append child paths by startup_cost descending
1378  *
1379  * For equal startup costs, we fall back to comparing total costs; if those
1380  * are equal too, break ties using bms_compare on the paths' relids.
1381  * (This is to avoid getting unpredictable results from qsort.)
1382  */
1383 static int
append_startup_cost_compare(const void * a,const void * b)1384 append_startup_cost_compare(const void *a, const void *b)
1385 {
1386 	Path	   *path1 = (Path *) lfirst(*(ListCell **) a);
1387 	Path	   *path2 = (Path *) lfirst(*(ListCell **) b);
1388 	int			cmp;
1389 
1390 	cmp = compare_path_costs(path1, path2, STARTUP_COST);
1391 	if (cmp != 0)
1392 		return -cmp;
1393 	return bms_compare(path1->parent->relids, path2->parent->relids);
1394 }
1395 
1396 /*
1397  * create_merge_append_path
1398  *	  Creates a path corresponding to a MergeAppend plan, returning the
1399  *	  pathnode.
1400  */
1401 MergeAppendPath *
create_merge_append_path(PlannerInfo * root,RelOptInfo * rel,List * subpaths,List * pathkeys,Relids required_outer,List * partitioned_rels)1402 create_merge_append_path(PlannerInfo *root,
1403 						 RelOptInfo *rel,
1404 						 List *subpaths,
1405 						 List *pathkeys,
1406 						 Relids required_outer,
1407 						 List *partitioned_rels)
1408 {
1409 	MergeAppendPath *pathnode = makeNode(MergeAppendPath);
1410 	Cost		input_startup_cost;
1411 	Cost		input_total_cost;
1412 	ListCell   *l;
1413 
1414 	pathnode->path.pathtype = T_MergeAppend;
1415 	pathnode->path.parent = rel;
1416 	pathnode->path.pathtarget = rel->reltarget;
1417 	pathnode->path.param_info = get_appendrel_parampathinfo(rel,
1418 															required_outer);
1419 	pathnode->path.parallel_aware = false;
1420 	pathnode->path.parallel_safe = rel->consider_parallel;
1421 	pathnode->path.parallel_workers = 0;
1422 	pathnode->path.pathkeys = pathkeys;
1423 	pathnode->partitioned_rels = list_copy(partitioned_rels);
1424 	pathnode->subpaths = subpaths;
1425 
1426 	/*
1427 	 * Apply query-wide LIMIT if known and path is for sole base relation.
1428 	 * (Handling this at this low level is a bit klugy.)
1429 	 */
1430 	if (bms_equal(rel->relids, root->all_baserels))
1431 		pathnode->limit_tuples = root->limit_tuples;
1432 	else
1433 		pathnode->limit_tuples = -1.0;
1434 
1435 	/*
1436 	 * Add up the sizes and costs of the input paths.
1437 	 */
1438 	pathnode->path.rows = 0;
1439 	input_startup_cost = 0;
1440 	input_total_cost = 0;
1441 	foreach(l, subpaths)
1442 	{
1443 		Path	   *subpath = (Path *) lfirst(l);
1444 
1445 		pathnode->path.rows += subpath->rows;
1446 		pathnode->path.parallel_safe = pathnode->path.parallel_safe &&
1447 			subpath->parallel_safe;
1448 
1449 		if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1450 		{
1451 			/* Subpath is adequately ordered, we won't need to sort it */
1452 			input_startup_cost += subpath->startup_cost;
1453 			input_total_cost += subpath->total_cost;
1454 		}
1455 		else
1456 		{
1457 			/* We'll need to insert a Sort node, so include cost for that */
1458 			Path		sort_path;	/* dummy for result of cost_sort */
1459 
1460 			cost_sort(&sort_path,
1461 					  root,
1462 					  pathkeys,
1463 					  subpath->total_cost,
1464 					  subpath->parent->tuples,
1465 					  subpath->pathtarget->width,
1466 					  0.0,
1467 					  work_mem,
1468 					  pathnode->limit_tuples);
1469 			input_startup_cost += sort_path.startup_cost;
1470 			input_total_cost += sort_path.total_cost;
1471 		}
1472 
1473 		/* All child paths must have same parameterization */
1474 		Assert(bms_equal(PATH_REQ_OUTER(subpath), required_outer));
1475 	}
1476 
1477 	/*
1478 	 * Now we can compute total costs of the MergeAppend.  If there's exactly
1479 	 * one child path, the MergeAppend is a no-op and will be discarded later
1480 	 * (in setrefs.c); otherwise we do the normal cost calculation.
1481 	 */
1482 	if (list_length(subpaths) == 1)
1483 	{
1484 		pathnode->path.startup_cost = input_startup_cost;
1485 		pathnode->path.total_cost = input_total_cost;
1486 	}
1487 	else
1488 		cost_merge_append(&pathnode->path, root,
1489 						  pathkeys, list_length(subpaths),
1490 						  input_startup_cost, input_total_cost,
1491 						  pathnode->path.rows);
1492 
1493 	return pathnode;
1494 }
1495 
1496 /*
1497  * create_group_result_path
1498  *	  Creates a path representing a Result-and-nothing-else plan.
1499  *
1500  * This is only used for degenerate grouping cases, in which we know we
1501  * need to produce one result row, possibly filtered by a HAVING qual.
1502  */
1503 GroupResultPath *
create_group_result_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,List * havingqual)1504 create_group_result_path(PlannerInfo *root, RelOptInfo *rel,
1505 						 PathTarget *target, List *havingqual)
1506 {
1507 	GroupResultPath *pathnode = makeNode(GroupResultPath);
1508 
1509 	pathnode->path.pathtype = T_Result;
1510 	pathnode->path.parent = rel;
1511 	pathnode->path.pathtarget = target;
1512 	pathnode->path.param_info = NULL;	/* there are no other rels... */
1513 	pathnode->path.parallel_aware = false;
1514 	pathnode->path.parallel_safe = rel->consider_parallel;
1515 	pathnode->path.parallel_workers = 0;
1516 	pathnode->path.pathkeys = NIL;
1517 	pathnode->quals = havingqual;
1518 
1519 	/*
1520 	 * We can't quite use cost_resultscan() because the quals we want to
1521 	 * account for are not baserestrict quals of the rel.  Might as well just
1522 	 * hack it here.
1523 	 */
1524 	pathnode->path.rows = 1;
1525 	pathnode->path.startup_cost = target->cost.startup;
1526 	pathnode->path.total_cost = target->cost.startup +
1527 		cpu_tuple_cost + target->cost.per_tuple;
1528 
1529 	/*
1530 	 * Add cost of qual, if any --- but we ignore its selectivity, since our
1531 	 * rowcount estimate should be 1 no matter what the qual is.
1532 	 */
1533 	if (havingqual)
1534 	{
1535 		QualCost	qual_cost;
1536 
1537 		cost_qual_eval(&qual_cost, havingqual, root);
1538 		/* havingqual is evaluated once at startup */
1539 		pathnode->path.startup_cost += qual_cost.startup + qual_cost.per_tuple;
1540 		pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
1541 	}
1542 
1543 	return pathnode;
1544 }
1545 
1546 /*
1547  * create_material_path
1548  *	  Creates a path corresponding to a Material plan, returning the
1549  *	  pathnode.
1550  */
1551 MaterialPath *
create_material_path(RelOptInfo * rel,Path * subpath)1552 create_material_path(RelOptInfo *rel, Path *subpath)
1553 {
1554 	MaterialPath *pathnode = makeNode(MaterialPath);
1555 
1556 	Assert(subpath->parent == rel);
1557 
1558 	pathnode->path.pathtype = T_Material;
1559 	pathnode->path.parent = rel;
1560 	pathnode->path.pathtarget = rel->reltarget;
1561 	pathnode->path.param_info = subpath->param_info;
1562 	pathnode->path.parallel_aware = false;
1563 	pathnode->path.parallel_safe = rel->consider_parallel &&
1564 		subpath->parallel_safe;
1565 	pathnode->path.parallel_workers = subpath->parallel_workers;
1566 	pathnode->path.pathkeys = subpath->pathkeys;
1567 
1568 	pathnode->subpath = subpath;
1569 
1570 	cost_material(&pathnode->path,
1571 				  subpath->startup_cost,
1572 				  subpath->total_cost,
1573 				  subpath->rows,
1574 				  subpath->pathtarget->width);
1575 
1576 	return pathnode;
1577 }
1578 
1579 /*
1580  * create_unique_path
1581  *	  Creates a path representing elimination of distinct rows from the
1582  *	  input data.  Distinct-ness is defined according to the needs of the
1583  *	  semijoin represented by sjinfo.  If it is not possible to identify
1584  *	  how to make the data unique, NULL is returned.
1585  *
1586  * If used at all, this is likely to be called repeatedly on the same rel;
1587  * and the input subpath should always be the same (the cheapest_total path
1588  * for the rel).  So we cache the result.
1589  */
1590 UniquePath *
create_unique_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,SpecialJoinInfo * sjinfo)1591 create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1592 				   SpecialJoinInfo *sjinfo)
1593 {
1594 	UniquePath *pathnode;
1595 	Path		sort_path;		/* dummy for result of cost_sort */
1596 	Path		agg_path;		/* dummy for result of cost_agg */
1597 	MemoryContext oldcontext;
1598 	int			numCols;
1599 
1600 	/* Caller made a mistake if subpath isn't cheapest_total ... */
1601 	Assert(subpath == rel->cheapest_total_path);
1602 	Assert(subpath->parent == rel);
1603 	/* ... or if SpecialJoinInfo is the wrong one */
1604 	Assert(sjinfo->jointype == JOIN_SEMI);
1605 	Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
1606 
1607 	/* If result already cached, return it */
1608 	if (rel->cheapest_unique_path)
1609 		return (UniquePath *) rel->cheapest_unique_path;
1610 
1611 	/* If it's not possible to unique-ify, return NULL */
1612 	if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
1613 		return NULL;
1614 
1615 	/*
1616 	 * When called during GEQO join planning, we are in a short-lived memory
1617 	 * context.  We must make sure that the path and any subsidiary data
1618 	 * structures created for a baserel survive the GEQO cycle, else the
1619 	 * baserel is trashed for future GEQO cycles.  On the other hand, when we
1620 	 * are creating those for a joinrel during GEQO, we don't want them to
1621 	 * clutter the main planning context.  Upshot is that the best solution is
1622 	 * to explicitly allocate memory in the same context the given RelOptInfo
1623 	 * is in.
1624 	 */
1625 	oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1626 
1627 	pathnode = makeNode(UniquePath);
1628 
1629 	pathnode->path.pathtype = T_Unique;
1630 	pathnode->path.parent = rel;
1631 	pathnode->path.pathtarget = rel->reltarget;
1632 	pathnode->path.param_info = subpath->param_info;
1633 	pathnode->path.parallel_aware = false;
1634 	pathnode->path.parallel_safe = rel->consider_parallel &&
1635 		subpath->parallel_safe;
1636 	pathnode->path.parallel_workers = subpath->parallel_workers;
1637 
1638 	/*
1639 	 * Assume the output is unsorted, since we don't necessarily have pathkeys
1640 	 * to represent it.  (This might get overridden below.)
1641 	 */
1642 	pathnode->path.pathkeys = NIL;
1643 
1644 	pathnode->subpath = subpath;
1645 	pathnode->in_operators = sjinfo->semi_operators;
1646 	pathnode->uniq_exprs = sjinfo->semi_rhs_exprs;
1647 
1648 	/*
1649 	 * If the input is a relation and it has a unique index that proves the
1650 	 * semi_rhs_exprs are unique, then we don't need to do anything.  Note
1651 	 * that relation_has_unique_index_for automatically considers restriction
1652 	 * clauses for the rel, as well.
1653 	 */
1654 	if (rel->rtekind == RTE_RELATION && sjinfo->semi_can_btree &&
1655 		relation_has_unique_index_for(root, rel, NIL,
1656 									  sjinfo->semi_rhs_exprs,
1657 									  sjinfo->semi_operators))
1658 	{
1659 		pathnode->umethod = UNIQUE_PATH_NOOP;
1660 		pathnode->path.rows = rel->rows;
1661 		pathnode->path.startup_cost = subpath->startup_cost;
1662 		pathnode->path.total_cost = subpath->total_cost;
1663 		pathnode->path.pathkeys = subpath->pathkeys;
1664 
1665 		rel->cheapest_unique_path = (Path *) pathnode;
1666 
1667 		MemoryContextSwitchTo(oldcontext);
1668 
1669 		return pathnode;
1670 	}
1671 
1672 	/*
1673 	 * If the input is a subquery whose output must be unique already, then we
1674 	 * don't need to do anything.  The test for uniqueness has to consider
1675 	 * exactly which columns we are extracting; for example "SELECT DISTINCT
1676 	 * x,y" doesn't guarantee that x alone is distinct. So we cannot check for
1677 	 * this optimization unless semi_rhs_exprs consists only of simple Vars
1678 	 * referencing subquery outputs.  (Possibly we could do something with
1679 	 * expressions in the subquery outputs, too, but for now keep it simple.)
1680 	 */
1681 	if (rel->rtekind == RTE_SUBQUERY)
1682 	{
1683 		RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1684 
1685 		if (query_supports_distinctness(rte->subquery))
1686 		{
1687 			List	   *sub_tlist_colnos;
1688 
1689 			sub_tlist_colnos = translate_sub_tlist(sjinfo->semi_rhs_exprs,
1690 												   rel->relid);
1691 
1692 			if (sub_tlist_colnos &&
1693 				query_is_distinct_for(rte->subquery,
1694 									  sub_tlist_colnos,
1695 									  sjinfo->semi_operators))
1696 			{
1697 				pathnode->umethod = UNIQUE_PATH_NOOP;
1698 				pathnode->path.rows = rel->rows;
1699 				pathnode->path.startup_cost = subpath->startup_cost;
1700 				pathnode->path.total_cost = subpath->total_cost;
1701 				pathnode->path.pathkeys = subpath->pathkeys;
1702 
1703 				rel->cheapest_unique_path = (Path *) pathnode;
1704 
1705 				MemoryContextSwitchTo(oldcontext);
1706 
1707 				return pathnode;
1708 			}
1709 		}
1710 	}
1711 
1712 	/* Estimate number of output rows */
1713 	pathnode->path.rows = estimate_num_groups(root,
1714 											  sjinfo->semi_rhs_exprs,
1715 											  rel->rows,
1716 											  NULL);
1717 	numCols = list_length(sjinfo->semi_rhs_exprs);
1718 
1719 	if (sjinfo->semi_can_btree)
1720 	{
1721 		/*
1722 		 * Estimate cost for sort+unique implementation
1723 		 */
1724 		cost_sort(&sort_path, root, NIL,
1725 				  subpath->total_cost,
1726 				  rel->rows,
1727 				  subpath->pathtarget->width,
1728 				  0.0,
1729 				  work_mem,
1730 				  -1.0);
1731 
1732 		/*
1733 		 * Charge one cpu_operator_cost per comparison per input tuple. We
1734 		 * assume all columns get compared at most of the tuples. (XXX
1735 		 * probably this is an overestimate.)  This should agree with
1736 		 * create_upper_unique_path.
1737 		 */
1738 		sort_path.total_cost += cpu_operator_cost * rel->rows * numCols;
1739 	}
1740 
1741 	if (sjinfo->semi_can_hash)
1742 	{
1743 		/*
1744 		 * Estimate the overhead per hashtable entry at 64 bytes (same as in
1745 		 * planner.c).
1746 		 */
1747 		int			hashentrysize = subpath->pathtarget->width + 64;
1748 
1749 		if (hashentrysize * pathnode->path.rows > work_mem * 1024L)
1750 		{
1751 			/*
1752 			 * We should not try to hash.  Hack the SpecialJoinInfo to
1753 			 * remember this, in case we come through here again.
1754 			 */
1755 			sjinfo->semi_can_hash = false;
1756 		}
1757 		else
1758 			cost_agg(&agg_path, root,
1759 					 AGG_HASHED, NULL,
1760 					 numCols, pathnode->path.rows,
1761 					 NIL,
1762 					 subpath->startup_cost,
1763 					 subpath->total_cost,
1764 					 rel->rows);
1765 	}
1766 
1767 	if (sjinfo->semi_can_btree && sjinfo->semi_can_hash)
1768 	{
1769 		if (agg_path.total_cost < sort_path.total_cost)
1770 			pathnode->umethod = UNIQUE_PATH_HASH;
1771 		else
1772 			pathnode->umethod = UNIQUE_PATH_SORT;
1773 	}
1774 	else if (sjinfo->semi_can_btree)
1775 		pathnode->umethod = UNIQUE_PATH_SORT;
1776 	else if (sjinfo->semi_can_hash)
1777 		pathnode->umethod = UNIQUE_PATH_HASH;
1778 	else
1779 	{
1780 		/* we can get here only if we abandoned hashing above */
1781 		MemoryContextSwitchTo(oldcontext);
1782 		return NULL;
1783 	}
1784 
1785 	if (pathnode->umethod == UNIQUE_PATH_HASH)
1786 	{
1787 		pathnode->path.startup_cost = agg_path.startup_cost;
1788 		pathnode->path.total_cost = agg_path.total_cost;
1789 	}
1790 	else
1791 	{
1792 		pathnode->path.startup_cost = sort_path.startup_cost;
1793 		pathnode->path.total_cost = sort_path.total_cost;
1794 	}
1795 
1796 	rel->cheapest_unique_path = (Path *) pathnode;
1797 
1798 	MemoryContextSwitchTo(oldcontext);
1799 
1800 	return pathnode;
1801 }
1802 
1803 /*
1804  * create_gather_merge_path
1805  *
1806  *	  Creates a path corresponding to a gather merge scan, returning
1807  *	  the pathnode.
1808  */
1809 GatherMergePath *
create_gather_merge_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,List * pathkeys,Relids required_outer,double * rows)1810 create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1811 						 PathTarget *target, List *pathkeys,
1812 						 Relids required_outer, double *rows)
1813 {
1814 	GatherMergePath *pathnode = makeNode(GatherMergePath);
1815 	Cost		input_startup_cost = 0;
1816 	Cost		input_total_cost = 0;
1817 
1818 	Assert(subpath->parallel_safe);
1819 	Assert(pathkeys);
1820 
1821 	pathnode->path.pathtype = T_GatherMerge;
1822 	pathnode->path.parent = rel;
1823 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1824 														  required_outer);
1825 	pathnode->path.parallel_aware = false;
1826 
1827 	pathnode->subpath = subpath;
1828 	pathnode->num_workers = subpath->parallel_workers;
1829 	pathnode->path.pathkeys = pathkeys;
1830 	pathnode->path.pathtarget = target ? target : rel->reltarget;
1831 	pathnode->path.rows += subpath->rows;
1832 
1833 	if (pathkeys_contained_in(pathkeys, subpath->pathkeys))
1834 	{
1835 		/* Subpath is adequately ordered, we won't need to sort it */
1836 		input_startup_cost += subpath->startup_cost;
1837 		input_total_cost += subpath->total_cost;
1838 	}
1839 	else
1840 	{
1841 		/* We'll need to insert a Sort node, so include cost for that */
1842 		Path		sort_path;	/* dummy for result of cost_sort */
1843 
1844 		cost_sort(&sort_path,
1845 				  root,
1846 				  pathkeys,
1847 				  subpath->total_cost,
1848 				  subpath->rows,
1849 				  subpath->pathtarget->width,
1850 				  0.0,
1851 				  work_mem,
1852 				  -1);
1853 		input_startup_cost += sort_path.startup_cost;
1854 		input_total_cost += sort_path.total_cost;
1855 	}
1856 
1857 	cost_gather_merge(pathnode, root, rel, pathnode->path.param_info,
1858 					  input_startup_cost, input_total_cost, rows);
1859 
1860 	return pathnode;
1861 }
1862 
1863 /*
1864  * translate_sub_tlist - get subquery column numbers represented by tlist
1865  *
1866  * The given targetlist usually contains only Vars referencing the given relid.
1867  * Extract their varattnos (ie, the column numbers of the subquery) and return
1868  * as an integer List.
1869  *
1870  * If any of the tlist items is not a simple Var, we cannot determine whether
1871  * the subquery's uniqueness condition (if any) matches ours, so punt and
1872  * return NIL.
1873  */
1874 static List *
translate_sub_tlist(List * tlist,int relid)1875 translate_sub_tlist(List *tlist, int relid)
1876 {
1877 	List	   *result = NIL;
1878 	ListCell   *l;
1879 
1880 	foreach(l, tlist)
1881 	{
1882 		Var		   *var = (Var *) lfirst(l);
1883 
1884 		if (!var || !IsA(var, Var) ||
1885 			var->varno != relid)
1886 			return NIL;			/* punt */
1887 
1888 		result = lappend_int(result, var->varattno);
1889 	}
1890 	return result;
1891 }
1892 
1893 /*
1894  * create_gather_path
1895  *	  Creates a path corresponding to a gather scan, returning the
1896  *	  pathnode.
1897  *
1898  * 'rows' may optionally be set to override row estimates from other sources.
1899  */
1900 GatherPath *
create_gather_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,Relids required_outer,double * rows)1901 create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1902 				   PathTarget *target, Relids required_outer, double *rows)
1903 {
1904 	GatherPath *pathnode = makeNode(GatherPath);
1905 
1906 	Assert(subpath->parallel_safe);
1907 
1908 	pathnode->path.pathtype = T_Gather;
1909 	pathnode->path.parent = rel;
1910 	pathnode->path.pathtarget = target;
1911 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1912 														  required_outer);
1913 	pathnode->path.parallel_aware = false;
1914 	pathnode->path.parallel_safe = false;
1915 	pathnode->path.parallel_workers = 0;
1916 	pathnode->path.pathkeys = NIL;	/* Gather has unordered result */
1917 
1918 	pathnode->subpath = subpath;
1919 	pathnode->num_workers = subpath->parallel_workers;
1920 	pathnode->single_copy = false;
1921 
1922 	if (pathnode->num_workers == 0)
1923 	{
1924 		pathnode->path.pathkeys = subpath->pathkeys;
1925 		pathnode->num_workers = 1;
1926 		pathnode->single_copy = true;
1927 	}
1928 
1929 	cost_gather(pathnode, root, rel, pathnode->path.param_info, rows);
1930 
1931 	return pathnode;
1932 }
1933 
1934 /*
1935  * create_subqueryscan_path
1936  *	  Creates a path corresponding to a scan of a subquery,
1937  *	  returning the pathnode.
1938  */
1939 SubqueryScanPath *
create_subqueryscan_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * pathkeys,Relids required_outer)1940 create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath,
1941 						 List *pathkeys, Relids required_outer)
1942 {
1943 	SubqueryScanPath *pathnode = makeNode(SubqueryScanPath);
1944 
1945 	pathnode->path.pathtype = T_SubqueryScan;
1946 	pathnode->path.parent = rel;
1947 	pathnode->path.pathtarget = rel->reltarget;
1948 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
1949 														  required_outer);
1950 	pathnode->path.parallel_aware = false;
1951 	pathnode->path.parallel_safe = rel->consider_parallel &&
1952 		subpath->parallel_safe;
1953 	pathnode->path.parallel_workers = subpath->parallel_workers;
1954 	pathnode->path.pathkeys = pathkeys;
1955 	pathnode->subpath = subpath;
1956 
1957 	cost_subqueryscan(pathnode, root, rel, pathnode->path.param_info);
1958 
1959 	return pathnode;
1960 }
1961 
1962 /*
1963  * create_functionscan_path
1964  *	  Creates a path corresponding to a sequential scan of a function,
1965  *	  returning the pathnode.
1966  */
1967 Path *
create_functionscan_path(PlannerInfo * root,RelOptInfo * rel,List * pathkeys,Relids required_outer)1968 create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
1969 						 List *pathkeys, Relids required_outer)
1970 {
1971 	Path	   *pathnode = makeNode(Path);
1972 
1973 	pathnode->pathtype = T_FunctionScan;
1974 	pathnode->parent = rel;
1975 	pathnode->pathtarget = rel->reltarget;
1976 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
1977 													 required_outer);
1978 	pathnode->parallel_aware = false;
1979 	pathnode->parallel_safe = rel->consider_parallel;
1980 	pathnode->parallel_workers = 0;
1981 	pathnode->pathkeys = pathkeys;
1982 
1983 	cost_functionscan(pathnode, root, rel, pathnode->param_info);
1984 
1985 	return pathnode;
1986 }
1987 
1988 /*
1989  * create_tablefuncscan_path
1990  *	  Creates a path corresponding to a sequential scan of a table function,
1991  *	  returning the pathnode.
1992  */
1993 Path *
create_tablefuncscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)1994 create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel,
1995 						  Relids required_outer)
1996 {
1997 	Path	   *pathnode = makeNode(Path);
1998 
1999 	pathnode->pathtype = T_TableFuncScan;
2000 	pathnode->parent = rel;
2001 	pathnode->pathtarget = rel->reltarget;
2002 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2003 													 required_outer);
2004 	pathnode->parallel_aware = false;
2005 	pathnode->parallel_safe = rel->consider_parallel;
2006 	pathnode->parallel_workers = 0;
2007 	pathnode->pathkeys = NIL;	/* result is always unordered */
2008 
2009 	cost_tablefuncscan(pathnode, root, rel, pathnode->param_info);
2010 
2011 	return pathnode;
2012 }
2013 
2014 /*
2015  * create_valuesscan_path
2016  *	  Creates a path corresponding to a scan of a VALUES list,
2017  *	  returning the pathnode.
2018  */
2019 Path *
create_valuesscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)2020 create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
2021 					   Relids required_outer)
2022 {
2023 	Path	   *pathnode = makeNode(Path);
2024 
2025 	pathnode->pathtype = T_ValuesScan;
2026 	pathnode->parent = rel;
2027 	pathnode->pathtarget = rel->reltarget;
2028 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2029 													 required_outer);
2030 	pathnode->parallel_aware = false;
2031 	pathnode->parallel_safe = rel->consider_parallel;
2032 	pathnode->parallel_workers = 0;
2033 	pathnode->pathkeys = NIL;	/* result is always unordered */
2034 
2035 	cost_valuesscan(pathnode, root, rel, pathnode->param_info);
2036 
2037 	return pathnode;
2038 }
2039 
2040 /*
2041  * create_ctescan_path
2042  *	  Creates a path corresponding to a scan of a non-self-reference CTE,
2043  *	  returning the pathnode.
2044  */
2045 Path *
create_ctescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)2046 create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
2047 {
2048 	Path	   *pathnode = makeNode(Path);
2049 
2050 	pathnode->pathtype = T_CteScan;
2051 	pathnode->parent = rel;
2052 	pathnode->pathtarget = rel->reltarget;
2053 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2054 													 required_outer);
2055 	pathnode->parallel_aware = false;
2056 	pathnode->parallel_safe = rel->consider_parallel;
2057 	pathnode->parallel_workers = 0;
2058 	pathnode->pathkeys = NIL;	/* XXX for now, result is always unordered */
2059 
2060 	cost_ctescan(pathnode, root, rel, pathnode->param_info);
2061 
2062 	return pathnode;
2063 }
2064 
2065 /*
2066  * create_namedtuplestorescan_path
2067  *	  Creates a path corresponding to a scan of a named tuplestore, returning
2068  *	  the pathnode.
2069  */
2070 Path *
create_namedtuplestorescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)2071 create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel,
2072 								Relids required_outer)
2073 {
2074 	Path	   *pathnode = makeNode(Path);
2075 
2076 	pathnode->pathtype = T_NamedTuplestoreScan;
2077 	pathnode->parent = rel;
2078 	pathnode->pathtarget = rel->reltarget;
2079 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2080 													 required_outer);
2081 	pathnode->parallel_aware = false;
2082 	pathnode->parallel_safe = rel->consider_parallel;
2083 	pathnode->parallel_workers = 0;
2084 	pathnode->pathkeys = NIL;	/* result is always unordered */
2085 
2086 	cost_namedtuplestorescan(pathnode, root, rel, pathnode->param_info);
2087 
2088 	return pathnode;
2089 }
2090 
2091 /*
2092  * create_resultscan_path
2093  *	  Creates a path corresponding to a scan of an RTE_RESULT relation,
2094  *	  returning the pathnode.
2095  */
2096 Path *
create_resultscan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)2097 create_resultscan_path(PlannerInfo *root, RelOptInfo *rel,
2098 					   Relids required_outer)
2099 {
2100 	Path	   *pathnode = makeNode(Path);
2101 
2102 	pathnode->pathtype = T_Result;
2103 	pathnode->parent = rel;
2104 	pathnode->pathtarget = rel->reltarget;
2105 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2106 													 required_outer);
2107 	pathnode->parallel_aware = false;
2108 	pathnode->parallel_safe = rel->consider_parallel;
2109 	pathnode->parallel_workers = 0;
2110 	pathnode->pathkeys = NIL;	/* result is always unordered */
2111 
2112 	cost_resultscan(pathnode, root, rel, pathnode->param_info);
2113 
2114 	return pathnode;
2115 }
2116 
2117 /*
2118  * create_worktablescan_path
2119  *	  Creates a path corresponding to a scan of a self-reference CTE,
2120  *	  returning the pathnode.
2121  */
2122 Path *
create_worktablescan_path(PlannerInfo * root,RelOptInfo * rel,Relids required_outer)2123 create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
2124 						  Relids required_outer)
2125 {
2126 	Path	   *pathnode = makeNode(Path);
2127 
2128 	pathnode->pathtype = T_WorkTableScan;
2129 	pathnode->parent = rel;
2130 	pathnode->pathtarget = rel->reltarget;
2131 	pathnode->param_info = get_baserel_parampathinfo(root, rel,
2132 													 required_outer);
2133 	pathnode->parallel_aware = false;
2134 	pathnode->parallel_safe = rel->consider_parallel;
2135 	pathnode->parallel_workers = 0;
2136 	pathnode->pathkeys = NIL;	/* result is always unordered */
2137 
2138 	/* Cost is the same as for a regular CTE scan */
2139 	cost_ctescan(pathnode, root, rel, pathnode->param_info);
2140 
2141 	return pathnode;
2142 }
2143 
2144 /*
2145  * create_foreignscan_path
2146  *	  Creates a path corresponding to a scan of a foreign base table,
2147  *	  returning the pathnode.
2148  *
2149  * This function is never called from core Postgres; rather, it's expected
2150  * to be called by the GetForeignPaths function of a foreign data wrapper.
2151  * We make the FDW supply all fields of the path, since we do not have any way
2152  * to calculate them in core.  However, there is a usually-sane default for
2153  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2154  */
2155 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)2156 create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
2157 						PathTarget *target,
2158 						double rows, Cost startup_cost, Cost total_cost,
2159 						List *pathkeys,
2160 						Relids required_outer,
2161 						Path *fdw_outerpath,
2162 						List *fdw_private)
2163 {
2164 	ForeignPath *pathnode = makeNode(ForeignPath);
2165 
2166 	/* Historically some FDWs were confused about when to use this */
2167 	Assert(IS_SIMPLE_REL(rel));
2168 
2169 	pathnode->path.pathtype = T_ForeignScan;
2170 	pathnode->path.parent = rel;
2171 	pathnode->path.pathtarget = target ? target : rel->reltarget;
2172 	pathnode->path.param_info = get_baserel_parampathinfo(root, rel,
2173 														  required_outer);
2174 	pathnode->path.parallel_aware = false;
2175 	pathnode->path.parallel_safe = rel->consider_parallel;
2176 	pathnode->path.parallel_workers = 0;
2177 	pathnode->path.rows = rows;
2178 	pathnode->path.startup_cost = startup_cost;
2179 	pathnode->path.total_cost = total_cost;
2180 	pathnode->path.pathkeys = pathkeys;
2181 
2182 	pathnode->fdw_outerpath = fdw_outerpath;
2183 	pathnode->fdw_private = fdw_private;
2184 
2185 	return pathnode;
2186 }
2187 
2188 /*
2189  * create_foreign_join_path
2190  *	  Creates a path corresponding to a scan of a foreign join,
2191  *	  returning the pathnode.
2192  *
2193  * This function is never called from core Postgres; rather, it's expected
2194  * to be called by the GetForeignJoinPaths function of a foreign data wrapper.
2195  * We make the FDW supply all fields of the path, since we do not have any way
2196  * to calculate them in core.  However, there is a usually-sane default for
2197  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2198  */
2199 ForeignPath *
create_foreign_join_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)2200 create_foreign_join_path(PlannerInfo *root, RelOptInfo *rel,
2201 						 PathTarget *target,
2202 						 double rows, Cost startup_cost, Cost total_cost,
2203 						 List *pathkeys,
2204 						 Relids required_outer,
2205 						 Path *fdw_outerpath,
2206 						 List *fdw_private)
2207 {
2208 	ForeignPath *pathnode = makeNode(ForeignPath);
2209 
2210 	/*
2211 	 * We should use get_joinrel_parampathinfo to handle parameterized paths,
2212 	 * but the API of this function doesn't support it, and existing
2213 	 * extensions aren't yet trying to build such paths anyway.  For the
2214 	 * moment just throw an error if someone tries it; eventually we should
2215 	 * revisit this.
2216 	 */
2217 	if (!bms_is_empty(required_outer) || !bms_is_empty(rel->lateral_relids))
2218 		elog(ERROR, "parameterized foreign joins are not supported yet");
2219 
2220 	pathnode->path.pathtype = T_ForeignScan;
2221 	pathnode->path.parent = rel;
2222 	pathnode->path.pathtarget = target ? target : rel->reltarget;
2223 	pathnode->path.param_info = NULL;	/* XXX see above */
2224 	pathnode->path.parallel_aware = false;
2225 	pathnode->path.parallel_safe = rel->consider_parallel;
2226 	pathnode->path.parallel_workers = 0;
2227 	pathnode->path.rows = rows;
2228 	pathnode->path.startup_cost = startup_cost;
2229 	pathnode->path.total_cost = total_cost;
2230 	pathnode->path.pathkeys = pathkeys;
2231 
2232 	pathnode->fdw_outerpath = fdw_outerpath;
2233 	pathnode->fdw_private = fdw_private;
2234 
2235 	return pathnode;
2236 }
2237 
2238 /*
2239  * create_foreign_upper_path
2240  *	  Creates a path corresponding to an upper relation that's computed
2241  *	  directly by an FDW, returning the pathnode.
2242  *
2243  * This function is never called from core Postgres; rather, it's expected to
2244  * be called by the GetForeignUpperPaths function of a foreign data wrapper.
2245  * We make the FDW supply all fields of the path, since we do not have any way
2246  * to calculate them in core.  However, there is a usually-sane default for
2247  * the pathtarget (rel->reltarget), so we let a NULL for "target" select that.
2248  */
2249 ForeignPath *
create_foreign_upper_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,double rows,Cost startup_cost,Cost total_cost,List * pathkeys,Path * fdw_outerpath,List * fdw_private)2250 create_foreign_upper_path(PlannerInfo *root, RelOptInfo *rel,
2251 						  PathTarget *target,
2252 						  double rows, Cost startup_cost, Cost total_cost,
2253 						  List *pathkeys,
2254 						  Path *fdw_outerpath,
2255 						  List *fdw_private)
2256 {
2257 	ForeignPath *pathnode = makeNode(ForeignPath);
2258 
2259 	/*
2260 	 * Upper relations should never have any lateral references, since joining
2261 	 * is complete.
2262 	 */
2263 	Assert(bms_is_empty(rel->lateral_relids));
2264 
2265 	pathnode->path.pathtype = T_ForeignScan;
2266 	pathnode->path.parent = rel;
2267 	pathnode->path.pathtarget = target ? target : rel->reltarget;
2268 	pathnode->path.param_info = NULL;
2269 	pathnode->path.parallel_aware = false;
2270 	pathnode->path.parallel_safe = rel->consider_parallel;
2271 	pathnode->path.parallel_workers = 0;
2272 	pathnode->path.rows = rows;
2273 	pathnode->path.startup_cost = startup_cost;
2274 	pathnode->path.total_cost = total_cost;
2275 	pathnode->path.pathkeys = pathkeys;
2276 
2277 	pathnode->fdw_outerpath = fdw_outerpath;
2278 	pathnode->fdw_private = fdw_private;
2279 
2280 	return pathnode;
2281 }
2282 
2283 /*
2284  * calc_nestloop_required_outer
2285  *	  Compute the required_outer set for a nestloop join path
2286  *
2287  * Note: result must not share storage with either input
2288  */
2289 Relids
calc_nestloop_required_outer(Relids outerrelids,Relids outer_paramrels,Relids innerrelids,Relids inner_paramrels)2290 calc_nestloop_required_outer(Relids outerrelids,
2291 							 Relids outer_paramrels,
2292 							 Relids innerrelids,
2293 							 Relids inner_paramrels)
2294 {
2295 	Relids		required_outer;
2296 
2297 	/* inner_path can require rels from outer path, but not vice versa */
2298 	Assert(!bms_overlap(outer_paramrels, innerrelids));
2299 	/* easy case if inner path is not parameterized */
2300 	if (!inner_paramrels)
2301 		return bms_copy(outer_paramrels);
2302 	/* else, form the union ... */
2303 	required_outer = bms_union(outer_paramrels, inner_paramrels);
2304 	/* ... and remove any mention of now-satisfied outer rels */
2305 	required_outer = bms_del_members(required_outer,
2306 									 outerrelids);
2307 	/* maintain invariant that required_outer is exactly NULL if empty */
2308 	if (bms_is_empty(required_outer))
2309 	{
2310 		bms_free(required_outer);
2311 		required_outer = NULL;
2312 	}
2313 	return required_outer;
2314 }
2315 
2316 /*
2317  * calc_non_nestloop_required_outer
2318  *	  Compute the required_outer set for a merge or hash join path
2319  *
2320  * Note: result must not share storage with either input
2321  */
2322 Relids
calc_non_nestloop_required_outer(Path * outer_path,Path * inner_path)2323 calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path)
2324 {
2325 	Relids		outer_paramrels = PATH_REQ_OUTER(outer_path);
2326 	Relids		inner_paramrels = PATH_REQ_OUTER(inner_path);
2327 	Relids		required_outer;
2328 
2329 	/* neither path can require rels from the other */
2330 	Assert(!bms_overlap(outer_paramrels, inner_path->parent->relids));
2331 	Assert(!bms_overlap(inner_paramrels, outer_path->parent->relids));
2332 	/* form the union ... */
2333 	required_outer = bms_union(outer_paramrels, inner_paramrels);
2334 	/* we do not need an explicit test for empty; bms_union gets it right */
2335 	return required_outer;
2336 }
2337 
2338 /*
2339  * create_nestloop_path
2340  *	  Creates a pathnode corresponding to a nestloop join between two
2341  *	  relations.
2342  *
2343  * 'joinrel' is the join relation.
2344  * 'jointype' is the type of join required
2345  * 'workspace' is the result from initial_cost_nestloop
2346  * 'extra' contains various information about the join
2347  * 'outer_path' is the outer path
2348  * 'inner_path' is the inner path
2349  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2350  * 'pathkeys' are the path keys of the new join path
2351  * 'required_outer' is the set of required outer rels
2352  *
2353  * Returns the resulting path node.
2354  */
2355 NestPath *
create_nestloop_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,JoinPathExtraData * extra,Path * outer_path,Path * inner_path,List * restrict_clauses,List * pathkeys,Relids required_outer)2356 create_nestloop_path(PlannerInfo *root,
2357 					 RelOptInfo *joinrel,
2358 					 JoinType jointype,
2359 					 JoinCostWorkspace *workspace,
2360 					 JoinPathExtraData *extra,
2361 					 Path *outer_path,
2362 					 Path *inner_path,
2363 					 List *restrict_clauses,
2364 					 List *pathkeys,
2365 					 Relids required_outer)
2366 {
2367 	NestPath   *pathnode = makeNode(NestPath);
2368 	Relids		inner_req_outer = PATH_REQ_OUTER(inner_path);
2369 
2370 	/*
2371 	 * If the inner path is parameterized by the outer, we must drop any
2372 	 * restrict_clauses that are due to be moved into the inner path.  We have
2373 	 * to do this now, rather than postpone the work till createplan time,
2374 	 * because the restrict_clauses list can affect the size and cost
2375 	 * estimates for this path.
2376 	 */
2377 	if (bms_overlap(inner_req_outer, outer_path->parent->relids))
2378 	{
2379 		Relids		inner_and_outer = bms_union(inner_path->parent->relids,
2380 												inner_req_outer);
2381 		List	   *jclauses = NIL;
2382 		ListCell   *lc;
2383 
2384 		foreach(lc, restrict_clauses)
2385 		{
2386 			RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2387 
2388 			if (!join_clause_is_movable_into(rinfo,
2389 											 inner_path->parent->relids,
2390 											 inner_and_outer))
2391 				jclauses = lappend(jclauses, rinfo);
2392 		}
2393 		restrict_clauses = jclauses;
2394 	}
2395 
2396 	pathnode->path.pathtype = T_NestLoop;
2397 	pathnode->path.parent = joinrel;
2398 	pathnode->path.pathtarget = joinrel->reltarget;
2399 	pathnode->path.param_info =
2400 		get_joinrel_parampathinfo(root,
2401 								  joinrel,
2402 								  outer_path,
2403 								  inner_path,
2404 								  extra->sjinfo,
2405 								  required_outer,
2406 								  &restrict_clauses);
2407 	pathnode->path.parallel_aware = false;
2408 	pathnode->path.parallel_safe = joinrel->consider_parallel &&
2409 		outer_path->parallel_safe && inner_path->parallel_safe;
2410 	/* This is a foolish way to estimate parallel_workers, but for now... */
2411 	pathnode->path.parallel_workers = outer_path->parallel_workers;
2412 	pathnode->path.pathkeys = pathkeys;
2413 	pathnode->jointype = jointype;
2414 	pathnode->inner_unique = extra->inner_unique;
2415 	pathnode->outerjoinpath = outer_path;
2416 	pathnode->innerjoinpath = inner_path;
2417 	pathnode->joinrestrictinfo = restrict_clauses;
2418 
2419 	final_cost_nestloop(root, pathnode, workspace, extra);
2420 
2421 	return pathnode;
2422 }
2423 
2424 /*
2425  * create_mergejoin_path
2426  *	  Creates a pathnode corresponding to a mergejoin join between
2427  *	  two relations
2428  *
2429  * 'joinrel' is the join relation
2430  * 'jointype' is the type of join required
2431  * 'workspace' is the result from initial_cost_mergejoin
2432  * 'extra' contains various information about the join
2433  * 'outer_path' is the outer path
2434  * 'inner_path' is the inner path
2435  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2436  * 'pathkeys' are the path keys of the new join path
2437  * 'required_outer' is the set of required outer rels
2438  * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
2439  *		(this should be a subset of the restrict_clauses list)
2440  * 'outersortkeys' are the sort varkeys for the outer relation
2441  * 'innersortkeys' are the sort varkeys for the inner relation
2442  */
2443 MergePath *
create_mergejoin_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,JoinPathExtraData * extra,Path * outer_path,Path * inner_path,List * restrict_clauses,List * pathkeys,Relids required_outer,List * mergeclauses,List * outersortkeys,List * innersortkeys)2444 create_mergejoin_path(PlannerInfo *root,
2445 					  RelOptInfo *joinrel,
2446 					  JoinType jointype,
2447 					  JoinCostWorkspace *workspace,
2448 					  JoinPathExtraData *extra,
2449 					  Path *outer_path,
2450 					  Path *inner_path,
2451 					  List *restrict_clauses,
2452 					  List *pathkeys,
2453 					  Relids required_outer,
2454 					  List *mergeclauses,
2455 					  List *outersortkeys,
2456 					  List *innersortkeys)
2457 {
2458 	MergePath  *pathnode = makeNode(MergePath);
2459 
2460 	pathnode->jpath.path.pathtype = T_MergeJoin;
2461 	pathnode->jpath.path.parent = joinrel;
2462 	pathnode->jpath.path.pathtarget = joinrel->reltarget;
2463 	pathnode->jpath.path.param_info =
2464 		get_joinrel_parampathinfo(root,
2465 								  joinrel,
2466 								  outer_path,
2467 								  inner_path,
2468 								  extra->sjinfo,
2469 								  required_outer,
2470 								  &restrict_clauses);
2471 	pathnode->jpath.path.parallel_aware = false;
2472 	pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2473 		outer_path->parallel_safe && inner_path->parallel_safe;
2474 	/* This is a foolish way to estimate parallel_workers, but for now... */
2475 	pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2476 	pathnode->jpath.path.pathkeys = pathkeys;
2477 	pathnode->jpath.jointype = jointype;
2478 	pathnode->jpath.inner_unique = extra->inner_unique;
2479 	pathnode->jpath.outerjoinpath = outer_path;
2480 	pathnode->jpath.innerjoinpath = inner_path;
2481 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
2482 	pathnode->path_mergeclauses = mergeclauses;
2483 	pathnode->outersortkeys = outersortkeys;
2484 	pathnode->innersortkeys = innersortkeys;
2485 	/* pathnode->skip_mark_restore will be set by final_cost_mergejoin */
2486 	/* pathnode->materialize_inner will be set by final_cost_mergejoin */
2487 
2488 	final_cost_mergejoin(root, pathnode, workspace, extra);
2489 
2490 	return pathnode;
2491 }
2492 
2493 /*
2494  * create_hashjoin_path
2495  *	  Creates a pathnode corresponding to a hash join between two relations.
2496  *
2497  * 'joinrel' is the join relation
2498  * 'jointype' is the type of join required
2499  * 'workspace' is the result from initial_cost_hashjoin
2500  * 'extra' contains various information about the join
2501  * 'outer_path' is the cheapest outer path
2502  * 'inner_path' is the cheapest inner path
2503  * 'parallel_hash' to select Parallel Hash of inner path (shared hash table)
2504  * 'restrict_clauses' are the RestrictInfo nodes to apply at the join
2505  * 'required_outer' is the set of required outer rels
2506  * 'hashclauses' are the RestrictInfo nodes to use as hash clauses
2507  *		(this should be a subset of the restrict_clauses list)
2508  */
2509 HashPath *
create_hashjoin_path(PlannerInfo * root,RelOptInfo * joinrel,JoinType jointype,JoinCostWorkspace * workspace,JoinPathExtraData * extra,Path * outer_path,Path * inner_path,bool parallel_hash,List * restrict_clauses,Relids required_outer,List * hashclauses)2510 create_hashjoin_path(PlannerInfo *root,
2511 					 RelOptInfo *joinrel,
2512 					 JoinType jointype,
2513 					 JoinCostWorkspace *workspace,
2514 					 JoinPathExtraData *extra,
2515 					 Path *outer_path,
2516 					 Path *inner_path,
2517 					 bool parallel_hash,
2518 					 List *restrict_clauses,
2519 					 Relids required_outer,
2520 					 List *hashclauses)
2521 {
2522 	HashPath   *pathnode = makeNode(HashPath);
2523 
2524 	pathnode->jpath.path.pathtype = T_HashJoin;
2525 	pathnode->jpath.path.parent = joinrel;
2526 	pathnode->jpath.path.pathtarget = joinrel->reltarget;
2527 	pathnode->jpath.path.param_info =
2528 		get_joinrel_parampathinfo(root,
2529 								  joinrel,
2530 								  outer_path,
2531 								  inner_path,
2532 								  extra->sjinfo,
2533 								  required_outer,
2534 								  &restrict_clauses);
2535 	pathnode->jpath.path.parallel_aware =
2536 		joinrel->consider_parallel && parallel_hash;
2537 	pathnode->jpath.path.parallel_safe = joinrel->consider_parallel &&
2538 		outer_path->parallel_safe && inner_path->parallel_safe;
2539 	/* This is a foolish way to estimate parallel_workers, but for now... */
2540 	pathnode->jpath.path.parallel_workers = outer_path->parallel_workers;
2541 
2542 	/*
2543 	 * A hashjoin never has pathkeys, since its output ordering is
2544 	 * unpredictable due to possible batching.  XXX If the inner relation is
2545 	 * small enough, we could instruct the executor that it must not batch,
2546 	 * and then we could assume that the output inherits the outer relation's
2547 	 * ordering, which might save a sort step.  However there is considerable
2548 	 * downside if our estimate of the inner relation size is badly off. For
2549 	 * the moment we don't risk it.  (Note also that if we wanted to take this
2550 	 * seriously, joinpath.c would have to consider many more paths for the
2551 	 * outer rel than it does now.)
2552 	 */
2553 	pathnode->jpath.path.pathkeys = NIL;
2554 	pathnode->jpath.jointype = jointype;
2555 	pathnode->jpath.inner_unique = extra->inner_unique;
2556 	pathnode->jpath.outerjoinpath = outer_path;
2557 	pathnode->jpath.innerjoinpath = inner_path;
2558 	pathnode->jpath.joinrestrictinfo = restrict_clauses;
2559 	pathnode->path_hashclauses = hashclauses;
2560 	/* final_cost_hashjoin will fill in pathnode->num_batches */
2561 
2562 	final_cost_hashjoin(root, pathnode, workspace, extra);
2563 
2564 	return pathnode;
2565 }
2566 
2567 /*
2568  * create_projection_path
2569  *	  Creates a pathnode that represents performing a projection.
2570  *
2571  * 'rel' is the parent relation associated with the result
2572  * 'subpath' is the path representing the source of data
2573  * 'target' is the PathTarget to be computed
2574  */
2575 ProjectionPath *
create_projection_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target)2576 create_projection_path(PlannerInfo *root,
2577 					   RelOptInfo *rel,
2578 					   Path *subpath,
2579 					   PathTarget *target)
2580 {
2581 	ProjectionPath *pathnode = makeNode(ProjectionPath);
2582 	PathTarget *oldtarget;
2583 
2584 	/*
2585 	 * We mustn't put a ProjectionPath directly above another; it's useless
2586 	 * and will confuse create_projection_plan.  Rather than making sure all
2587 	 * callers handle that, let's implement it here, by stripping off any
2588 	 * ProjectionPath in what we're given.  Given this rule, there won't be
2589 	 * more than one.
2590 	 */
2591 	if (IsA(subpath, ProjectionPath))
2592 	{
2593 		ProjectionPath *subpp = (ProjectionPath *) subpath;
2594 
2595 		Assert(subpp->path.parent == rel);
2596 		subpath = subpp->subpath;
2597 		Assert(!IsA(subpath, ProjectionPath));
2598 	}
2599 
2600 	pathnode->path.pathtype = T_Result;
2601 	pathnode->path.parent = rel;
2602 	pathnode->path.pathtarget = target;
2603 	/* For now, assume we are above any joins, so no parameterization */
2604 	pathnode->path.param_info = NULL;
2605 	pathnode->path.parallel_aware = false;
2606 	pathnode->path.parallel_safe = rel->consider_parallel &&
2607 		subpath->parallel_safe &&
2608 		is_parallel_safe(root, (Node *) target->exprs);
2609 	pathnode->path.parallel_workers = subpath->parallel_workers;
2610 	/* Projection does not change the sort order */
2611 	pathnode->path.pathkeys = subpath->pathkeys;
2612 
2613 	pathnode->subpath = subpath;
2614 
2615 	/*
2616 	 * We might not need a separate Result node.  If the input plan node type
2617 	 * can project, we can just tell it to project something else.  Or, if it
2618 	 * can't project but the desired target has the same expression list as
2619 	 * what the input will produce anyway, we can still give it the desired
2620 	 * tlist (possibly changing its ressortgroupref labels, but nothing else).
2621 	 * Note: in the latter case, create_projection_plan has to recheck our
2622 	 * conclusion; see comments therein.
2623 	 */
2624 	oldtarget = subpath->pathtarget;
2625 	if (is_projection_capable_path(subpath) ||
2626 		equal(oldtarget->exprs, target->exprs))
2627 	{
2628 		/* No separate Result node needed */
2629 		pathnode->dummypp = true;
2630 
2631 		/*
2632 		 * Set cost of plan as subpath's cost, adjusted for tlist replacement.
2633 		 */
2634 		pathnode->path.rows = subpath->rows;
2635 		pathnode->path.startup_cost = subpath->startup_cost +
2636 			(target->cost.startup - oldtarget->cost.startup);
2637 		pathnode->path.total_cost = subpath->total_cost +
2638 			(target->cost.startup - oldtarget->cost.startup) +
2639 			(target->cost.per_tuple - oldtarget->cost.per_tuple) * subpath->rows;
2640 	}
2641 	else
2642 	{
2643 		/* We really do need the Result node */
2644 		pathnode->dummypp = false;
2645 
2646 		/*
2647 		 * The Result node's cost is cpu_tuple_cost per row, plus the cost of
2648 		 * evaluating the tlist.  There is no qual to worry about.
2649 		 */
2650 		pathnode->path.rows = subpath->rows;
2651 		pathnode->path.startup_cost = subpath->startup_cost +
2652 			target->cost.startup;
2653 		pathnode->path.total_cost = subpath->total_cost +
2654 			target->cost.startup +
2655 			(cpu_tuple_cost + target->cost.per_tuple) * subpath->rows;
2656 	}
2657 
2658 	return pathnode;
2659 }
2660 
2661 /*
2662  * apply_projection_to_path
2663  *	  Add a projection step, or just apply the target directly to given path.
2664  *
2665  * This has the same net effect as create_projection_path(), except that if
2666  * a separate Result plan node isn't needed, we just replace the given path's
2667  * pathtarget with the desired one.  This must be used only when the caller
2668  * knows that the given path isn't referenced elsewhere and so can be modified
2669  * in-place.
2670  *
2671  * If the input path is a GatherPath or GatherMergePath, we try to push the
2672  * new target down to its input as well; this is a yet more invasive
2673  * modification of the input path, which create_projection_path() can't do.
2674  *
2675  * Note that we mustn't change the source path's parent link; so when it is
2676  * add_path'd to "rel" things will be a bit inconsistent.  So far that has
2677  * not caused any trouble.
2678  *
2679  * 'rel' is the parent relation associated with the result
2680  * 'path' is the path representing the source of data
2681  * 'target' is the PathTarget to be computed
2682  */
2683 Path *
apply_projection_to_path(PlannerInfo * root,RelOptInfo * rel,Path * path,PathTarget * target)2684 apply_projection_to_path(PlannerInfo *root,
2685 						 RelOptInfo *rel,
2686 						 Path *path,
2687 						 PathTarget *target)
2688 {
2689 	QualCost	oldcost;
2690 
2691 	/*
2692 	 * If given path can't project, we might need a Result node, so make a
2693 	 * separate ProjectionPath.
2694 	 */
2695 	if (!is_projection_capable_path(path))
2696 		return (Path *) create_projection_path(root, rel, path, target);
2697 
2698 	/*
2699 	 * We can just jam the desired tlist into the existing path, being sure to
2700 	 * update its cost estimates appropriately.
2701 	 */
2702 	oldcost = path->pathtarget->cost;
2703 	path->pathtarget = target;
2704 
2705 	path->startup_cost += target->cost.startup - oldcost.startup;
2706 	path->total_cost += target->cost.startup - oldcost.startup +
2707 		(target->cost.per_tuple - oldcost.per_tuple) * path->rows;
2708 
2709 	/*
2710 	 * If the path happens to be a Gather or GatherMerge path, we'd like to
2711 	 * arrange for the subpath to return the required target list so that
2712 	 * workers can help project.  But if there is something that is not
2713 	 * parallel-safe in the target expressions, then we can't.
2714 	 */
2715 	if ((IsA(path, GatherPath) ||IsA(path, GatherMergePath)) &&
2716 		is_parallel_safe(root, (Node *) target->exprs))
2717 	{
2718 		/*
2719 		 * We always use create_projection_path here, even if the subpath is
2720 		 * projection-capable, so as to avoid modifying the subpath in place.
2721 		 * It seems unlikely at present that there could be any other
2722 		 * references to the subpath, but better safe than sorry.
2723 		 *
2724 		 * Note that we don't change the parallel path's cost estimates; it
2725 		 * might be appropriate to do so, to reflect the fact that the bulk of
2726 		 * the target evaluation will happen in workers.
2727 		 */
2728 		if (IsA(path, GatherPath))
2729 		{
2730 			GatherPath *gpath = (GatherPath *) path;
2731 
2732 			gpath->subpath = (Path *)
2733 				create_projection_path(root,
2734 									   gpath->subpath->parent,
2735 									   gpath->subpath,
2736 									   target);
2737 		}
2738 		else
2739 		{
2740 			GatherMergePath *gmpath = (GatherMergePath *) path;
2741 
2742 			gmpath->subpath = (Path *)
2743 				create_projection_path(root,
2744 									   gmpath->subpath->parent,
2745 									   gmpath->subpath,
2746 									   target);
2747 		}
2748 	}
2749 	else if (path->parallel_safe &&
2750 			 !is_parallel_safe(root, (Node *) target->exprs))
2751 	{
2752 		/*
2753 		 * We're inserting a parallel-restricted target list into a path
2754 		 * currently marked parallel-safe, so we have to mark it as no longer
2755 		 * safe.
2756 		 */
2757 		path->parallel_safe = false;
2758 	}
2759 
2760 	return path;
2761 }
2762 
2763 /*
2764  * create_set_projection_path
2765  *	  Creates a pathnode that represents performing a projection that
2766  *	  includes set-returning functions.
2767  *
2768  * 'rel' is the parent relation associated with the result
2769  * 'subpath' is the path representing the source of data
2770  * 'target' is the PathTarget to be computed
2771  */
2772 ProjectSetPath *
create_set_projection_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target)2773 create_set_projection_path(PlannerInfo *root,
2774 						   RelOptInfo *rel,
2775 						   Path *subpath,
2776 						   PathTarget *target)
2777 {
2778 	ProjectSetPath *pathnode = makeNode(ProjectSetPath);
2779 	double		tlist_rows;
2780 	ListCell   *lc;
2781 
2782 	pathnode->path.pathtype = T_ProjectSet;
2783 	pathnode->path.parent = rel;
2784 	pathnode->path.pathtarget = target;
2785 	/* For now, assume we are above any joins, so no parameterization */
2786 	pathnode->path.param_info = NULL;
2787 	pathnode->path.parallel_aware = false;
2788 	pathnode->path.parallel_safe = rel->consider_parallel &&
2789 		subpath->parallel_safe &&
2790 		is_parallel_safe(root, (Node *) target->exprs);
2791 	pathnode->path.parallel_workers = subpath->parallel_workers;
2792 	/* Projection does not change the sort order XXX? */
2793 	pathnode->path.pathkeys = subpath->pathkeys;
2794 
2795 	pathnode->subpath = subpath;
2796 
2797 	/*
2798 	 * Estimate number of rows produced by SRFs for each row of input; if
2799 	 * there's more than one in this node, use the maximum.
2800 	 */
2801 	tlist_rows = 1;
2802 	foreach(lc, target->exprs)
2803 	{
2804 		Node	   *node = (Node *) lfirst(lc);
2805 		double		itemrows;
2806 
2807 		itemrows = expression_returns_set_rows(root, node);
2808 		if (tlist_rows < itemrows)
2809 			tlist_rows = itemrows;
2810 	}
2811 
2812 	/*
2813 	 * In addition to the cost of evaluating the tlist, charge cpu_tuple_cost
2814 	 * per input row, and half of cpu_tuple_cost for each added output row.
2815 	 * This is slightly bizarre maybe, but it's what 9.6 did; we may revisit
2816 	 * this estimate later.
2817 	 */
2818 	pathnode->path.rows = subpath->rows * tlist_rows;
2819 	pathnode->path.startup_cost = subpath->startup_cost +
2820 		target->cost.startup;
2821 	pathnode->path.total_cost = subpath->total_cost +
2822 		target->cost.startup +
2823 		(cpu_tuple_cost + target->cost.per_tuple) * subpath->rows +
2824 		(pathnode->path.rows - subpath->rows) * cpu_tuple_cost / 2;
2825 
2826 	return pathnode;
2827 }
2828 
2829 /*
2830  * create_sort_path
2831  *	  Creates a pathnode that represents performing an explicit sort.
2832  *
2833  * 'rel' is the parent relation associated with the result
2834  * 'subpath' is the path representing the source of data
2835  * 'pathkeys' represents the desired sort order
2836  * 'limit_tuples' is the estimated bound on the number of output tuples,
2837  *		or -1 if no LIMIT or couldn't estimate
2838  */
2839 SortPath *
create_sort_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * pathkeys,double limit_tuples)2840 create_sort_path(PlannerInfo *root,
2841 				 RelOptInfo *rel,
2842 				 Path *subpath,
2843 				 List *pathkeys,
2844 				 double limit_tuples)
2845 {
2846 	SortPath   *pathnode = makeNode(SortPath);
2847 
2848 	pathnode->path.pathtype = T_Sort;
2849 	pathnode->path.parent = rel;
2850 	/* Sort doesn't project, so use source path's pathtarget */
2851 	pathnode->path.pathtarget = subpath->pathtarget;
2852 	/* For now, assume we are above any joins, so no parameterization */
2853 	pathnode->path.param_info = NULL;
2854 	pathnode->path.parallel_aware = false;
2855 	pathnode->path.parallel_safe = rel->consider_parallel &&
2856 		subpath->parallel_safe;
2857 	pathnode->path.parallel_workers = subpath->parallel_workers;
2858 	pathnode->path.pathkeys = pathkeys;
2859 
2860 	pathnode->subpath = subpath;
2861 
2862 	cost_sort(&pathnode->path, root, pathkeys,
2863 			  subpath->total_cost,
2864 			  subpath->rows,
2865 			  subpath->pathtarget->width,
2866 			  0.0,				/* XXX comparison_cost shouldn't be 0? */
2867 			  work_mem, limit_tuples);
2868 
2869 	return pathnode;
2870 }
2871 
2872 /*
2873  * create_group_path
2874  *	  Creates a pathnode that represents performing grouping of presorted input
2875  *
2876  * 'rel' is the parent relation associated with the result
2877  * 'subpath' is the path representing the source of data
2878  * 'target' is the PathTarget to be computed
2879  * 'groupClause' is a list of SortGroupClause's representing the grouping
2880  * 'qual' is the HAVING quals if any
2881  * 'numGroups' is the estimated number of groups
2882  */
2883 GroupPath *
create_group_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * groupClause,List * qual,double numGroups)2884 create_group_path(PlannerInfo *root,
2885 				  RelOptInfo *rel,
2886 				  Path *subpath,
2887 				  List *groupClause,
2888 				  List *qual,
2889 				  double numGroups)
2890 {
2891 	GroupPath  *pathnode = makeNode(GroupPath);
2892 	PathTarget *target = rel->reltarget;
2893 
2894 	pathnode->path.pathtype = T_Group;
2895 	pathnode->path.parent = rel;
2896 	pathnode->path.pathtarget = target;
2897 	/* For now, assume we are above any joins, so no parameterization */
2898 	pathnode->path.param_info = NULL;
2899 	pathnode->path.parallel_aware = false;
2900 	pathnode->path.parallel_safe = rel->consider_parallel &&
2901 		subpath->parallel_safe;
2902 	pathnode->path.parallel_workers = subpath->parallel_workers;
2903 	/* Group doesn't change sort ordering */
2904 	pathnode->path.pathkeys = subpath->pathkeys;
2905 
2906 	pathnode->subpath = subpath;
2907 
2908 	pathnode->groupClause = groupClause;
2909 	pathnode->qual = qual;
2910 
2911 	cost_group(&pathnode->path, root,
2912 			   list_length(groupClause),
2913 			   numGroups,
2914 			   qual,
2915 			   subpath->startup_cost, subpath->total_cost,
2916 			   subpath->rows);
2917 
2918 	/* add tlist eval cost for each output row */
2919 	pathnode->path.startup_cost += target->cost.startup;
2920 	pathnode->path.total_cost += target->cost.startup +
2921 		target->cost.per_tuple * pathnode->path.rows;
2922 
2923 	return pathnode;
2924 }
2925 
2926 /*
2927  * create_upper_unique_path
2928  *	  Creates a pathnode that represents performing an explicit Unique step
2929  *	  on presorted input.
2930  *
2931  * This produces a Unique plan node, but the use-case is so different from
2932  * create_unique_path that it doesn't seem worth trying to merge the two.
2933  *
2934  * 'rel' is the parent relation associated with the result
2935  * 'subpath' is the path representing the source of data
2936  * 'numCols' is the number of grouping columns
2937  * 'numGroups' is the estimated number of groups
2938  *
2939  * The input path must be sorted on the grouping columns, plus possibly
2940  * additional columns; so the first numCols pathkeys are the grouping columns
2941  */
2942 UpperUniquePath *
create_upper_unique_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,int numCols,double numGroups)2943 create_upper_unique_path(PlannerInfo *root,
2944 						 RelOptInfo *rel,
2945 						 Path *subpath,
2946 						 int numCols,
2947 						 double numGroups)
2948 {
2949 	UpperUniquePath *pathnode = makeNode(UpperUniquePath);
2950 
2951 	pathnode->path.pathtype = T_Unique;
2952 	pathnode->path.parent = rel;
2953 	/* Unique doesn't project, so use source path's pathtarget */
2954 	pathnode->path.pathtarget = subpath->pathtarget;
2955 	/* For now, assume we are above any joins, so no parameterization */
2956 	pathnode->path.param_info = NULL;
2957 	pathnode->path.parallel_aware = false;
2958 	pathnode->path.parallel_safe = rel->consider_parallel &&
2959 		subpath->parallel_safe;
2960 	pathnode->path.parallel_workers = subpath->parallel_workers;
2961 	/* Unique doesn't change the input ordering */
2962 	pathnode->path.pathkeys = subpath->pathkeys;
2963 
2964 	pathnode->subpath = subpath;
2965 	pathnode->numkeys = numCols;
2966 
2967 	/*
2968 	 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2969 	 * all columns get compared at most of the tuples.  (XXX probably this is
2970 	 * an overestimate.)
2971 	 */
2972 	pathnode->path.startup_cost = subpath->startup_cost;
2973 	pathnode->path.total_cost = subpath->total_cost +
2974 		cpu_operator_cost * subpath->rows * numCols;
2975 	pathnode->path.rows = numGroups;
2976 
2977 	return pathnode;
2978 }
2979 
2980 /*
2981  * create_agg_path
2982  *	  Creates a pathnode that represents performing aggregation/grouping
2983  *
2984  * 'rel' is the parent relation associated with the result
2985  * 'subpath' is the path representing the source of data
2986  * 'target' is the PathTarget to be computed
2987  * 'aggstrategy' is the Agg node's basic implementation strategy
2988  * 'aggsplit' is the Agg node's aggregate-splitting mode
2989  * 'groupClause' is a list of SortGroupClause's representing the grouping
2990  * 'qual' is the HAVING quals if any
2991  * 'aggcosts' contains cost info about the aggregate functions to be computed
2992  * 'numGroups' is the estimated number of groups (1 if not grouping)
2993  */
2994 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)2995 create_agg_path(PlannerInfo *root,
2996 				RelOptInfo *rel,
2997 				Path *subpath,
2998 				PathTarget *target,
2999 				AggStrategy aggstrategy,
3000 				AggSplit aggsplit,
3001 				List *groupClause,
3002 				List *qual,
3003 				const AggClauseCosts *aggcosts,
3004 				double numGroups)
3005 {
3006 	AggPath    *pathnode = makeNode(AggPath);
3007 
3008 	pathnode->path.pathtype = T_Agg;
3009 	pathnode->path.parent = rel;
3010 	pathnode->path.pathtarget = target;
3011 	/* For now, assume we are above any joins, so no parameterization */
3012 	pathnode->path.param_info = NULL;
3013 	pathnode->path.parallel_aware = false;
3014 	pathnode->path.parallel_safe = rel->consider_parallel &&
3015 		subpath->parallel_safe;
3016 	pathnode->path.parallel_workers = subpath->parallel_workers;
3017 	if (aggstrategy == AGG_SORTED)
3018 		pathnode->path.pathkeys = subpath->pathkeys;	/* preserves order */
3019 	else
3020 		pathnode->path.pathkeys = NIL;	/* output is unordered */
3021 	pathnode->subpath = subpath;
3022 
3023 	pathnode->aggstrategy = aggstrategy;
3024 	pathnode->aggsplit = aggsplit;
3025 	pathnode->numGroups = numGroups;
3026 	pathnode->groupClause = groupClause;
3027 	pathnode->qual = qual;
3028 
3029 	cost_agg(&pathnode->path, root,
3030 			 aggstrategy, aggcosts,
3031 			 list_length(groupClause), numGroups,
3032 			 qual,
3033 			 subpath->startup_cost, subpath->total_cost,
3034 			 subpath->rows);
3035 
3036 	/* add tlist eval cost for each output row */
3037 	pathnode->path.startup_cost += target->cost.startup;
3038 	pathnode->path.total_cost += target->cost.startup +
3039 		target->cost.per_tuple * pathnode->path.rows;
3040 
3041 	return pathnode;
3042 }
3043 
3044 /*
3045  * create_groupingsets_path
3046  *	  Creates a pathnode that represents performing GROUPING SETS aggregation
3047  *
3048  * GroupingSetsPath represents sorted grouping with one or more grouping sets.
3049  * The input path's result must be sorted to match the last entry in
3050  * rollup_groupclauses.
3051  *
3052  * 'rel' is the parent relation associated with the result
3053  * 'subpath' is the path representing the source of data
3054  * 'target' is the PathTarget to be computed
3055  * 'having_qual' is the HAVING quals if any
3056  * 'rollups' is a list of RollupData nodes
3057  * 'agg_costs' contains cost info about the aggregate functions to be computed
3058  * 'numGroups' is the estimated total number of groups
3059  */
3060 GroupingSetsPath *
create_groupingsets_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * having_qual,AggStrategy aggstrategy,List * rollups,const AggClauseCosts * agg_costs,double numGroups)3061 create_groupingsets_path(PlannerInfo *root,
3062 						 RelOptInfo *rel,
3063 						 Path *subpath,
3064 						 List *having_qual,
3065 						 AggStrategy aggstrategy,
3066 						 List *rollups,
3067 						 const AggClauseCosts *agg_costs,
3068 						 double numGroups)
3069 {
3070 	GroupingSetsPath *pathnode = makeNode(GroupingSetsPath);
3071 	PathTarget *target = rel->reltarget;
3072 	ListCell   *lc;
3073 	bool		is_first = true;
3074 	bool		is_first_sort = true;
3075 
3076 	/* The topmost generated Plan node will be an Agg */
3077 	pathnode->path.pathtype = T_Agg;
3078 	pathnode->path.parent = rel;
3079 	pathnode->path.pathtarget = target;
3080 	pathnode->path.param_info = subpath->param_info;
3081 	pathnode->path.parallel_aware = false;
3082 	pathnode->path.parallel_safe = rel->consider_parallel &&
3083 		subpath->parallel_safe;
3084 	pathnode->path.parallel_workers = subpath->parallel_workers;
3085 	pathnode->subpath = subpath;
3086 
3087 	/*
3088 	 * Simplify callers by downgrading AGG_SORTED to AGG_PLAIN, and AGG_MIXED
3089 	 * to AGG_HASHED, here if possible.
3090 	 */
3091 	if (aggstrategy == AGG_SORTED &&
3092 		list_length(rollups) == 1 &&
3093 		((RollupData *) linitial(rollups))->groupClause == NIL)
3094 		aggstrategy = AGG_PLAIN;
3095 
3096 	if (aggstrategy == AGG_MIXED &&
3097 		list_length(rollups) == 1)
3098 		aggstrategy = AGG_HASHED;
3099 
3100 	/*
3101 	 * Output will be in sorted order by group_pathkeys if, and only if, there
3102 	 * is a single rollup operation on a non-empty list of grouping
3103 	 * expressions.
3104 	 */
3105 	if (aggstrategy == AGG_SORTED && list_length(rollups) == 1)
3106 		pathnode->path.pathkeys = root->group_pathkeys;
3107 	else
3108 		pathnode->path.pathkeys = NIL;
3109 
3110 	pathnode->aggstrategy = aggstrategy;
3111 	pathnode->rollups = rollups;
3112 	pathnode->qual = having_qual;
3113 
3114 	Assert(rollups != NIL);
3115 	Assert(aggstrategy != AGG_PLAIN || list_length(rollups) == 1);
3116 	Assert(aggstrategy != AGG_MIXED || list_length(rollups) > 1);
3117 
3118 	foreach(lc, rollups)
3119 	{
3120 		RollupData *rollup = lfirst(lc);
3121 		List	   *gsets = rollup->gsets;
3122 		int			numGroupCols = list_length(linitial(gsets));
3123 
3124 		/*
3125 		 * In AGG_SORTED or AGG_PLAIN mode, the first rollup takes the
3126 		 * (already-sorted) input, and following ones do their own sort.
3127 		 *
3128 		 * In AGG_HASHED mode, there is one rollup for each grouping set.
3129 		 *
3130 		 * In AGG_MIXED mode, the first rollups are hashed, the first
3131 		 * non-hashed one takes the (already-sorted) input, and following ones
3132 		 * do their own sort.
3133 		 */
3134 		if (is_first)
3135 		{
3136 			cost_agg(&pathnode->path, root,
3137 					 aggstrategy,
3138 					 agg_costs,
3139 					 numGroupCols,
3140 					 rollup->numGroups,
3141 					 having_qual,
3142 					 subpath->startup_cost,
3143 					 subpath->total_cost,
3144 					 subpath->rows);
3145 			is_first = false;
3146 			if (!rollup->is_hashed)
3147 				is_first_sort = false;
3148 		}
3149 		else
3150 		{
3151 			Path		sort_path;	/* dummy for result of cost_sort */
3152 			Path		agg_path;	/* dummy for result of cost_agg */
3153 
3154 			if (rollup->is_hashed || is_first_sort)
3155 			{
3156 				/*
3157 				 * Account for cost of aggregation, but don't charge input
3158 				 * cost again
3159 				 */
3160 				cost_agg(&agg_path, root,
3161 						 rollup->is_hashed ? AGG_HASHED : AGG_SORTED,
3162 						 agg_costs,
3163 						 numGroupCols,
3164 						 rollup->numGroups,
3165 						 having_qual,
3166 						 0.0, 0.0,
3167 						 subpath->rows);
3168 				if (!rollup->is_hashed)
3169 					is_first_sort = false;
3170 			}
3171 			else
3172 			{
3173 				/* Account for cost of sort, but don't charge input cost again */
3174 				cost_sort(&sort_path, root, NIL,
3175 						  0.0,
3176 						  subpath->rows,
3177 						  subpath->pathtarget->width,
3178 						  0.0,
3179 						  work_mem,
3180 						  -1.0);
3181 
3182 				/* Account for cost of aggregation */
3183 
3184 				cost_agg(&agg_path, root,
3185 						 AGG_SORTED,
3186 						 agg_costs,
3187 						 numGroupCols,
3188 						 rollup->numGroups,
3189 						 having_qual,
3190 						 sort_path.startup_cost,
3191 						 sort_path.total_cost,
3192 						 sort_path.rows);
3193 			}
3194 
3195 			pathnode->path.total_cost += agg_path.total_cost;
3196 			pathnode->path.rows += agg_path.rows;
3197 		}
3198 	}
3199 
3200 	/* add tlist eval cost for each output row */
3201 	pathnode->path.startup_cost += target->cost.startup;
3202 	pathnode->path.total_cost += target->cost.startup +
3203 		target->cost.per_tuple * pathnode->path.rows;
3204 
3205 	return pathnode;
3206 }
3207 
3208 /*
3209  * create_minmaxagg_path
3210  *	  Creates a pathnode that represents computation of MIN/MAX aggregates
3211  *
3212  * 'rel' is the parent relation associated with the result
3213  * 'target' is the PathTarget to be computed
3214  * 'mmaggregates' is a list of MinMaxAggInfo structs
3215  * 'quals' is the HAVING quals if any
3216  */
3217 MinMaxAggPath *
create_minmaxagg_path(PlannerInfo * root,RelOptInfo * rel,PathTarget * target,List * mmaggregates,List * quals)3218 create_minmaxagg_path(PlannerInfo *root,
3219 					  RelOptInfo *rel,
3220 					  PathTarget *target,
3221 					  List *mmaggregates,
3222 					  List *quals)
3223 {
3224 	MinMaxAggPath *pathnode = makeNode(MinMaxAggPath);
3225 	Cost		initplan_cost;
3226 	ListCell   *lc;
3227 
3228 	/* The topmost generated Plan node will be a Result */
3229 	pathnode->path.pathtype = T_Result;
3230 	pathnode->path.parent = rel;
3231 	pathnode->path.pathtarget = target;
3232 	/* For now, assume we are above any joins, so no parameterization */
3233 	pathnode->path.param_info = NULL;
3234 	pathnode->path.parallel_aware = false;
3235 	/* A MinMaxAggPath implies use of subplans, so cannot be parallel-safe */
3236 	pathnode->path.parallel_safe = false;
3237 	pathnode->path.parallel_workers = 0;
3238 	/* Result is one unordered row */
3239 	pathnode->path.rows = 1;
3240 	pathnode->path.pathkeys = NIL;
3241 
3242 	pathnode->mmaggregates = mmaggregates;
3243 	pathnode->quals = quals;
3244 
3245 	/* Calculate cost of all the initplans ... */
3246 	initplan_cost = 0;
3247 	foreach(lc, mmaggregates)
3248 	{
3249 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3250 
3251 		initplan_cost += mminfo->pathcost;
3252 	}
3253 
3254 	/* add tlist eval cost for each output row, plus cpu_tuple_cost */
3255 	pathnode->path.startup_cost = initplan_cost + target->cost.startup;
3256 	pathnode->path.total_cost = initplan_cost + target->cost.startup +
3257 		target->cost.per_tuple + cpu_tuple_cost;
3258 
3259 	/*
3260 	 * Add cost of qual, if any --- but we ignore its selectivity, since our
3261 	 * rowcount estimate should be 1 no matter what the qual is.
3262 	 */
3263 	if (quals)
3264 	{
3265 		QualCost	qual_cost;
3266 
3267 		cost_qual_eval(&qual_cost, quals, root);
3268 		pathnode->path.startup_cost += qual_cost.startup;
3269 		pathnode->path.total_cost += qual_cost.startup + qual_cost.per_tuple;
3270 	}
3271 
3272 	return pathnode;
3273 }
3274 
3275 /*
3276  * create_windowagg_path
3277  *	  Creates a pathnode that represents computation of window functions
3278  *
3279  * 'rel' is the parent relation associated with the result
3280  * 'subpath' is the path representing the source of data
3281  * 'target' is the PathTarget to be computed
3282  * 'windowFuncs' is a list of WindowFunc structs
3283  * 'winclause' is a WindowClause that is common to all the WindowFuncs
3284  *
3285  * The input must be sorted according to the WindowClause's PARTITION keys
3286  * plus ORDER BY keys.
3287  */
3288 WindowAggPath *
create_windowagg_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,PathTarget * target,List * windowFuncs,WindowClause * winclause)3289 create_windowagg_path(PlannerInfo *root,
3290 					  RelOptInfo *rel,
3291 					  Path *subpath,
3292 					  PathTarget *target,
3293 					  List *windowFuncs,
3294 					  WindowClause *winclause)
3295 {
3296 	WindowAggPath *pathnode = makeNode(WindowAggPath);
3297 
3298 	pathnode->path.pathtype = T_WindowAgg;
3299 	pathnode->path.parent = rel;
3300 	pathnode->path.pathtarget = target;
3301 	/* For now, assume we are above any joins, so no parameterization */
3302 	pathnode->path.param_info = NULL;
3303 	pathnode->path.parallel_aware = false;
3304 	pathnode->path.parallel_safe = rel->consider_parallel &&
3305 		subpath->parallel_safe;
3306 	pathnode->path.parallel_workers = subpath->parallel_workers;
3307 	/* WindowAgg preserves the input sort order */
3308 	pathnode->path.pathkeys = subpath->pathkeys;
3309 
3310 	pathnode->subpath = subpath;
3311 	pathnode->winclause = winclause;
3312 
3313 	/*
3314 	 * For costing purposes, assume that there are no redundant partitioning
3315 	 * or ordering columns; it's not worth the trouble to deal with that
3316 	 * corner case here.  So we just pass the unmodified list lengths to
3317 	 * cost_windowagg.
3318 	 */
3319 	cost_windowagg(&pathnode->path, root,
3320 				   windowFuncs,
3321 				   list_length(winclause->partitionClause),
3322 				   list_length(winclause->orderClause),
3323 				   subpath->startup_cost,
3324 				   subpath->total_cost,
3325 				   subpath->rows);
3326 
3327 	/* add tlist eval cost for each output row */
3328 	pathnode->path.startup_cost += target->cost.startup;
3329 	pathnode->path.total_cost += target->cost.startup +
3330 		target->cost.per_tuple * pathnode->path.rows;
3331 
3332 	return pathnode;
3333 }
3334 
3335 /*
3336  * create_setop_path
3337  *	  Creates a pathnode that represents computation of INTERSECT or EXCEPT
3338  *
3339  * 'rel' is the parent relation associated with the result
3340  * 'subpath' is the path representing the source of data
3341  * 'cmd' is the specific semantics (INTERSECT or EXCEPT, with/without ALL)
3342  * 'strategy' is the implementation strategy (sorted or hashed)
3343  * 'distinctList' is a list of SortGroupClause's representing the grouping
3344  * 'flagColIdx' is the column number where the flag column will be, if any
3345  * 'firstFlag' is the flag value for the first input relation when hashing;
3346  *		or -1 when sorting
3347  * 'numGroups' is the estimated number of distinct groups
3348  * 'outputRows' is the estimated number of output rows
3349  */
3350 SetOpPath *
create_setop_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,SetOpCmd cmd,SetOpStrategy strategy,List * distinctList,AttrNumber flagColIdx,int firstFlag,double numGroups,double outputRows)3351 create_setop_path(PlannerInfo *root,
3352 				  RelOptInfo *rel,
3353 				  Path *subpath,
3354 				  SetOpCmd cmd,
3355 				  SetOpStrategy strategy,
3356 				  List *distinctList,
3357 				  AttrNumber flagColIdx,
3358 				  int firstFlag,
3359 				  double numGroups,
3360 				  double outputRows)
3361 {
3362 	SetOpPath  *pathnode = makeNode(SetOpPath);
3363 
3364 	pathnode->path.pathtype = T_SetOp;
3365 	pathnode->path.parent = rel;
3366 	/* SetOp doesn't project, so use source path's pathtarget */
3367 	pathnode->path.pathtarget = subpath->pathtarget;
3368 	/* For now, assume we are above any joins, so no parameterization */
3369 	pathnode->path.param_info = NULL;
3370 	pathnode->path.parallel_aware = false;
3371 	pathnode->path.parallel_safe = rel->consider_parallel &&
3372 		subpath->parallel_safe;
3373 	pathnode->path.parallel_workers = subpath->parallel_workers;
3374 	/* SetOp preserves the input sort order if in sort mode */
3375 	pathnode->path.pathkeys =
3376 		(strategy == SETOP_SORTED) ? subpath->pathkeys : NIL;
3377 
3378 	pathnode->subpath = subpath;
3379 	pathnode->cmd = cmd;
3380 	pathnode->strategy = strategy;
3381 	pathnode->distinctList = distinctList;
3382 	pathnode->flagColIdx = flagColIdx;
3383 	pathnode->firstFlag = firstFlag;
3384 	pathnode->numGroups = numGroups;
3385 
3386 	/*
3387 	 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3388 	 * all columns get compared at most of the tuples.
3389 	 */
3390 	pathnode->path.startup_cost = subpath->startup_cost;
3391 	pathnode->path.total_cost = subpath->total_cost +
3392 		cpu_operator_cost * subpath->rows * list_length(distinctList);
3393 	pathnode->path.rows = outputRows;
3394 
3395 	return pathnode;
3396 }
3397 
3398 /*
3399  * create_recursiveunion_path
3400  *	  Creates a pathnode that represents a recursive UNION node
3401  *
3402  * 'rel' is the parent relation associated with the result
3403  * 'leftpath' is the source of data for the non-recursive term
3404  * 'rightpath' is the source of data for the recursive term
3405  * 'target' is the PathTarget to be computed
3406  * 'distinctList' is a list of SortGroupClause's representing the grouping
3407  * 'wtParam' is the ID of Param representing work table
3408  * 'numGroups' is the estimated number of groups
3409  *
3410  * For recursive UNION ALL, distinctList is empty and numGroups is zero
3411  */
3412 RecursiveUnionPath *
create_recursiveunion_path(PlannerInfo * root,RelOptInfo * rel,Path * leftpath,Path * rightpath,PathTarget * target,List * distinctList,int wtParam,double numGroups)3413 create_recursiveunion_path(PlannerInfo *root,
3414 						   RelOptInfo *rel,
3415 						   Path *leftpath,
3416 						   Path *rightpath,
3417 						   PathTarget *target,
3418 						   List *distinctList,
3419 						   int wtParam,
3420 						   double numGroups)
3421 {
3422 	RecursiveUnionPath *pathnode = makeNode(RecursiveUnionPath);
3423 
3424 	pathnode->path.pathtype = T_RecursiveUnion;
3425 	pathnode->path.parent = rel;
3426 	pathnode->path.pathtarget = target;
3427 	/* For now, assume we are above any joins, so no parameterization */
3428 	pathnode->path.param_info = NULL;
3429 	pathnode->path.parallel_aware = false;
3430 	pathnode->path.parallel_safe = rel->consider_parallel &&
3431 		leftpath->parallel_safe && rightpath->parallel_safe;
3432 	/* Foolish, but we'll do it like joins for now: */
3433 	pathnode->path.parallel_workers = leftpath->parallel_workers;
3434 	/* RecursiveUnion result is always unsorted */
3435 	pathnode->path.pathkeys = NIL;
3436 
3437 	pathnode->leftpath = leftpath;
3438 	pathnode->rightpath = rightpath;
3439 	pathnode->distinctList = distinctList;
3440 	pathnode->wtParam = wtParam;
3441 	pathnode->numGroups = numGroups;
3442 
3443 	cost_recursive_union(&pathnode->path, leftpath, rightpath);
3444 
3445 	return pathnode;
3446 }
3447 
3448 /*
3449  * create_lockrows_path
3450  *	  Creates a pathnode that represents acquiring row locks
3451  *
3452  * 'rel' is the parent relation associated with the result
3453  * 'subpath' is the path representing the source of data
3454  * 'rowMarks' is a list of PlanRowMark's
3455  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3456  */
3457 LockRowsPath *
create_lockrows_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,List * rowMarks,int epqParam)3458 create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
3459 					 Path *subpath, List *rowMarks, int epqParam)
3460 {
3461 	LockRowsPath *pathnode = makeNode(LockRowsPath);
3462 
3463 	pathnode->path.pathtype = T_LockRows;
3464 	pathnode->path.parent = rel;
3465 	/* LockRows doesn't project, so use source path's pathtarget */
3466 	pathnode->path.pathtarget = subpath->pathtarget;
3467 	/* For now, assume we are above any joins, so no parameterization */
3468 	pathnode->path.param_info = NULL;
3469 	pathnode->path.parallel_aware = false;
3470 	pathnode->path.parallel_safe = false;
3471 	pathnode->path.parallel_workers = 0;
3472 	pathnode->path.rows = subpath->rows;
3473 
3474 	/*
3475 	 * The result cannot be assumed sorted, since locking might cause the sort
3476 	 * key columns to be replaced with new values.
3477 	 */
3478 	pathnode->path.pathkeys = NIL;
3479 
3480 	pathnode->subpath = subpath;
3481 	pathnode->rowMarks = rowMarks;
3482 	pathnode->epqParam = epqParam;
3483 
3484 	/*
3485 	 * We should charge something extra for the costs of row locking and
3486 	 * possible refetches, but it's hard to say how much.  For now, use
3487 	 * cpu_tuple_cost per row.
3488 	 */
3489 	pathnode->path.startup_cost = subpath->startup_cost;
3490 	pathnode->path.total_cost = subpath->total_cost +
3491 		cpu_tuple_cost * subpath->rows;
3492 
3493 	return pathnode;
3494 }
3495 
3496 /*
3497  * create_modifytable_path
3498  *	  Creates a pathnode that represents performing INSERT/UPDATE/DELETE mods
3499  *
3500  * 'rel' is the parent relation associated with the result
3501  * 'operation' is the operation type
3502  * 'canSetTag' is true if we set the command tag/es_processed
3503  * 'nominalRelation' is the parent RT index for use of EXPLAIN
3504  * 'rootRelation' is the partitioned table root RT index, or 0 if none
3505  * 'partColsUpdated' is true if any partitioning columns are being updated,
3506  *		either from the target relation or a descendent partitioned table.
3507  * 'resultRelations' is an integer list of actual RT indexes of target rel(s)
3508  * 'subpaths' is a list of Path(s) producing source data (one per rel)
3509  * 'subroots' is a list of PlannerInfo structs (one per rel)
3510  * 'withCheckOptionLists' is a list of WCO lists (one per rel)
3511  * 'returningLists' is a list of RETURNING tlists (one per rel)
3512  * 'rowMarks' is a list of PlanRowMarks (non-locking only)
3513  * 'onconflict' is the ON CONFLICT clause, or NULL
3514  * 'epqParam' is the ID of Param for EvalPlanQual re-eval
3515  */
3516 ModifyTablePath *
create_modifytable_path(PlannerInfo * root,RelOptInfo * rel,CmdType operation,bool canSetTag,Index nominalRelation,Index rootRelation,bool partColsUpdated,List * resultRelations,List * subpaths,List * subroots,List * withCheckOptionLists,List * returningLists,List * rowMarks,OnConflictExpr * onconflict,int epqParam)3517 create_modifytable_path(PlannerInfo *root, RelOptInfo *rel,
3518 						CmdType operation, bool canSetTag,
3519 						Index nominalRelation, Index rootRelation,
3520 						bool partColsUpdated,
3521 						List *resultRelations, List *subpaths,
3522 						List *subroots,
3523 						List *withCheckOptionLists, List *returningLists,
3524 						List *rowMarks, OnConflictExpr *onconflict,
3525 						int epqParam)
3526 {
3527 	ModifyTablePath *pathnode = makeNode(ModifyTablePath);
3528 	double		total_size;
3529 	ListCell   *lc;
3530 
3531 	Assert(list_length(resultRelations) == list_length(subpaths));
3532 	Assert(list_length(resultRelations) == list_length(subroots));
3533 	Assert(withCheckOptionLists == NIL ||
3534 		   list_length(resultRelations) == list_length(withCheckOptionLists));
3535 	Assert(returningLists == NIL ||
3536 		   list_length(resultRelations) == list_length(returningLists));
3537 
3538 	pathnode->path.pathtype = T_ModifyTable;
3539 	pathnode->path.parent = rel;
3540 	/* pathtarget is not interesting, just make it minimally valid */
3541 	pathnode->path.pathtarget = rel->reltarget;
3542 	/* For now, assume we are above any joins, so no parameterization */
3543 	pathnode->path.param_info = NULL;
3544 	pathnode->path.parallel_aware = false;
3545 	pathnode->path.parallel_safe = false;
3546 	pathnode->path.parallel_workers = 0;
3547 	pathnode->path.pathkeys = NIL;
3548 
3549 	/*
3550 	 * Compute cost & rowcount as sum of subpath costs & rowcounts.
3551 	 *
3552 	 * Currently, we don't charge anything extra for the actual table
3553 	 * modification work, nor for the WITH CHECK OPTIONS or RETURNING
3554 	 * expressions if any.  It would only be window dressing, since
3555 	 * ModifyTable is always a top-level node and there is no way for the
3556 	 * costs to change any higher-level planning choices.  But we might want
3557 	 * to make it look better sometime.
3558 	 */
3559 	pathnode->path.startup_cost = 0;
3560 	pathnode->path.total_cost = 0;
3561 	pathnode->path.rows = 0;
3562 	total_size = 0;
3563 	foreach(lc, subpaths)
3564 	{
3565 		Path	   *subpath = (Path *) lfirst(lc);
3566 
3567 		if (lc == list_head(subpaths))	/* first node? */
3568 			pathnode->path.startup_cost = subpath->startup_cost;
3569 		pathnode->path.total_cost += subpath->total_cost;
3570 		pathnode->path.rows += subpath->rows;
3571 		total_size += subpath->pathtarget->width * subpath->rows;
3572 	}
3573 
3574 	/*
3575 	 * Set width to the average width of the subpath outputs.  XXX this is
3576 	 * totally wrong: we should report zero if no RETURNING, else an average
3577 	 * of the RETURNING tlist widths.  But it's what happened historically,
3578 	 * and improving it is a task for another day.
3579 	 */
3580 	if (pathnode->path.rows > 0)
3581 		total_size /= pathnode->path.rows;
3582 	pathnode->path.pathtarget->width = rint(total_size);
3583 
3584 	pathnode->operation = operation;
3585 	pathnode->canSetTag = canSetTag;
3586 	pathnode->nominalRelation = nominalRelation;
3587 	pathnode->rootRelation = rootRelation;
3588 	pathnode->partColsUpdated = partColsUpdated;
3589 	pathnode->resultRelations = resultRelations;
3590 	pathnode->subpaths = subpaths;
3591 	pathnode->subroots = subroots;
3592 	pathnode->withCheckOptionLists = withCheckOptionLists;
3593 	pathnode->returningLists = returningLists;
3594 	pathnode->rowMarks = rowMarks;
3595 	pathnode->onconflict = onconflict;
3596 	pathnode->epqParam = epqParam;
3597 
3598 	return pathnode;
3599 }
3600 
3601 /*
3602  * create_limit_path
3603  *	  Creates a pathnode that represents performing LIMIT/OFFSET
3604  *
3605  * In addition to providing the actual OFFSET and LIMIT expressions,
3606  * the caller must provide estimates of their values for costing purposes.
3607  * The estimates are as computed by preprocess_limit(), ie, 0 represents
3608  * the clause not being present, and -1 means it's present but we could
3609  * not estimate its value.
3610  *
3611  * 'rel' is the parent relation associated with the result
3612  * 'subpath' is the path representing the source of data
3613  * 'limitOffset' is the actual OFFSET expression, or NULL
3614  * 'limitCount' is the actual LIMIT expression, or NULL
3615  * 'offset_est' is the estimated value of the OFFSET expression
3616  * 'count_est' is the estimated value of the LIMIT expression
3617  */
3618 LimitPath *
create_limit_path(PlannerInfo * root,RelOptInfo * rel,Path * subpath,Node * limitOffset,Node * limitCount,int64 offset_est,int64 count_est)3619 create_limit_path(PlannerInfo *root, RelOptInfo *rel,
3620 				  Path *subpath,
3621 				  Node *limitOffset, Node *limitCount,
3622 				  int64 offset_est, int64 count_est)
3623 {
3624 	LimitPath  *pathnode = makeNode(LimitPath);
3625 
3626 	pathnode->path.pathtype = T_Limit;
3627 	pathnode->path.parent = rel;
3628 	/* Limit doesn't project, so use source path's pathtarget */
3629 	pathnode->path.pathtarget = subpath->pathtarget;
3630 	/* For now, assume we are above any joins, so no parameterization */
3631 	pathnode->path.param_info = NULL;
3632 	pathnode->path.parallel_aware = false;
3633 	pathnode->path.parallel_safe = rel->consider_parallel &&
3634 		subpath->parallel_safe;
3635 	pathnode->path.parallel_workers = subpath->parallel_workers;
3636 	pathnode->path.rows = subpath->rows;
3637 	pathnode->path.startup_cost = subpath->startup_cost;
3638 	pathnode->path.total_cost = subpath->total_cost;
3639 	pathnode->path.pathkeys = subpath->pathkeys;
3640 	pathnode->subpath = subpath;
3641 	pathnode->limitOffset = limitOffset;
3642 	pathnode->limitCount = limitCount;
3643 
3644 	/*
3645 	 * Adjust the output rows count and costs according to the offset/limit.
3646 	 */
3647 	adjust_limit_rows_costs(&pathnode->path.rows,
3648 							&pathnode->path.startup_cost,
3649 							&pathnode->path.total_cost,
3650 							offset_est, count_est);
3651 
3652 	return pathnode;
3653 }
3654 
3655 /*
3656  * adjust_limit_rows_costs
3657  *	  Adjust the size and cost estimates for a LimitPath node according to the
3658  *	  offset/limit.
3659  *
3660  * This is only a cosmetic issue if we are at top level, but if we are
3661  * building a subquery then it's important to report correct info to the outer
3662  * planner.
3663  *
3664  * When the offset or count couldn't be estimated, use 10% of the estimated
3665  * number of rows emitted from the subpath.
3666  *
3667  * XXX we don't bother to add eval costs of the offset/limit expressions
3668  * themselves to the path costs.  In theory we should, but in most cases those
3669  * expressions are trivial and it's just not worth the trouble.
3670  */
3671 void
adjust_limit_rows_costs(double * rows,Cost * startup_cost,Cost * total_cost,int64 offset_est,int64 count_est)3672 adjust_limit_rows_costs(double *rows,	/* in/out parameter */
3673 						Cost *startup_cost, /* in/out parameter */
3674 						Cost *total_cost,	/* in/out parameter */
3675 						int64 offset_est,
3676 						int64 count_est)
3677 {
3678 	double		input_rows = *rows;
3679 	Cost		input_startup_cost = *startup_cost;
3680 	Cost		input_total_cost = *total_cost;
3681 
3682 	if (offset_est != 0)
3683 	{
3684 		double		offset_rows;
3685 
3686 		if (offset_est > 0)
3687 			offset_rows = (double) offset_est;
3688 		else
3689 			offset_rows = clamp_row_est(input_rows * 0.10);
3690 		if (offset_rows > *rows)
3691 			offset_rows = *rows;
3692 		if (input_rows > 0)
3693 			*startup_cost +=
3694 				(input_total_cost - input_startup_cost)
3695 				* offset_rows / input_rows;
3696 		*rows -= offset_rows;
3697 		if (*rows < 1)
3698 			*rows = 1;
3699 	}
3700 
3701 	if (count_est != 0)
3702 	{
3703 		double		count_rows;
3704 
3705 		if (count_est > 0)
3706 			count_rows = (double) count_est;
3707 		else
3708 			count_rows = clamp_row_est(input_rows * 0.10);
3709 		if (count_rows > *rows)
3710 			count_rows = *rows;
3711 		if (input_rows > 0)
3712 			*total_cost = *startup_cost +
3713 				(input_total_cost - input_startup_cost)
3714 				* count_rows / input_rows;
3715 		*rows = count_rows;
3716 		if (*rows < 1)
3717 			*rows = 1;
3718 	}
3719 }
3720 
3721 
3722 /*
3723  * reparameterize_path
3724  *		Attempt to modify a Path to have greater parameterization
3725  *
3726  * We use this to attempt to bring all child paths of an appendrel to the
3727  * same parameterization level, ensuring that they all enforce the same set
3728  * of join quals (and thus that that parameterization can be attributed to
3729  * an append path built from such paths).  Currently, only a few path types
3730  * are supported here, though more could be added at need.  We return NULL
3731  * if we can't reparameterize the given path.
3732  *
3733  * Note: we intentionally do not pass created paths to add_path(); it would
3734  * possibly try to delete them on the grounds of being cost-inferior to the
3735  * paths they were made from, and we don't want that.  Paths made here are
3736  * not necessarily of general-purpose usefulness, but they can be useful
3737  * as members of an append path.
3738  */
3739 Path *
reparameterize_path(PlannerInfo * root,Path * path,Relids required_outer,double loop_count)3740 reparameterize_path(PlannerInfo *root, Path *path,
3741 					Relids required_outer,
3742 					double loop_count)
3743 {
3744 	RelOptInfo *rel = path->parent;
3745 
3746 	/* Can only increase, not decrease, path's parameterization */
3747 	if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
3748 		return NULL;
3749 	switch (path->pathtype)
3750 	{
3751 		case T_SeqScan:
3752 			return create_seqscan_path(root, rel, required_outer, 0);
3753 		case T_SampleScan:
3754 			return (Path *) create_samplescan_path(root, rel, required_outer);
3755 		case T_IndexScan:
3756 		case T_IndexOnlyScan:
3757 			{
3758 				IndexPath  *ipath = (IndexPath *) path;
3759 				IndexPath  *newpath = makeNode(IndexPath);
3760 
3761 				/*
3762 				 * We can't use create_index_path directly, and would not want
3763 				 * to because it would re-compute the indexqual conditions
3764 				 * which is wasted effort.  Instead we hack things a bit:
3765 				 * flat-copy the path node, revise its param_info, and redo
3766 				 * the cost estimate.
3767 				 */
3768 				memcpy(newpath, ipath, sizeof(IndexPath));
3769 				newpath->path.param_info =
3770 					get_baserel_parampathinfo(root, rel, required_outer);
3771 				cost_index(newpath, root, loop_count, false);
3772 				return (Path *) newpath;
3773 			}
3774 		case T_BitmapHeapScan:
3775 			{
3776 				BitmapHeapPath *bpath = (BitmapHeapPath *) path;
3777 
3778 				return (Path *) create_bitmap_heap_path(root,
3779 														rel,
3780 														bpath->bitmapqual,
3781 														required_outer,
3782 														loop_count, 0);
3783 			}
3784 		case T_SubqueryScan:
3785 			{
3786 				SubqueryScanPath *spath = (SubqueryScanPath *) path;
3787 
3788 				return (Path *) create_subqueryscan_path(root,
3789 														 rel,
3790 														 spath->subpath,
3791 														 spath->path.pathkeys,
3792 														 required_outer);
3793 			}
3794 		case T_Result:
3795 			/* Supported only for RTE_RESULT scan paths */
3796 			if (IsA(path, Path))
3797 				return create_resultscan_path(root, rel, required_outer);
3798 			break;
3799 		case T_Append:
3800 			{
3801 				AppendPath *apath = (AppendPath *) path;
3802 				List	   *childpaths = NIL;
3803 				List	   *partialpaths = NIL;
3804 				int			i;
3805 				ListCell   *lc;
3806 
3807 				/* Reparameterize the children */
3808 				i = 0;
3809 				foreach(lc, apath->subpaths)
3810 				{
3811 					Path	   *spath = (Path *) lfirst(lc);
3812 
3813 					spath = reparameterize_path(root, spath,
3814 												required_outer,
3815 												loop_count);
3816 					if (spath == NULL)
3817 						return NULL;
3818 					/* We have to re-split the regular and partial paths */
3819 					if (i < apath->first_partial_path)
3820 						childpaths = lappend(childpaths, spath);
3821 					else
3822 						partialpaths = lappend(partialpaths, spath);
3823 					i++;
3824 				}
3825 				return (Path *)
3826 					create_append_path(root, rel, childpaths, partialpaths,
3827 									   apath->path.pathkeys, required_outer,
3828 									   apath->path.parallel_workers,
3829 									   apath->path.parallel_aware,
3830 									   apath->partitioned_rels,
3831 									   -1);
3832 			}
3833 		default:
3834 			break;
3835 	}
3836 	return NULL;
3837 }
3838 
3839 /*
3840  * reparameterize_path_by_child
3841  * 		Given a path parameterized by the parent of the given child relation,
3842  * 		translate the path to be parameterized by the given child relation.
3843  *
3844  * The function creates a new path of the same type as the given path, but
3845  * parameterized by the given child relation.  Most fields from the original
3846  * path can simply be flat-copied, but any expressions must be adjusted to
3847  * refer to the correct varnos, and any paths must be recursively
3848  * reparameterized.  Other fields that refer to specific relids also need
3849  * adjustment.
3850  *
3851  * The cost, number of rows, width and parallel path properties depend upon
3852  * path->parent, which does not change during the translation. Hence those
3853  * members are copied as they are.
3854  *
3855  * If the given path can not be reparameterized, the function returns NULL.
3856  */
3857 Path *
reparameterize_path_by_child(PlannerInfo * root,Path * path,RelOptInfo * child_rel)3858 reparameterize_path_by_child(PlannerInfo *root, Path *path,
3859 							 RelOptInfo *child_rel)
3860 {
3861 
3862 #define FLAT_COPY_PATH(newnode, node, nodetype)  \
3863 	( (newnode) = makeNode(nodetype), \
3864 	  memcpy((newnode), (node), sizeof(nodetype)) )
3865 
3866 #define ADJUST_CHILD_ATTRS(node) \
3867 	((node) = \
3868 	 (List *) adjust_appendrel_attrs_multilevel(root, (Node *) (node), \
3869 												child_rel->relids, \
3870 												child_rel->top_parent_relids))
3871 
3872 #define REPARAMETERIZE_CHILD_PATH(path) \
3873 do { \
3874 	(path) = reparameterize_path_by_child(root, (path), child_rel); \
3875 	if ((path) == NULL) \
3876 		return NULL; \
3877 } while(0)
3878 
3879 #define REPARAMETERIZE_CHILD_PATH_LIST(pathlist) \
3880 do { \
3881 	if ((pathlist) != NIL) \
3882 	{ \
3883 		(pathlist) = reparameterize_pathlist_by_child(root, (pathlist), \
3884 													  child_rel); \
3885 		if ((pathlist) == NIL) \
3886 			return NULL; \
3887 	} \
3888 } while(0)
3889 
3890 	Path	   *new_path;
3891 	ParamPathInfo *new_ppi;
3892 	ParamPathInfo *old_ppi;
3893 	Relids		required_outer;
3894 
3895 	/*
3896 	 * If the path is not parameterized by parent of the given relation, it
3897 	 * doesn't need reparameterization.
3898 	 */
3899 	if (!path->param_info ||
3900 		!bms_overlap(PATH_REQ_OUTER(path), child_rel->top_parent_relids))
3901 		return path;
3902 
3903 	/*
3904 	 * If possible, reparameterize the given path, making a copy.
3905 	 *
3906 	 * This function is currently only applied to the inner side of a nestloop
3907 	 * join that is being partitioned by the partitionwise-join code.  Hence,
3908 	 * we need only support path types that plausibly arise in that context.
3909 	 * (In particular, supporting sorted path types would be a waste of code
3910 	 * and cycles: even if we translated them here, they'd just lose in
3911 	 * subsequent cost comparisons.)  If we do see an unsupported path type,
3912 	 * that just means we won't be able to generate a partitionwise-join plan
3913 	 * using that path type.
3914 	 */
3915 	switch (nodeTag(path))
3916 	{
3917 		case T_Path:
3918 			FLAT_COPY_PATH(new_path, path, Path);
3919 			break;
3920 
3921 		case T_IndexPath:
3922 			{
3923 				IndexPath  *ipath;
3924 
3925 				FLAT_COPY_PATH(ipath, path, IndexPath);
3926 				ADJUST_CHILD_ATTRS(ipath->indexclauses);
3927 				new_path = (Path *) ipath;
3928 			}
3929 			break;
3930 
3931 		case T_BitmapHeapPath:
3932 			{
3933 				BitmapHeapPath *bhpath;
3934 
3935 				FLAT_COPY_PATH(bhpath, path, BitmapHeapPath);
3936 				REPARAMETERIZE_CHILD_PATH(bhpath->bitmapqual);
3937 				new_path = (Path *) bhpath;
3938 			}
3939 			break;
3940 
3941 		case T_BitmapAndPath:
3942 			{
3943 				BitmapAndPath *bapath;
3944 
3945 				FLAT_COPY_PATH(bapath, path, BitmapAndPath);
3946 				REPARAMETERIZE_CHILD_PATH_LIST(bapath->bitmapquals);
3947 				new_path = (Path *) bapath;
3948 			}
3949 			break;
3950 
3951 		case T_BitmapOrPath:
3952 			{
3953 				BitmapOrPath *bopath;
3954 
3955 				FLAT_COPY_PATH(bopath, path, BitmapOrPath);
3956 				REPARAMETERIZE_CHILD_PATH_LIST(bopath->bitmapquals);
3957 				new_path = (Path *) bopath;
3958 			}
3959 			break;
3960 
3961 		case T_ForeignPath:
3962 			{
3963 				ForeignPath *fpath;
3964 				ReparameterizeForeignPathByChild_function rfpc_func;
3965 
3966 				FLAT_COPY_PATH(fpath, path, ForeignPath);
3967 				if (fpath->fdw_outerpath)
3968 					REPARAMETERIZE_CHILD_PATH(fpath->fdw_outerpath);
3969 
3970 				/* Hand over to FDW if needed. */
3971 				rfpc_func =
3972 					path->parent->fdwroutine->ReparameterizeForeignPathByChild;
3973 				if (rfpc_func)
3974 					fpath->fdw_private = rfpc_func(root, fpath->fdw_private,
3975 												   child_rel);
3976 				new_path = (Path *) fpath;
3977 			}
3978 			break;
3979 
3980 		case T_CustomPath:
3981 			{
3982 				CustomPath *cpath;
3983 
3984 				FLAT_COPY_PATH(cpath, path, CustomPath);
3985 				REPARAMETERIZE_CHILD_PATH_LIST(cpath->custom_paths);
3986 				if (cpath->methods &&
3987 					cpath->methods->ReparameterizeCustomPathByChild)
3988 					cpath->custom_private =
3989 						cpath->methods->ReparameterizeCustomPathByChild(root,
3990 																		cpath->custom_private,
3991 																		child_rel);
3992 				new_path = (Path *) cpath;
3993 			}
3994 			break;
3995 
3996 		case T_NestPath:
3997 			{
3998 				JoinPath   *jpath;
3999 
4000 				FLAT_COPY_PATH(jpath, path, NestPath);
4001 
4002 				REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4003 				REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4004 				ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4005 				new_path = (Path *) jpath;
4006 			}
4007 			break;
4008 
4009 		case T_MergePath:
4010 			{
4011 				JoinPath   *jpath;
4012 				MergePath  *mpath;
4013 
4014 				FLAT_COPY_PATH(mpath, path, MergePath);
4015 
4016 				jpath = (JoinPath *) mpath;
4017 				REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4018 				REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4019 				ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4020 				ADJUST_CHILD_ATTRS(mpath->path_mergeclauses);
4021 				new_path = (Path *) mpath;
4022 			}
4023 			break;
4024 
4025 		case T_HashPath:
4026 			{
4027 				JoinPath   *jpath;
4028 				HashPath   *hpath;
4029 
4030 				FLAT_COPY_PATH(hpath, path, HashPath);
4031 
4032 				jpath = (JoinPath *) hpath;
4033 				REPARAMETERIZE_CHILD_PATH(jpath->outerjoinpath);
4034 				REPARAMETERIZE_CHILD_PATH(jpath->innerjoinpath);
4035 				ADJUST_CHILD_ATTRS(jpath->joinrestrictinfo);
4036 				ADJUST_CHILD_ATTRS(hpath->path_hashclauses);
4037 				new_path = (Path *) hpath;
4038 			}
4039 			break;
4040 
4041 		case T_AppendPath:
4042 			{
4043 				AppendPath *apath;
4044 
4045 				FLAT_COPY_PATH(apath, path, AppendPath);
4046 				REPARAMETERIZE_CHILD_PATH_LIST(apath->subpaths);
4047 				new_path = (Path *) apath;
4048 			}
4049 			break;
4050 
4051 		case T_GatherPath:
4052 			{
4053 				GatherPath *gpath;
4054 
4055 				FLAT_COPY_PATH(gpath, path, GatherPath);
4056 				REPARAMETERIZE_CHILD_PATH(gpath->subpath);
4057 				new_path = (Path *) gpath;
4058 			}
4059 			break;
4060 
4061 		default:
4062 
4063 			/* We don't know how to reparameterize this path. */
4064 			return NULL;
4065 	}
4066 
4067 	/*
4068 	 * Adjust the parameterization information, which refers to the topmost
4069 	 * parent. The topmost parent can be multiple levels away from the given
4070 	 * child, hence use multi-level expression adjustment routines.
4071 	 */
4072 	old_ppi = new_path->param_info;
4073 	required_outer =
4074 		adjust_child_relids_multilevel(root, old_ppi->ppi_req_outer,
4075 									   child_rel->relids,
4076 									   child_rel->top_parent_relids);
4077 
4078 	/* If we already have a PPI for this parameterization, just return it */
4079 	new_ppi = find_param_path_info(new_path->parent, required_outer);
4080 
4081 	/*
4082 	 * If not, build a new one and link it to the list of PPIs. For the same
4083 	 * reason as explained in mark_dummy_rel(), allocate new PPI in the same
4084 	 * context the given RelOptInfo is in.
4085 	 */
4086 	if (new_ppi == NULL)
4087 	{
4088 		MemoryContext oldcontext;
4089 		RelOptInfo *rel = path->parent;
4090 
4091 		oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
4092 
4093 		new_ppi = makeNode(ParamPathInfo);
4094 		new_ppi->ppi_req_outer = bms_copy(required_outer);
4095 		new_ppi->ppi_rows = old_ppi->ppi_rows;
4096 		new_ppi->ppi_clauses = old_ppi->ppi_clauses;
4097 		ADJUST_CHILD_ATTRS(new_ppi->ppi_clauses);
4098 		rel->ppilist = lappend(rel->ppilist, new_ppi);
4099 
4100 		MemoryContextSwitchTo(oldcontext);
4101 	}
4102 	bms_free(required_outer);
4103 
4104 	new_path->param_info = new_ppi;
4105 
4106 	/*
4107 	 * Adjust the path target if the parent of the outer relation is
4108 	 * referenced in the targetlist. This can happen when only the parent of
4109 	 * outer relation is laterally referenced in this relation.
4110 	 */
4111 	if (bms_overlap(path->parent->lateral_relids,
4112 					child_rel->top_parent_relids))
4113 	{
4114 		new_path->pathtarget = copy_pathtarget(new_path->pathtarget);
4115 		ADJUST_CHILD_ATTRS(new_path->pathtarget->exprs);
4116 	}
4117 
4118 	return new_path;
4119 }
4120 
4121 /*
4122  * reparameterize_pathlist_by_child
4123  * 		Helper function to reparameterize a list of paths by given child rel.
4124  */
4125 static List *
reparameterize_pathlist_by_child(PlannerInfo * root,List * pathlist,RelOptInfo * child_rel)4126 reparameterize_pathlist_by_child(PlannerInfo *root,
4127 								 List *pathlist,
4128 								 RelOptInfo *child_rel)
4129 {
4130 	ListCell   *lc;
4131 	List	   *result = NIL;
4132 
4133 	foreach(lc, pathlist)
4134 	{
4135 		Path	   *path = reparameterize_path_by_child(root, lfirst(lc),
4136 														child_rel);
4137 
4138 		if (path == NULL)
4139 		{
4140 			list_free(result);
4141 			return NIL;
4142 		}
4143 
4144 		result = lappend(result, path);
4145 	}
4146 
4147 	return result;
4148 }
4149