1 /*-------------------------------------------------------------------------
2  *
3  * createplan.c
4  *	  Routines to create the desired plan for processing a query.
5  *	  Planning is complete, we just need to convert the selected
6  *	  Path into a Plan.
7  *
8  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
9  * Portions Copyright (c) 1994, Regents of the University of California
10  *
11  *
12  * IDENTIFICATION
13  *	  src/backend/optimizer/plan/createplan.c
14  *
15  *-------------------------------------------------------------------------
16  */
17 #include "postgres.h"
18 
19 #include <limits.h>
20 #include <math.h>
21 
22 #include "access/sysattr.h"
23 #include "catalog/pg_class.h"
24 #include "foreign/fdwapi.h"
25 #include "miscadmin.h"
26 #include "nodes/extensible.h"
27 #include "nodes/makefuncs.h"
28 #include "nodes/nodeFuncs.h"
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/paramassign.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/placeholder.h"
34 #include "optimizer/plancat.h"
35 #include "optimizer/planmain.h"
36 #include "optimizer/predtest.h"
37 #include "optimizer/restrictinfo.h"
38 #include "optimizer/subselect.h"
39 #include "optimizer/tlist.h"
40 #include "optimizer/var.h"
41 #include "parser/parse_clause.h"
42 #include "parser/parsetree.h"
43 #include "utils/lsyscache.h"
44 
45 
46 /*
47  * Flag bits that can appear in the flags argument of create_plan_recurse().
48  * These can be OR-ed together.
49  *
50  * CP_EXACT_TLIST specifies that the generated plan node must return exactly
51  * the tlist specified by the path's pathtarget (this overrides both
52  * CP_SMALL_TLIST and CP_LABEL_TLIST, if those are set).  Otherwise, the
53  * plan node is allowed to return just the Vars and PlaceHolderVars needed
54  * to evaluate the pathtarget.
55  *
56  * CP_SMALL_TLIST specifies that a narrower tlist is preferred.  This is
57  * passed down by parent nodes such as Sort and Hash, which will have to
58  * store the returned tuples.
59  *
60  * CP_LABEL_TLIST specifies that the plan node must return columns matching
61  * any sortgrouprefs specified in its pathtarget, with appropriate
62  * ressortgroupref labels.  This is passed down by parent nodes such as Sort
63  * and Group, which need these values to be available in their inputs.
64  */
65 #define CP_EXACT_TLIST		0x0001	/* Plan must return specified tlist */
66 #define CP_SMALL_TLIST		0x0002	/* Prefer narrower tlists */
67 #define CP_LABEL_TLIST		0x0004	/* tlist must contain sortgrouprefs */
68 
69 
70 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
71 					int flags);
72 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
73 				 int flags);
74 static List *build_path_tlist(PlannerInfo *root, Path *path);
75 static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
76 static List *get_gating_quals(PlannerInfo *root, List *quals);
77 static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
78 				   List *gating_quals);
79 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
80 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
81 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
82 						 int flags);
83 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
84 static ProjectSet *create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path);
85 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
86 					 int flags);
87 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path,
88 				   int flags);
89 static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
90 static Plan *create_projection_plan(PlannerInfo *root, ProjectionPath *best_path);
91 static Plan *inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe);
92 static Sort *create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags);
93 static Group *create_group_plan(PlannerInfo *root, GroupPath *best_path);
94 static Unique *create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path,
95 						 int flags);
96 static Agg *create_agg_plan(PlannerInfo *root, AggPath *best_path);
97 static Plan *create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path);
98 static Result *create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path);
99 static WindowAgg *create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path);
100 static SetOp *create_setop_plan(PlannerInfo *root, SetOpPath *best_path,
101 				  int flags);
102 static RecursiveUnion *create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path);
103 static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
104 						   List *tlist,
105 						   int numSortCols, AttrNumber *sortColIdx,
106 						   int *partNumCols,
107 						   AttrNumber **partColIdx,
108 						   Oid **partOperators,
109 						   int *ordNumCols,
110 						   AttrNumber **ordColIdx,
111 						   Oid **ordOperators);
112 static LockRows *create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
113 					 int flags);
114 static ModifyTable *create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path);
115 static Limit *create_limit_plan(PlannerInfo *root, LimitPath *best_path,
116 				  int flags);
117 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
118 					List *tlist, List *scan_clauses);
119 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
120 					   List *tlist, List *scan_clauses);
121 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
122 					  List *tlist, List *scan_clauses, bool indexonly);
123 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
124 						BitmapHeapPath *best_path,
125 						List *tlist, List *scan_clauses);
126 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
127 					  List **qual, List **indexqual, List **indexECs);
128 static void bitmap_subplan_mark_shared(Plan *plan);
129 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
130 					List *tlist, List *scan_clauses);
131 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root,
132 						 SubqueryScanPath *best_path,
133 						 List *tlist, List *scan_clauses);
134 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
135 						 List *tlist, List *scan_clauses);
136 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
137 					   List *tlist, List *scan_clauses);
138 static TableFuncScan *create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
139 						  List *tlist, List *scan_clauses);
140 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
141 					List *tlist, List *scan_clauses);
142 static NamedTuplestoreScan *create_namedtuplestorescan_plan(PlannerInfo *root,
143 								Path *best_path, List *tlist, List *scan_clauses);
144 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
145 						  List *tlist, List *scan_clauses);
146 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
147 						List *tlist, List *scan_clauses);
148 static CustomScan *create_customscan_plan(PlannerInfo *root,
149 					   CustomPath *best_path,
150 					   List *tlist, List *scan_clauses);
151 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path);
152 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path);
153 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
154 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
155 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
156 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
157 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
158 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
159 static List *get_switched_clauses(List *clauses, Relids outerrelids);
160 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
161 static void copy_generic_path_info(Plan *dest, Path *src);
162 static void copy_plan_costsize(Plan *dest, Plan *src);
163 static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
164 						 double limit_tuples);
165 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
166 static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
167 				TableSampleClause *tsc);
168 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
169 			   Oid indexid, List *indexqual, List *indexqualorig,
170 			   List *indexorderby, List *indexorderbyorig,
171 			   List *indexorderbyops,
172 			   ScanDirection indexscandir);
173 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
174 				   Index scanrelid, Oid indexid,
175 				   List *indexqual, List *indexorderby,
176 				   List *indextlist,
177 				   ScanDirection indexscandir);
178 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
179 					  List *indexqual,
180 					  List *indexqualorig);
181 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
182 					 List *qpqual,
183 					 Plan *lefttree,
184 					 List *bitmapqualorig,
185 					 Index scanrelid);
186 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
187 			 List *tidquals);
188 static SubqueryScan *make_subqueryscan(List *qptlist,
189 				  List *qpqual,
190 				  Index scanrelid,
191 				  Plan *subplan);
192 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
193 				  Index scanrelid, List *functions, bool funcordinality);
194 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
195 				Index scanrelid, List *values_lists);
196 static TableFuncScan *make_tablefuncscan(List *qptlist, List *qpqual,
197 				   Index scanrelid, TableFunc *tablefunc);
198 static CteScan *make_ctescan(List *qptlist, List *qpqual,
199 			 Index scanrelid, int ctePlanId, int cteParam);
200 static NamedTuplestoreScan *make_namedtuplestorescan(List *qptlist, List *qpqual,
201 						 Index scanrelid, char *enrname);
202 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
203 				   Index scanrelid, int wtParam);
204 static Append *make_append(List *appendplans, List *tlist, List *partitioned_rels);
205 static RecursiveUnion *make_recursive_union(List *tlist,
206 					 Plan *lefttree,
207 					 Plan *righttree,
208 					 int wtParam,
209 					 List *distinctList,
210 					 long numGroups);
211 static BitmapAnd *make_bitmap_and(List *bitmapplans);
212 static BitmapOr *make_bitmap_or(List *bitmapplans);
213 static NestLoop *make_nestloop(List *tlist,
214 			  List *joinclauses, List *otherclauses, List *nestParams,
215 			  Plan *lefttree, Plan *righttree,
216 			  JoinType jointype, bool inner_unique);
217 static HashJoin *make_hashjoin(List *tlist,
218 			  List *joinclauses, List *otherclauses,
219 			  List *hashclauses,
220 			  Plan *lefttree, Plan *righttree,
221 			  JoinType jointype, bool inner_unique);
222 static Hash *make_hash(Plan *lefttree,
223 		  Oid skewTable,
224 		  AttrNumber skewColumn,
225 		  bool skewInherit);
226 static MergeJoin *make_mergejoin(List *tlist,
227 			   List *joinclauses, List *otherclauses,
228 			   List *mergeclauses,
229 			   Oid *mergefamilies,
230 			   Oid *mergecollations,
231 			   int *mergestrategies,
232 			   bool *mergenullsfirst,
233 			   Plan *lefttree, Plan *righttree,
234 			   JoinType jointype, bool inner_unique,
235 			   bool skip_mark_restore);
236 static Sort *make_sort(Plan *lefttree, int numCols,
237 		  AttrNumber *sortColIdx, Oid *sortOperators,
238 		  Oid *collations, bool *nullsFirst);
239 static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
240 						   Relids relids,
241 						   const AttrNumber *reqColIdx,
242 						   bool adjust_tlist_in_place,
243 						   int *p_numsortkeys,
244 						   AttrNumber **p_sortColIdx,
245 						   Oid **p_sortOperators,
246 						   Oid **p_collations,
247 						   bool **p_nullsFirst);
248 static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
249 					   TargetEntry *tle,
250 					   Relids relids);
251 static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys);
252 static Sort *make_sort_from_groupcols(List *groupcls,
253 						 AttrNumber *grpColIdx,
254 						 Plan *lefttree);
255 static Material *make_material(Plan *lefttree);
256 static WindowAgg *make_windowagg(List *tlist, Index winref,
257 			   int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
258 			   int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
259 			   int frameOptions, Node *startOffset, Node *endOffset,
260 			   Plan *lefttree);
261 static Group *make_group(List *tlist, List *qual, int numGroupCols,
262 		   AttrNumber *grpColIdx, Oid *grpOperators,
263 		   Plan *lefttree);
264 static Unique *make_unique_from_sortclauses(Plan *lefttree, List *distinctList);
265 static Unique *make_unique_from_pathkeys(Plan *lefttree,
266 						  List *pathkeys, int numCols);
267 static Gather *make_gather(List *qptlist, List *qpqual,
268 			int nworkers, int rescan_param, bool single_copy, Plan *subplan);
269 static SetOp *make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
270 		   List *distinctList, AttrNumber flagColIdx, int firstFlag,
271 		   long numGroups);
272 static LockRows *make_lockrows(Plan *lefttree, List *rowMarks, int epqParam);
273 static Result *make_result(List *tlist, Node *resconstantqual, Plan *subplan);
274 static ProjectSet *make_project_set(List *tlist, Plan *subplan);
275 static ModifyTable *make_modifytable(PlannerInfo *root,
276 				 CmdType operation, bool canSetTag,
277 				 Index nominalRelation, List *partitioned_rels,
278 				 List *resultRelations, List *subplans,
279 				 List *withCheckOptionLists, List *returningLists,
280 				 List *rowMarks, OnConflictExpr *onconflict, int epqParam);
281 static GatherMerge *create_gather_merge_plan(PlannerInfo *root,
282 						 GatherMergePath *best_path);
283 
284 
285 /*
286  * create_plan
287  *	  Creates the access plan for a query by recursively processing the
288  *	  desired tree of pathnodes, starting at the node 'best_path'.  For
289  *	  every pathnode found, we create a corresponding plan node containing
290  *	  appropriate id, target list, and qualification information.
291  *
292  *	  The tlists and quals in the plan tree are still in planner format,
293  *	  ie, Vars still correspond to the parser's numbering.  This will be
294  *	  fixed later by setrefs.c.
295  *
296  *	  best_path is the best access path
297  *
298  *	  Returns a Plan tree.
299  */
300 Plan *
create_plan(PlannerInfo * root,Path * best_path)301 create_plan(PlannerInfo *root, Path *best_path)
302 {
303 	Plan	   *plan;
304 
305 	/* plan_params should not be in use in current query level */
306 	Assert(root->plan_params == NIL);
307 
308 	/* Initialize this module's workspace in PlannerInfo */
309 	root->curOuterRels = NULL;
310 	root->curOuterParams = NIL;
311 
312 	/* Recursively process the path tree, demanding the correct tlist result */
313 	plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
314 
315 	/*
316 	 * Make sure the topmost plan node's targetlist exposes the original
317 	 * column names and other decorative info.  Targetlists generated within
318 	 * the planner don't bother with that stuff, but we must have it on the
319 	 * top-level tlist seen at execution time.  However, ModifyTable plan
320 	 * nodes don't have a tlist matching the querytree targetlist.
321 	 */
322 	if (!IsA(plan, ModifyTable))
323 		apply_tlist_labeling(plan->targetlist, root->processed_tlist);
324 
325 	/*
326 	 * Attach any initPlans created in this query level to the topmost plan
327 	 * node.  (In principle the initplans could go in any plan node at or
328 	 * above where they're referenced, but there seems no reason to put them
329 	 * any lower than the topmost node for the query level.  Also, see
330 	 * comments for SS_finalize_plan before you try to change this.)
331 	 */
332 	SS_attach_initplans(root, plan);
333 
334 	/* Check we successfully assigned all NestLoopParams to plan nodes */
335 	if (root->curOuterParams != NIL)
336 		elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
337 
338 	/*
339 	 * Reset plan_params to ensure param IDs used for nestloop params are not
340 	 * re-used later
341 	 */
342 	root->plan_params = NIL;
343 
344 	return plan;
345 }
346 
347 /*
348  * create_plan_recurse
349  *	  Recursive guts of create_plan().
350  */
351 static Plan *
create_plan_recurse(PlannerInfo * root,Path * best_path,int flags)352 create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
353 {
354 	Plan	   *plan;
355 
356 	/* Guard against stack overflow due to overly complex plans */
357 	check_stack_depth();
358 
359 	switch (best_path->pathtype)
360 	{
361 		case T_SeqScan:
362 		case T_SampleScan:
363 		case T_IndexScan:
364 		case T_IndexOnlyScan:
365 		case T_BitmapHeapScan:
366 		case T_TidScan:
367 		case T_SubqueryScan:
368 		case T_FunctionScan:
369 		case T_TableFuncScan:
370 		case T_ValuesScan:
371 		case T_CteScan:
372 		case T_WorkTableScan:
373 		case T_NamedTuplestoreScan:
374 		case T_ForeignScan:
375 		case T_CustomScan:
376 			plan = create_scan_plan(root, best_path, flags);
377 			break;
378 		case T_HashJoin:
379 		case T_MergeJoin:
380 		case T_NestLoop:
381 			plan = create_join_plan(root,
382 									(JoinPath *) best_path);
383 			break;
384 		case T_Append:
385 			plan = create_append_plan(root,
386 									  (AppendPath *) best_path);
387 			break;
388 		case T_MergeAppend:
389 			plan = create_merge_append_plan(root,
390 											(MergeAppendPath *) best_path,
391 											flags);
392 			break;
393 		case T_Result:
394 			if (IsA(best_path, ProjectionPath))
395 			{
396 				plan = create_projection_plan(root,
397 											  (ProjectionPath *) best_path);
398 			}
399 			else if (IsA(best_path, MinMaxAggPath))
400 			{
401 				plan = (Plan *) create_minmaxagg_plan(root,
402 													  (MinMaxAggPath *) best_path);
403 			}
404 			else
405 			{
406 				Assert(IsA(best_path, ResultPath));
407 				plan = (Plan *) create_result_plan(root,
408 												   (ResultPath *) best_path);
409 			}
410 			break;
411 		case T_ProjectSet:
412 			plan = (Plan *) create_project_set_plan(root,
413 													(ProjectSetPath *) best_path);
414 			break;
415 		case T_Material:
416 			plan = (Plan *) create_material_plan(root,
417 												 (MaterialPath *) best_path,
418 												 flags);
419 			break;
420 		case T_Unique:
421 			if (IsA(best_path, UpperUniquePath))
422 			{
423 				plan = (Plan *) create_upper_unique_plan(root,
424 														 (UpperUniquePath *) best_path,
425 														 flags);
426 			}
427 			else
428 			{
429 				Assert(IsA(best_path, UniquePath));
430 				plan = create_unique_plan(root,
431 										  (UniquePath *) best_path,
432 										  flags);
433 			}
434 			break;
435 		case T_Gather:
436 			plan = (Plan *) create_gather_plan(root,
437 											   (GatherPath *) best_path);
438 			break;
439 		case T_Sort:
440 			plan = (Plan *) create_sort_plan(root,
441 											 (SortPath *) best_path,
442 											 flags);
443 			break;
444 		case T_Group:
445 			plan = (Plan *) create_group_plan(root,
446 											  (GroupPath *) best_path);
447 			break;
448 		case T_Agg:
449 			if (IsA(best_path, GroupingSetsPath))
450 				plan = create_groupingsets_plan(root,
451 												(GroupingSetsPath *) best_path);
452 			else
453 			{
454 				Assert(IsA(best_path, AggPath));
455 				plan = (Plan *) create_agg_plan(root,
456 												(AggPath *) best_path);
457 			}
458 			break;
459 		case T_WindowAgg:
460 			plan = (Plan *) create_windowagg_plan(root,
461 												  (WindowAggPath *) best_path);
462 			break;
463 		case T_SetOp:
464 			plan = (Plan *) create_setop_plan(root,
465 											  (SetOpPath *) best_path,
466 											  flags);
467 			break;
468 		case T_RecursiveUnion:
469 			plan = (Plan *) create_recursiveunion_plan(root,
470 													   (RecursiveUnionPath *) best_path);
471 			break;
472 		case T_LockRows:
473 			plan = (Plan *) create_lockrows_plan(root,
474 												 (LockRowsPath *) best_path,
475 												 flags);
476 			break;
477 		case T_ModifyTable:
478 			plan = (Plan *) create_modifytable_plan(root,
479 													(ModifyTablePath *) best_path);
480 			break;
481 		case T_Limit:
482 			plan = (Plan *) create_limit_plan(root,
483 											  (LimitPath *) best_path,
484 											  flags);
485 			break;
486 		case T_GatherMerge:
487 			plan = (Plan *) create_gather_merge_plan(root,
488 													 (GatherMergePath *) best_path);
489 			break;
490 		default:
491 			elog(ERROR, "unrecognized node type: %d",
492 				 (int) best_path->pathtype);
493 			plan = NULL;		/* keep compiler quiet */
494 			break;
495 	}
496 
497 	return plan;
498 }
499 
500 /*
501  * create_scan_plan
502  *	 Create a scan plan for the parent relation of 'best_path'.
503  */
504 static Plan *
create_scan_plan(PlannerInfo * root,Path * best_path,int flags)505 create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
506 {
507 	RelOptInfo *rel = best_path->parent;
508 	List	   *scan_clauses;
509 	List	   *gating_clauses;
510 	List	   *tlist;
511 	Plan	   *plan;
512 
513 	/*
514 	 * Extract the relevant restriction clauses from the parent relation. The
515 	 * executor must apply all these restrictions during the scan, except for
516 	 * pseudoconstants which we'll take care of below.
517 	 *
518 	 * If this is a plain indexscan or index-only scan, we need not consider
519 	 * restriction clauses that are implied by the index's predicate, so use
520 	 * indrestrictinfo not baserestrictinfo.  Note that we can't do that for
521 	 * bitmap indexscans, since there's not necessarily a single index
522 	 * involved; but it doesn't matter since create_bitmap_scan_plan() will be
523 	 * able to get rid of such clauses anyway via predicate proof.
524 	 */
525 	switch (best_path->pathtype)
526 	{
527 		case T_IndexScan:
528 		case T_IndexOnlyScan:
529 			scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
530 			break;
531 		default:
532 			scan_clauses = rel->baserestrictinfo;
533 			break;
534 	}
535 
536 	/*
537 	 * If this is a parameterized scan, we also need to enforce all the join
538 	 * clauses available from the outer relation(s).
539 	 *
540 	 * For paranoia's sake, don't modify the stored baserestrictinfo list.
541 	 */
542 	if (best_path->param_info)
543 		scan_clauses = list_concat(list_copy(scan_clauses),
544 								   best_path->param_info->ppi_clauses);
545 
546 	/*
547 	 * Detect whether we have any pseudoconstant quals to deal with.  Then, if
548 	 * we'll need a gating Result node, it will be able to project, so there
549 	 * are no requirements on the child's tlist.
550 	 */
551 	gating_clauses = get_gating_quals(root, scan_clauses);
552 	if (gating_clauses)
553 		flags = 0;
554 
555 	/*
556 	 * For table scans, rather than using the relation targetlist (which is
557 	 * only those Vars actually needed by the query), we prefer to generate a
558 	 * tlist containing all Vars in order.  This will allow the executor to
559 	 * optimize away projection of the table tuples, if possible.
560 	 */
561 	if (use_physical_tlist(root, best_path, flags))
562 	{
563 		if (best_path->pathtype == T_IndexOnlyScan)
564 		{
565 			/* For index-only scan, the preferred tlist is the index's */
566 			tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
567 
568 			/*
569 			 * Transfer sortgroupref data to the replacement tlist, if
570 			 * requested (use_physical_tlist checked that this will work).
571 			 */
572 			if (flags & CP_LABEL_TLIST)
573 				apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
574 		}
575 		else
576 		{
577 			tlist = build_physical_tlist(root, rel);
578 			if (tlist == NIL)
579 			{
580 				/* Failed because of dropped cols, so use regular method */
581 				tlist = build_path_tlist(root, best_path);
582 			}
583 			else
584 			{
585 				/* As above, transfer sortgroupref data to replacement tlist */
586 				if (flags & CP_LABEL_TLIST)
587 					apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
588 			}
589 		}
590 	}
591 	else
592 	{
593 		tlist = build_path_tlist(root, best_path);
594 	}
595 
596 	switch (best_path->pathtype)
597 	{
598 		case T_SeqScan:
599 			plan = (Plan *) create_seqscan_plan(root,
600 												best_path,
601 												tlist,
602 												scan_clauses);
603 			break;
604 
605 		case T_SampleScan:
606 			plan = (Plan *) create_samplescan_plan(root,
607 												   best_path,
608 												   tlist,
609 												   scan_clauses);
610 			break;
611 
612 		case T_IndexScan:
613 			plan = (Plan *) create_indexscan_plan(root,
614 												  (IndexPath *) best_path,
615 												  tlist,
616 												  scan_clauses,
617 												  false);
618 			break;
619 
620 		case T_IndexOnlyScan:
621 			plan = (Plan *) create_indexscan_plan(root,
622 												  (IndexPath *) best_path,
623 												  tlist,
624 												  scan_clauses,
625 												  true);
626 			break;
627 
628 		case T_BitmapHeapScan:
629 			plan = (Plan *) create_bitmap_scan_plan(root,
630 													(BitmapHeapPath *) best_path,
631 													tlist,
632 													scan_clauses);
633 			break;
634 
635 		case T_TidScan:
636 			plan = (Plan *) create_tidscan_plan(root,
637 												(TidPath *) best_path,
638 												tlist,
639 												scan_clauses);
640 			break;
641 
642 		case T_SubqueryScan:
643 			plan = (Plan *) create_subqueryscan_plan(root,
644 													 (SubqueryScanPath *) best_path,
645 													 tlist,
646 													 scan_clauses);
647 			break;
648 
649 		case T_FunctionScan:
650 			plan = (Plan *) create_functionscan_plan(root,
651 													 best_path,
652 													 tlist,
653 													 scan_clauses);
654 			break;
655 
656 		case T_TableFuncScan:
657 			plan = (Plan *) create_tablefuncscan_plan(root,
658 													  best_path,
659 													  tlist,
660 													  scan_clauses);
661 			break;
662 
663 		case T_ValuesScan:
664 			plan = (Plan *) create_valuesscan_plan(root,
665 												   best_path,
666 												   tlist,
667 												   scan_clauses);
668 			break;
669 
670 		case T_CteScan:
671 			plan = (Plan *) create_ctescan_plan(root,
672 												best_path,
673 												tlist,
674 												scan_clauses);
675 			break;
676 
677 		case T_NamedTuplestoreScan:
678 			plan = (Plan *) create_namedtuplestorescan_plan(root,
679 															best_path,
680 															tlist,
681 															scan_clauses);
682 			break;
683 
684 		case T_WorkTableScan:
685 			plan = (Plan *) create_worktablescan_plan(root,
686 													  best_path,
687 													  tlist,
688 													  scan_clauses);
689 			break;
690 
691 		case T_ForeignScan:
692 			plan = (Plan *) create_foreignscan_plan(root,
693 													(ForeignPath *) best_path,
694 													tlist,
695 													scan_clauses);
696 			break;
697 
698 		case T_CustomScan:
699 			plan = (Plan *) create_customscan_plan(root,
700 												   (CustomPath *) best_path,
701 												   tlist,
702 												   scan_clauses);
703 			break;
704 
705 		default:
706 			elog(ERROR, "unrecognized node type: %d",
707 				 (int) best_path->pathtype);
708 			plan = NULL;		/* keep compiler quiet */
709 			break;
710 	}
711 
712 	/*
713 	 * If there are any pseudoconstant clauses attached to this node, insert a
714 	 * gating Result node that evaluates the pseudoconstants as one-time
715 	 * quals.
716 	 */
717 	if (gating_clauses)
718 		plan = create_gating_plan(root, best_path, plan, gating_clauses);
719 
720 	return plan;
721 }
722 
723 /*
724  * Build a target list (ie, a list of TargetEntry) for the Path's output.
725  *
726  * This is almost just make_tlist_from_pathtarget(), but we also have to
727  * deal with replacing nestloop params.
728  */
729 static List *
build_path_tlist(PlannerInfo * root,Path * path)730 build_path_tlist(PlannerInfo *root, Path *path)
731 {
732 	List	   *tlist = NIL;
733 	Index	   *sortgrouprefs = path->pathtarget->sortgrouprefs;
734 	int			resno = 1;
735 	ListCell   *v;
736 
737 	foreach(v, path->pathtarget->exprs)
738 	{
739 		Node	   *node = (Node *) lfirst(v);
740 		TargetEntry *tle;
741 
742 		/*
743 		 * If it's a parameterized path, there might be lateral references in
744 		 * the tlist, which need to be replaced with Params.  There's no need
745 		 * to remake the TargetEntry nodes, so apply this to each list item
746 		 * separately.
747 		 */
748 		if (path->param_info)
749 			node = replace_nestloop_params(root, node);
750 
751 		tle = makeTargetEntry((Expr *) node,
752 							  resno,
753 							  NULL,
754 							  false);
755 		if (sortgrouprefs)
756 			tle->ressortgroupref = sortgrouprefs[resno - 1];
757 
758 		tlist = lappend(tlist, tle);
759 		resno++;
760 	}
761 	return tlist;
762 }
763 
764 /*
765  * use_physical_tlist
766  *		Decide whether to use a tlist matching relation structure,
767  *		rather than only those Vars actually referenced.
768  */
769 static bool
use_physical_tlist(PlannerInfo * root,Path * path,int flags)770 use_physical_tlist(PlannerInfo *root, Path *path, int flags)
771 {
772 	RelOptInfo *rel = path->parent;
773 	int			i;
774 	ListCell   *lc;
775 
776 	/*
777 	 * Forget it if either exact tlist or small tlist is demanded.
778 	 */
779 	if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
780 		return false;
781 
782 	/*
783 	 * We can do this for real relation scans, subquery scans, function scans,
784 	 * tablefunc scans, values scans, and CTE scans (but not for, eg, joins).
785 	 */
786 	if (rel->rtekind != RTE_RELATION &&
787 		rel->rtekind != RTE_SUBQUERY &&
788 		rel->rtekind != RTE_FUNCTION &&
789 		rel->rtekind != RTE_TABLEFUNC &&
790 		rel->rtekind != RTE_VALUES &&
791 		rel->rtekind != RTE_CTE)
792 		return false;
793 
794 	/*
795 	 * Can't do it with inheritance cases either (mainly because Append
796 	 * doesn't project; this test may be unnecessary now that
797 	 * create_append_plan instructs its children to return an exact tlist).
798 	 */
799 	if (rel->reloptkind != RELOPT_BASEREL)
800 		return false;
801 
802 	/*
803 	 * Also, don't do it to a CustomPath; the premise that we're extracting
804 	 * columns from a simple physical tuple is unlikely to hold for those.
805 	 * (When it does make sense, the custom path creator can set up the path's
806 	 * pathtarget that way.)
807 	 */
808 	if (IsA(path, CustomPath))
809 		return false;
810 
811 	/*
812 	 * Can't do it if any system columns or whole-row Vars are requested.
813 	 * (This could possibly be fixed but would take some fragile assumptions
814 	 * in setrefs.c, I think.)
815 	 */
816 	for (i = rel->min_attr; i <= 0; i++)
817 	{
818 		if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
819 			return false;
820 	}
821 
822 	/*
823 	 * Can't do it if the rel is required to emit any placeholder expressions,
824 	 * either.
825 	 */
826 	foreach(lc, root->placeholder_list)
827 	{
828 		PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
829 
830 		if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
831 			bms_is_subset(phinfo->ph_eval_at, rel->relids))
832 			return false;
833 	}
834 
835 	/*
836 	 * Also, can't do it if CP_LABEL_TLIST is specified and path is requested
837 	 * to emit any sort/group columns that are not simple Vars.  (If they are
838 	 * simple Vars, they should appear in the physical tlist, and
839 	 * apply_pathtarget_labeling_to_tlist will take care of getting them
840 	 * labeled again.)	We also have to check that no two sort/group columns
841 	 * are the same Var, else that element of the physical tlist would need
842 	 * conflicting ressortgroupref labels.
843 	 */
844 	if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
845 	{
846 		Bitmapset  *sortgroupatts = NULL;
847 
848 		i = 0;
849 		foreach(lc, path->pathtarget->exprs)
850 		{
851 			Expr	   *expr = (Expr *) lfirst(lc);
852 
853 			if (path->pathtarget->sortgrouprefs[i])
854 			{
855 				if (expr && IsA(expr, Var))
856 				{
857 					int			attno = ((Var *) expr)->varattno;
858 
859 					attno -= FirstLowInvalidHeapAttributeNumber;
860 					if (bms_is_member(attno, sortgroupatts))
861 						return false;
862 					sortgroupatts = bms_add_member(sortgroupatts, attno);
863 				}
864 				else
865 					return false;
866 			}
867 			i++;
868 		}
869 	}
870 
871 	return true;
872 }
873 
874 /*
875  * get_gating_quals
876  *	  See if there are pseudoconstant quals in a node's quals list
877  *
878  * If the node's quals list includes any pseudoconstant quals,
879  * return just those quals.
880  */
881 static List *
get_gating_quals(PlannerInfo * root,List * quals)882 get_gating_quals(PlannerInfo *root, List *quals)
883 {
884 	/* No need to look if we know there are no pseudoconstants */
885 	if (!root->hasPseudoConstantQuals)
886 		return NIL;
887 
888 	/* Sort into desirable execution order while still in RestrictInfo form */
889 	quals = order_qual_clauses(root, quals);
890 
891 	/* Pull out any pseudoconstant quals from the RestrictInfo list */
892 	return extract_actual_clauses(quals, true);
893 }
894 
895 /*
896  * create_gating_plan
897  *	  Deal with pseudoconstant qual clauses
898  *
899  * Add a gating Result node atop the already-built plan.
900  */
901 static Plan *
create_gating_plan(PlannerInfo * root,Path * path,Plan * plan,List * gating_quals)902 create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
903 				   List *gating_quals)
904 {
905 	Plan	   *gplan;
906 
907 	Assert(gating_quals);
908 
909 	/*
910 	 * Since we need a Result node anyway, always return the path's requested
911 	 * tlist; that's never a wrong choice, even if the parent node didn't ask
912 	 * for CP_EXACT_TLIST.
913 	 */
914 	gplan = (Plan *) make_result(build_path_tlist(root, path),
915 								 (Node *) gating_quals,
916 								 plan);
917 
918 	/*
919 	 * Notice that we don't change cost or size estimates when doing gating.
920 	 * The costs of qual eval were already included in the subplan's cost.
921 	 * Leaving the size alone amounts to assuming that the gating qual will
922 	 * succeed, which is the conservative estimate for planning upper queries.
923 	 * We certainly don't want to assume the output size is zero (unless the
924 	 * gating qual is actually constant FALSE, and that case is dealt with in
925 	 * clausesel.c).  Interpolating between the two cases is silly, because it
926 	 * doesn't reflect what will really happen at runtime, and besides which
927 	 * in most cases we have only a very bad idea of the probability of the
928 	 * gating qual being true.
929 	 */
930 	copy_plan_costsize(gplan, plan);
931 
932 	/* Gating quals could be unsafe, so better use the Path's safety flag */
933 	gplan->parallel_safe = path->parallel_safe;
934 
935 	return gplan;
936 }
937 
938 /*
939  * create_join_plan
940  *	  Create a join plan for 'best_path' and (recursively) plans for its
941  *	  inner and outer paths.
942  */
943 static Plan *
create_join_plan(PlannerInfo * root,JoinPath * best_path)944 create_join_plan(PlannerInfo *root, JoinPath *best_path)
945 {
946 	Plan	   *plan;
947 	List	   *gating_clauses;
948 
949 	switch (best_path->path.pathtype)
950 	{
951 		case T_MergeJoin:
952 			plan = (Plan *) create_mergejoin_plan(root,
953 												  (MergePath *) best_path);
954 			break;
955 		case T_HashJoin:
956 			plan = (Plan *) create_hashjoin_plan(root,
957 												 (HashPath *) best_path);
958 			break;
959 		case T_NestLoop:
960 			plan = (Plan *) create_nestloop_plan(root,
961 												 (NestPath *) best_path);
962 			break;
963 		default:
964 			elog(ERROR, "unrecognized node type: %d",
965 				 (int) best_path->path.pathtype);
966 			plan = NULL;		/* keep compiler quiet */
967 			break;
968 	}
969 
970 	/*
971 	 * If there are any pseudoconstant clauses attached to this node, insert a
972 	 * gating Result node that evaluates the pseudoconstants as one-time
973 	 * quals.
974 	 */
975 	gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
976 	if (gating_clauses)
977 		plan = create_gating_plan(root, (Path *) best_path, plan,
978 								  gating_clauses);
979 
980 #ifdef NOT_USED
981 
982 	/*
983 	 * * Expensive function pullups may have pulled local predicates * into
984 	 * this path node.  Put them in the qpqual of the plan node. * JMH,
985 	 * 6/15/92
986 	 */
987 	if (get_loc_restrictinfo(best_path) != NIL)
988 		set_qpqual((Plan) plan,
989 				   list_concat(get_qpqual((Plan) plan),
990 							   get_actual_clauses(get_loc_restrictinfo(best_path))));
991 #endif
992 
993 	return plan;
994 }
995 
996 /*
997  * create_append_plan
998  *	  Create an Append plan for 'best_path' and (recursively) plans
999  *	  for its subpaths.
1000  *
1001  *	  Returns a Plan node.
1002  */
1003 static Plan *
create_append_plan(PlannerInfo * root,AppendPath * best_path)1004 create_append_plan(PlannerInfo *root, AppendPath *best_path)
1005 {
1006 	Append	   *plan;
1007 	List	   *tlist = build_path_tlist(root, &best_path->path);
1008 	List	   *subplans = NIL;
1009 	ListCell   *subpaths;
1010 
1011 	/*
1012 	 * The subpaths list could be empty, if every child was proven empty by
1013 	 * constraint exclusion.  In that case generate a dummy plan that returns
1014 	 * no rows.
1015 	 *
1016 	 * Note that an AppendPath with no members is also generated in certain
1017 	 * cases where there was no appending construct at all, but we know the
1018 	 * relation is empty (see set_dummy_rel_pathlist and mark_dummy_rel).
1019 	 */
1020 	if (best_path->subpaths == NIL)
1021 	{
1022 		/* Generate a Result plan with constant-FALSE gating qual */
1023 		Plan	   *plan;
1024 
1025 		plan = (Plan *) make_result(tlist,
1026 									(Node *) list_make1(makeBoolConst(false,
1027 																	  false)),
1028 									NULL);
1029 
1030 		copy_generic_path_info(plan, (Path *) best_path);
1031 
1032 		return plan;
1033 	}
1034 
1035 	/* Build the plan for each child */
1036 	foreach(subpaths, best_path->subpaths)
1037 	{
1038 		Path	   *subpath = (Path *) lfirst(subpaths);
1039 		Plan	   *subplan;
1040 
1041 		/* Must insist that all children return the same tlist */
1042 		subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1043 
1044 		subplans = lappend(subplans, subplan);
1045 	}
1046 
1047 	/*
1048 	 * XXX ideally, if there's just one child, we'd not bother to generate an
1049 	 * Append node but just return the single child.  At the moment this does
1050 	 * not work because the varno of the child scan plan won't match the
1051 	 * parent-rel Vars it'll be asked to emit.
1052 	 */
1053 
1054 	plan = make_append(subplans, tlist, best_path->partitioned_rels);
1055 
1056 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1057 
1058 	return (Plan *) plan;
1059 }
1060 
1061 /*
1062  * create_merge_append_plan
1063  *	  Create a MergeAppend plan for 'best_path' and (recursively) plans
1064  *	  for its subpaths.
1065  *
1066  *	  Returns a Plan node.
1067  */
1068 static Plan *
create_merge_append_plan(PlannerInfo * root,MergeAppendPath * best_path,int flags)1069 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
1070 						 int flags)
1071 {
1072 	MergeAppend *node = makeNode(MergeAppend);
1073 	Plan	   *plan = &node->plan;
1074 	List	   *tlist = build_path_tlist(root, &best_path->path);
1075 	int			orig_tlist_length = list_length(tlist);
1076 	bool		tlist_was_changed;
1077 	List	   *pathkeys = best_path->path.pathkeys;
1078 	List	   *subplans = NIL;
1079 	ListCell   *subpaths;
1080 
1081 	/*
1082 	 * We don't have the actual creation of the MergeAppend node split out
1083 	 * into a separate make_xxx function.  This is because we want to run
1084 	 * prepare_sort_from_pathkeys on it before we do so on the individual
1085 	 * child plans, to make cross-checking the sort info easier.
1086 	 */
1087 	copy_generic_path_info(plan, (Path *) best_path);
1088 	plan->targetlist = tlist;
1089 	plan->qual = NIL;
1090 	plan->lefttree = NULL;
1091 	plan->righttree = NULL;
1092 
1093 	/*
1094 	 * Compute sort column info, and adjust MergeAppend's tlist as needed.
1095 	 * Because we pass adjust_tlist_in_place = true, we may ignore the
1096 	 * function result; it must be the same plan node.  However, we then need
1097 	 * to detect whether any tlist entries were added.
1098 	 */
1099 	(void) prepare_sort_from_pathkeys(plan, pathkeys,
1100 									  best_path->path.parent->relids,
1101 									  NULL,
1102 									  true,
1103 									  &node->numCols,
1104 									  &node->sortColIdx,
1105 									  &node->sortOperators,
1106 									  &node->collations,
1107 									  &node->nullsFirst);
1108 	tlist_was_changed = (orig_tlist_length != list_length(plan->targetlist));
1109 
1110 	/*
1111 	 * Now prepare the child plans.  We must apply prepare_sort_from_pathkeys
1112 	 * even to subplans that don't need an explicit sort, to make sure they
1113 	 * are returning the same sort key columns the MergeAppend expects.
1114 	 */
1115 	foreach(subpaths, best_path->subpaths)
1116 	{
1117 		Path	   *subpath = (Path *) lfirst(subpaths);
1118 		Plan	   *subplan;
1119 		int			numsortkeys;
1120 		AttrNumber *sortColIdx;
1121 		Oid		   *sortOperators;
1122 		Oid		   *collations;
1123 		bool	   *nullsFirst;
1124 
1125 		/* Build the child plan */
1126 		/* Must insist that all children return the same tlist */
1127 		subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1128 
1129 		/* Compute sort column info, and adjust subplan's tlist as needed */
1130 		subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1131 											 subpath->parent->relids,
1132 											 node->sortColIdx,
1133 											 false,
1134 											 &numsortkeys,
1135 											 &sortColIdx,
1136 											 &sortOperators,
1137 											 &collations,
1138 											 &nullsFirst);
1139 
1140 		/*
1141 		 * Check that we got the same sort key information.  We just Assert
1142 		 * that the sortops match, since those depend only on the pathkeys;
1143 		 * but it seems like a good idea to check the sort column numbers
1144 		 * explicitly, to ensure the tlists really do match up.
1145 		 */
1146 		Assert(numsortkeys == node->numCols);
1147 		if (memcmp(sortColIdx, node->sortColIdx,
1148 				   numsortkeys * sizeof(AttrNumber)) != 0)
1149 			elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
1150 		Assert(memcmp(sortOperators, node->sortOperators,
1151 					  numsortkeys * sizeof(Oid)) == 0);
1152 		Assert(memcmp(collations, node->collations,
1153 					  numsortkeys * sizeof(Oid)) == 0);
1154 		Assert(memcmp(nullsFirst, node->nullsFirst,
1155 					  numsortkeys * sizeof(bool)) == 0);
1156 
1157 		/* Now, insert a Sort node if subplan isn't sufficiently ordered */
1158 		if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1159 		{
1160 			Sort	   *sort = make_sort(subplan, numsortkeys,
1161 										 sortColIdx, sortOperators,
1162 										 collations, nullsFirst);
1163 
1164 			label_sort_with_costsize(root, sort, best_path->limit_tuples);
1165 			subplan = (Plan *) sort;
1166 		}
1167 
1168 		subplans = lappend(subplans, subplan);
1169 	}
1170 
1171 	node->partitioned_rels = best_path->partitioned_rels;
1172 	node->mergeplans = subplans;
1173 
1174 	/*
1175 	 * If prepare_sort_from_pathkeys added sort columns, but we were told to
1176 	 * produce either the exact tlist or a narrow tlist, we should get rid of
1177 	 * the sort columns again.  We must inject a projection node to do so.
1178 	 */
1179 	if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
1180 	{
1181 		tlist = list_truncate(list_copy(plan->targetlist), orig_tlist_length);
1182 		return inject_projection_plan(plan, tlist, plan->parallel_safe);
1183 	}
1184 	else
1185 		return plan;
1186 }
1187 
1188 /*
1189  * create_result_plan
1190  *	  Create a Result plan for 'best_path'.
1191  *	  This is only used for degenerate cases, such as a query with an empty
1192  *	  jointree.
1193  *
1194  *	  Returns a Plan node.
1195  */
1196 static Result *
create_result_plan(PlannerInfo * root,ResultPath * best_path)1197 create_result_plan(PlannerInfo *root, ResultPath *best_path)
1198 {
1199 	Result	   *plan;
1200 	List	   *tlist;
1201 	List	   *quals;
1202 
1203 	tlist = build_path_tlist(root, &best_path->path);
1204 
1205 	/* best_path->quals is just bare clauses */
1206 	quals = order_qual_clauses(root, best_path->quals);
1207 
1208 	plan = make_result(tlist, (Node *) quals, NULL);
1209 
1210 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1211 
1212 	return plan;
1213 }
1214 
1215 /*
1216  * create_project_set_plan
1217  *	  Create a ProjectSet plan for 'best_path'.
1218  *
1219  *	  Returns a Plan node.
1220  */
1221 static ProjectSet *
create_project_set_plan(PlannerInfo * root,ProjectSetPath * best_path)1222 create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path)
1223 {
1224 	ProjectSet *plan;
1225 	Plan	   *subplan;
1226 	List	   *tlist;
1227 
1228 	/* Since we intend to project, we don't need to constrain child tlist */
1229 	subplan = create_plan_recurse(root, best_path->subpath, 0);
1230 
1231 	tlist = build_path_tlist(root, &best_path->path);
1232 
1233 	plan = make_project_set(tlist, subplan);
1234 
1235 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1236 
1237 	return plan;
1238 }
1239 
1240 /*
1241  * create_material_plan
1242  *	  Create a Material plan for 'best_path' and (recursively) plans
1243  *	  for its subpaths.
1244  *
1245  *	  Returns a Plan node.
1246  */
1247 static Material *
create_material_plan(PlannerInfo * root,MaterialPath * best_path,int flags)1248 create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
1249 {
1250 	Material   *plan;
1251 	Plan	   *subplan;
1252 
1253 	/*
1254 	 * We don't want any excess columns in the materialized tuples, so request
1255 	 * a smaller tlist.  Otherwise, since Material doesn't project, tlist
1256 	 * requirements pass through.
1257 	 */
1258 	subplan = create_plan_recurse(root, best_path->subpath,
1259 								  flags | CP_SMALL_TLIST);
1260 
1261 	plan = make_material(subplan);
1262 
1263 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1264 
1265 	return plan;
1266 }
1267 
1268 /*
1269  * create_unique_plan
1270  *	  Create a Unique plan for 'best_path' and (recursively) plans
1271  *	  for its subpaths.
1272  *
1273  *	  Returns a Plan node.
1274  */
1275 static Plan *
create_unique_plan(PlannerInfo * root,UniquePath * best_path,int flags)1276 create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
1277 {
1278 	Plan	   *plan;
1279 	Plan	   *subplan;
1280 	List	   *in_operators;
1281 	List	   *uniq_exprs;
1282 	List	   *newtlist;
1283 	int			nextresno;
1284 	bool		newitems;
1285 	int			numGroupCols;
1286 	AttrNumber *groupColIdx;
1287 	int			groupColPos;
1288 	ListCell   *l;
1289 
1290 	/* Unique doesn't project, so tlist requirements pass through */
1291 	subplan = create_plan_recurse(root, best_path->subpath, flags);
1292 
1293 	/* Done if we don't need to do any actual unique-ifying */
1294 	if (best_path->umethod == UNIQUE_PATH_NOOP)
1295 		return subplan;
1296 
1297 	/*
1298 	 * As constructed, the subplan has a "flat" tlist containing just the Vars
1299 	 * needed here and at upper levels.  The values we are supposed to
1300 	 * unique-ify may be expressions in these variables.  We have to add any
1301 	 * such expressions to the subplan's tlist.
1302 	 *
1303 	 * The subplan may have a "physical" tlist if it is a simple scan plan. If
1304 	 * we're going to sort, this should be reduced to the regular tlist, so
1305 	 * that we don't sort more data than we need to.  For hashing, the tlist
1306 	 * should be left as-is if we don't need to add any expressions; but if we
1307 	 * do have to add expressions, then a projection step will be needed at
1308 	 * runtime anyway, so we may as well remove unneeded items. Therefore
1309 	 * newtlist starts from build_path_tlist() not just a copy of the
1310 	 * subplan's tlist; and we don't install it into the subplan unless we are
1311 	 * sorting or stuff has to be added.
1312 	 */
1313 	in_operators = best_path->in_operators;
1314 	uniq_exprs = best_path->uniq_exprs;
1315 
1316 	/* initialize modified subplan tlist as just the "required" vars */
1317 	newtlist = build_path_tlist(root, &best_path->path);
1318 	nextresno = list_length(newtlist) + 1;
1319 	newitems = false;
1320 
1321 	foreach(l, uniq_exprs)
1322 	{
1323 		Expr	   *uniqexpr = lfirst(l);
1324 		TargetEntry *tle;
1325 
1326 		tle = tlist_member(uniqexpr, newtlist);
1327 		if (!tle)
1328 		{
1329 			tle = makeTargetEntry((Expr *) uniqexpr,
1330 								  nextresno,
1331 								  NULL,
1332 								  false);
1333 			newtlist = lappend(newtlist, tle);
1334 			nextresno++;
1335 			newitems = true;
1336 		}
1337 	}
1338 
1339 	/* Use change_plan_targetlist in case we need to insert a Result node */
1340 	if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
1341 		subplan = change_plan_targetlist(subplan, newtlist,
1342 										 best_path->path.parallel_safe);
1343 
1344 	/*
1345 	 * Build control information showing which subplan output columns are to
1346 	 * be examined by the grouping step.  Unfortunately we can't merge this
1347 	 * with the previous loop, since we didn't then know which version of the
1348 	 * subplan tlist we'd end up using.
1349 	 */
1350 	newtlist = subplan->targetlist;
1351 	numGroupCols = list_length(uniq_exprs);
1352 	groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
1353 
1354 	groupColPos = 0;
1355 	foreach(l, uniq_exprs)
1356 	{
1357 		Expr	   *uniqexpr = lfirst(l);
1358 		TargetEntry *tle;
1359 
1360 		tle = tlist_member(uniqexpr, newtlist);
1361 		if (!tle)				/* shouldn't happen */
1362 			elog(ERROR, "failed to find unique expression in subplan tlist");
1363 		groupColIdx[groupColPos++] = tle->resno;
1364 	}
1365 
1366 	if (best_path->umethod == UNIQUE_PATH_HASH)
1367 	{
1368 		Oid		   *groupOperators;
1369 
1370 		/*
1371 		 * Get the hashable equality operators for the Agg node to use.
1372 		 * Normally these are the same as the IN clause operators, but if
1373 		 * those are cross-type operators then the equality operators are the
1374 		 * ones for the IN clause operators' RHS datatype.
1375 		 */
1376 		groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
1377 		groupColPos = 0;
1378 		foreach(l, in_operators)
1379 		{
1380 			Oid			in_oper = lfirst_oid(l);
1381 			Oid			eq_oper;
1382 
1383 			if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
1384 				elog(ERROR, "could not find compatible hash operator for operator %u",
1385 					 in_oper);
1386 			groupOperators[groupColPos++] = eq_oper;
1387 		}
1388 
1389 		/*
1390 		 * Since the Agg node is going to project anyway, we can give it the
1391 		 * minimum output tlist, without any stuff we might have added to the
1392 		 * subplan tlist.
1393 		 */
1394 		plan = (Plan *) make_agg(build_path_tlist(root, &best_path->path),
1395 								 NIL,
1396 								 AGG_HASHED,
1397 								 AGGSPLIT_SIMPLE,
1398 								 numGroupCols,
1399 								 groupColIdx,
1400 								 groupOperators,
1401 								 NIL,
1402 								 NIL,
1403 								 best_path->path.rows,
1404 								 subplan);
1405 	}
1406 	else
1407 	{
1408 		List	   *sortList = NIL;
1409 		Sort	   *sort;
1410 
1411 		/* Create an ORDER BY list to sort the input compatibly */
1412 		groupColPos = 0;
1413 		foreach(l, in_operators)
1414 		{
1415 			Oid			in_oper = lfirst_oid(l);
1416 			Oid			sortop;
1417 			Oid			eqop;
1418 			TargetEntry *tle;
1419 			SortGroupClause *sortcl;
1420 
1421 			sortop = get_ordering_op_for_equality_op(in_oper, false);
1422 			if (!OidIsValid(sortop))	/* shouldn't happen */
1423 				elog(ERROR, "could not find ordering operator for equality operator %u",
1424 					 in_oper);
1425 
1426 			/*
1427 			 * The Unique node will need equality operators.  Normally these
1428 			 * are the same as the IN clause operators, but if those are
1429 			 * cross-type operators then the equality operators are the ones
1430 			 * for the IN clause operators' RHS datatype.
1431 			 */
1432 			eqop = get_equality_op_for_ordering_op(sortop, NULL);
1433 			if (!OidIsValid(eqop))	/* shouldn't happen */
1434 				elog(ERROR, "could not find equality operator for ordering operator %u",
1435 					 sortop);
1436 
1437 			tle = get_tle_by_resno(subplan->targetlist,
1438 								   groupColIdx[groupColPos]);
1439 			Assert(tle != NULL);
1440 
1441 			sortcl = makeNode(SortGroupClause);
1442 			sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1443 														 subplan->targetlist);
1444 			sortcl->eqop = eqop;
1445 			sortcl->sortop = sortop;
1446 			sortcl->nulls_first = false;
1447 			sortcl->hashable = false;	/* no need to make this accurate */
1448 			sortList = lappend(sortList, sortcl);
1449 			groupColPos++;
1450 		}
1451 		sort = make_sort_from_sortclauses(sortList, subplan);
1452 		label_sort_with_costsize(root, sort, -1.0);
1453 		plan = (Plan *) make_unique_from_sortclauses((Plan *) sort, sortList);
1454 	}
1455 
1456 	/* Copy cost data from Path to Plan */
1457 	copy_generic_path_info(plan, &best_path->path);
1458 
1459 	return plan;
1460 }
1461 
1462 /*
1463  * create_gather_plan
1464  *
1465  *	  Create a Gather plan for 'best_path' and (recursively) plans
1466  *	  for its subpaths.
1467  */
1468 static Gather *
create_gather_plan(PlannerInfo * root,GatherPath * best_path)1469 create_gather_plan(PlannerInfo *root, GatherPath *best_path)
1470 {
1471 	Gather	   *gather_plan;
1472 	Plan	   *subplan;
1473 	List	   *tlist;
1474 
1475 	/*
1476 	 * Although the Gather node can project, we prefer to push down such work
1477 	 * to its child node, so demand an exact tlist from the child.
1478 	 */
1479 	subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1480 
1481 	tlist = build_path_tlist(root, &best_path->path);
1482 
1483 	gather_plan = make_gather(tlist,
1484 							  NIL,
1485 							  best_path->num_workers,
1486 							  assign_special_exec_param(root),
1487 							  best_path->single_copy,
1488 							  subplan);
1489 
1490 	copy_generic_path_info(&gather_plan->plan, &best_path->path);
1491 
1492 	/* use parallel mode for parallel plans. */
1493 	root->glob->parallelModeNeeded = true;
1494 
1495 	return gather_plan;
1496 }
1497 
1498 /*
1499  * create_gather_merge_plan
1500  *
1501  *	  Create a Gather Merge plan for 'best_path' and (recursively)
1502  *	  plans for its subpaths.
1503  */
1504 static GatherMerge *
create_gather_merge_plan(PlannerInfo * root,GatherMergePath * best_path)1505 create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
1506 {
1507 	GatherMerge *gm_plan;
1508 	Plan	   *subplan;
1509 	List	   *pathkeys = best_path->path.pathkeys;
1510 	List	   *tlist = build_path_tlist(root, &best_path->path);
1511 
1512 	/* As with Gather, it's best to project away columns in the workers. */
1513 	subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1514 
1515 	/* Create a shell for a GatherMerge plan. */
1516 	gm_plan = makeNode(GatherMerge);
1517 	gm_plan->plan.targetlist = tlist;
1518 	gm_plan->num_workers = best_path->num_workers;
1519 	copy_generic_path_info(&gm_plan->plan, &best_path->path);
1520 
1521 	/* Assign the rescan Param. */
1522 	gm_plan->rescan_param = assign_special_exec_param(root);
1523 
1524 	/* Gather Merge is pointless with no pathkeys; use Gather instead. */
1525 	Assert(pathkeys != NIL);
1526 
1527 	/* Compute sort column info, and adjust subplan's tlist as needed */
1528 	subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1529 										 best_path->subpath->parent->relids,
1530 										 gm_plan->sortColIdx,
1531 										 false,
1532 										 &gm_plan->numCols,
1533 										 &gm_plan->sortColIdx,
1534 										 &gm_plan->sortOperators,
1535 										 &gm_plan->collations,
1536 										 &gm_plan->nullsFirst);
1537 
1538 
1539 	/* Now, insert a Sort node if subplan isn't sufficiently ordered */
1540 	if (!pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys))
1541 		subplan = (Plan *) make_sort(subplan, gm_plan->numCols,
1542 									 gm_plan->sortColIdx,
1543 									 gm_plan->sortOperators,
1544 									 gm_plan->collations,
1545 									 gm_plan->nullsFirst);
1546 
1547 	/* Now insert the subplan under GatherMerge. */
1548 	gm_plan->plan.lefttree = subplan;
1549 
1550 	/* use parallel mode for parallel plans. */
1551 	root->glob->parallelModeNeeded = true;
1552 
1553 	return gm_plan;
1554 }
1555 
1556 /*
1557  * create_projection_plan
1558  *
1559  *	  Create a plan tree to do a projection step and (recursively) plans
1560  *	  for its subpaths.  We may need a Result node for the projection,
1561  *	  but sometimes we can just let the subplan do the work.
1562  */
1563 static Plan *
create_projection_plan(PlannerInfo * root,ProjectionPath * best_path)1564 create_projection_plan(PlannerInfo *root, ProjectionPath *best_path)
1565 {
1566 	Plan	   *plan;
1567 	Plan	   *subplan;
1568 	List	   *tlist;
1569 
1570 	/* Since we intend to project, we don't need to constrain child tlist */
1571 	subplan = create_plan_recurse(root, best_path->subpath, 0);
1572 
1573 	tlist = build_path_tlist(root, &best_path->path);
1574 
1575 	/*
1576 	 * We might not really need a Result node here, either because the subplan
1577 	 * can project or because it's returning the right list of expressions
1578 	 * anyway.  Usually create_projection_path will have detected that and set
1579 	 * dummypp if we don't need a Result; but its decision can't be final,
1580 	 * because some createplan.c routines change the tlists of their nodes.
1581 	 * (An example is that create_merge_append_plan might add resjunk sort
1582 	 * columns to a MergeAppend.)  So we have to recheck here.  If we do
1583 	 * arrive at a different answer than create_projection_path did, we'll
1584 	 * have made slightly wrong cost estimates; but label the plan with the
1585 	 * cost estimates we actually used, not "corrected" ones.  (XXX this could
1586 	 * be cleaned up if we moved more of the sortcolumn setup logic into Path
1587 	 * creation, but that would add expense to creating Paths we might end up
1588 	 * not using.)
1589 	 */
1590 	if (is_projection_capable_path(best_path->subpath) ||
1591 		tlist_same_exprs(tlist, subplan->targetlist))
1592 	{
1593 		/* Don't need a separate Result, just assign tlist to subplan */
1594 		plan = subplan;
1595 		plan->targetlist = tlist;
1596 
1597 		/* Label plan with the estimated costs we actually used */
1598 		plan->startup_cost = best_path->path.startup_cost;
1599 		plan->total_cost = best_path->path.total_cost;
1600 		plan->plan_rows = best_path->path.rows;
1601 		plan->plan_width = best_path->path.pathtarget->width;
1602 		plan->parallel_safe = best_path->path.parallel_safe;
1603 		/* ... but don't change subplan's parallel_aware flag */
1604 	}
1605 	else
1606 	{
1607 		/* We need a Result node */
1608 		plan = (Plan *) make_result(tlist, NULL, subplan);
1609 
1610 		copy_generic_path_info(plan, (Path *) best_path);
1611 	}
1612 
1613 	return plan;
1614 }
1615 
1616 /*
1617  * inject_projection_plan
1618  *	  Insert a Result node to do a projection step.
1619  *
1620  * This is used in a few places where we decide on-the-fly that we need a
1621  * projection step as part of the tree generated for some Path node.
1622  * We should try to get rid of this in favor of doing it more honestly.
1623  *
1624  * One reason it's ugly is we have to be told the right parallel_safe marking
1625  * to apply (since the tlist might be unsafe even if the child plan is safe).
1626  */
1627 static Plan *
inject_projection_plan(Plan * subplan,List * tlist,bool parallel_safe)1628 inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
1629 {
1630 	Plan	   *plan;
1631 
1632 	plan = (Plan *) make_result(tlist, NULL, subplan);
1633 
1634 	/*
1635 	 * In principle, we should charge tlist eval cost plus cpu_per_tuple per
1636 	 * row for the Result node.  But the former has probably been factored in
1637 	 * already and the latter was not accounted for during Path construction,
1638 	 * so being formally correct might just make the EXPLAIN output look less
1639 	 * consistent not more so.  Hence, just copy the subplan's cost.
1640 	 */
1641 	copy_plan_costsize(plan, subplan);
1642 	plan->parallel_safe = parallel_safe;
1643 
1644 	return plan;
1645 }
1646 
1647 /*
1648  * change_plan_targetlist
1649  *	  Externally available wrapper for inject_projection_plan.
1650  *
1651  * This is meant for use by FDW plan-generation functions, which might
1652  * want to adjust the tlist computed by some subplan tree.  In general,
1653  * a Result node is needed to compute the new tlist, but we can optimize
1654  * some cases.
1655  *
1656  * In most cases, tlist_parallel_safe can just be passed as the parallel_safe
1657  * flag of the FDW's own Path node.
1658  */
1659 Plan *
change_plan_targetlist(Plan * subplan,List * tlist,bool tlist_parallel_safe)1660 change_plan_targetlist(Plan *subplan, List *tlist, bool tlist_parallel_safe)
1661 {
1662 	/*
1663 	 * If the top plan node can't do projections and its existing target list
1664 	 * isn't already what we need, we need to add a Result node to help it
1665 	 * along.
1666 	 */
1667 	if (!is_projection_capable_plan(subplan) &&
1668 		!tlist_same_exprs(tlist, subplan->targetlist))
1669 		subplan = inject_projection_plan(subplan, tlist,
1670 										 subplan->parallel_safe &&
1671 										 tlist_parallel_safe);
1672 	else
1673 	{
1674 		/* Else we can just replace the plan node's tlist */
1675 		subplan->targetlist = tlist;
1676 		subplan->parallel_safe &= tlist_parallel_safe;
1677 	}
1678 	return subplan;
1679 }
1680 
1681 /*
1682  * create_sort_plan
1683  *
1684  *	  Create a Sort plan for 'best_path' and (recursively) plans
1685  *	  for its subpaths.
1686  */
1687 static Sort *
create_sort_plan(PlannerInfo * root,SortPath * best_path,int flags)1688 create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
1689 {
1690 	Sort	   *plan;
1691 	Plan	   *subplan;
1692 
1693 	/*
1694 	 * We don't want any excess columns in the sorted tuples, so request a
1695 	 * smaller tlist.  Otherwise, since Sort doesn't project, tlist
1696 	 * requirements pass through.
1697 	 */
1698 	subplan = create_plan_recurse(root, best_path->subpath,
1699 								  flags | CP_SMALL_TLIST);
1700 
1701 	plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys);
1702 
1703 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1704 
1705 	return plan;
1706 }
1707 
1708 /*
1709  * create_group_plan
1710  *
1711  *	  Create a Group plan for 'best_path' and (recursively) plans
1712  *	  for its subpaths.
1713  */
1714 static Group *
create_group_plan(PlannerInfo * root,GroupPath * best_path)1715 create_group_plan(PlannerInfo *root, GroupPath *best_path)
1716 {
1717 	Group	   *plan;
1718 	Plan	   *subplan;
1719 	List	   *tlist;
1720 	List	   *quals;
1721 
1722 	/*
1723 	 * Group can project, so no need to be terribly picky about child tlist,
1724 	 * but we do need grouping columns to be available
1725 	 */
1726 	subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1727 
1728 	tlist = build_path_tlist(root, &best_path->path);
1729 
1730 	quals = order_qual_clauses(root, best_path->qual);
1731 
1732 	plan = make_group(tlist,
1733 					  quals,
1734 					  list_length(best_path->groupClause),
1735 					  extract_grouping_cols(best_path->groupClause,
1736 											subplan->targetlist),
1737 					  extract_grouping_ops(best_path->groupClause),
1738 					  subplan);
1739 
1740 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1741 
1742 	return plan;
1743 }
1744 
1745 /*
1746  * create_upper_unique_plan
1747  *
1748  *	  Create a Unique plan for 'best_path' and (recursively) plans
1749  *	  for its subpaths.
1750  */
1751 static Unique *
create_upper_unique_plan(PlannerInfo * root,UpperUniquePath * best_path,int flags)1752 create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path, int flags)
1753 {
1754 	Unique	   *plan;
1755 	Plan	   *subplan;
1756 
1757 	/*
1758 	 * Unique doesn't project, so tlist requirements pass through; moreover we
1759 	 * need grouping columns to be labeled.
1760 	 */
1761 	subplan = create_plan_recurse(root, best_path->subpath,
1762 								  flags | CP_LABEL_TLIST);
1763 
1764 	plan = make_unique_from_pathkeys(subplan,
1765 									 best_path->path.pathkeys,
1766 									 best_path->numkeys);
1767 
1768 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1769 
1770 	return plan;
1771 }
1772 
1773 /*
1774  * create_agg_plan
1775  *
1776  *	  Create an Agg plan for 'best_path' and (recursively) plans
1777  *	  for its subpaths.
1778  */
1779 static Agg *
create_agg_plan(PlannerInfo * root,AggPath * best_path)1780 create_agg_plan(PlannerInfo *root, AggPath *best_path)
1781 {
1782 	Agg		   *plan;
1783 	Plan	   *subplan;
1784 	List	   *tlist;
1785 	List	   *quals;
1786 
1787 	/*
1788 	 * Agg can project, so no need to be terribly picky about child tlist, but
1789 	 * we do need grouping columns to be available
1790 	 */
1791 	subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1792 
1793 	tlist = build_path_tlist(root, &best_path->path);
1794 
1795 	quals = order_qual_clauses(root, best_path->qual);
1796 
1797 	plan = make_agg(tlist, quals,
1798 					best_path->aggstrategy,
1799 					best_path->aggsplit,
1800 					list_length(best_path->groupClause),
1801 					extract_grouping_cols(best_path->groupClause,
1802 										  subplan->targetlist),
1803 					extract_grouping_ops(best_path->groupClause),
1804 					NIL,
1805 					NIL,
1806 					best_path->numGroups,
1807 					subplan);
1808 
1809 	copy_generic_path_info(&plan->plan, (Path *) best_path);
1810 
1811 	return plan;
1812 }
1813 
1814 /*
1815  * Given a groupclause for a collection of grouping sets, produce the
1816  * corresponding groupColIdx.
1817  *
1818  * root->grouping_map maps the tleSortGroupRef to the actual column position in
1819  * the input tuple. So we get the ref from the entries in the groupclause and
1820  * look them up there.
1821  */
1822 static AttrNumber *
remap_groupColIdx(PlannerInfo * root,List * groupClause)1823 remap_groupColIdx(PlannerInfo *root, List *groupClause)
1824 {
1825 	AttrNumber *grouping_map = root->grouping_map;
1826 	AttrNumber *new_grpColIdx;
1827 	ListCell   *lc;
1828 	int			i;
1829 
1830 	Assert(grouping_map);
1831 
1832 	new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
1833 
1834 	i = 0;
1835 	foreach(lc, groupClause)
1836 	{
1837 		SortGroupClause *clause = lfirst(lc);
1838 
1839 		new_grpColIdx[i++] = grouping_map[clause->tleSortGroupRef];
1840 	}
1841 
1842 	return new_grpColIdx;
1843 }
1844 
1845 /*
1846  * create_groupingsets_plan
1847  *	  Create a plan for 'best_path' and (recursively) plans
1848  *	  for its subpaths.
1849  *
1850  *	  What we emit is an Agg plan with some vestigial Agg and Sort nodes
1851  *	  hanging off the side.  The top Agg implements the last grouping set
1852  *	  specified in the GroupingSetsPath, and any additional grouping sets
1853  *	  each give rise to a subsidiary Agg and Sort node in the top Agg's
1854  *	  "chain" list.  These nodes don't participate in the plan directly,
1855  *	  but they are a convenient way to represent the required data for
1856  *	  the extra steps.
1857  *
1858  *	  Returns a Plan node.
1859  */
1860 static Plan *
create_groupingsets_plan(PlannerInfo * root,GroupingSetsPath * best_path)1861 create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
1862 {
1863 	Agg		   *plan;
1864 	Plan	   *subplan;
1865 	List	   *rollups = best_path->rollups;
1866 	AttrNumber *grouping_map;
1867 	int			maxref;
1868 	List	   *chain;
1869 	ListCell   *lc;
1870 
1871 	/* Shouldn't get here without grouping sets */
1872 	Assert(root->parse->groupingSets);
1873 	Assert(rollups != NIL);
1874 
1875 	/*
1876 	 * Agg can project, so no need to be terribly picky about child tlist, but
1877 	 * we do need grouping columns to be available
1878 	 */
1879 	subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1880 
1881 	/*
1882 	 * Compute the mapping from tleSortGroupRef to column index in the child's
1883 	 * tlist.  First, identify max SortGroupRef in groupClause, for array
1884 	 * sizing.
1885 	 */
1886 	maxref = 0;
1887 	foreach(lc, root->parse->groupClause)
1888 	{
1889 		SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1890 
1891 		if (gc->tleSortGroupRef > maxref)
1892 			maxref = gc->tleSortGroupRef;
1893 	}
1894 
1895 	grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
1896 
1897 	/* Now look up the column numbers in the child's tlist */
1898 	foreach(lc, root->parse->groupClause)
1899 	{
1900 		SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1901 		TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
1902 
1903 		grouping_map[gc->tleSortGroupRef] = tle->resno;
1904 	}
1905 
1906 	/*
1907 	 * During setrefs.c, we'll need the grouping_map to fix up the cols lists
1908 	 * in GroupingFunc nodes.  Save it for setrefs.c to use.
1909 	 *
1910 	 * This doesn't work if we're in an inheritance subtree (see notes in
1911 	 * create_modifytable_plan).  Fortunately we can't be because there would
1912 	 * never be grouping in an UPDATE/DELETE; but let's Assert that.
1913 	 */
1914 	Assert(!root->hasInheritedTarget);
1915 	Assert(root->grouping_map == NULL);
1916 	root->grouping_map = grouping_map;
1917 
1918 	/*
1919 	 * Generate the side nodes that describe the other sort and group
1920 	 * operations besides the top one.  Note that we don't worry about putting
1921 	 * accurate cost estimates in the side nodes; only the topmost Agg node's
1922 	 * costs will be shown by EXPLAIN.
1923 	 */
1924 	chain = NIL;
1925 	if (list_length(rollups) > 1)
1926 	{
1927 		ListCell   *lc2 = lnext(list_head(rollups));
1928 		bool		is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
1929 
1930 		for_each_cell(lc, lc2)
1931 		{
1932 			RollupData *rollup = lfirst(lc);
1933 			AttrNumber *new_grpColIdx;
1934 			Plan	   *sort_plan = NULL;
1935 			Plan	   *agg_plan;
1936 			AggStrategy strat;
1937 
1938 			new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1939 
1940 			if (!rollup->is_hashed && !is_first_sort)
1941 			{
1942 				sort_plan = (Plan *)
1943 					make_sort_from_groupcols(rollup->groupClause,
1944 											 new_grpColIdx,
1945 											 subplan);
1946 			}
1947 
1948 			if (!rollup->is_hashed)
1949 				is_first_sort = false;
1950 
1951 			if (rollup->is_hashed)
1952 				strat = AGG_HASHED;
1953 			else if (list_length(linitial(rollup->gsets)) == 0)
1954 				strat = AGG_PLAIN;
1955 			else
1956 				strat = AGG_SORTED;
1957 
1958 			agg_plan = (Plan *) make_agg(NIL,
1959 										 NIL,
1960 										 strat,
1961 										 AGGSPLIT_SIMPLE,
1962 										 list_length((List *) linitial(rollup->gsets)),
1963 										 new_grpColIdx,
1964 										 extract_grouping_ops(rollup->groupClause),
1965 										 rollup->gsets,
1966 										 NIL,
1967 										 rollup->numGroups,
1968 										 sort_plan);
1969 
1970 			/*
1971 			 * Remove stuff we don't need to avoid bloating debug output.
1972 			 */
1973 			if (sort_plan)
1974 			{
1975 				sort_plan->targetlist = NIL;
1976 				sort_plan->lefttree = NULL;
1977 			}
1978 
1979 			chain = lappend(chain, agg_plan);
1980 		}
1981 	}
1982 
1983 	/*
1984 	 * Now make the real Agg node
1985 	 */
1986 	{
1987 		RollupData *rollup = linitial(rollups);
1988 		AttrNumber *top_grpColIdx;
1989 		int			numGroupCols;
1990 
1991 		top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1992 
1993 		numGroupCols = list_length((List *) linitial(rollup->gsets));
1994 
1995 		plan = make_agg(build_path_tlist(root, &best_path->path),
1996 						best_path->qual,
1997 						best_path->aggstrategy,
1998 						AGGSPLIT_SIMPLE,
1999 						numGroupCols,
2000 						top_grpColIdx,
2001 						extract_grouping_ops(rollup->groupClause),
2002 						rollup->gsets,
2003 						chain,
2004 						rollup->numGroups,
2005 						subplan);
2006 
2007 		/* Copy cost data from Path to Plan */
2008 		copy_generic_path_info(&plan->plan, &best_path->path);
2009 	}
2010 
2011 	return (Plan *) plan;
2012 }
2013 
2014 /*
2015  * create_minmaxagg_plan
2016  *
2017  *	  Create a Result plan for 'best_path' and (recursively) plans
2018  *	  for its subpaths.
2019  */
2020 static Result *
create_minmaxagg_plan(PlannerInfo * root,MinMaxAggPath * best_path)2021 create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
2022 {
2023 	Result	   *plan;
2024 	List	   *tlist;
2025 	ListCell   *lc;
2026 
2027 	/* Prepare an InitPlan for each aggregate's subquery. */
2028 	foreach(lc, best_path->mmaggregates)
2029 	{
2030 		MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2031 		PlannerInfo *subroot = mminfo->subroot;
2032 		Query	   *subparse = subroot->parse;
2033 		Plan	   *plan;
2034 
2035 		/*
2036 		 * Generate the plan for the subquery. We already have a Path, but we
2037 		 * have to convert it to a Plan and attach a LIMIT node above it.
2038 		 * Since we are entering a different planner context (subroot),
2039 		 * recurse to create_plan not create_plan_recurse.
2040 		 */
2041 		plan = create_plan(subroot, mminfo->path);
2042 
2043 		plan = (Plan *) make_limit(plan,
2044 								   subparse->limitOffset,
2045 								   subparse->limitCount);
2046 
2047 		/* Must apply correct cost/width data to Limit node */
2048 		plan->startup_cost = mminfo->path->startup_cost;
2049 		plan->total_cost = mminfo->pathcost;
2050 		plan->plan_rows = 1;
2051 		plan->plan_width = mminfo->path->pathtarget->width;
2052 		plan->parallel_aware = false;
2053 		plan->parallel_safe = mminfo->path->parallel_safe;
2054 
2055 		/* Convert the plan into an InitPlan in the outer query. */
2056 		SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
2057 	}
2058 
2059 	/* Generate the output plan --- basically just a Result */
2060 	tlist = build_path_tlist(root, &best_path->path);
2061 
2062 	plan = make_result(tlist, (Node *) best_path->quals, NULL);
2063 
2064 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2065 
2066 	/*
2067 	 * During setrefs.c, we'll need to replace references to the Agg nodes
2068 	 * with InitPlan output params.  (We can't just do that locally in the
2069 	 * MinMaxAgg node, because path nodes above here may have Agg references
2070 	 * as well.)  Save the mmaggregates list to tell setrefs.c to do that.
2071 	 *
2072 	 * This doesn't work if we're in an inheritance subtree (see notes in
2073 	 * create_modifytable_plan).  Fortunately we can't be because there would
2074 	 * never be aggregates in an UPDATE/DELETE; but let's Assert that.
2075 	 */
2076 	Assert(!root->hasInheritedTarget);
2077 	Assert(root->minmax_aggs == NIL);
2078 	root->minmax_aggs = best_path->mmaggregates;
2079 
2080 	return plan;
2081 }
2082 
2083 /*
2084  * create_windowagg_plan
2085  *
2086  *	  Create a WindowAgg plan for 'best_path' and (recursively) plans
2087  *	  for its subpaths.
2088  */
2089 static WindowAgg *
create_windowagg_plan(PlannerInfo * root,WindowAggPath * best_path)2090 create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
2091 {
2092 	WindowAgg  *plan;
2093 	WindowClause *wc = best_path->winclause;
2094 	Plan	   *subplan;
2095 	List	   *tlist;
2096 	int			numsortkeys;
2097 	AttrNumber *sortColIdx;
2098 	Oid		   *sortOperators;
2099 	Oid		   *collations;
2100 	bool	   *nullsFirst;
2101 	int			partNumCols;
2102 	AttrNumber *partColIdx;
2103 	Oid		   *partOperators;
2104 	int			ordNumCols;
2105 	AttrNumber *ordColIdx;
2106 	Oid		   *ordOperators;
2107 
2108 	/*
2109 	 * Choice of tlist here is motivated by the fact that WindowAgg will be
2110 	 * storing the input rows of window frames in a tuplestore; it therefore
2111 	 * behooves us to request a small tlist to avoid wasting space. We do of
2112 	 * course need grouping columns to be available.
2113 	 */
2114 	subplan = create_plan_recurse(root, best_path->subpath,
2115 								  CP_LABEL_TLIST | CP_SMALL_TLIST);
2116 
2117 	tlist = build_path_tlist(root, &best_path->path);
2118 
2119 	/*
2120 	 * We shouldn't need to actually sort, but it's convenient to use
2121 	 * prepare_sort_from_pathkeys to identify the input's sort columns.
2122 	 */
2123 	subplan = prepare_sort_from_pathkeys(subplan,
2124 										 best_path->winpathkeys,
2125 										 NULL,
2126 										 NULL,
2127 										 false,
2128 										 &numsortkeys,
2129 										 &sortColIdx,
2130 										 &sortOperators,
2131 										 &collations,
2132 										 &nullsFirst);
2133 
2134 	/* Now deconstruct that into partition and ordering portions */
2135 	get_column_info_for_window(root,
2136 							   wc,
2137 							   subplan->targetlist,
2138 							   numsortkeys,
2139 							   sortColIdx,
2140 							   &partNumCols,
2141 							   &partColIdx,
2142 							   &partOperators,
2143 							   &ordNumCols,
2144 							   &ordColIdx,
2145 							   &ordOperators);
2146 
2147 	/* And finally we can make the WindowAgg node */
2148 	plan = make_windowagg(tlist,
2149 						  wc->winref,
2150 						  partNumCols,
2151 						  partColIdx,
2152 						  partOperators,
2153 						  ordNumCols,
2154 						  ordColIdx,
2155 						  ordOperators,
2156 						  wc->frameOptions,
2157 						  wc->startOffset,
2158 						  wc->endOffset,
2159 						  subplan);
2160 
2161 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2162 
2163 	return plan;
2164 }
2165 
2166 /*
2167  * get_column_info_for_window
2168  *		Get the partitioning/ordering column numbers and equality operators
2169  *		for a WindowAgg node.
2170  *
2171  * This depends on the behavior of planner.c's make_pathkeys_for_window!
2172  *
2173  * We are given the target WindowClause and an array of the input column
2174  * numbers associated with the resulting pathkeys.  In the easy case, there
2175  * are the same number of pathkey columns as partitioning + ordering columns
2176  * and we just have to copy some data around.  However, it's possible that
2177  * some of the original partitioning + ordering columns were eliminated as
2178  * redundant during the transformation to pathkeys.  (This can happen even
2179  * though the parser gets rid of obvious duplicates.  A typical scenario is a
2180  * window specification "PARTITION BY x ORDER BY y" coupled with a clause
2181  * "WHERE x = y" that causes the two sort columns to be recognized as
2182  * redundant.)	In that unusual case, we have to work a lot harder to
2183  * determine which keys are significant.
2184  *
2185  * The method used here is a bit brute-force: add the sort columns to a list
2186  * one at a time and note when the resulting pathkey list gets longer.  But
2187  * it's a sufficiently uncommon case that a faster way doesn't seem worth
2188  * the amount of code refactoring that'd be needed.
2189  */
2190 static void
get_column_info_for_window(PlannerInfo * root,WindowClause * wc,List * tlist,int numSortCols,AttrNumber * sortColIdx,int * partNumCols,AttrNumber ** partColIdx,Oid ** partOperators,int * ordNumCols,AttrNumber ** ordColIdx,Oid ** ordOperators)2191 get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
2192 						   int numSortCols, AttrNumber *sortColIdx,
2193 						   int *partNumCols,
2194 						   AttrNumber **partColIdx,
2195 						   Oid **partOperators,
2196 						   int *ordNumCols,
2197 						   AttrNumber **ordColIdx,
2198 						   Oid **ordOperators)
2199 {
2200 	int			numPart = list_length(wc->partitionClause);
2201 	int			numOrder = list_length(wc->orderClause);
2202 
2203 	if (numSortCols == numPart + numOrder)
2204 	{
2205 		/* easy case */
2206 		*partNumCols = numPart;
2207 		*partColIdx = sortColIdx;
2208 		*partOperators = extract_grouping_ops(wc->partitionClause);
2209 		*ordNumCols = numOrder;
2210 		*ordColIdx = sortColIdx + numPart;
2211 		*ordOperators = extract_grouping_ops(wc->orderClause);
2212 	}
2213 	else
2214 	{
2215 		List	   *sortclauses;
2216 		List	   *pathkeys;
2217 		int			scidx;
2218 		ListCell   *lc;
2219 
2220 		/* first, allocate what's certainly enough space for the arrays */
2221 		*partNumCols = 0;
2222 		*partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
2223 		*partOperators = (Oid *) palloc(numPart * sizeof(Oid));
2224 		*ordNumCols = 0;
2225 		*ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
2226 		*ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
2227 		sortclauses = NIL;
2228 		pathkeys = NIL;
2229 		scidx = 0;
2230 		foreach(lc, wc->partitionClause)
2231 		{
2232 			SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2233 			List	   *new_pathkeys;
2234 
2235 			sortclauses = lappend(sortclauses, sgc);
2236 			new_pathkeys = make_pathkeys_for_sortclauses(root,
2237 														 sortclauses,
2238 														 tlist);
2239 			if (list_length(new_pathkeys) > list_length(pathkeys))
2240 			{
2241 				/* this sort clause is actually significant */
2242 				(*partColIdx)[*partNumCols] = sortColIdx[scidx++];
2243 				(*partOperators)[*partNumCols] = sgc->eqop;
2244 				(*partNumCols)++;
2245 				pathkeys = new_pathkeys;
2246 			}
2247 		}
2248 		foreach(lc, wc->orderClause)
2249 		{
2250 			SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2251 			List	   *new_pathkeys;
2252 
2253 			sortclauses = lappend(sortclauses, sgc);
2254 			new_pathkeys = make_pathkeys_for_sortclauses(root,
2255 														 sortclauses,
2256 														 tlist);
2257 			if (list_length(new_pathkeys) > list_length(pathkeys))
2258 			{
2259 				/* this sort clause is actually significant */
2260 				(*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
2261 				(*ordOperators)[*ordNumCols] = sgc->eqop;
2262 				(*ordNumCols)++;
2263 				pathkeys = new_pathkeys;
2264 			}
2265 		}
2266 		/* complain if we didn't eat exactly the right number of sort cols */
2267 		if (scidx != numSortCols)
2268 			elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
2269 	}
2270 }
2271 
2272 /*
2273  * create_setop_plan
2274  *
2275  *	  Create a SetOp plan for 'best_path' and (recursively) plans
2276  *	  for its subpaths.
2277  */
2278 static SetOp *
create_setop_plan(PlannerInfo * root,SetOpPath * best_path,int flags)2279 create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
2280 {
2281 	SetOp	   *plan;
2282 	Plan	   *subplan;
2283 	long		numGroups;
2284 
2285 	/*
2286 	 * SetOp doesn't project, so tlist requirements pass through; moreover we
2287 	 * need grouping columns to be labeled.
2288 	 */
2289 	subplan = create_plan_recurse(root, best_path->subpath,
2290 								  flags | CP_LABEL_TLIST);
2291 
2292 	/* Convert numGroups to long int --- but 'ware overflow! */
2293 	numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2294 
2295 	plan = make_setop(best_path->cmd,
2296 					  best_path->strategy,
2297 					  subplan,
2298 					  best_path->distinctList,
2299 					  best_path->flagColIdx,
2300 					  best_path->firstFlag,
2301 					  numGroups);
2302 
2303 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2304 
2305 	return plan;
2306 }
2307 
2308 /*
2309  * create_recursiveunion_plan
2310  *
2311  *	  Create a RecursiveUnion plan for 'best_path' and (recursively) plans
2312  *	  for its subpaths.
2313  */
2314 static RecursiveUnion *
create_recursiveunion_plan(PlannerInfo * root,RecursiveUnionPath * best_path)2315 create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
2316 {
2317 	RecursiveUnion *plan;
2318 	Plan	   *leftplan;
2319 	Plan	   *rightplan;
2320 	List	   *tlist;
2321 	long		numGroups;
2322 
2323 	/* Need both children to produce same tlist, so force it */
2324 	leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
2325 	rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
2326 
2327 	tlist = build_path_tlist(root, &best_path->path);
2328 
2329 	/* Convert numGroups to long int --- but 'ware overflow! */
2330 	numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2331 
2332 	plan = make_recursive_union(tlist,
2333 								leftplan,
2334 								rightplan,
2335 								best_path->wtParam,
2336 								best_path->distinctList,
2337 								numGroups);
2338 
2339 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2340 
2341 	return plan;
2342 }
2343 
2344 /*
2345  * create_lockrows_plan
2346  *
2347  *	  Create a LockRows plan for 'best_path' and (recursively) plans
2348  *	  for its subpaths.
2349  */
2350 static LockRows *
create_lockrows_plan(PlannerInfo * root,LockRowsPath * best_path,int flags)2351 create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
2352 					 int flags)
2353 {
2354 	LockRows   *plan;
2355 	Plan	   *subplan;
2356 
2357 	/* LockRows doesn't project, so tlist requirements pass through */
2358 	subplan = create_plan_recurse(root, best_path->subpath, flags);
2359 
2360 	plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2361 
2362 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2363 
2364 	return plan;
2365 }
2366 
2367 /*
2368  * create_modifytable_plan
2369  *	  Create a ModifyTable plan for 'best_path'.
2370  *
2371  *	  Returns a Plan node.
2372  */
2373 static ModifyTable *
create_modifytable_plan(PlannerInfo * root,ModifyTablePath * best_path)2374 create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
2375 {
2376 	ModifyTable *plan;
2377 	List	   *subplans = NIL;
2378 	ListCell   *subpaths,
2379 			   *subroots;
2380 
2381 	/* Build the plan for each input path */
2382 	forboth(subpaths, best_path->subpaths,
2383 			subroots, best_path->subroots)
2384 	{
2385 		Path	   *subpath = (Path *) lfirst(subpaths);
2386 		PlannerInfo *subroot = (PlannerInfo *) lfirst(subroots);
2387 		Plan	   *subplan;
2388 
2389 		/*
2390 		 * In an inherited UPDATE/DELETE, reference the per-child modified
2391 		 * subroot while creating Plans from Paths for the child rel.  This is
2392 		 * a kluge, but otherwise it's too hard to ensure that Plan creation
2393 		 * functions (particularly in FDWs) don't depend on the contents of
2394 		 * "root" matching what they saw at Path creation time.  The main
2395 		 * downside is that creation functions for Plans that might appear
2396 		 * below a ModifyTable cannot expect to modify the contents of "root"
2397 		 * and have it "stick" for subsequent processing such as setrefs.c.
2398 		 * That's not great, but it seems better than the alternative.
2399 		 */
2400 		subplan = create_plan_recurse(subroot, subpath, CP_EXACT_TLIST);
2401 
2402 		/* Transfer resname/resjunk labeling, too, to keep executor happy */
2403 		apply_tlist_labeling(subplan->targetlist, subroot->processed_tlist);
2404 
2405 		subplans = lappend(subplans, subplan);
2406 	}
2407 
2408 	plan = make_modifytable(root,
2409 							best_path->operation,
2410 							best_path->canSetTag,
2411 							best_path->nominalRelation,
2412 							best_path->partitioned_rels,
2413 							best_path->resultRelations,
2414 							subplans,
2415 							best_path->withCheckOptionLists,
2416 							best_path->returningLists,
2417 							best_path->rowMarks,
2418 							best_path->onconflict,
2419 							best_path->epqParam);
2420 
2421 	copy_generic_path_info(&plan->plan, &best_path->path);
2422 
2423 	return plan;
2424 }
2425 
2426 /*
2427  * create_limit_plan
2428  *
2429  *	  Create a Limit plan for 'best_path' and (recursively) plans
2430  *	  for its subpaths.
2431  */
2432 static Limit *
create_limit_plan(PlannerInfo * root,LimitPath * best_path,int flags)2433 create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
2434 {
2435 	Limit	   *plan;
2436 	Plan	   *subplan;
2437 
2438 	/* Limit doesn't project, so tlist requirements pass through */
2439 	subplan = create_plan_recurse(root, best_path->subpath, flags);
2440 
2441 	plan = make_limit(subplan,
2442 					  best_path->limitOffset,
2443 					  best_path->limitCount);
2444 
2445 	copy_generic_path_info(&plan->plan, (Path *) best_path);
2446 
2447 	return plan;
2448 }
2449 
2450 
2451 /*****************************************************************************
2452  *
2453  *	BASE-RELATION SCAN METHODS
2454  *
2455  *****************************************************************************/
2456 
2457 
2458 /*
2459  * create_seqscan_plan
2460  *	 Returns a seqscan plan for the base relation scanned by 'best_path'
2461  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2462  */
2463 static SeqScan *
create_seqscan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)2464 create_seqscan_plan(PlannerInfo *root, Path *best_path,
2465 					List *tlist, List *scan_clauses)
2466 {
2467 	SeqScan    *scan_plan;
2468 	Index		scan_relid = best_path->parent->relid;
2469 
2470 	/* it should be a base rel... */
2471 	Assert(scan_relid > 0);
2472 	Assert(best_path->parent->rtekind == RTE_RELATION);
2473 
2474 	/* Sort clauses into best execution order */
2475 	scan_clauses = order_qual_clauses(root, scan_clauses);
2476 
2477 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2478 	scan_clauses = extract_actual_clauses(scan_clauses, false);
2479 
2480 	/* Replace any outer-relation variables with nestloop params */
2481 	if (best_path->param_info)
2482 	{
2483 		scan_clauses = (List *)
2484 			replace_nestloop_params(root, (Node *) scan_clauses);
2485 	}
2486 
2487 	scan_plan = make_seqscan(tlist,
2488 							 scan_clauses,
2489 							 scan_relid);
2490 
2491 	copy_generic_path_info(&scan_plan->plan, best_path);
2492 
2493 	return scan_plan;
2494 }
2495 
2496 /*
2497  * create_samplescan_plan
2498  *	 Returns a samplescan plan for the base relation scanned by 'best_path'
2499  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2500  */
2501 static SampleScan *
create_samplescan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)2502 create_samplescan_plan(PlannerInfo *root, Path *best_path,
2503 					   List *tlist, List *scan_clauses)
2504 {
2505 	SampleScan *scan_plan;
2506 	Index		scan_relid = best_path->parent->relid;
2507 	RangeTblEntry *rte;
2508 	TableSampleClause *tsc;
2509 
2510 	/* it should be a base rel with a tablesample clause... */
2511 	Assert(scan_relid > 0);
2512 	rte = planner_rt_fetch(scan_relid, root);
2513 	Assert(rte->rtekind == RTE_RELATION);
2514 	tsc = rte->tablesample;
2515 	Assert(tsc != NULL);
2516 
2517 	/* Sort clauses into best execution order */
2518 	scan_clauses = order_qual_clauses(root, scan_clauses);
2519 
2520 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2521 	scan_clauses = extract_actual_clauses(scan_clauses, false);
2522 
2523 	/* Replace any outer-relation variables with nestloop params */
2524 	if (best_path->param_info)
2525 	{
2526 		scan_clauses = (List *)
2527 			replace_nestloop_params(root, (Node *) scan_clauses);
2528 		tsc = (TableSampleClause *)
2529 			replace_nestloop_params(root, (Node *) tsc);
2530 	}
2531 
2532 	scan_plan = make_samplescan(tlist,
2533 								scan_clauses,
2534 								scan_relid,
2535 								tsc);
2536 
2537 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
2538 
2539 	return scan_plan;
2540 }
2541 
2542 /*
2543  * create_indexscan_plan
2544  *	  Returns an indexscan plan for the base relation scanned by 'best_path'
2545  *	  with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2546  *
2547  * We use this for both plain IndexScans and IndexOnlyScans, because the
2548  * qual preprocessing work is the same for both.  Note that the caller tells
2549  * us which to build --- we don't look at best_path->path.pathtype, because
2550  * create_bitmap_subplan needs to be able to override the prior decision.
2551  */
2552 static Scan *
create_indexscan_plan(PlannerInfo * root,IndexPath * best_path,List * tlist,List * scan_clauses,bool indexonly)2553 create_indexscan_plan(PlannerInfo *root,
2554 					  IndexPath *best_path,
2555 					  List *tlist,
2556 					  List *scan_clauses,
2557 					  bool indexonly)
2558 {
2559 	Scan	   *scan_plan;
2560 	List	   *indexquals = best_path->indexquals;
2561 	List	   *indexorderbys = best_path->indexorderbys;
2562 	Index		baserelid = best_path->path.parent->relid;
2563 	Oid			indexoid = best_path->indexinfo->indexoid;
2564 	List	   *qpqual;
2565 	List	   *stripped_indexquals;
2566 	List	   *fixed_indexquals;
2567 	List	   *fixed_indexorderbys;
2568 	List	   *indexorderbyops = NIL;
2569 	ListCell   *l;
2570 
2571 	/* it should be a base rel... */
2572 	Assert(baserelid > 0);
2573 	Assert(best_path->path.parent->rtekind == RTE_RELATION);
2574 
2575 	/*
2576 	 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
2577 	 * executor as indexqualorig
2578 	 */
2579 	stripped_indexquals = get_actual_clauses(indexquals);
2580 
2581 	/*
2582 	 * The executor needs a copy with the indexkey on the left of each clause
2583 	 * and with index Vars substituted for table ones.
2584 	 */
2585 	fixed_indexquals = fix_indexqual_references(root, best_path);
2586 
2587 	/*
2588 	 * Likewise fix up index attr references in the ORDER BY expressions.
2589 	 */
2590 	fixed_indexorderbys = fix_indexorderby_references(root, best_path);
2591 
2592 	/*
2593 	 * The qpqual list must contain all restrictions not automatically handled
2594 	 * by the index, other than pseudoconstant clauses which will be handled
2595 	 * by a separate gating plan node.  All the predicates in the indexquals
2596 	 * will be checked (either by the index itself, or by nodeIndexscan.c),
2597 	 * but if there are any "special" operators involved then they must be
2598 	 * included in qpqual.  The upshot is that qpqual must contain
2599 	 * scan_clauses minus whatever appears in indexquals.
2600 	 *
2601 	 * In normal cases simple pointer equality checks will be enough to spot
2602 	 * duplicate RestrictInfos, so we try that first.
2603 	 *
2604 	 * Another common case is that a scan_clauses entry is generated from the
2605 	 * same EquivalenceClass as some indexqual, and is therefore redundant
2606 	 * with it, though not equal.  (This happens when indxpath.c prefers a
2607 	 * different derived equality than what generate_join_implied_equalities
2608 	 * picked for a parameterized scan's ppi_clauses.)
2609 	 *
2610 	 * In some situations (particularly with OR'd index conditions) we may
2611 	 * have scan_clauses that are not equal to, but are logically implied by,
2612 	 * the index quals; so we also try a predicate_implied_by() check to see
2613 	 * if we can discard quals that way.  (predicate_implied_by assumes its
2614 	 * first input contains only immutable functions, so we have to check
2615 	 * that.)
2616 	 *
2617 	 * Note: if you change this bit of code you should also look at
2618 	 * extract_nonindex_conditions() in costsize.c.
2619 	 */
2620 	qpqual = NIL;
2621 	foreach(l, scan_clauses)
2622 	{
2623 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2624 
2625 		if (rinfo->pseudoconstant)
2626 			continue;			/* we may drop pseudoconstants here */
2627 		if (list_member_ptr(indexquals, rinfo))
2628 			continue;			/* simple duplicate */
2629 		if (is_redundant_derived_clause(rinfo, indexquals))
2630 			continue;			/* derived from same EquivalenceClass */
2631 		if (!contain_mutable_functions((Node *) rinfo->clause) &&
2632 			predicate_implied_by(list_make1(rinfo->clause), indexquals, false))
2633 			continue;			/* provably implied by indexquals */
2634 		qpqual = lappend(qpqual, rinfo);
2635 	}
2636 
2637 	/* Sort clauses into best execution order */
2638 	qpqual = order_qual_clauses(root, qpqual);
2639 
2640 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2641 	qpqual = extract_actual_clauses(qpqual, false);
2642 
2643 	/*
2644 	 * We have to replace any outer-relation variables with nestloop params in
2645 	 * the indexqualorig, qpqual, and indexorderbyorig expressions.  A bit
2646 	 * annoying to have to do this separately from the processing in
2647 	 * fix_indexqual_references --- rethink this when generalizing the inner
2648 	 * indexscan support.  But note we can't really do this earlier because
2649 	 * it'd break the comparisons to predicates above ... (or would it?  Those
2650 	 * wouldn't have outer refs)
2651 	 */
2652 	if (best_path->path.param_info)
2653 	{
2654 		stripped_indexquals = (List *)
2655 			replace_nestloop_params(root, (Node *) stripped_indexquals);
2656 		qpqual = (List *)
2657 			replace_nestloop_params(root, (Node *) qpqual);
2658 		indexorderbys = (List *)
2659 			replace_nestloop_params(root, (Node *) indexorderbys);
2660 	}
2661 
2662 	/*
2663 	 * If there are ORDER BY expressions, look up the sort operators for their
2664 	 * result datatypes.
2665 	 */
2666 	if (indexorderbys)
2667 	{
2668 		ListCell   *pathkeyCell,
2669 				   *exprCell;
2670 
2671 		/*
2672 		 * PathKey contains OID of the btree opfamily we're sorting by, but
2673 		 * that's not quite enough because we need the expression's datatype
2674 		 * to look up the sort operator in the operator family.
2675 		 */
2676 		Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
2677 		forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
2678 		{
2679 			PathKey    *pathkey = (PathKey *) lfirst(pathkeyCell);
2680 			Node	   *expr = (Node *) lfirst(exprCell);
2681 			Oid			exprtype = exprType(expr);
2682 			Oid			sortop;
2683 
2684 			/* Get sort operator from opfamily */
2685 			sortop = get_opfamily_member(pathkey->pk_opfamily,
2686 										 exprtype,
2687 										 exprtype,
2688 										 pathkey->pk_strategy);
2689 			if (!OidIsValid(sortop))
2690 				elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2691 					 pathkey->pk_strategy, exprtype, exprtype, pathkey->pk_opfamily);
2692 			indexorderbyops = lappend_oid(indexorderbyops, sortop);
2693 		}
2694 	}
2695 
2696 	/* Finally ready to build the plan node */
2697 	if (indexonly)
2698 		scan_plan = (Scan *) make_indexonlyscan(tlist,
2699 												qpqual,
2700 												baserelid,
2701 												indexoid,
2702 												fixed_indexquals,
2703 												fixed_indexorderbys,
2704 												best_path->indexinfo->indextlist,
2705 												best_path->indexscandir);
2706 	else
2707 		scan_plan = (Scan *) make_indexscan(tlist,
2708 											qpqual,
2709 											baserelid,
2710 											indexoid,
2711 											fixed_indexquals,
2712 											stripped_indexquals,
2713 											fixed_indexorderbys,
2714 											indexorderbys,
2715 											indexorderbyops,
2716 											best_path->indexscandir);
2717 
2718 	copy_generic_path_info(&scan_plan->plan, &best_path->path);
2719 
2720 	return scan_plan;
2721 }
2722 
2723 /*
2724  * create_bitmap_scan_plan
2725  *	  Returns a bitmap scan plan for the base relation scanned by 'best_path'
2726  *	  with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2727  */
2728 static BitmapHeapScan *
create_bitmap_scan_plan(PlannerInfo * root,BitmapHeapPath * best_path,List * tlist,List * scan_clauses)2729 create_bitmap_scan_plan(PlannerInfo *root,
2730 						BitmapHeapPath *best_path,
2731 						List *tlist,
2732 						List *scan_clauses)
2733 {
2734 	Index		baserelid = best_path->path.parent->relid;
2735 	Plan	   *bitmapqualplan;
2736 	List	   *bitmapqualorig;
2737 	List	   *indexquals;
2738 	List	   *indexECs;
2739 	List	   *qpqual;
2740 	ListCell   *l;
2741 	BitmapHeapScan *scan_plan;
2742 
2743 	/* it should be a base rel... */
2744 	Assert(baserelid > 0);
2745 	Assert(best_path->path.parent->rtekind == RTE_RELATION);
2746 
2747 	/* Process the bitmapqual tree into a Plan tree and qual lists */
2748 	bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
2749 										   &bitmapqualorig, &indexquals,
2750 										   &indexECs);
2751 
2752 	if (best_path->path.parallel_aware)
2753 		bitmap_subplan_mark_shared(bitmapqualplan);
2754 
2755 	/*
2756 	 * The qpqual list must contain all restrictions not automatically handled
2757 	 * by the index, other than pseudoconstant clauses which will be handled
2758 	 * by a separate gating plan node.  All the predicates in the indexquals
2759 	 * will be checked (either by the index itself, or by
2760 	 * nodeBitmapHeapscan.c), but if there are any "special" operators
2761 	 * involved then they must be added to qpqual.  The upshot is that qpqual
2762 	 * must contain scan_clauses minus whatever appears in indexquals.
2763 	 *
2764 	 * This loop is similar to the comparable code in create_indexscan_plan(),
2765 	 * but with some differences because it has to compare the scan clauses to
2766 	 * stripped (no RestrictInfos) indexquals.  See comments there for more
2767 	 * info.
2768 	 *
2769 	 * In normal cases simple equal() checks will be enough to spot duplicate
2770 	 * clauses, so we try that first.  We next see if the scan clause is
2771 	 * redundant with any top-level indexqual by virtue of being generated
2772 	 * from the same EC.  After that, try predicate_implied_by().
2773 	 *
2774 	 * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
2775 	 * useful for getting rid of qpquals that are implied by index predicates,
2776 	 * because the predicate conditions are included in the "indexquals"
2777 	 * returned by create_bitmap_subplan().  Bitmap scans have to do it that
2778 	 * way because predicate conditions need to be rechecked if the scan
2779 	 * becomes lossy, so they have to be included in bitmapqualorig.
2780 	 */
2781 	qpqual = NIL;
2782 	foreach(l, scan_clauses)
2783 	{
2784 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2785 		Node	   *clause = (Node *) rinfo->clause;
2786 
2787 		if (rinfo->pseudoconstant)
2788 			continue;			/* we may drop pseudoconstants here */
2789 		if (list_member(indexquals, clause))
2790 			continue;			/* simple duplicate */
2791 		if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
2792 			continue;			/* derived from same EquivalenceClass */
2793 		if (!contain_mutable_functions(clause) &&
2794 			predicate_implied_by(list_make1(clause), indexquals, false))
2795 			continue;			/* provably implied by indexquals */
2796 		qpqual = lappend(qpqual, rinfo);
2797 	}
2798 
2799 	/* Sort clauses into best execution order */
2800 	qpqual = order_qual_clauses(root, qpqual);
2801 
2802 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2803 	qpqual = extract_actual_clauses(qpqual, false);
2804 
2805 	/*
2806 	 * When dealing with special operators, we will at this point have
2807 	 * duplicate clauses in qpqual and bitmapqualorig.  We may as well drop
2808 	 * 'em from bitmapqualorig, since there's no point in making the tests
2809 	 * twice.
2810 	 */
2811 	bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
2812 
2813 	/*
2814 	 * We have to replace any outer-relation variables with nestloop params in
2815 	 * the qpqual and bitmapqualorig expressions.  (This was already done for
2816 	 * expressions attached to plan nodes in the bitmapqualplan tree.)
2817 	 */
2818 	if (best_path->path.param_info)
2819 	{
2820 		qpqual = (List *)
2821 			replace_nestloop_params(root, (Node *) qpqual);
2822 		bitmapqualorig = (List *)
2823 			replace_nestloop_params(root, (Node *) bitmapqualorig);
2824 	}
2825 
2826 	/* Finally ready to build the plan node */
2827 	scan_plan = make_bitmap_heapscan(tlist,
2828 									 qpqual,
2829 									 bitmapqualplan,
2830 									 bitmapqualorig,
2831 									 baserelid);
2832 
2833 	copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2834 
2835 	return scan_plan;
2836 }
2837 
2838 /*
2839  * Given a bitmapqual tree, generate the Plan tree that implements it
2840  *
2841  * As byproducts, we also return in *qual and *indexqual the qual lists
2842  * (in implicit-AND form, without RestrictInfos) describing the original index
2843  * conditions and the generated indexqual conditions.  (These are the same in
2844  * simple cases, but when special index operators are involved, the former
2845  * list includes the special conditions while the latter includes the actual
2846  * indexable conditions derived from them.)  Both lists include partial-index
2847  * predicates, because we have to recheck predicates as well as index
2848  * conditions if the bitmap scan becomes lossy.
2849  *
2850  * In addition, we return a list of EquivalenceClass pointers for all the
2851  * top-level indexquals that were possibly-redundantly derived from ECs.
2852  * This allows removal of scan_clauses that are redundant with such quals.
2853  * (We do not attempt to detect such redundancies for quals that are within
2854  * OR subtrees.  This could be done in a less hacky way if we returned the
2855  * indexquals in RestrictInfo form, but that would be slower and still pretty
2856  * messy, since we'd have to build new RestrictInfos in many cases.)
2857  */
2858 static Plan *
create_bitmap_subplan(PlannerInfo * root,Path * bitmapqual,List ** qual,List ** indexqual,List ** indexECs)2859 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
2860 					  List **qual, List **indexqual, List **indexECs)
2861 {
2862 	Plan	   *plan;
2863 
2864 	if (IsA(bitmapqual, BitmapAndPath))
2865 	{
2866 		BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2867 		List	   *subplans = NIL;
2868 		List	   *subquals = NIL;
2869 		List	   *subindexquals = NIL;
2870 		List	   *subindexECs = NIL;
2871 		ListCell   *l;
2872 
2873 		/*
2874 		 * There may well be redundant quals among the subplans, since a
2875 		 * top-level WHERE qual might have gotten used to form several
2876 		 * different index quals.  We don't try exceedingly hard to eliminate
2877 		 * redundancies, but we do eliminate obvious duplicates by using
2878 		 * list_concat_unique.
2879 		 */
2880 		foreach(l, apath->bitmapquals)
2881 		{
2882 			Plan	   *subplan;
2883 			List	   *subqual;
2884 			List	   *subindexqual;
2885 			List	   *subindexEC;
2886 
2887 			subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2888 											&subqual, &subindexqual,
2889 											&subindexEC);
2890 			subplans = lappend(subplans, subplan);
2891 			subquals = list_concat_unique(subquals, subqual);
2892 			subindexquals = list_concat_unique(subindexquals, subindexqual);
2893 			/* Duplicates in indexECs aren't worth getting rid of */
2894 			subindexECs = list_concat(subindexECs, subindexEC);
2895 		}
2896 		plan = (Plan *) make_bitmap_and(subplans);
2897 		plan->startup_cost = apath->path.startup_cost;
2898 		plan->total_cost = apath->path.total_cost;
2899 		plan->plan_rows =
2900 			clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
2901 		plan->plan_width = 0;	/* meaningless */
2902 		plan->parallel_aware = false;
2903 		plan->parallel_safe = apath->path.parallel_safe;
2904 		*qual = subquals;
2905 		*indexqual = subindexquals;
2906 		*indexECs = subindexECs;
2907 	}
2908 	else if (IsA(bitmapqual, BitmapOrPath))
2909 	{
2910 		BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2911 		List	   *subplans = NIL;
2912 		List	   *subquals = NIL;
2913 		List	   *subindexquals = NIL;
2914 		bool		const_true_subqual = false;
2915 		bool		const_true_subindexqual = false;
2916 		ListCell   *l;
2917 
2918 		/*
2919 		 * Here, we only detect qual-free subplans.  A qual-free subplan would
2920 		 * cause us to generate "... OR true ..."  which we may as well reduce
2921 		 * to just "true".  We do not try to eliminate redundant subclauses
2922 		 * because (a) it's not as likely as in the AND case, and (b) we might
2923 		 * well be working with hundreds or even thousands of OR conditions,
2924 		 * perhaps from a long IN list.  The performance of list_append_unique
2925 		 * would be unacceptable.
2926 		 */
2927 		foreach(l, opath->bitmapquals)
2928 		{
2929 			Plan	   *subplan;
2930 			List	   *subqual;
2931 			List	   *subindexqual;
2932 			List	   *subindexEC;
2933 
2934 			subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2935 											&subqual, &subindexqual,
2936 											&subindexEC);
2937 			subplans = lappend(subplans, subplan);
2938 			if (subqual == NIL)
2939 				const_true_subqual = true;
2940 			else if (!const_true_subqual)
2941 				subquals = lappend(subquals,
2942 								   make_ands_explicit(subqual));
2943 			if (subindexqual == NIL)
2944 				const_true_subindexqual = true;
2945 			else if (!const_true_subindexqual)
2946 				subindexquals = lappend(subindexquals,
2947 										make_ands_explicit(subindexqual));
2948 		}
2949 
2950 		/*
2951 		 * In the presence of ScalarArrayOpExpr quals, we might have built
2952 		 * BitmapOrPaths with just one subpath; don't add an OR step.
2953 		 */
2954 		if (list_length(subplans) == 1)
2955 		{
2956 			plan = (Plan *) linitial(subplans);
2957 		}
2958 		else
2959 		{
2960 			plan = (Plan *) make_bitmap_or(subplans);
2961 			plan->startup_cost = opath->path.startup_cost;
2962 			plan->total_cost = opath->path.total_cost;
2963 			plan->plan_rows =
2964 				clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
2965 			plan->plan_width = 0;	/* meaningless */
2966 			plan->parallel_aware = false;
2967 			plan->parallel_safe = opath->path.parallel_safe;
2968 		}
2969 
2970 		/*
2971 		 * If there were constant-TRUE subquals, the OR reduces to constant
2972 		 * TRUE.  Also, avoid generating one-element ORs, which could happen
2973 		 * due to redundancy elimination or ScalarArrayOpExpr quals.
2974 		 */
2975 		if (const_true_subqual)
2976 			*qual = NIL;
2977 		else if (list_length(subquals) <= 1)
2978 			*qual = subquals;
2979 		else
2980 			*qual = list_make1(make_orclause(subquals));
2981 		if (const_true_subindexqual)
2982 			*indexqual = NIL;
2983 		else if (list_length(subindexquals) <= 1)
2984 			*indexqual = subindexquals;
2985 		else
2986 			*indexqual = list_make1(make_orclause(subindexquals));
2987 		*indexECs = NIL;
2988 	}
2989 	else if (IsA(bitmapqual, IndexPath))
2990 	{
2991 		IndexPath  *ipath = (IndexPath *) bitmapqual;
2992 		IndexScan  *iscan;
2993 		List	   *subindexECs;
2994 		ListCell   *l;
2995 
2996 		/* Use the regular indexscan plan build machinery... */
2997 		iscan = castNode(IndexScan,
2998 						 create_indexscan_plan(root, ipath,
2999 											   NIL, NIL, false));
3000 		/* then convert to a bitmap indexscan */
3001 		plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
3002 											  iscan->indexid,
3003 											  iscan->indexqual,
3004 											  iscan->indexqualorig);
3005 		/* and set its cost/width fields appropriately */
3006 		plan->startup_cost = 0.0;
3007 		plan->total_cost = ipath->indextotalcost;
3008 		plan->plan_rows =
3009 			clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
3010 		plan->plan_width = 0;	/* meaningless */
3011 		plan->parallel_aware = false;
3012 		plan->parallel_safe = ipath->path.parallel_safe;
3013 		*qual = get_actual_clauses(ipath->indexclauses);
3014 		*indexqual = get_actual_clauses(ipath->indexquals);
3015 		foreach(l, ipath->indexinfo->indpred)
3016 		{
3017 			Expr	   *pred = (Expr *) lfirst(l);
3018 
3019 			/*
3020 			 * We know that the index predicate must have been implied by the
3021 			 * query condition as a whole, but it may or may not be implied by
3022 			 * the conditions that got pushed into the bitmapqual.  Avoid
3023 			 * generating redundant conditions.
3024 			 */
3025 			if (!predicate_implied_by(list_make1(pred), ipath->indexclauses,
3026 									  false))
3027 			{
3028 				*qual = lappend(*qual, pred);
3029 				*indexqual = lappend(*indexqual, pred);
3030 			}
3031 		}
3032 		subindexECs = NIL;
3033 		foreach(l, ipath->indexquals)
3034 		{
3035 			RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3036 
3037 			if (rinfo->parent_ec)
3038 				subindexECs = lappend(subindexECs, rinfo->parent_ec);
3039 		}
3040 		*indexECs = subindexECs;
3041 	}
3042 	else
3043 	{
3044 		elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
3045 		plan = NULL;			/* keep compiler quiet */
3046 	}
3047 
3048 	return plan;
3049 }
3050 
3051 /*
3052  * create_tidscan_plan
3053  *	 Returns a tidscan plan for the base relation scanned by 'best_path'
3054  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3055  */
3056 static TidScan *
create_tidscan_plan(PlannerInfo * root,TidPath * best_path,List * tlist,List * scan_clauses)3057 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
3058 					List *tlist, List *scan_clauses)
3059 {
3060 	TidScan    *scan_plan;
3061 	Index		scan_relid = best_path->path.parent->relid;
3062 	List	   *tidquals = best_path->tidquals;
3063 	List	   *ortidquals;
3064 
3065 	/* it should be a base rel... */
3066 	Assert(scan_relid > 0);
3067 	Assert(best_path->path.parent->rtekind == RTE_RELATION);
3068 
3069 	/* Sort clauses into best execution order */
3070 	scan_clauses = order_qual_clauses(root, scan_clauses);
3071 
3072 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3073 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3074 
3075 	/* Replace any outer-relation variables with nestloop params */
3076 	if (best_path->path.param_info)
3077 	{
3078 		tidquals = (List *)
3079 			replace_nestloop_params(root, (Node *) tidquals);
3080 		scan_clauses = (List *)
3081 			replace_nestloop_params(root, (Node *) scan_clauses);
3082 	}
3083 
3084 	/*
3085 	 * Remove any clauses that are TID quals.  This is a bit tricky since the
3086 	 * tidquals list has implicit OR semantics.
3087 	 */
3088 	ortidquals = tidquals;
3089 	if (list_length(ortidquals) > 1)
3090 		ortidquals = list_make1(make_orclause(ortidquals));
3091 	scan_clauses = list_difference(scan_clauses, ortidquals);
3092 
3093 	scan_plan = make_tidscan(tlist,
3094 							 scan_clauses,
3095 							 scan_relid,
3096 							 tidquals);
3097 
3098 	copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3099 
3100 	return scan_plan;
3101 }
3102 
3103 /*
3104  * create_subqueryscan_plan
3105  *	 Returns a subqueryscan plan for the base relation scanned by 'best_path'
3106  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3107  */
3108 static SubqueryScan *
create_subqueryscan_plan(PlannerInfo * root,SubqueryScanPath * best_path,List * tlist,List * scan_clauses)3109 create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path,
3110 						 List *tlist, List *scan_clauses)
3111 {
3112 	SubqueryScan *scan_plan;
3113 	RelOptInfo *rel = best_path->path.parent;
3114 	Index		scan_relid = rel->relid;
3115 	Plan	   *subplan;
3116 
3117 	/* it should be a subquery base rel... */
3118 	Assert(scan_relid > 0);
3119 	Assert(rel->rtekind == RTE_SUBQUERY);
3120 
3121 	/*
3122 	 * Recursively create Plan from Path for subquery.  Since we are entering
3123 	 * a different planner context (subroot), recurse to create_plan not
3124 	 * create_plan_recurse.
3125 	 */
3126 	subplan = create_plan(rel->subroot, best_path->subpath);
3127 
3128 	/* Sort clauses into best execution order */
3129 	scan_clauses = order_qual_clauses(root, scan_clauses);
3130 
3131 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3132 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3133 
3134 	/* Replace any outer-relation variables with nestloop params */
3135 	if (best_path->path.param_info)
3136 	{
3137 		scan_clauses = (List *)
3138 			replace_nestloop_params(root, (Node *) scan_clauses);
3139 		process_subquery_nestloop_params(root,
3140 										 rel->subplan_params);
3141 	}
3142 
3143 	scan_plan = make_subqueryscan(tlist,
3144 								  scan_clauses,
3145 								  scan_relid,
3146 								  subplan);
3147 
3148 	copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3149 
3150 	return scan_plan;
3151 }
3152 
3153 /*
3154  * create_functionscan_plan
3155  *	 Returns a functionscan plan for the base relation scanned by 'best_path'
3156  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3157  */
3158 static FunctionScan *
create_functionscan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3159 create_functionscan_plan(PlannerInfo *root, Path *best_path,
3160 						 List *tlist, List *scan_clauses)
3161 {
3162 	FunctionScan *scan_plan;
3163 	Index		scan_relid = best_path->parent->relid;
3164 	RangeTblEntry *rte;
3165 	List	   *functions;
3166 
3167 	/* it should be a function base rel... */
3168 	Assert(scan_relid > 0);
3169 	rte = planner_rt_fetch(scan_relid, root);
3170 	Assert(rte->rtekind == RTE_FUNCTION);
3171 	functions = rte->functions;
3172 
3173 	/* Sort clauses into best execution order */
3174 	scan_clauses = order_qual_clauses(root, scan_clauses);
3175 
3176 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3177 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3178 
3179 	/* Replace any outer-relation variables with nestloop params */
3180 	if (best_path->param_info)
3181 	{
3182 		scan_clauses = (List *)
3183 			replace_nestloop_params(root, (Node *) scan_clauses);
3184 		/* The function expressions could contain nestloop params, too */
3185 		functions = (List *) replace_nestloop_params(root, (Node *) functions);
3186 	}
3187 
3188 	scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
3189 								  functions, rte->funcordinality);
3190 
3191 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3192 
3193 	return scan_plan;
3194 }
3195 
3196 /*
3197  * create_tablefuncscan_plan
3198  *	 Returns a tablefuncscan plan for the base relation scanned by 'best_path'
3199  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3200  */
3201 static TableFuncScan *
create_tablefuncscan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3202 create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
3203 						  List *tlist, List *scan_clauses)
3204 {
3205 	TableFuncScan *scan_plan;
3206 	Index		scan_relid = best_path->parent->relid;
3207 	RangeTblEntry *rte;
3208 	TableFunc  *tablefunc;
3209 
3210 	/* it should be a function base rel... */
3211 	Assert(scan_relid > 0);
3212 	rte = planner_rt_fetch(scan_relid, root);
3213 	Assert(rte->rtekind == RTE_TABLEFUNC);
3214 	tablefunc = rte->tablefunc;
3215 
3216 	/* Sort clauses into best execution order */
3217 	scan_clauses = order_qual_clauses(root, scan_clauses);
3218 
3219 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3220 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3221 
3222 	/* Replace any outer-relation variables with nestloop params */
3223 	if (best_path->param_info)
3224 	{
3225 		scan_clauses = (List *)
3226 			replace_nestloop_params(root, (Node *) scan_clauses);
3227 		/* The function expressions could contain nestloop params, too */
3228 		tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
3229 	}
3230 
3231 	scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
3232 								   tablefunc);
3233 
3234 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3235 
3236 	return scan_plan;
3237 }
3238 
3239 /*
3240  * create_valuesscan_plan
3241  *	 Returns a valuesscan plan for the base relation scanned by 'best_path'
3242  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3243  */
3244 static ValuesScan *
create_valuesscan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3245 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
3246 					   List *tlist, List *scan_clauses)
3247 {
3248 	ValuesScan *scan_plan;
3249 	Index		scan_relid = best_path->parent->relid;
3250 	RangeTblEntry *rte;
3251 	List	   *values_lists;
3252 
3253 	/* it should be a values base rel... */
3254 	Assert(scan_relid > 0);
3255 	rte = planner_rt_fetch(scan_relid, root);
3256 	Assert(rte->rtekind == RTE_VALUES);
3257 	values_lists = rte->values_lists;
3258 
3259 	/* Sort clauses into best execution order */
3260 	scan_clauses = order_qual_clauses(root, scan_clauses);
3261 
3262 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3263 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3264 
3265 	/* Replace any outer-relation variables with nestloop params */
3266 	if (best_path->param_info)
3267 	{
3268 		scan_clauses = (List *)
3269 			replace_nestloop_params(root, (Node *) scan_clauses);
3270 		/* The values lists could contain nestloop params, too */
3271 		values_lists = (List *)
3272 			replace_nestloop_params(root, (Node *) values_lists);
3273 	}
3274 
3275 	scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
3276 								values_lists);
3277 
3278 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3279 
3280 	return scan_plan;
3281 }
3282 
3283 /*
3284  * create_ctescan_plan
3285  *	 Returns a ctescan plan for the base relation scanned by 'best_path'
3286  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3287  */
3288 static CteScan *
create_ctescan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3289 create_ctescan_plan(PlannerInfo *root, Path *best_path,
3290 					List *tlist, List *scan_clauses)
3291 {
3292 	CteScan    *scan_plan;
3293 	Index		scan_relid = best_path->parent->relid;
3294 	RangeTblEntry *rte;
3295 	SubPlan    *ctesplan = NULL;
3296 	int			plan_id;
3297 	int			cte_param_id;
3298 	PlannerInfo *cteroot;
3299 	Index		levelsup;
3300 	int			ndx;
3301 	ListCell   *lc;
3302 
3303 	Assert(scan_relid > 0);
3304 	rte = planner_rt_fetch(scan_relid, root);
3305 	Assert(rte->rtekind == RTE_CTE);
3306 	Assert(!rte->self_reference);
3307 
3308 	/*
3309 	 * Find the referenced CTE, and locate the SubPlan previously made for it.
3310 	 */
3311 	levelsup = rte->ctelevelsup;
3312 	cteroot = root;
3313 	while (levelsup-- > 0)
3314 	{
3315 		cteroot = cteroot->parent_root;
3316 		if (!cteroot)			/* shouldn't happen */
3317 			elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3318 	}
3319 
3320 	/*
3321 	 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3322 	 * on planning the CTEs (ie, this is a side-reference from another CTE).
3323 	 * So we mustn't use forboth here.
3324 	 */
3325 	ndx = 0;
3326 	foreach(lc, cteroot->parse->cteList)
3327 	{
3328 		CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3329 
3330 		if (strcmp(cte->ctename, rte->ctename) == 0)
3331 			break;
3332 		ndx++;
3333 	}
3334 	if (lc == NULL)				/* shouldn't happen */
3335 		elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3336 	if (ndx >= list_length(cteroot->cte_plan_ids))
3337 		elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3338 	plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3339 	Assert(plan_id > 0);
3340 	foreach(lc, cteroot->init_plans)
3341 	{
3342 		ctesplan = (SubPlan *) lfirst(lc);
3343 		if (ctesplan->plan_id == plan_id)
3344 			break;
3345 	}
3346 	if (lc == NULL)				/* shouldn't happen */
3347 		elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3348 
3349 	/*
3350 	 * We need the CTE param ID, which is the sole member of the SubPlan's
3351 	 * setParam list.
3352 	 */
3353 	cte_param_id = linitial_int(ctesplan->setParam);
3354 
3355 	/* Sort clauses into best execution order */
3356 	scan_clauses = order_qual_clauses(root, scan_clauses);
3357 
3358 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3359 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3360 
3361 	/* Replace any outer-relation variables with nestloop params */
3362 	if (best_path->param_info)
3363 	{
3364 		scan_clauses = (List *)
3365 			replace_nestloop_params(root, (Node *) scan_clauses);
3366 	}
3367 
3368 	scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3369 							 plan_id, cte_param_id);
3370 
3371 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3372 
3373 	return scan_plan;
3374 }
3375 
3376 /*
3377  * create_namedtuplestorescan_plan
3378  *	 Returns a tuplestorescan plan for the base relation scanned by
3379  *	'best_path' with restriction clauses 'scan_clauses' and targetlist
3380  *	'tlist'.
3381  */
3382 static NamedTuplestoreScan *
create_namedtuplestorescan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3383 create_namedtuplestorescan_plan(PlannerInfo *root, Path *best_path,
3384 								List *tlist, List *scan_clauses)
3385 {
3386 	NamedTuplestoreScan *scan_plan;
3387 	Index		scan_relid = best_path->parent->relid;
3388 	RangeTblEntry *rte;
3389 
3390 	Assert(scan_relid > 0);
3391 	rte = planner_rt_fetch(scan_relid, root);
3392 	Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
3393 
3394 	/* Sort clauses into best execution order */
3395 	scan_clauses = order_qual_clauses(root, scan_clauses);
3396 
3397 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3398 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3399 
3400 	/* Replace any outer-relation variables with nestloop params */
3401 	if (best_path->param_info)
3402 	{
3403 		scan_clauses = (List *)
3404 			replace_nestloop_params(root, (Node *) scan_clauses);
3405 	}
3406 
3407 	scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
3408 										 rte->enrname);
3409 
3410 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3411 
3412 	return scan_plan;
3413 }
3414 
3415 /*
3416  * create_worktablescan_plan
3417  *	 Returns a worktablescan plan for the base relation scanned by 'best_path'
3418  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3419  */
3420 static WorkTableScan *
create_worktablescan_plan(PlannerInfo * root,Path * best_path,List * tlist,List * scan_clauses)3421 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
3422 						  List *tlist, List *scan_clauses)
3423 {
3424 	WorkTableScan *scan_plan;
3425 	Index		scan_relid = best_path->parent->relid;
3426 	RangeTblEntry *rte;
3427 	Index		levelsup;
3428 	PlannerInfo *cteroot;
3429 
3430 	Assert(scan_relid > 0);
3431 	rte = planner_rt_fetch(scan_relid, root);
3432 	Assert(rte->rtekind == RTE_CTE);
3433 	Assert(rte->self_reference);
3434 
3435 	/*
3436 	 * We need to find the worktable param ID, which is in the plan level
3437 	 * that's processing the recursive UNION, which is one level *below* where
3438 	 * the CTE comes from.
3439 	 */
3440 	levelsup = rte->ctelevelsup;
3441 	if (levelsup == 0)			/* shouldn't happen */
3442 		elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3443 	levelsup--;
3444 	cteroot = root;
3445 	while (levelsup-- > 0)
3446 	{
3447 		cteroot = cteroot->parent_root;
3448 		if (!cteroot)			/* shouldn't happen */
3449 			elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3450 	}
3451 	if (cteroot->wt_param_id < 0)	/* shouldn't happen */
3452 		elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
3453 
3454 	/* Sort clauses into best execution order */
3455 	scan_clauses = order_qual_clauses(root, scan_clauses);
3456 
3457 	/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3458 	scan_clauses = extract_actual_clauses(scan_clauses, false);
3459 
3460 	/* Replace any outer-relation variables with nestloop params */
3461 	if (best_path->param_info)
3462 	{
3463 		scan_clauses = (List *)
3464 			replace_nestloop_params(root, (Node *) scan_clauses);
3465 	}
3466 
3467 	scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
3468 								   cteroot->wt_param_id);
3469 
3470 	copy_generic_path_info(&scan_plan->scan.plan, best_path);
3471 
3472 	return scan_plan;
3473 }
3474 
3475 /*
3476  * create_foreignscan_plan
3477  *	 Returns a foreignscan plan for the relation scanned by 'best_path'
3478  *	 with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3479  */
3480 static ForeignScan *
create_foreignscan_plan(PlannerInfo * root,ForeignPath * best_path,List * tlist,List * scan_clauses)3481 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
3482 						List *tlist, List *scan_clauses)
3483 {
3484 	ForeignScan *scan_plan;
3485 	RelOptInfo *rel = best_path->path.parent;
3486 	Index		scan_relid = rel->relid;
3487 	Oid			rel_oid = InvalidOid;
3488 	Plan	   *outer_plan = NULL;
3489 
3490 	Assert(rel->fdwroutine != NULL);
3491 
3492 	/* transform the child path if any */
3493 	if (best_path->fdw_outerpath)
3494 		outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3495 										 CP_EXACT_TLIST);
3496 
3497 	/*
3498 	 * If we're scanning a base relation, fetch its OID.  (Irrelevant if
3499 	 * scanning a join relation.)
3500 	 */
3501 	if (scan_relid > 0)
3502 	{
3503 		RangeTblEntry *rte;
3504 
3505 		Assert(rel->rtekind == RTE_RELATION);
3506 		rte = planner_rt_fetch(scan_relid, root);
3507 		Assert(rte->rtekind == RTE_RELATION);
3508 		rel_oid = rte->relid;
3509 	}
3510 
3511 	/*
3512 	 * Sort clauses into best execution order.  We do this first since the FDW
3513 	 * might have more info than we do and wish to adjust the ordering.
3514 	 */
3515 	scan_clauses = order_qual_clauses(root, scan_clauses);
3516 
3517 	/*
3518 	 * Let the FDW perform its processing on the restriction clauses and
3519 	 * generate the plan node.  Note that the FDW might remove restriction
3520 	 * clauses that it intends to execute remotely, or even add more (if it
3521 	 * has selected some join clauses for remote use but also wants them
3522 	 * rechecked locally).
3523 	 */
3524 	scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
3525 												best_path,
3526 												tlist, scan_clauses,
3527 												outer_plan);
3528 
3529 	/* Copy cost data from Path to Plan; no need to make FDW do this */
3530 	copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3531 
3532 	/* Copy foreign server OID; likewise, no need to make FDW do this */
3533 	scan_plan->fs_server = rel->serverid;
3534 
3535 	/*
3536 	 * Likewise, copy the relids that are represented by this foreign scan. An
3537 	 * upper rel doesn't have relids set, but it covers all the base relations
3538 	 * participating in the underlying scan, so use root's all_baserels.
3539 	 */
3540 	if (IS_UPPER_REL(rel))
3541 		scan_plan->fs_relids = root->all_baserels;
3542 	else
3543 		scan_plan->fs_relids = best_path->path.parent->relids;
3544 
3545 	/*
3546 	 * If this is a foreign join, and to make it valid to push down we had to
3547 	 * assume that the current user is the same as some user explicitly named
3548 	 * in the query, mark the finished plan as depending on the current user.
3549 	 */
3550 	if (rel->useridiscurrent)
3551 		root->glob->dependsOnRole = true;
3552 
3553 	/*
3554 	 * Replace any outer-relation variables with nestloop params in the qual,
3555 	 * fdw_exprs and fdw_recheck_quals expressions.  We do this last so that
3556 	 * the FDW doesn't have to be involved.  (Note that parts of fdw_exprs or
3557 	 * fdw_recheck_quals could have come from join clauses, so doing this
3558 	 * beforehand on the scan_clauses wouldn't work.)  We assume
3559 	 * fdw_scan_tlist contains no such variables.
3560 	 */
3561 	if (best_path->path.param_info)
3562 	{
3563 		scan_plan->scan.plan.qual = (List *)
3564 			replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
3565 		scan_plan->fdw_exprs = (List *)
3566 			replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
3567 		scan_plan->fdw_recheck_quals = (List *)
3568 			replace_nestloop_params(root,
3569 									(Node *) scan_plan->fdw_recheck_quals);
3570 	}
3571 
3572 	/*
3573 	 * If rel is a base relation, detect whether any system columns are
3574 	 * requested from the rel.  (If rel is a join relation, rel->relid will be
3575 	 * 0, but there can be no Var with relid 0 in the rel's targetlist or the
3576 	 * restriction clauses, so we skip this in that case.  Note that any such
3577 	 * columns in base relations that were joined are assumed to be contained
3578 	 * in fdw_scan_tlist.)	This is a bit of a kluge and might go away
3579 	 * someday, so we intentionally leave it out of the API presented to FDWs.
3580 	 */
3581 	scan_plan->fsSystemCol = false;
3582 	if (scan_relid > 0)
3583 	{
3584 		Bitmapset  *attrs_used = NULL;
3585 		ListCell   *lc;
3586 		int			i;
3587 
3588 		/*
3589 		 * First, examine all the attributes needed for joins or final output.
3590 		 * Note: we must look at rel's targetlist, not the attr_needed data,
3591 		 * because attr_needed isn't computed for inheritance child rels.
3592 		 */
3593 		pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
3594 
3595 		/* Add all the attributes used by restriction clauses. */
3596 		foreach(lc, rel->baserestrictinfo)
3597 		{
3598 			RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3599 
3600 			pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
3601 		}
3602 
3603 		/* Now, are any system columns requested from rel? */
3604 		for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
3605 		{
3606 			if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
3607 			{
3608 				scan_plan->fsSystemCol = true;
3609 				break;
3610 			}
3611 		}
3612 
3613 		bms_free(attrs_used);
3614 	}
3615 
3616 	return scan_plan;
3617 }
3618 
3619 /*
3620  * create_custom_plan
3621  *
3622  * Transform a CustomPath into a Plan.
3623  */
3624 static CustomScan *
create_customscan_plan(PlannerInfo * root,CustomPath * best_path,List * tlist,List * scan_clauses)3625 create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
3626 					   List *tlist, List *scan_clauses)
3627 {
3628 	CustomScan *cplan;
3629 	RelOptInfo *rel = best_path->path.parent;
3630 	List	   *custom_plans = NIL;
3631 	ListCell   *lc;
3632 
3633 	/* Recursively transform child paths. */
3634 	foreach(lc, best_path->custom_paths)
3635 	{
3636 		Plan	   *plan = create_plan_recurse(root, (Path *) lfirst(lc),
3637 											   CP_EXACT_TLIST);
3638 
3639 		custom_plans = lappend(custom_plans, plan);
3640 	}
3641 
3642 	/*
3643 	 * Sort clauses into the best execution order, although custom-scan
3644 	 * provider can reorder them again.
3645 	 */
3646 	scan_clauses = order_qual_clauses(root, scan_clauses);
3647 
3648 	/*
3649 	 * Invoke custom plan provider to create the Plan node represented by the
3650 	 * CustomPath.
3651 	 */
3652 	cplan = castNode(CustomScan,
3653 					 best_path->methods->PlanCustomPath(root,
3654 														rel,
3655 														best_path,
3656 														tlist,
3657 														scan_clauses,
3658 														custom_plans));
3659 
3660 	/*
3661 	 * Copy cost data from Path to Plan; no need to make custom-plan providers
3662 	 * do this
3663 	 */
3664 	copy_generic_path_info(&cplan->scan.plan, &best_path->path);
3665 
3666 	/* Likewise, copy the relids that are represented by this custom scan */
3667 	cplan->custom_relids = best_path->path.parent->relids;
3668 
3669 	/*
3670 	 * Replace any outer-relation variables with nestloop params in the qual
3671 	 * and custom_exprs expressions.  We do this last so that the custom-plan
3672 	 * provider doesn't have to be involved.  (Note that parts of custom_exprs
3673 	 * could have come from join clauses, so doing this beforehand on the
3674 	 * scan_clauses wouldn't work.)  We assume custom_scan_tlist contains no
3675 	 * such variables.
3676 	 */
3677 	if (best_path->path.param_info)
3678 	{
3679 		cplan->scan.plan.qual = (List *)
3680 			replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
3681 		cplan->custom_exprs = (List *)
3682 			replace_nestloop_params(root, (Node *) cplan->custom_exprs);
3683 	}
3684 
3685 	return cplan;
3686 }
3687 
3688 
3689 /*****************************************************************************
3690  *
3691  *	JOIN METHODS
3692  *
3693  *****************************************************************************/
3694 
3695 static NestLoop *
create_nestloop_plan(PlannerInfo * root,NestPath * best_path)3696 create_nestloop_plan(PlannerInfo *root,
3697 					 NestPath *best_path)
3698 {
3699 	NestLoop   *join_plan;
3700 	Plan	   *outer_plan;
3701 	Plan	   *inner_plan;
3702 	List	   *tlist = build_path_tlist(root, &best_path->path);
3703 	List	   *joinrestrictclauses = best_path->joinrestrictinfo;
3704 	List	   *joinclauses;
3705 	List	   *otherclauses;
3706 	Relids		outerrelids;
3707 	List	   *nestParams;
3708 	Relids		saveOuterRels = root->curOuterRels;
3709 
3710 	/* NestLoop can project, so no need to be picky about child tlists */
3711 	outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
3712 
3713 	/* For a nestloop, include outer relids in curOuterRels for inner side */
3714 	root->curOuterRels = bms_union(root->curOuterRels,
3715 								   best_path->outerjoinpath->parent->relids);
3716 
3717 	inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
3718 
3719 	/* Restore curOuterRels */
3720 	bms_free(root->curOuterRels);
3721 	root->curOuterRels = saveOuterRels;
3722 
3723 	/* Sort join qual clauses into best execution order */
3724 	joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
3725 
3726 	/* Get the join qual clauses (in plain expression form) */
3727 	/* Any pseudoconstant clauses are ignored here */
3728 	if (IS_OUTER_JOIN(best_path->jointype))
3729 	{
3730 		extract_actual_join_clauses(joinrestrictclauses,
3731 									best_path->path.parent->relids,
3732 									&joinclauses, &otherclauses);
3733 	}
3734 	else
3735 	{
3736 		/* We can treat all clauses alike for an inner join */
3737 		joinclauses = extract_actual_clauses(joinrestrictclauses, false);
3738 		otherclauses = NIL;
3739 	}
3740 
3741 	/* Replace any outer-relation variables with nestloop params */
3742 	if (best_path->path.param_info)
3743 	{
3744 		joinclauses = (List *)
3745 			replace_nestloop_params(root, (Node *) joinclauses);
3746 		otherclauses = (List *)
3747 			replace_nestloop_params(root, (Node *) otherclauses);
3748 	}
3749 
3750 	/*
3751 	 * Identify any nestloop parameters that should be supplied by this join
3752 	 * node, and remove them from root->curOuterParams.
3753 	 */
3754 	outerrelids = best_path->outerjoinpath->parent->relids;
3755 	nestParams = identify_current_nestloop_params(root, outerrelids);
3756 
3757 	join_plan = make_nestloop(tlist,
3758 							  joinclauses,
3759 							  otherclauses,
3760 							  nestParams,
3761 							  outer_plan,
3762 							  inner_plan,
3763 							  best_path->jointype,
3764 							  best_path->inner_unique);
3765 
3766 	copy_generic_path_info(&join_plan->join.plan, &best_path->path);
3767 
3768 	return join_plan;
3769 }
3770 
3771 static MergeJoin *
create_mergejoin_plan(PlannerInfo * root,MergePath * best_path)3772 create_mergejoin_plan(PlannerInfo *root,
3773 					  MergePath *best_path)
3774 {
3775 	MergeJoin  *join_plan;
3776 	Plan	   *outer_plan;
3777 	Plan	   *inner_plan;
3778 	List	   *tlist = build_path_tlist(root, &best_path->jpath.path);
3779 	List	   *joinclauses;
3780 	List	   *otherclauses;
3781 	List	   *mergeclauses;
3782 	List	   *outerpathkeys;
3783 	List	   *innerpathkeys;
3784 	int			nClauses;
3785 	Oid		   *mergefamilies;
3786 	Oid		   *mergecollations;
3787 	int		   *mergestrategies;
3788 	bool	   *mergenullsfirst;
3789 	PathKey    *opathkey;
3790 	EquivalenceClass *opeclass;
3791 	int			i;
3792 	ListCell   *lc;
3793 	ListCell   *lop;
3794 	ListCell   *lip;
3795 
3796 	/*
3797 	 * MergeJoin can project, so we don't have to demand exact tlists from the
3798 	 * inputs.  However, if we're intending to sort an input's result, it's
3799 	 * best to request a small tlist so we aren't sorting more data than
3800 	 * necessary.
3801 	 */
3802 	outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3803 									 (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3804 
3805 	inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3806 									 (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3807 
3808 	/* Sort join qual clauses into best execution order */
3809 	/* NB: do NOT reorder the mergeclauses */
3810 	joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3811 
3812 	/* Get the join qual clauses (in plain expression form) */
3813 	/* Any pseudoconstant clauses are ignored here */
3814 	if (IS_OUTER_JOIN(best_path->jpath.jointype))
3815 	{
3816 		extract_actual_join_clauses(joinclauses,
3817 									best_path->jpath.path.parent->relids,
3818 									&joinclauses, &otherclauses);
3819 	}
3820 	else
3821 	{
3822 		/* We can treat all clauses alike for an inner join */
3823 		joinclauses = extract_actual_clauses(joinclauses, false);
3824 		otherclauses = NIL;
3825 	}
3826 
3827 	/*
3828 	 * Remove the mergeclauses from the list of join qual clauses, leaving the
3829 	 * list of quals that must be checked as qpquals.
3830 	 */
3831 	mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
3832 	joinclauses = list_difference(joinclauses, mergeclauses);
3833 
3834 	/*
3835 	 * Replace any outer-relation variables with nestloop params.  There
3836 	 * should not be any in the mergeclauses.
3837 	 */
3838 	if (best_path->jpath.path.param_info)
3839 	{
3840 		joinclauses = (List *)
3841 			replace_nestloop_params(root, (Node *) joinclauses);
3842 		otherclauses = (List *)
3843 			replace_nestloop_params(root, (Node *) otherclauses);
3844 	}
3845 
3846 	/*
3847 	 * Rearrange mergeclauses, if needed, so that the outer variable is always
3848 	 * on the left; mark the mergeclause restrictinfos with correct
3849 	 * outer_is_left status.
3850 	 */
3851 	mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
3852 										best_path->jpath.outerjoinpath->parent->relids);
3853 
3854 	/*
3855 	 * Create explicit sort nodes for the outer and inner paths if necessary.
3856 	 */
3857 	if (best_path->outersortkeys)
3858 	{
3859 		Sort	   *sort = make_sort_from_pathkeys(outer_plan,
3860 												   best_path->outersortkeys);
3861 
3862 		label_sort_with_costsize(root, sort, -1.0);
3863 		outer_plan = (Plan *) sort;
3864 		outerpathkeys = best_path->outersortkeys;
3865 	}
3866 	else
3867 		outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
3868 
3869 	if (best_path->innersortkeys)
3870 	{
3871 		Sort	   *sort = make_sort_from_pathkeys(inner_plan,
3872 												   best_path->innersortkeys);
3873 
3874 		label_sort_with_costsize(root, sort, -1.0);
3875 		inner_plan = (Plan *) sort;
3876 		innerpathkeys = best_path->innersortkeys;
3877 	}
3878 	else
3879 		innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
3880 
3881 	/*
3882 	 * If specified, add a materialize node to shield the inner plan from the
3883 	 * need to handle mark/restore.
3884 	 */
3885 	if (best_path->materialize_inner)
3886 	{
3887 		Plan	   *matplan = (Plan *) make_material(inner_plan);
3888 
3889 		/*
3890 		 * We assume the materialize will not spill to disk, and therefore
3891 		 * charge just cpu_operator_cost per tuple.  (Keep this estimate in
3892 		 * sync with final_cost_mergejoin.)
3893 		 */
3894 		copy_plan_costsize(matplan, inner_plan);
3895 		matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
3896 
3897 		inner_plan = matplan;
3898 	}
3899 
3900 	/*
3901 	 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
3902 	 * executor.  The information is in the pathkeys for the two inputs, but
3903 	 * we need to be careful about the possibility of mergeclauses sharing a
3904 	 * pathkey, as well as the possibility that the inner pathkeys are not in
3905 	 * an order matching the mergeclauses.
3906 	 */
3907 	nClauses = list_length(mergeclauses);
3908 	Assert(nClauses == list_length(best_path->path_mergeclauses));
3909 	mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
3910 	mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
3911 	mergestrategies = (int *) palloc(nClauses * sizeof(int));
3912 	mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
3913 
3914 	opathkey = NULL;
3915 	opeclass = NULL;
3916 	lop = list_head(outerpathkeys);
3917 	lip = list_head(innerpathkeys);
3918 	i = 0;
3919 	foreach(lc, best_path->path_mergeclauses)
3920 	{
3921 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3922 		EquivalenceClass *oeclass;
3923 		EquivalenceClass *ieclass;
3924 		PathKey    *ipathkey = NULL;
3925 		EquivalenceClass *ipeclass = NULL;
3926 		bool		first_inner_match = false;
3927 
3928 		/* fetch outer/inner eclass from mergeclause */
3929 		if (rinfo->outer_is_left)
3930 		{
3931 			oeclass = rinfo->left_ec;
3932 			ieclass = rinfo->right_ec;
3933 		}
3934 		else
3935 		{
3936 			oeclass = rinfo->right_ec;
3937 			ieclass = rinfo->left_ec;
3938 		}
3939 		Assert(oeclass != NULL);
3940 		Assert(ieclass != NULL);
3941 
3942 		/*
3943 		 * We must identify the pathkey elements associated with this clause
3944 		 * by matching the eclasses (which should give a unique match, since
3945 		 * the pathkey lists should be canonical).  In typical cases the merge
3946 		 * clauses are one-to-one with the pathkeys, but when dealing with
3947 		 * partially redundant query conditions, things are more complicated.
3948 		 *
3949 		 * lop and lip reference the first as-yet-unmatched pathkey elements.
3950 		 * If they're NULL then all pathkey elements have been matched.
3951 		 *
3952 		 * The ordering of the outer pathkeys should match the mergeclauses,
3953 		 * by construction (see find_mergeclauses_for_outer_pathkeys()). There
3954 		 * could be more than one mergeclause for the same outer pathkey, but
3955 		 * no pathkey may be entirely skipped over.
3956 		 */
3957 		if (oeclass != opeclass)	/* multiple matches are not interesting */
3958 		{
3959 			/* doesn't match the current opathkey, so must match the next */
3960 			if (lop == NULL)
3961 				elog(ERROR, "outer pathkeys do not match mergeclauses");
3962 			opathkey = (PathKey *) lfirst(lop);
3963 			opeclass = opathkey->pk_eclass;
3964 			lop = lnext(lop);
3965 			if (oeclass != opeclass)
3966 				elog(ERROR, "outer pathkeys do not match mergeclauses");
3967 		}
3968 
3969 		/*
3970 		 * The inner pathkeys likewise should not have skipped-over keys, but
3971 		 * it's possible for a mergeclause to reference some earlier inner
3972 		 * pathkey if we had redundant pathkeys.  For example we might have
3973 		 * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x".  The
3974 		 * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
3975 		 * mechanism drops the second sort by x as redundant, and this code
3976 		 * must cope.
3977 		 *
3978 		 * It's also possible for the implied inner-rel ordering to be like
3979 		 * "ORDER BY x, y, x DESC".  We still drop the second instance of x as
3980 		 * redundant; but this means that the sort ordering of a redundant
3981 		 * inner pathkey should not be considered significant.  So we must
3982 		 * detect whether this is the first clause matching an inner pathkey.
3983 		 */
3984 		if (lip)
3985 		{
3986 			ipathkey = (PathKey *) lfirst(lip);
3987 			ipeclass = ipathkey->pk_eclass;
3988 			if (ieclass == ipeclass)
3989 			{
3990 				/* successful first match to this inner pathkey */
3991 				lip = lnext(lip);
3992 				first_inner_match = true;
3993 			}
3994 		}
3995 		if (!first_inner_match)
3996 		{
3997 			/* redundant clause ... must match something before lip */
3998 			ListCell   *l2;
3999 
4000 			foreach(l2, innerpathkeys)
4001 			{
4002 				if (l2 == lip)
4003 					break;
4004 				ipathkey = (PathKey *) lfirst(l2);
4005 				ipeclass = ipathkey->pk_eclass;
4006 				if (ieclass == ipeclass)
4007 					break;
4008 			}
4009 			if (ieclass != ipeclass)
4010 				elog(ERROR, "inner pathkeys do not match mergeclauses");
4011 		}
4012 
4013 		/*
4014 		 * The pathkeys should always match each other as to opfamily and
4015 		 * collation (which affect equality), but if we're considering a
4016 		 * redundant inner pathkey, its sort ordering might not match.  In
4017 		 * such cases we may ignore the inner pathkey's sort ordering and use
4018 		 * the outer's.  (In effect, we're lying to the executor about the
4019 		 * sort direction of this inner column, but it does not matter since
4020 		 * the run-time row comparisons would only reach this column when
4021 		 * there's equality for the earlier column containing the same eclass.
4022 		 * There could be only one value in this column for the range of inner
4023 		 * rows having a given value in the earlier column, so it does not
4024 		 * matter which way we imagine this column to be ordered.)  But a
4025 		 * non-redundant inner pathkey had better match outer's ordering too.
4026 		 */
4027 		if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4028 			opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
4029 			elog(ERROR, "left and right pathkeys do not match in mergejoin");
4030 		if (first_inner_match &&
4031 			(opathkey->pk_strategy != ipathkey->pk_strategy ||
4032 			 opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
4033 			elog(ERROR, "left and right pathkeys do not match in mergejoin");
4034 
4035 		/* OK, save info for executor */
4036 		mergefamilies[i] = opathkey->pk_opfamily;
4037 		mergecollations[i] = opathkey->pk_eclass->ec_collation;
4038 		mergestrategies[i] = opathkey->pk_strategy;
4039 		mergenullsfirst[i] = opathkey->pk_nulls_first;
4040 		i++;
4041 	}
4042 
4043 	/*
4044 	 * Note: it is not an error if we have additional pathkey elements (i.e.,
4045 	 * lop or lip isn't NULL here).  The input paths might be better-sorted
4046 	 * than we need for the current mergejoin.
4047 	 */
4048 
4049 	/*
4050 	 * Now we can build the mergejoin node.
4051 	 */
4052 	join_plan = make_mergejoin(tlist,
4053 							   joinclauses,
4054 							   otherclauses,
4055 							   mergeclauses,
4056 							   mergefamilies,
4057 							   mergecollations,
4058 							   mergestrategies,
4059 							   mergenullsfirst,
4060 							   outer_plan,
4061 							   inner_plan,
4062 							   best_path->jpath.jointype,
4063 							   best_path->jpath.inner_unique,
4064 							   best_path->skip_mark_restore);
4065 
4066 	/* Costs of sort and material steps are included in path cost already */
4067 	copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4068 
4069 	return join_plan;
4070 }
4071 
4072 static HashJoin *
create_hashjoin_plan(PlannerInfo * root,HashPath * best_path)4073 create_hashjoin_plan(PlannerInfo *root,
4074 					 HashPath *best_path)
4075 {
4076 	HashJoin   *join_plan;
4077 	Hash	   *hash_plan;
4078 	Plan	   *outer_plan;
4079 	Plan	   *inner_plan;
4080 	List	   *tlist = build_path_tlist(root, &best_path->jpath.path);
4081 	List	   *joinclauses;
4082 	List	   *otherclauses;
4083 	List	   *hashclauses;
4084 	Oid			skewTable = InvalidOid;
4085 	AttrNumber	skewColumn = InvalidAttrNumber;
4086 	bool		skewInherit = false;
4087 
4088 	/*
4089 	 * HashJoin can project, so we don't have to demand exact tlists from the
4090 	 * inputs.  However, it's best to request a small tlist from the inner
4091 	 * side, so that we aren't storing more data than necessary.  Likewise, if
4092 	 * we anticipate batching, request a small tlist from the outer side so
4093 	 * that we don't put extra data in the outer batch files.
4094 	 */
4095 	outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4096 									 (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4097 
4098 	inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4099 									 CP_SMALL_TLIST);
4100 
4101 	/* Sort join qual clauses into best execution order */
4102 	joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4103 	/* There's no point in sorting the hash clauses ... */
4104 
4105 	/* Get the join qual clauses (in plain expression form) */
4106 	/* Any pseudoconstant clauses are ignored here */
4107 	if (IS_OUTER_JOIN(best_path->jpath.jointype))
4108 	{
4109 		extract_actual_join_clauses(joinclauses,
4110 									best_path->jpath.path.parent->relids,
4111 									&joinclauses, &otherclauses);
4112 	}
4113 	else
4114 	{
4115 		/* We can treat all clauses alike for an inner join */
4116 		joinclauses = extract_actual_clauses(joinclauses, false);
4117 		otherclauses = NIL;
4118 	}
4119 
4120 	/*
4121 	 * Remove the hashclauses from the list of join qual clauses, leaving the
4122 	 * list of quals that must be checked as qpquals.
4123 	 */
4124 	hashclauses = get_actual_clauses(best_path->path_hashclauses);
4125 	joinclauses = list_difference(joinclauses, hashclauses);
4126 
4127 	/*
4128 	 * Replace any outer-relation variables with nestloop params.  There
4129 	 * should not be any in the hashclauses.
4130 	 */
4131 	if (best_path->jpath.path.param_info)
4132 	{
4133 		joinclauses = (List *)
4134 			replace_nestloop_params(root, (Node *) joinclauses);
4135 		otherclauses = (List *)
4136 			replace_nestloop_params(root, (Node *) otherclauses);
4137 	}
4138 
4139 	/*
4140 	 * Rearrange hashclauses, if needed, so that the outer variable is always
4141 	 * on the left.
4142 	 */
4143 	hashclauses = get_switched_clauses(best_path->path_hashclauses,
4144 									   best_path->jpath.outerjoinpath->parent->relids);
4145 
4146 	/*
4147 	 * If there is a single join clause and we can identify the outer variable
4148 	 * as a simple column reference, supply its identity for possible use in
4149 	 * skew optimization.  (Note: in principle we could do skew optimization
4150 	 * with multiple join clauses, but we'd have to be able to determine the
4151 	 * most common combinations of outer values, which we don't currently have
4152 	 * enough stats for.)
4153 	 */
4154 	if (list_length(hashclauses) == 1)
4155 	{
4156 		OpExpr	   *clause = (OpExpr *) linitial(hashclauses);
4157 		Node	   *node;
4158 
4159 		Assert(is_opclause(clause));
4160 		node = (Node *) linitial(clause->args);
4161 		if (IsA(node, RelabelType))
4162 			node = (Node *) ((RelabelType *) node)->arg;
4163 		if (IsA(node, Var))
4164 		{
4165 			Var		   *var = (Var *) node;
4166 			RangeTblEntry *rte;
4167 
4168 			rte = root->simple_rte_array[var->varno];
4169 			if (rte->rtekind == RTE_RELATION)
4170 			{
4171 				skewTable = rte->relid;
4172 				skewColumn = var->varattno;
4173 				skewInherit = rte->inh;
4174 			}
4175 		}
4176 	}
4177 
4178 	/*
4179 	 * Build the hash node and hash join node.
4180 	 */
4181 	hash_plan = make_hash(inner_plan,
4182 						  skewTable,
4183 						  skewColumn,
4184 						  skewInherit);
4185 
4186 	/*
4187 	 * Set Hash node's startup & total costs equal to total cost of input
4188 	 * plan; this only affects EXPLAIN display not decisions.
4189 	 */
4190 	copy_plan_costsize(&hash_plan->plan, inner_plan);
4191 	hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4192 
4193 	join_plan = make_hashjoin(tlist,
4194 							  joinclauses,
4195 							  otherclauses,
4196 							  hashclauses,
4197 							  outer_plan,
4198 							  (Plan *) hash_plan,
4199 							  best_path->jpath.jointype,
4200 							  best_path->jpath.inner_unique);
4201 
4202 	copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4203 
4204 	return join_plan;
4205 }
4206 
4207 
4208 /*****************************************************************************
4209  *
4210  *	SUPPORTING ROUTINES
4211  *
4212  *****************************************************************************/
4213 
4214 /*
4215  * replace_nestloop_params
4216  *	  Replace outer-relation Vars and PlaceHolderVars in the given expression
4217  *	  with nestloop Params
4218  *
4219  * All Vars and PlaceHolderVars belonging to the relation(s) identified by
4220  * root->curOuterRels are replaced by Params, and entries are added to
4221  * root->curOuterParams if not already present.
4222  */
4223 static Node *
replace_nestloop_params(PlannerInfo * root,Node * expr)4224 replace_nestloop_params(PlannerInfo *root, Node *expr)
4225 {
4226 	/* No setup needed for tree walk, so away we go */
4227 	return replace_nestloop_params_mutator(expr, root);
4228 }
4229 
4230 static Node *
replace_nestloop_params_mutator(Node * node,PlannerInfo * root)4231 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
4232 {
4233 	if (node == NULL)
4234 		return NULL;
4235 	if (IsA(node, Var))
4236 	{
4237 		Var		   *var = (Var *) node;
4238 
4239 		/* Upper-level Vars should be long gone at this point */
4240 		Assert(var->varlevelsup == 0);
4241 		/* If not to be replaced, we can just return the Var unmodified */
4242 		if (!bms_is_member(var->varno, root->curOuterRels))
4243 			return node;
4244 		/* Replace the Var with a nestloop Param */
4245 		return (Node *) replace_nestloop_param_var(root, var);
4246 	}
4247 	if (IsA(node, PlaceHolderVar))
4248 	{
4249 		PlaceHolderVar *phv = (PlaceHolderVar *) node;
4250 
4251 		/* Upper-level PlaceHolderVars should be long gone at this point */
4252 		Assert(phv->phlevelsup == 0);
4253 
4254 		/*
4255 		 * Check whether we need to replace the PHV.  We use bms_overlap as a
4256 		 * cheap/quick test to see if the PHV might be evaluated in the outer
4257 		 * rels, and then grab its PlaceHolderInfo to tell for sure.
4258 		 */
4259 		if (!bms_overlap(phv->phrels, root->curOuterRels) ||
4260 			!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4261 						   root->curOuterRels))
4262 		{
4263 			/*
4264 			 * We can't replace the whole PHV, but we might still need to
4265 			 * replace Vars or PHVs within its expression, in case it ends up
4266 			 * actually getting evaluated here.  (It might get evaluated in
4267 			 * this plan node, or some child node; in the latter case we don't
4268 			 * really need to process the expression here, but we haven't got
4269 			 * enough info to tell if that's the case.)  Flat-copy the PHV
4270 			 * node and then recurse on its expression.
4271 			 *
4272 			 * Note that after doing this, we might have different
4273 			 * representations of the contents of the same PHV in different
4274 			 * parts of the plan tree.  This is OK because equal() will just
4275 			 * match on phid/phlevelsup, so setrefs.c will still recognize an
4276 			 * upper-level reference to a lower-level copy of the same PHV.
4277 			 */
4278 			PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
4279 
4280 			memcpy(newphv, phv, sizeof(PlaceHolderVar));
4281 			newphv->phexpr = (Expr *)
4282 				replace_nestloop_params_mutator((Node *) phv->phexpr,
4283 												root);
4284 			return (Node *) newphv;
4285 		}
4286 		/* Replace the PlaceHolderVar with a nestloop Param */
4287 		return (Node *) replace_nestloop_param_placeholdervar(root, phv);
4288 	}
4289 	return expression_tree_mutator(node,
4290 								   replace_nestloop_params_mutator,
4291 								   (void *) root);
4292 }
4293 
4294 /*
4295  * fix_indexqual_references
4296  *	  Adjust indexqual clauses to the form the executor's indexqual
4297  *	  machinery needs.
4298  *
4299  * We have four tasks here:
4300  *	* Remove RestrictInfo nodes from the input clauses.
4301  *	* Replace any outer-relation Var or PHV nodes with nestloop Params.
4302  *	  (XXX eventually, that responsibility should go elsewhere?)
4303  *	* Index keys must be represented by Var nodes with varattno set to the
4304  *	  index's attribute number, not the attribute number in the original rel.
4305  *	* If the index key is on the right, commute the clause to put it on the
4306  *	  left.
4307  *
4308  * The result is a modified copy of the path's indexquals list --- the
4309  * original is not changed.  Note also that the copy shares no substructure
4310  * with the original; this is needed in case there is a subplan in it (we need
4311  * two separate copies of the subplan tree, or things will go awry).
4312  */
4313 static List *
fix_indexqual_references(PlannerInfo * root,IndexPath * index_path)4314 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
4315 {
4316 	IndexOptInfo *index = index_path->indexinfo;
4317 	List	   *fixed_indexquals;
4318 	ListCell   *lcc,
4319 			   *lci;
4320 
4321 	fixed_indexquals = NIL;
4322 
4323 	forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
4324 	{
4325 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
4326 		int			indexcol = lfirst_int(lci);
4327 		Node	   *clause;
4328 
4329 		/*
4330 		 * Replace any outer-relation variables with nestloop params.
4331 		 *
4332 		 * This also makes a copy of the clause, so it's safe to modify it
4333 		 * in-place below.
4334 		 */
4335 		clause = replace_nestloop_params(root, (Node *) rinfo->clause);
4336 
4337 		if (IsA(clause, OpExpr))
4338 		{
4339 			OpExpr	   *op = (OpExpr *) clause;
4340 
4341 			if (list_length(op->args) != 2)
4342 				elog(ERROR, "indexqual clause is not binary opclause");
4343 
4344 			/*
4345 			 * Check to see if the indexkey is on the right; if so, commute
4346 			 * the clause.  The indexkey should be the side that refers to
4347 			 * (only) the base relation.
4348 			 */
4349 			if (!bms_equal(rinfo->left_relids, index->rel->relids))
4350 				CommuteOpExpr(op);
4351 
4352 			/*
4353 			 * Now replace the indexkey expression with an index Var.
4354 			 */
4355 			linitial(op->args) = fix_indexqual_operand(linitial(op->args),
4356 													   index,
4357 													   indexcol);
4358 		}
4359 		else if (IsA(clause, RowCompareExpr))
4360 		{
4361 			RowCompareExpr *rc = (RowCompareExpr *) clause;
4362 			Expr	   *newrc;
4363 			List	   *indexcolnos;
4364 			bool		var_on_left;
4365 			ListCell   *lca,
4366 					   *lcai;
4367 
4368 			/*
4369 			 * Re-discover which index columns are used in the rowcompare.
4370 			 */
4371 			newrc = adjust_rowcompare_for_index(rc,
4372 												index,
4373 												indexcol,
4374 												&indexcolnos,
4375 												&var_on_left);
4376 
4377 			/*
4378 			 * Trouble if adjust_rowcompare_for_index thought the
4379 			 * RowCompareExpr didn't match the index as-is; the clause should
4380 			 * have gone through that routine already.
4381 			 */
4382 			if (newrc != (Expr *) rc)
4383 				elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
4384 
4385 			/*
4386 			 * Check to see if the indexkey is on the right; if so, commute
4387 			 * the clause.
4388 			 */
4389 			if (!var_on_left)
4390 				CommuteRowCompareExpr(rc);
4391 
4392 			/*
4393 			 * Now replace the indexkey expressions with index Vars.
4394 			 */
4395 			Assert(list_length(rc->largs) == list_length(indexcolnos));
4396 			forboth(lca, rc->largs, lcai, indexcolnos)
4397 			{
4398 				lfirst(lca) = fix_indexqual_operand(lfirst(lca),
4399 													index,
4400 													lfirst_int(lcai));
4401 			}
4402 		}
4403 		else if (IsA(clause, ScalarArrayOpExpr))
4404 		{
4405 			ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
4406 
4407 			/* Never need to commute... */
4408 
4409 			/* Replace the indexkey expression with an index Var. */
4410 			linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
4411 														 index,
4412 														 indexcol);
4413 		}
4414 		else if (IsA(clause, NullTest))
4415 		{
4416 			NullTest   *nt = (NullTest *) clause;
4417 
4418 			/* Replace the indexkey expression with an index Var. */
4419 			nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
4420 													 index,
4421 													 indexcol);
4422 		}
4423 		else
4424 			elog(ERROR, "unsupported indexqual type: %d",
4425 				 (int) nodeTag(clause));
4426 
4427 		fixed_indexquals = lappend(fixed_indexquals, clause);
4428 	}
4429 
4430 	return fixed_indexquals;
4431 }
4432 
4433 /*
4434  * fix_indexorderby_references
4435  *	  Adjust indexorderby clauses to the form the executor's index
4436  *	  machinery needs.
4437  *
4438  * This is a simplified version of fix_indexqual_references.  The input does
4439  * not have RestrictInfo nodes, and we assume that indxpath.c already
4440  * commuted the clauses to put the index keys on the left.  Also, we don't
4441  * bother to support any cases except simple OpExprs, since nothing else
4442  * is allowed for ordering operators.
4443  */
4444 static List *
fix_indexorderby_references(PlannerInfo * root,IndexPath * index_path)4445 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
4446 {
4447 	IndexOptInfo *index = index_path->indexinfo;
4448 	List	   *fixed_indexorderbys;
4449 	ListCell   *lcc,
4450 			   *lci;
4451 
4452 	fixed_indexorderbys = NIL;
4453 
4454 	forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
4455 	{
4456 		Node	   *clause = (Node *) lfirst(lcc);
4457 		int			indexcol = lfirst_int(lci);
4458 
4459 		/*
4460 		 * Replace any outer-relation variables with nestloop params.
4461 		 *
4462 		 * This also makes a copy of the clause, so it's safe to modify it
4463 		 * in-place below.
4464 		 */
4465 		clause = replace_nestloop_params(root, clause);
4466 
4467 		if (IsA(clause, OpExpr))
4468 		{
4469 			OpExpr	   *op = (OpExpr *) clause;
4470 
4471 			if (list_length(op->args) != 2)
4472 				elog(ERROR, "indexorderby clause is not binary opclause");
4473 
4474 			/*
4475 			 * Now replace the indexkey expression with an index Var.
4476 			 */
4477 			linitial(op->args) = fix_indexqual_operand(linitial(op->args),
4478 													   index,
4479 													   indexcol);
4480 		}
4481 		else
4482 			elog(ERROR, "unsupported indexorderby type: %d",
4483 				 (int) nodeTag(clause));
4484 
4485 		fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
4486 	}
4487 
4488 	return fixed_indexorderbys;
4489 }
4490 
4491 /*
4492  * fix_indexqual_operand
4493  *	  Convert an indexqual expression to a Var referencing the index column.
4494  *
4495  * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
4496  * equal to the index's attribute number (index column position).
4497  *
4498  * Most of the code here is just for sanity cross-checking that the given
4499  * expression actually matches the index column it's claimed to.
4500  */
4501 static Node *
fix_indexqual_operand(Node * node,IndexOptInfo * index,int indexcol)4502 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
4503 {
4504 	Var		   *result;
4505 	int			pos;
4506 	ListCell   *indexpr_item;
4507 
4508 	/*
4509 	 * Remove any binary-compatible relabeling of the indexkey
4510 	 */
4511 	if (IsA(node, RelabelType))
4512 		node = (Node *) ((RelabelType *) node)->arg;
4513 
4514 	Assert(indexcol >= 0 && indexcol < index->ncolumns);
4515 
4516 	if (index->indexkeys[indexcol] != 0)
4517 	{
4518 		/* It's a simple index column */
4519 		if (IsA(node, Var) &&
4520 			((Var *) node)->varno == index->rel->relid &&
4521 			((Var *) node)->varattno == index->indexkeys[indexcol])
4522 		{
4523 			result = (Var *) copyObject(node);
4524 			result->varno = INDEX_VAR;
4525 			result->varattno = indexcol + 1;
4526 			return (Node *) result;
4527 		}
4528 		else
4529 			elog(ERROR, "index key does not match expected index column");
4530 	}
4531 
4532 	/* It's an index expression, so find and cross-check the expression */
4533 	indexpr_item = list_head(index->indexprs);
4534 	for (pos = 0; pos < index->ncolumns; pos++)
4535 	{
4536 		if (index->indexkeys[pos] == 0)
4537 		{
4538 			if (indexpr_item == NULL)
4539 				elog(ERROR, "too few entries in indexprs list");
4540 			if (pos == indexcol)
4541 			{
4542 				Node	   *indexkey;
4543 
4544 				indexkey = (Node *) lfirst(indexpr_item);
4545 				if (indexkey && IsA(indexkey, RelabelType))
4546 					indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4547 				if (equal(node, indexkey))
4548 				{
4549 					result = makeVar(INDEX_VAR, indexcol + 1,
4550 									 exprType(lfirst(indexpr_item)), -1,
4551 									 exprCollation(lfirst(indexpr_item)),
4552 									 0);
4553 					return (Node *) result;
4554 				}
4555 				else
4556 					elog(ERROR, "index key does not match expected index column");
4557 			}
4558 			indexpr_item = lnext(indexpr_item);
4559 		}
4560 	}
4561 
4562 	/* Oops... */
4563 	elog(ERROR, "index key does not match expected index column");
4564 	return NULL;				/* keep compiler quiet */
4565 }
4566 
4567 /*
4568  * get_switched_clauses
4569  *	  Given a list of merge or hash joinclauses (as RestrictInfo nodes),
4570  *	  extract the bare clauses, and rearrange the elements within the
4571  *	  clauses, if needed, so the outer join variable is on the left and
4572  *	  the inner is on the right.  The original clause data structure is not
4573  *	  touched; a modified list is returned.  We do, however, set the transient
4574  *	  outer_is_left field in each RestrictInfo to show which side was which.
4575  */
4576 static List *
get_switched_clauses(List * clauses,Relids outerrelids)4577 get_switched_clauses(List *clauses, Relids outerrelids)
4578 {
4579 	List	   *t_list = NIL;
4580 	ListCell   *l;
4581 
4582 	foreach(l, clauses)
4583 	{
4584 		RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
4585 		OpExpr	   *clause = (OpExpr *) restrictinfo->clause;
4586 
4587 		Assert(is_opclause(clause));
4588 		if (bms_is_subset(restrictinfo->right_relids, outerrelids))
4589 		{
4590 			/*
4591 			 * Duplicate just enough of the structure to allow commuting the
4592 			 * clause without changing the original list.  Could use
4593 			 * copyObject, but a complete deep copy is overkill.
4594 			 */
4595 			OpExpr	   *temp = makeNode(OpExpr);
4596 
4597 			temp->opno = clause->opno;
4598 			temp->opfuncid = InvalidOid;
4599 			temp->opresulttype = clause->opresulttype;
4600 			temp->opretset = clause->opretset;
4601 			temp->opcollid = clause->opcollid;
4602 			temp->inputcollid = clause->inputcollid;
4603 			temp->args = list_copy(clause->args);
4604 			temp->location = clause->location;
4605 			/* Commute it --- note this modifies the temp node in-place. */
4606 			CommuteOpExpr(temp);
4607 			t_list = lappend(t_list, temp);
4608 			restrictinfo->outer_is_left = false;
4609 		}
4610 		else
4611 		{
4612 			Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
4613 			t_list = lappend(t_list, clause);
4614 			restrictinfo->outer_is_left = true;
4615 		}
4616 	}
4617 	return t_list;
4618 }
4619 
4620 /*
4621  * order_qual_clauses
4622  *		Given a list of qual clauses that will all be evaluated at the same
4623  *		plan node, sort the list into the order we want to check the quals
4624  *		in at runtime.
4625  *
4626  * When security barrier quals are used in the query, we may have quals with
4627  * different security levels in the list.  Quals of lower security_level
4628  * must go before quals of higher security_level, except that we can grant
4629  * exceptions to move up quals that are leakproof.  When security level
4630  * doesn't force the decision, we prefer to order clauses by estimated
4631  * execution cost, cheapest first.
4632  *
4633  * Ideally the order should be driven by a combination of execution cost and
4634  * selectivity, but it's not immediately clear how to account for both,
4635  * and given the uncertainty of the estimates the reliability of the decisions
4636  * would be doubtful anyway.  So we just order by security level then
4637  * estimated per-tuple cost, being careful not to change the order when
4638  * (as is often the case) the estimates are identical.
4639  *
4640  * Although this will work on either bare clauses or RestrictInfos, it's
4641  * much faster to apply it to RestrictInfos, since it can re-use cost
4642  * information that is cached in RestrictInfos.  XXX in the bare-clause
4643  * case, we are also not able to apply security considerations.  That is
4644  * all right for the moment, because the bare-clause case doesn't occur
4645  * anywhere that barrier quals could be present, but it would be better to
4646  * get rid of it.
4647  *
4648  * Note: some callers pass lists that contain entries that will later be
4649  * removed; this is the easiest way to let this routine see RestrictInfos
4650  * instead of bare clauses.  This is another reason why trying to consider
4651  * selectivity in the ordering would likely do the wrong thing.
4652  */
4653 static List *
order_qual_clauses(PlannerInfo * root,List * clauses)4654 order_qual_clauses(PlannerInfo *root, List *clauses)
4655 {
4656 	typedef struct
4657 	{
4658 		Node	   *clause;
4659 		Cost		cost;
4660 		Index		security_level;
4661 	} QualItem;
4662 	int			nitems = list_length(clauses);
4663 	QualItem   *items;
4664 	ListCell   *lc;
4665 	int			i;
4666 	List	   *result;
4667 
4668 	/* No need to work hard for 0 or 1 clause */
4669 	if (nitems <= 1)
4670 		return clauses;
4671 
4672 	/*
4673 	 * Collect the items and costs into an array.  This is to avoid repeated
4674 	 * cost_qual_eval work if the inputs aren't RestrictInfos.
4675 	 */
4676 	items = (QualItem *) palloc(nitems * sizeof(QualItem));
4677 	i = 0;
4678 	foreach(lc, clauses)
4679 	{
4680 		Node	   *clause = (Node *) lfirst(lc);
4681 		QualCost	qcost;
4682 
4683 		cost_qual_eval_node(&qcost, clause, root);
4684 		items[i].clause = clause;
4685 		items[i].cost = qcost.per_tuple;
4686 		if (IsA(clause, RestrictInfo))
4687 		{
4688 			RestrictInfo *rinfo = (RestrictInfo *) clause;
4689 
4690 			/*
4691 			 * If a clause is leakproof, it doesn't have to be constrained by
4692 			 * its nominal security level.  If it's also reasonably cheap
4693 			 * (here defined as 10X cpu_operator_cost), pretend it has
4694 			 * security_level 0, which will allow it to go in front of
4695 			 * more-expensive quals of lower security levels.  Of course, that
4696 			 * will also force it to go in front of cheaper quals of its own
4697 			 * security level, which is not so great, but we can alleviate
4698 			 * that risk by applying the cost limit cutoff.
4699 			 */
4700 			if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
4701 				items[i].security_level = 0;
4702 			else
4703 				items[i].security_level = rinfo->security_level;
4704 		}
4705 		else
4706 			items[i].security_level = 0;
4707 		i++;
4708 	}
4709 
4710 	/*
4711 	 * Sort.  We don't use qsort() because it's not guaranteed stable for
4712 	 * equal keys.  The expected number of entries is small enough that a
4713 	 * simple insertion sort should be good enough.
4714 	 */
4715 	for (i = 1; i < nitems; i++)
4716 	{
4717 		QualItem	newitem = items[i];
4718 		int			j;
4719 
4720 		/* insert newitem into the already-sorted subarray */
4721 		for (j = i; j > 0; j--)
4722 		{
4723 			QualItem   *olditem = &items[j - 1];
4724 
4725 			if (newitem.security_level > olditem->security_level ||
4726 				(newitem.security_level == olditem->security_level &&
4727 				 newitem.cost >= olditem->cost))
4728 				break;
4729 			items[j] = *olditem;
4730 		}
4731 		items[j] = newitem;
4732 	}
4733 
4734 	/* Convert back to a list */
4735 	result = NIL;
4736 	for (i = 0; i < nitems; i++)
4737 		result = lappend(result, items[i].clause);
4738 
4739 	return result;
4740 }
4741 
4742 /*
4743  * Copy cost and size info from a Path node to the Plan node created from it.
4744  * The executor usually won't use this info, but it's needed by EXPLAIN.
4745  * Also copy the parallel-related flags, which the executor *will* use.
4746  */
4747 static void
copy_generic_path_info(Plan * dest,Path * src)4748 copy_generic_path_info(Plan *dest, Path *src)
4749 {
4750 	dest->startup_cost = src->startup_cost;
4751 	dest->total_cost = src->total_cost;
4752 	dest->plan_rows = src->rows;
4753 	dest->plan_width = src->pathtarget->width;
4754 	dest->parallel_aware = src->parallel_aware;
4755 	dest->parallel_safe = src->parallel_safe;
4756 }
4757 
4758 /*
4759  * Copy cost and size info from a lower plan node to an inserted node.
4760  * (Most callers alter the info after copying it.)
4761  */
4762 static void
copy_plan_costsize(Plan * dest,Plan * src)4763 copy_plan_costsize(Plan *dest, Plan *src)
4764 {
4765 	dest->startup_cost = src->startup_cost;
4766 	dest->total_cost = src->total_cost;
4767 	dest->plan_rows = src->plan_rows;
4768 	dest->plan_width = src->plan_width;
4769 	/* Assume the inserted node is not parallel-aware. */
4770 	dest->parallel_aware = false;
4771 	/* Assume the inserted node is parallel-safe, if child plan is. */
4772 	dest->parallel_safe = src->parallel_safe;
4773 }
4774 
4775 /*
4776  * Some places in this file build Sort nodes that don't have a directly
4777  * corresponding Path node.  The cost of the sort is, or should have been,
4778  * included in the cost of the Path node we're working from, but since it's
4779  * not split out, we have to re-figure it using cost_sort().  This is just
4780  * to label the Sort node nicely for EXPLAIN.
4781  *
4782  * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4783  */
4784 static void
label_sort_with_costsize(PlannerInfo * root,Sort * plan,double limit_tuples)4785 label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
4786 {
4787 	Plan	   *lefttree = plan->plan.lefttree;
4788 	Path		sort_path;		/* dummy for result of cost_sort */
4789 
4790 	cost_sort(&sort_path, root, NIL,
4791 			  lefttree->total_cost,
4792 			  lefttree->plan_rows,
4793 			  lefttree->plan_width,
4794 			  0.0,
4795 			  work_mem,
4796 			  limit_tuples);
4797 	plan->plan.startup_cost = sort_path.startup_cost;
4798 	plan->plan.total_cost = sort_path.total_cost;
4799 	plan->plan.plan_rows = lefttree->plan_rows;
4800 	plan->plan.plan_width = lefttree->plan_width;
4801 	plan->plan.parallel_aware = false;
4802 	plan->plan.parallel_safe = lefttree->parallel_safe;
4803 }
4804 
4805 /*
4806  * bitmap_subplan_mark_shared
4807  *	 Set isshared flag in bitmap subplan so that it will be created in
4808  *	 shared memory.
4809  */
4810 static void
bitmap_subplan_mark_shared(Plan * plan)4811 bitmap_subplan_mark_shared(Plan *plan)
4812 {
4813 	if (IsA(plan, BitmapAnd))
4814 		bitmap_subplan_mark_shared(
4815 								   linitial(((BitmapAnd *) plan)->bitmapplans));
4816 	else if (IsA(plan, BitmapOr))
4817 	{
4818 		((BitmapOr *) plan)->isshared = true;
4819 		bitmap_subplan_mark_shared(
4820 								   linitial(((BitmapOr *) plan)->bitmapplans));
4821 	}
4822 	else if (IsA(plan, BitmapIndexScan))
4823 		((BitmapIndexScan *) plan)->isshared = true;
4824 	else
4825 		elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
4826 }
4827 
4828 /*****************************************************************************
4829  *
4830  *	PLAN NODE BUILDING ROUTINES
4831  *
4832  * In general, these functions are not passed the original Path and therefore
4833  * leave it to the caller to fill in the cost/width fields from the Path,
4834  * typically by calling copy_generic_path_info().  This convention is
4835  * somewhat historical, but it does support a few places above where we build
4836  * a plan node without having an exactly corresponding Path node.  Under no
4837  * circumstances should one of these functions do its own cost calculations,
4838  * as that would be redundant with calculations done while building Paths.
4839  *
4840  *****************************************************************************/
4841 
4842 static SeqScan *
make_seqscan(List * qptlist,List * qpqual,Index scanrelid)4843 make_seqscan(List *qptlist,
4844 			 List *qpqual,
4845 			 Index scanrelid)
4846 {
4847 	SeqScan    *node = makeNode(SeqScan);
4848 	Plan	   *plan = &node->plan;
4849 
4850 	plan->targetlist = qptlist;
4851 	plan->qual = qpqual;
4852 	plan->lefttree = NULL;
4853 	plan->righttree = NULL;
4854 	node->scanrelid = scanrelid;
4855 
4856 	return node;
4857 }
4858 
4859 static SampleScan *
make_samplescan(List * qptlist,List * qpqual,Index scanrelid,TableSampleClause * tsc)4860 make_samplescan(List *qptlist,
4861 				List *qpqual,
4862 				Index scanrelid,
4863 				TableSampleClause *tsc)
4864 {
4865 	SampleScan *node = makeNode(SampleScan);
4866 	Plan	   *plan = &node->scan.plan;
4867 
4868 	plan->targetlist = qptlist;
4869 	plan->qual = qpqual;
4870 	plan->lefttree = NULL;
4871 	plan->righttree = NULL;
4872 	node->scan.scanrelid = scanrelid;
4873 	node->tablesample = tsc;
4874 
4875 	return node;
4876 }
4877 
4878 static IndexScan *
make_indexscan(List * qptlist,List * qpqual,Index scanrelid,Oid indexid,List * indexqual,List * indexqualorig,List * indexorderby,List * indexorderbyorig,List * indexorderbyops,ScanDirection indexscandir)4879 make_indexscan(List *qptlist,
4880 			   List *qpqual,
4881 			   Index scanrelid,
4882 			   Oid indexid,
4883 			   List *indexqual,
4884 			   List *indexqualorig,
4885 			   List *indexorderby,
4886 			   List *indexorderbyorig,
4887 			   List *indexorderbyops,
4888 			   ScanDirection indexscandir)
4889 {
4890 	IndexScan  *node = makeNode(IndexScan);
4891 	Plan	   *plan = &node->scan.plan;
4892 
4893 	plan->targetlist = qptlist;
4894 	plan->qual = qpqual;
4895 	plan->lefttree = NULL;
4896 	plan->righttree = NULL;
4897 	node->scan.scanrelid = scanrelid;
4898 	node->indexid = indexid;
4899 	node->indexqual = indexqual;
4900 	node->indexqualorig = indexqualorig;
4901 	node->indexorderby = indexorderby;
4902 	node->indexorderbyorig = indexorderbyorig;
4903 	node->indexorderbyops = indexorderbyops;
4904 	node->indexorderdir = indexscandir;
4905 
4906 	return node;
4907 }
4908 
4909 static IndexOnlyScan *
make_indexonlyscan(List * qptlist,List * qpqual,Index scanrelid,Oid indexid,List * indexqual,List * indexorderby,List * indextlist,ScanDirection indexscandir)4910 make_indexonlyscan(List *qptlist,
4911 				   List *qpqual,
4912 				   Index scanrelid,
4913 				   Oid indexid,
4914 				   List *indexqual,
4915 				   List *indexorderby,
4916 				   List *indextlist,
4917 				   ScanDirection indexscandir)
4918 {
4919 	IndexOnlyScan *node = makeNode(IndexOnlyScan);
4920 	Plan	   *plan = &node->scan.plan;
4921 
4922 	plan->targetlist = qptlist;
4923 	plan->qual = qpqual;
4924 	plan->lefttree = NULL;
4925 	plan->righttree = NULL;
4926 	node->scan.scanrelid = scanrelid;
4927 	node->indexid = indexid;
4928 	node->indexqual = indexqual;
4929 	node->indexorderby = indexorderby;
4930 	node->indextlist = indextlist;
4931 	node->indexorderdir = indexscandir;
4932 
4933 	return node;
4934 }
4935 
4936 static BitmapIndexScan *
make_bitmap_indexscan(Index scanrelid,Oid indexid,List * indexqual,List * indexqualorig)4937 make_bitmap_indexscan(Index scanrelid,
4938 					  Oid indexid,
4939 					  List *indexqual,
4940 					  List *indexqualorig)
4941 {
4942 	BitmapIndexScan *node = makeNode(BitmapIndexScan);
4943 	Plan	   *plan = &node->scan.plan;
4944 
4945 	plan->targetlist = NIL;		/* not used */
4946 	plan->qual = NIL;			/* not used */
4947 	plan->lefttree = NULL;
4948 	plan->righttree = NULL;
4949 	node->scan.scanrelid = scanrelid;
4950 	node->indexid = indexid;
4951 	node->indexqual = indexqual;
4952 	node->indexqualorig = indexqualorig;
4953 
4954 	return node;
4955 }
4956 
4957 static BitmapHeapScan *
make_bitmap_heapscan(List * qptlist,List * qpqual,Plan * lefttree,List * bitmapqualorig,Index scanrelid)4958 make_bitmap_heapscan(List *qptlist,
4959 					 List *qpqual,
4960 					 Plan *lefttree,
4961 					 List *bitmapqualorig,
4962 					 Index scanrelid)
4963 {
4964 	BitmapHeapScan *node = makeNode(BitmapHeapScan);
4965 	Plan	   *plan = &node->scan.plan;
4966 
4967 	plan->targetlist = qptlist;
4968 	plan->qual = qpqual;
4969 	plan->lefttree = lefttree;
4970 	plan->righttree = NULL;
4971 	node->scan.scanrelid = scanrelid;
4972 	node->bitmapqualorig = bitmapqualorig;
4973 
4974 	return node;
4975 }
4976 
4977 static TidScan *
make_tidscan(List * qptlist,List * qpqual,Index scanrelid,List * tidquals)4978 make_tidscan(List *qptlist,
4979 			 List *qpqual,
4980 			 Index scanrelid,
4981 			 List *tidquals)
4982 {
4983 	TidScan    *node = makeNode(TidScan);
4984 	Plan	   *plan = &node->scan.plan;
4985 
4986 	plan->targetlist = qptlist;
4987 	plan->qual = qpqual;
4988 	plan->lefttree = NULL;
4989 	plan->righttree = NULL;
4990 	node->scan.scanrelid = scanrelid;
4991 	node->tidquals = tidquals;
4992 
4993 	return node;
4994 }
4995 
4996 static SubqueryScan *
make_subqueryscan(List * qptlist,List * qpqual,Index scanrelid,Plan * subplan)4997 make_subqueryscan(List *qptlist,
4998 				  List *qpqual,
4999 				  Index scanrelid,
5000 				  Plan *subplan)
5001 {
5002 	SubqueryScan *node = makeNode(SubqueryScan);
5003 	Plan	   *plan = &node->scan.plan;
5004 
5005 	plan->targetlist = qptlist;
5006 	plan->qual = qpqual;
5007 	plan->lefttree = NULL;
5008 	plan->righttree = NULL;
5009 	node->scan.scanrelid = scanrelid;
5010 	node->subplan = subplan;
5011 
5012 	return node;
5013 }
5014 
5015 static FunctionScan *
make_functionscan(List * qptlist,List * qpqual,Index scanrelid,List * functions,bool funcordinality)5016 make_functionscan(List *qptlist,
5017 				  List *qpqual,
5018 				  Index scanrelid,
5019 				  List *functions,
5020 				  bool funcordinality)
5021 {
5022 	FunctionScan *node = makeNode(FunctionScan);
5023 	Plan	   *plan = &node->scan.plan;
5024 
5025 	plan->targetlist = qptlist;
5026 	plan->qual = qpqual;
5027 	plan->lefttree = NULL;
5028 	plan->righttree = NULL;
5029 	node->scan.scanrelid = scanrelid;
5030 	node->functions = functions;
5031 	node->funcordinality = funcordinality;
5032 
5033 	return node;
5034 }
5035 
5036 static TableFuncScan *
make_tablefuncscan(List * qptlist,List * qpqual,Index scanrelid,TableFunc * tablefunc)5037 make_tablefuncscan(List *qptlist,
5038 				   List *qpqual,
5039 				   Index scanrelid,
5040 				   TableFunc *tablefunc)
5041 {
5042 	TableFuncScan *node = makeNode(TableFuncScan);
5043 	Plan	   *plan = &node->scan.plan;
5044 
5045 	plan->targetlist = qptlist;
5046 	plan->qual = qpqual;
5047 	plan->lefttree = NULL;
5048 	plan->righttree = NULL;
5049 	node->scan.scanrelid = scanrelid;
5050 	node->tablefunc = tablefunc;
5051 
5052 	return node;
5053 }
5054 
5055 static ValuesScan *
make_valuesscan(List * qptlist,List * qpqual,Index scanrelid,List * values_lists)5056 make_valuesscan(List *qptlist,
5057 				List *qpqual,
5058 				Index scanrelid,
5059 				List *values_lists)
5060 {
5061 	ValuesScan *node = makeNode(ValuesScan);
5062 	Plan	   *plan = &node->scan.plan;
5063 
5064 	plan->targetlist = qptlist;
5065 	plan->qual = qpqual;
5066 	plan->lefttree = NULL;
5067 	plan->righttree = NULL;
5068 	node->scan.scanrelid = scanrelid;
5069 	node->values_lists = values_lists;
5070 
5071 	return node;
5072 }
5073 
5074 static CteScan *
make_ctescan(List * qptlist,List * qpqual,Index scanrelid,int ctePlanId,int cteParam)5075 make_ctescan(List *qptlist,
5076 			 List *qpqual,
5077 			 Index scanrelid,
5078 			 int ctePlanId,
5079 			 int cteParam)
5080 {
5081 	CteScan    *node = makeNode(CteScan);
5082 	Plan	   *plan = &node->scan.plan;
5083 
5084 	plan->targetlist = qptlist;
5085 	plan->qual = qpqual;
5086 	plan->lefttree = NULL;
5087 	plan->righttree = NULL;
5088 	node->scan.scanrelid = scanrelid;
5089 	node->ctePlanId = ctePlanId;
5090 	node->cteParam = cteParam;
5091 
5092 	return node;
5093 }
5094 
5095 static NamedTuplestoreScan *
make_namedtuplestorescan(List * qptlist,List * qpqual,Index scanrelid,char * enrname)5096 make_namedtuplestorescan(List *qptlist,
5097 						 List *qpqual,
5098 						 Index scanrelid,
5099 						 char *enrname)
5100 {
5101 	NamedTuplestoreScan *node = makeNode(NamedTuplestoreScan);
5102 	Plan	   *plan = &node->scan.plan;
5103 
5104 	/* cost should be inserted by caller */
5105 	plan->targetlist = qptlist;
5106 	plan->qual = qpqual;
5107 	plan->lefttree = NULL;
5108 	plan->righttree = NULL;
5109 	node->scan.scanrelid = scanrelid;
5110 	node->enrname = enrname;
5111 
5112 	return node;
5113 }
5114 
5115 static WorkTableScan *
make_worktablescan(List * qptlist,List * qpqual,Index scanrelid,int wtParam)5116 make_worktablescan(List *qptlist,
5117 				   List *qpqual,
5118 				   Index scanrelid,
5119 				   int wtParam)
5120 {
5121 	WorkTableScan *node = makeNode(WorkTableScan);
5122 	Plan	   *plan = &node->scan.plan;
5123 
5124 	plan->targetlist = qptlist;
5125 	plan->qual = qpqual;
5126 	plan->lefttree = NULL;
5127 	plan->righttree = NULL;
5128 	node->scan.scanrelid = scanrelid;
5129 	node->wtParam = wtParam;
5130 
5131 	return node;
5132 }
5133 
5134 ForeignScan *
make_foreignscan(List * qptlist,List * qpqual,Index scanrelid,List * fdw_exprs,List * fdw_private,List * fdw_scan_tlist,List * fdw_recheck_quals,Plan * outer_plan)5135 make_foreignscan(List *qptlist,
5136 				 List *qpqual,
5137 				 Index scanrelid,
5138 				 List *fdw_exprs,
5139 				 List *fdw_private,
5140 				 List *fdw_scan_tlist,
5141 				 List *fdw_recheck_quals,
5142 				 Plan *outer_plan)
5143 {
5144 	ForeignScan *node = makeNode(ForeignScan);
5145 	Plan	   *plan = &node->scan.plan;
5146 
5147 	/* cost will be filled in by create_foreignscan_plan */
5148 	plan->targetlist = qptlist;
5149 	plan->qual = qpqual;
5150 	plan->lefttree = outer_plan;
5151 	plan->righttree = NULL;
5152 	node->scan.scanrelid = scanrelid;
5153 	node->operation = CMD_SELECT;
5154 	/* fs_server will be filled in by create_foreignscan_plan */
5155 	node->fs_server = InvalidOid;
5156 	node->fdw_exprs = fdw_exprs;
5157 	node->fdw_private = fdw_private;
5158 	node->fdw_scan_tlist = fdw_scan_tlist;
5159 	node->fdw_recheck_quals = fdw_recheck_quals;
5160 	/* fs_relids will be filled in by create_foreignscan_plan */
5161 	node->fs_relids = NULL;
5162 	/* fsSystemCol will be filled in by create_foreignscan_plan */
5163 	node->fsSystemCol = false;
5164 
5165 	return node;
5166 }
5167 
5168 static Append *
make_append(List * appendplans,List * tlist,List * partitioned_rels)5169 make_append(List *appendplans, List *tlist, List *partitioned_rels)
5170 {
5171 	Append	   *node = makeNode(Append);
5172 	Plan	   *plan = &node->plan;
5173 
5174 	plan->targetlist = tlist;
5175 	plan->qual = NIL;
5176 	plan->lefttree = NULL;
5177 	plan->righttree = NULL;
5178 	node->partitioned_rels = partitioned_rels;
5179 	node->appendplans = appendplans;
5180 
5181 	return node;
5182 }
5183 
5184 static RecursiveUnion *
make_recursive_union(List * tlist,Plan * lefttree,Plan * righttree,int wtParam,List * distinctList,long numGroups)5185 make_recursive_union(List *tlist,
5186 					 Plan *lefttree,
5187 					 Plan *righttree,
5188 					 int wtParam,
5189 					 List *distinctList,
5190 					 long numGroups)
5191 {
5192 	RecursiveUnion *node = makeNode(RecursiveUnion);
5193 	Plan	   *plan = &node->plan;
5194 	int			numCols = list_length(distinctList);
5195 
5196 	plan->targetlist = tlist;
5197 	plan->qual = NIL;
5198 	plan->lefttree = lefttree;
5199 	plan->righttree = righttree;
5200 	node->wtParam = wtParam;
5201 
5202 	/*
5203 	 * convert SortGroupClause list into arrays of attr indexes and equality
5204 	 * operators, as wanted by executor
5205 	 */
5206 	node->numCols = numCols;
5207 	if (numCols > 0)
5208 	{
5209 		int			keyno = 0;
5210 		AttrNumber *dupColIdx;
5211 		Oid		   *dupOperators;
5212 		ListCell   *slitem;
5213 
5214 		dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5215 		dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5216 
5217 		foreach(slitem, distinctList)
5218 		{
5219 			SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
5220 			TargetEntry *tle = get_sortgroupclause_tle(sortcl,
5221 													   plan->targetlist);
5222 
5223 			dupColIdx[keyno] = tle->resno;
5224 			dupOperators[keyno] = sortcl->eqop;
5225 			Assert(OidIsValid(dupOperators[keyno]));
5226 			keyno++;
5227 		}
5228 		node->dupColIdx = dupColIdx;
5229 		node->dupOperators = dupOperators;
5230 	}
5231 	node->numGroups = numGroups;
5232 
5233 	return node;
5234 }
5235 
5236 static BitmapAnd *
make_bitmap_and(List * bitmapplans)5237 make_bitmap_and(List *bitmapplans)
5238 {
5239 	BitmapAnd  *node = makeNode(BitmapAnd);
5240 	Plan	   *plan = &node->plan;
5241 
5242 	plan->targetlist = NIL;
5243 	plan->qual = NIL;
5244 	plan->lefttree = NULL;
5245 	plan->righttree = NULL;
5246 	node->bitmapplans = bitmapplans;
5247 
5248 	return node;
5249 }
5250 
5251 static BitmapOr *
make_bitmap_or(List * bitmapplans)5252 make_bitmap_or(List *bitmapplans)
5253 {
5254 	BitmapOr   *node = makeNode(BitmapOr);
5255 	Plan	   *plan = &node->plan;
5256 
5257 	plan->targetlist = NIL;
5258 	plan->qual = NIL;
5259 	plan->lefttree = NULL;
5260 	plan->righttree = NULL;
5261 	node->bitmapplans = bitmapplans;
5262 
5263 	return node;
5264 }
5265 
5266 static NestLoop *
make_nestloop(List * tlist,List * joinclauses,List * otherclauses,List * nestParams,Plan * lefttree,Plan * righttree,JoinType jointype,bool inner_unique)5267 make_nestloop(List *tlist,
5268 			  List *joinclauses,
5269 			  List *otherclauses,
5270 			  List *nestParams,
5271 			  Plan *lefttree,
5272 			  Plan *righttree,
5273 			  JoinType jointype,
5274 			  bool inner_unique)
5275 {
5276 	NestLoop   *node = makeNode(NestLoop);
5277 	Plan	   *plan = &node->join.plan;
5278 
5279 	plan->targetlist = tlist;
5280 	plan->qual = otherclauses;
5281 	plan->lefttree = lefttree;
5282 	plan->righttree = righttree;
5283 	node->join.jointype = jointype;
5284 	node->join.inner_unique = inner_unique;
5285 	node->join.joinqual = joinclauses;
5286 	node->nestParams = nestParams;
5287 
5288 	return node;
5289 }
5290 
5291 static HashJoin *
make_hashjoin(List * tlist,List * joinclauses,List * otherclauses,List * hashclauses,Plan * lefttree,Plan * righttree,JoinType jointype,bool inner_unique)5292 make_hashjoin(List *tlist,
5293 			  List *joinclauses,
5294 			  List *otherclauses,
5295 			  List *hashclauses,
5296 			  Plan *lefttree,
5297 			  Plan *righttree,
5298 			  JoinType jointype,
5299 			  bool inner_unique)
5300 {
5301 	HashJoin   *node = makeNode(HashJoin);
5302 	Plan	   *plan = &node->join.plan;
5303 
5304 	plan->targetlist = tlist;
5305 	plan->qual = otherclauses;
5306 	plan->lefttree = lefttree;
5307 	plan->righttree = righttree;
5308 	node->hashclauses = hashclauses;
5309 	node->join.jointype = jointype;
5310 	node->join.inner_unique = inner_unique;
5311 	node->join.joinqual = joinclauses;
5312 
5313 	return node;
5314 }
5315 
5316 static Hash *
make_hash(Plan * lefttree,Oid skewTable,AttrNumber skewColumn,bool skewInherit)5317 make_hash(Plan *lefttree,
5318 		  Oid skewTable,
5319 		  AttrNumber skewColumn,
5320 		  bool skewInherit)
5321 {
5322 	Hash	   *node = makeNode(Hash);
5323 	Plan	   *plan = &node->plan;
5324 
5325 	plan->targetlist = lefttree->targetlist;
5326 	plan->qual = NIL;
5327 	plan->lefttree = lefttree;
5328 	plan->righttree = NULL;
5329 
5330 	node->skewTable = skewTable;
5331 	node->skewColumn = skewColumn;
5332 	node->skewInherit = skewInherit;
5333 
5334 	return node;
5335 }
5336 
5337 static MergeJoin *
make_mergejoin(List * tlist,List * joinclauses,List * otherclauses,List * mergeclauses,Oid * mergefamilies,Oid * mergecollations,int * mergestrategies,bool * mergenullsfirst,Plan * lefttree,Plan * righttree,JoinType jointype,bool inner_unique,bool skip_mark_restore)5338 make_mergejoin(List *tlist,
5339 			   List *joinclauses,
5340 			   List *otherclauses,
5341 			   List *mergeclauses,
5342 			   Oid *mergefamilies,
5343 			   Oid *mergecollations,
5344 			   int *mergestrategies,
5345 			   bool *mergenullsfirst,
5346 			   Plan *lefttree,
5347 			   Plan *righttree,
5348 			   JoinType jointype,
5349 			   bool inner_unique,
5350 			   bool skip_mark_restore)
5351 {
5352 	MergeJoin  *node = makeNode(MergeJoin);
5353 	Plan	   *plan = &node->join.plan;
5354 
5355 	plan->targetlist = tlist;
5356 	plan->qual = otherclauses;
5357 	plan->lefttree = lefttree;
5358 	plan->righttree = righttree;
5359 	node->skip_mark_restore = skip_mark_restore;
5360 	node->mergeclauses = mergeclauses;
5361 	node->mergeFamilies = mergefamilies;
5362 	node->mergeCollations = mergecollations;
5363 	node->mergeStrategies = mergestrategies;
5364 	node->mergeNullsFirst = mergenullsfirst;
5365 	node->join.jointype = jointype;
5366 	node->join.inner_unique = inner_unique;
5367 	node->join.joinqual = joinclauses;
5368 
5369 	return node;
5370 }
5371 
5372 /*
5373  * make_sort --- basic routine to build a Sort plan node
5374  *
5375  * Caller must have built the sortColIdx, sortOperators, collations, and
5376  * nullsFirst arrays already.
5377  */
5378 static Sort *
make_sort(Plan * lefttree,int numCols,AttrNumber * sortColIdx,Oid * sortOperators,Oid * collations,bool * nullsFirst)5379 make_sort(Plan *lefttree, int numCols,
5380 		  AttrNumber *sortColIdx, Oid *sortOperators,
5381 		  Oid *collations, bool *nullsFirst)
5382 {
5383 	Sort	   *node = makeNode(Sort);
5384 	Plan	   *plan = &node->plan;
5385 
5386 	plan->targetlist = lefttree->targetlist;
5387 	plan->qual = NIL;
5388 	plan->lefttree = lefttree;
5389 	plan->righttree = NULL;
5390 	node->numCols = numCols;
5391 	node->sortColIdx = sortColIdx;
5392 	node->sortOperators = sortOperators;
5393 	node->collations = collations;
5394 	node->nullsFirst = nullsFirst;
5395 
5396 	return node;
5397 }
5398 
5399 /*
5400  * prepare_sort_from_pathkeys
5401  *	  Prepare to sort according to given pathkeys
5402  *
5403  * This is used to set up for Sort, MergeAppend, and Gather Merge nodes.  It
5404  * calculates the executor's representation of the sort key information, and
5405  * adjusts the plan targetlist if needed to add resjunk sort columns.
5406  *
5407  * Input parameters:
5408  *	  'lefttree' is the plan node which yields input tuples
5409  *	  'pathkeys' is the list of pathkeys by which the result is to be sorted
5410  *	  'relids' identifies the child relation being sorted, if any
5411  *	  'reqColIdx' is NULL or an array of required sort key column numbers
5412  *	  'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
5413  *
5414  * We must convert the pathkey information into arrays of sort key column
5415  * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
5416  * which is the representation the executor wants.  These are returned into
5417  * the output parameters *p_numsortkeys etc.
5418  *
5419  * When looking for matches to an EquivalenceClass's members, we will only
5420  * consider child EC members if they match 'relids'.  This protects against
5421  * possible incorrect matches to child expressions that contain no Vars.
5422  *
5423  * If reqColIdx isn't NULL then it contains sort key column numbers that
5424  * we should match.  This is used when making child plans for a MergeAppend;
5425  * it's an error if we can't match the columns.
5426  *
5427  * If the pathkeys include expressions that aren't simple Vars, we will
5428  * usually need to add resjunk items to the input plan's targetlist to
5429  * compute these expressions, since a Sort or MergeAppend node itself won't
5430  * do any such calculations.  If the input plan type isn't one that can do
5431  * projections, this means adding a Result node just to do the projection.
5432  * However, the caller can pass adjust_tlist_in_place = TRUE to force the
5433  * lefttree tlist to be modified in-place regardless of whether the node type
5434  * can project --- we use this for fixing the tlist of MergeAppend itself.
5435  *
5436  * Returns the node which is to be the input to the Sort (either lefttree,
5437  * or a Result stacked atop lefttree).
5438  */
5439 static Plan *
prepare_sort_from_pathkeys(Plan * lefttree,List * pathkeys,Relids relids,const AttrNumber * reqColIdx,bool adjust_tlist_in_place,int * p_numsortkeys,AttrNumber ** p_sortColIdx,Oid ** p_sortOperators,Oid ** p_collations,bool ** p_nullsFirst)5440 prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
5441 						   Relids relids,
5442 						   const AttrNumber *reqColIdx,
5443 						   bool adjust_tlist_in_place,
5444 						   int *p_numsortkeys,
5445 						   AttrNumber **p_sortColIdx,
5446 						   Oid **p_sortOperators,
5447 						   Oid **p_collations,
5448 						   bool **p_nullsFirst)
5449 {
5450 	List	   *tlist = lefttree->targetlist;
5451 	ListCell   *i;
5452 	int			numsortkeys;
5453 	AttrNumber *sortColIdx;
5454 	Oid		   *sortOperators;
5455 	Oid		   *collations;
5456 	bool	   *nullsFirst;
5457 
5458 	/*
5459 	 * We will need at most list_length(pathkeys) sort columns; possibly less
5460 	 */
5461 	numsortkeys = list_length(pathkeys);
5462 	sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5463 	sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5464 	collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5465 	nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5466 
5467 	numsortkeys = 0;
5468 
5469 	foreach(i, pathkeys)
5470 	{
5471 		PathKey    *pathkey = (PathKey *) lfirst(i);
5472 		EquivalenceClass *ec = pathkey->pk_eclass;
5473 		EquivalenceMember *em;
5474 		TargetEntry *tle = NULL;
5475 		Oid			pk_datatype = InvalidOid;
5476 		Oid			sortop;
5477 		ListCell   *j;
5478 
5479 		if (ec->ec_has_volatile)
5480 		{
5481 			/*
5482 			 * If the pathkey's EquivalenceClass is volatile, then it must
5483 			 * have come from an ORDER BY clause, and we have to match it to
5484 			 * that same targetlist entry.
5485 			 */
5486 			if (ec->ec_sortref == 0)	/* can't happen */
5487 				elog(ERROR, "volatile EquivalenceClass has no sortref");
5488 			tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
5489 			Assert(tle);
5490 			Assert(list_length(ec->ec_members) == 1);
5491 			pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
5492 		}
5493 		else if (reqColIdx != NULL)
5494 		{
5495 			/*
5496 			 * If we are given a sort column number to match, only consider
5497 			 * the single TLE at that position.  It's possible that there is
5498 			 * no such TLE, in which case fall through and generate a resjunk
5499 			 * targetentry (we assume this must have happened in the parent
5500 			 * plan as well).  If there is a TLE but it doesn't match the
5501 			 * pathkey's EC, we do the same, which is probably the wrong thing
5502 			 * but we'll leave it to caller to complain about the mismatch.
5503 			 */
5504 			tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
5505 			if (tle)
5506 			{
5507 				em = find_ec_member_for_tle(ec, tle, relids);
5508 				if (em)
5509 				{
5510 					/* found expr at right place in tlist */
5511 					pk_datatype = em->em_datatype;
5512 				}
5513 				else
5514 					tle = NULL;
5515 			}
5516 		}
5517 		else
5518 		{
5519 			/*
5520 			 * Otherwise, we can sort by any non-constant expression listed in
5521 			 * the pathkey's EquivalenceClass.  For now, we take the first
5522 			 * tlist item found in the EC. If there's no match, we'll generate
5523 			 * a resjunk entry using the first EC member that is an expression
5524 			 * in the input's vars.  (The non-const restriction only matters
5525 			 * if the EC is below_outer_join; but if it isn't, it won't
5526 			 * contain consts anyway, else we'd have discarded the pathkey as
5527 			 * redundant.)
5528 			 *
5529 			 * XXX if we have a choice, is there any way of figuring out which
5530 			 * might be cheapest to execute?  (For example, int4lt is likely
5531 			 * much cheaper to execute than numericlt, but both might appear
5532 			 * in the same equivalence class...)  Not clear that we ever will
5533 			 * have an interesting choice in practice, so it may not matter.
5534 			 */
5535 			foreach(j, tlist)
5536 			{
5537 				tle = (TargetEntry *) lfirst(j);
5538 				em = find_ec_member_for_tle(ec, tle, relids);
5539 				if (em)
5540 				{
5541 					/* found expr already in tlist */
5542 					pk_datatype = em->em_datatype;
5543 					break;
5544 				}
5545 				tle = NULL;
5546 			}
5547 		}
5548 
5549 		if (!tle)
5550 		{
5551 			/*
5552 			 * No matching tlist item; look for a computable expression. Note
5553 			 * that we treat Aggrefs as if they were variables; this is
5554 			 * necessary when attempting to sort the output from an Agg node
5555 			 * for use in a WindowFunc (since grouping_planner will have
5556 			 * treated the Aggrefs as variables, too).  Likewise, if we find a
5557 			 * WindowFunc in a sort expression, treat it as a variable.
5558 			 */
5559 			Expr	   *sortexpr = NULL;
5560 
5561 			foreach(j, ec->ec_members)
5562 			{
5563 				EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
5564 				List	   *exprvars;
5565 				ListCell   *k;
5566 
5567 				/*
5568 				 * We shouldn't be trying to sort by an equivalence class that
5569 				 * contains a constant, so no need to consider such cases any
5570 				 * further.
5571 				 */
5572 				if (em->em_is_const)
5573 					continue;
5574 
5575 				/*
5576 				 * Ignore child members unless they match the rel being
5577 				 * sorted.
5578 				 */
5579 				if (em->em_is_child &&
5580 					!bms_equal(em->em_relids, relids))
5581 					continue;
5582 
5583 				sortexpr = em->em_expr;
5584 				exprvars = pull_var_clause((Node *) sortexpr,
5585 										   PVC_INCLUDE_AGGREGATES |
5586 										   PVC_INCLUDE_WINDOWFUNCS |
5587 										   PVC_INCLUDE_PLACEHOLDERS);
5588 				foreach(k, exprvars)
5589 				{
5590 					if (!tlist_member_ignore_relabel(lfirst(k), tlist))
5591 						break;
5592 				}
5593 				list_free(exprvars);
5594 				if (!k)
5595 				{
5596 					pk_datatype = em->em_datatype;
5597 					break;		/* found usable expression */
5598 				}
5599 			}
5600 			if (!j)
5601 				elog(ERROR, "could not find pathkey item to sort");
5602 
5603 			/*
5604 			 * Do we need to insert a Result node?
5605 			 */
5606 			if (!adjust_tlist_in_place &&
5607 				!is_projection_capable_plan(lefttree))
5608 			{
5609 				/* copy needed so we don't modify input's tlist below */
5610 				tlist = copyObject(tlist);
5611 				lefttree = inject_projection_plan(lefttree, tlist,
5612 												  lefttree->parallel_safe);
5613 			}
5614 
5615 			/* Don't bother testing is_projection_capable_plan again */
5616 			adjust_tlist_in_place = true;
5617 
5618 			/*
5619 			 * Add resjunk entry to input's tlist
5620 			 */
5621 			tle = makeTargetEntry(sortexpr,
5622 								  list_length(tlist) + 1,
5623 								  NULL,
5624 								  true);
5625 			tlist = lappend(tlist, tle);
5626 			lefttree->targetlist = tlist;	/* just in case NIL before */
5627 		}
5628 
5629 		/*
5630 		 * Look up the correct sort operator from the PathKey's slightly
5631 		 * abstracted representation.
5632 		 */
5633 		sortop = get_opfamily_member(pathkey->pk_opfamily,
5634 									 pk_datatype,
5635 									 pk_datatype,
5636 									 pathkey->pk_strategy);
5637 		if (!OidIsValid(sortop))	/* should not happen */
5638 			elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
5639 				 pathkey->pk_strategy, pk_datatype, pk_datatype,
5640 				 pathkey->pk_opfamily);
5641 
5642 		/* Add the column to the sort arrays */
5643 		sortColIdx[numsortkeys] = tle->resno;
5644 		sortOperators[numsortkeys] = sortop;
5645 		collations[numsortkeys] = ec->ec_collation;
5646 		nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
5647 		numsortkeys++;
5648 	}
5649 
5650 	/* Return results */
5651 	*p_numsortkeys = numsortkeys;
5652 	*p_sortColIdx = sortColIdx;
5653 	*p_sortOperators = sortOperators;
5654 	*p_collations = collations;
5655 	*p_nullsFirst = nullsFirst;
5656 
5657 	return lefttree;
5658 }
5659 
5660 /*
5661  * find_ec_member_for_tle
5662  *		Locate an EquivalenceClass member matching the given TLE, if any
5663  *
5664  * Child EC members are ignored unless they match 'relids'.
5665  */
5666 static EquivalenceMember *
find_ec_member_for_tle(EquivalenceClass * ec,TargetEntry * tle,Relids relids)5667 find_ec_member_for_tle(EquivalenceClass *ec,
5668 					   TargetEntry *tle,
5669 					   Relids relids)
5670 {
5671 	Expr	   *tlexpr;
5672 	ListCell   *lc;
5673 
5674 	/* We ignore binary-compatible relabeling on both ends */
5675 	tlexpr = tle->expr;
5676 	while (tlexpr && IsA(tlexpr, RelabelType))
5677 		tlexpr = ((RelabelType *) tlexpr)->arg;
5678 
5679 	foreach(lc, ec->ec_members)
5680 	{
5681 		EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
5682 		Expr	   *emexpr;
5683 
5684 		/*
5685 		 * We shouldn't be trying to sort by an equivalence class that
5686 		 * contains a constant, so no need to consider such cases any further.
5687 		 */
5688 		if (em->em_is_const)
5689 			continue;
5690 
5691 		/*
5692 		 * Ignore child members unless they match the rel being sorted.
5693 		 */
5694 		if (em->em_is_child &&
5695 			!bms_equal(em->em_relids, relids))
5696 			continue;
5697 
5698 		/* Match if same expression (after stripping relabel) */
5699 		emexpr = em->em_expr;
5700 		while (emexpr && IsA(emexpr, RelabelType))
5701 			emexpr = ((RelabelType *) emexpr)->arg;
5702 
5703 		if (equal(emexpr, tlexpr))
5704 			return em;
5705 	}
5706 
5707 	return NULL;
5708 }
5709 
5710 /*
5711  * make_sort_from_pathkeys
5712  *	  Create sort plan to sort according to given pathkeys
5713  *
5714  *	  'lefttree' is the node which yields input tuples
5715  *	  'pathkeys' is the list of pathkeys by which the result is to be sorted
5716  */
5717 static Sort *
make_sort_from_pathkeys(Plan * lefttree,List * pathkeys)5718 make_sort_from_pathkeys(Plan *lefttree, List *pathkeys)
5719 {
5720 	int			numsortkeys;
5721 	AttrNumber *sortColIdx;
5722 	Oid		   *sortOperators;
5723 	Oid		   *collations;
5724 	bool	   *nullsFirst;
5725 
5726 	/* Compute sort column info, and adjust lefttree as needed */
5727 	lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
5728 										  NULL,
5729 										  NULL,
5730 										  false,
5731 										  &numsortkeys,
5732 										  &sortColIdx,
5733 										  &sortOperators,
5734 										  &collations,
5735 										  &nullsFirst);
5736 
5737 	/* Now build the Sort node */
5738 	return make_sort(lefttree, numsortkeys,
5739 					 sortColIdx, sortOperators,
5740 					 collations, nullsFirst);
5741 }
5742 
5743 /*
5744  * make_sort_from_sortclauses
5745  *	  Create sort plan to sort according to given sortclauses
5746  *
5747  *	  'sortcls' is a list of SortGroupClauses
5748  *	  'lefttree' is the node which yields input tuples
5749  */
5750 Sort *
make_sort_from_sortclauses(List * sortcls,Plan * lefttree)5751 make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
5752 {
5753 	List	   *sub_tlist = lefttree->targetlist;
5754 	ListCell   *l;
5755 	int			numsortkeys;
5756 	AttrNumber *sortColIdx;
5757 	Oid		   *sortOperators;
5758 	Oid		   *collations;
5759 	bool	   *nullsFirst;
5760 
5761 	/* Convert list-ish representation to arrays wanted by executor */
5762 	numsortkeys = list_length(sortcls);
5763 	sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5764 	sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5765 	collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5766 	nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5767 
5768 	numsortkeys = 0;
5769 	foreach(l, sortcls)
5770 	{
5771 		SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
5772 		TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
5773 
5774 		sortColIdx[numsortkeys] = tle->resno;
5775 		sortOperators[numsortkeys] = sortcl->sortop;
5776 		collations[numsortkeys] = exprCollation((Node *) tle->expr);
5777 		nullsFirst[numsortkeys] = sortcl->nulls_first;
5778 		numsortkeys++;
5779 	}
5780 
5781 	return make_sort(lefttree, numsortkeys,
5782 					 sortColIdx, sortOperators,
5783 					 collations, nullsFirst);
5784 }
5785 
5786 /*
5787  * make_sort_from_groupcols
5788  *	  Create sort plan to sort based on grouping columns
5789  *
5790  * 'groupcls' is the list of SortGroupClauses
5791  * 'grpColIdx' gives the column numbers to use
5792  *
5793  * This might look like it could be merged with make_sort_from_sortclauses,
5794  * but presently we *must* use the grpColIdx[] array to locate sort columns,
5795  * because the child plan's tlist is not marked with ressortgroupref info
5796  * appropriate to the grouping node.  So, only the sort ordering info
5797  * is used from the SortGroupClause entries.
5798  */
5799 static Sort *
make_sort_from_groupcols(List * groupcls,AttrNumber * grpColIdx,Plan * lefttree)5800 make_sort_from_groupcols(List *groupcls,
5801 						 AttrNumber *grpColIdx,
5802 						 Plan *lefttree)
5803 {
5804 	List	   *sub_tlist = lefttree->targetlist;
5805 	ListCell   *l;
5806 	int			numsortkeys;
5807 	AttrNumber *sortColIdx;
5808 	Oid		   *sortOperators;
5809 	Oid		   *collations;
5810 	bool	   *nullsFirst;
5811 
5812 	/* Convert list-ish representation to arrays wanted by executor */
5813 	numsortkeys = list_length(groupcls);
5814 	sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5815 	sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5816 	collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5817 	nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5818 
5819 	numsortkeys = 0;
5820 	foreach(l, groupcls)
5821 	{
5822 		SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
5823 		TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
5824 
5825 		if (!tle)
5826 			elog(ERROR, "could not retrieve tle for sort-from-groupcols");
5827 
5828 		sortColIdx[numsortkeys] = tle->resno;
5829 		sortOperators[numsortkeys] = grpcl->sortop;
5830 		collations[numsortkeys] = exprCollation((Node *) tle->expr);
5831 		nullsFirst[numsortkeys] = grpcl->nulls_first;
5832 		numsortkeys++;
5833 	}
5834 
5835 	return make_sort(lefttree, numsortkeys,
5836 					 sortColIdx, sortOperators,
5837 					 collations, nullsFirst);
5838 }
5839 
5840 static Material *
make_material(Plan * lefttree)5841 make_material(Plan *lefttree)
5842 {
5843 	Material   *node = makeNode(Material);
5844 	Plan	   *plan = &node->plan;
5845 
5846 	plan->targetlist = lefttree->targetlist;
5847 	plan->qual = NIL;
5848 	plan->lefttree = lefttree;
5849 	plan->righttree = NULL;
5850 
5851 	return node;
5852 }
5853 
5854 /*
5855  * materialize_finished_plan: stick a Material node atop a completed plan
5856  *
5857  * There are a couple of places where we want to attach a Material node
5858  * after completion of create_plan(), without any MaterialPath path.
5859  * Those places should probably be refactored someday to do this on the
5860  * Path representation, but it's not worth the trouble yet.
5861  */
5862 Plan *
materialize_finished_plan(Plan * subplan)5863 materialize_finished_plan(Plan *subplan)
5864 {
5865 	Plan	   *matplan;
5866 	Path		matpath;		/* dummy for result of cost_material */
5867 
5868 	matplan = (Plan *) make_material(subplan);
5869 
5870 	/*
5871 	 * XXX horrid kluge: if there are any initPlans attached to the subplan,
5872 	 * move them up to the Material node, which is now effectively the top
5873 	 * plan node in its query level.  This prevents failure in
5874 	 * SS_finalize_plan(), which see for comments.  We don't bother adjusting
5875 	 * the subplan's cost estimate for this.
5876 	 */
5877 	matplan->initPlan = subplan->initPlan;
5878 	subplan->initPlan = NIL;
5879 
5880 	/* Set cost data */
5881 	cost_material(&matpath,
5882 				  subplan->startup_cost,
5883 				  subplan->total_cost,
5884 				  subplan->plan_rows,
5885 				  subplan->plan_width);
5886 	matplan->startup_cost = matpath.startup_cost;
5887 	matplan->total_cost = matpath.total_cost;
5888 	matplan->plan_rows = subplan->plan_rows;
5889 	matplan->plan_width = subplan->plan_width;
5890 	matplan->parallel_aware = false;
5891 	matplan->parallel_safe = subplan->parallel_safe;
5892 
5893 	return matplan;
5894 }
5895 
5896 Agg *
make_agg(List * tlist,List * qual,AggStrategy aggstrategy,AggSplit aggsplit,int numGroupCols,AttrNumber * grpColIdx,Oid * grpOperators,List * groupingSets,List * chain,double dNumGroups,Plan * lefttree)5897 make_agg(List *tlist, List *qual,
5898 		 AggStrategy aggstrategy, AggSplit aggsplit,
5899 		 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
5900 		 List *groupingSets, List *chain,
5901 		 double dNumGroups, Plan *lefttree)
5902 {
5903 	Agg		   *node = makeNode(Agg);
5904 	Plan	   *plan = &node->plan;
5905 	long		numGroups;
5906 
5907 	/* Reduce to long, but 'ware overflow! */
5908 	numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
5909 
5910 	node->aggstrategy = aggstrategy;
5911 	node->aggsplit = aggsplit;
5912 	node->numCols = numGroupCols;
5913 	node->grpColIdx = grpColIdx;
5914 	node->grpOperators = grpOperators;
5915 	node->numGroups = numGroups;
5916 	node->aggParams = NULL;		/* SS_finalize_plan() will fill this */
5917 	node->groupingSets = groupingSets;
5918 	node->chain = chain;
5919 
5920 	plan->qual = qual;
5921 	plan->targetlist = tlist;
5922 	plan->lefttree = lefttree;
5923 	plan->righttree = NULL;
5924 
5925 	return node;
5926 }
5927 
5928 static WindowAgg *
make_windowagg(List * tlist,Index winref,int partNumCols,AttrNumber * partColIdx,Oid * partOperators,int ordNumCols,AttrNumber * ordColIdx,Oid * ordOperators,int frameOptions,Node * startOffset,Node * endOffset,Plan * lefttree)5929 make_windowagg(List *tlist, Index winref,
5930 			   int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
5931 			   int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
5932 			   int frameOptions, Node *startOffset, Node *endOffset,
5933 			   Plan *lefttree)
5934 {
5935 	WindowAgg  *node = makeNode(WindowAgg);
5936 	Plan	   *plan = &node->plan;
5937 
5938 	node->winref = winref;
5939 	node->partNumCols = partNumCols;
5940 	node->partColIdx = partColIdx;
5941 	node->partOperators = partOperators;
5942 	node->ordNumCols = ordNumCols;
5943 	node->ordColIdx = ordColIdx;
5944 	node->ordOperators = ordOperators;
5945 	node->frameOptions = frameOptions;
5946 	node->startOffset = startOffset;
5947 	node->endOffset = endOffset;
5948 
5949 	plan->targetlist = tlist;
5950 	plan->lefttree = lefttree;
5951 	plan->righttree = NULL;
5952 	/* WindowAgg nodes never have a qual clause */
5953 	plan->qual = NIL;
5954 
5955 	return node;
5956 }
5957 
5958 static Group *
make_group(List * tlist,List * qual,int numGroupCols,AttrNumber * grpColIdx,Oid * grpOperators,Plan * lefttree)5959 make_group(List *tlist,
5960 		   List *qual,
5961 		   int numGroupCols,
5962 		   AttrNumber *grpColIdx,
5963 		   Oid *grpOperators,
5964 		   Plan *lefttree)
5965 {
5966 	Group	   *node = makeNode(Group);
5967 	Plan	   *plan = &node->plan;
5968 
5969 	node->numCols = numGroupCols;
5970 	node->grpColIdx = grpColIdx;
5971 	node->grpOperators = grpOperators;
5972 
5973 	plan->qual = qual;
5974 	plan->targetlist = tlist;
5975 	plan->lefttree = lefttree;
5976 	plan->righttree = NULL;
5977 
5978 	return node;
5979 }
5980 
5981 /*
5982  * distinctList is a list of SortGroupClauses, identifying the targetlist items
5983  * that should be considered by the Unique filter.  The input path must
5984  * already be sorted accordingly.
5985  */
5986 static Unique *
make_unique_from_sortclauses(Plan * lefttree,List * distinctList)5987 make_unique_from_sortclauses(Plan *lefttree, List *distinctList)
5988 {
5989 	Unique	   *node = makeNode(Unique);
5990 	Plan	   *plan = &node->plan;
5991 	int			numCols = list_length(distinctList);
5992 	int			keyno = 0;
5993 	AttrNumber *uniqColIdx;
5994 	Oid		   *uniqOperators;
5995 	ListCell   *slitem;
5996 
5997 	plan->targetlist = lefttree->targetlist;
5998 	plan->qual = NIL;
5999 	plan->lefttree = lefttree;
6000 	plan->righttree = NULL;
6001 
6002 	/*
6003 	 * convert SortGroupClause list into arrays of attr indexes and equality
6004 	 * operators, as wanted by executor
6005 	 */
6006 	Assert(numCols > 0);
6007 	uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
6008 	uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
6009 
6010 	foreach(slitem, distinctList)
6011 	{
6012 		SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
6013 		TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
6014 
6015 		uniqColIdx[keyno] = tle->resno;
6016 		uniqOperators[keyno] = sortcl->eqop;
6017 		Assert(OidIsValid(uniqOperators[keyno]));
6018 		keyno++;
6019 	}
6020 
6021 	node->numCols = numCols;
6022 	node->uniqColIdx = uniqColIdx;
6023 	node->uniqOperators = uniqOperators;
6024 
6025 	return node;
6026 }
6027 
6028 /*
6029  * as above, but use pathkeys to identify the sort columns and semantics
6030  */
6031 static Unique *
make_unique_from_pathkeys(Plan * lefttree,List * pathkeys,int numCols)6032 make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols)
6033 {
6034 	Unique	   *node = makeNode(Unique);
6035 	Plan	   *plan = &node->plan;
6036 	int			keyno = 0;
6037 	AttrNumber *uniqColIdx;
6038 	Oid		   *uniqOperators;
6039 	ListCell   *lc;
6040 
6041 	plan->targetlist = lefttree->targetlist;
6042 	plan->qual = NIL;
6043 	plan->lefttree = lefttree;
6044 	plan->righttree = NULL;
6045 
6046 	/*
6047 	 * Convert pathkeys list into arrays of attr indexes and equality
6048 	 * operators, as wanted by executor.  This has a lot in common with
6049 	 * prepare_sort_from_pathkeys ... maybe unify sometime?
6050 	 */
6051 	Assert(numCols >= 0 && numCols <= list_length(pathkeys));
6052 	uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
6053 	uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
6054 
6055 	foreach(lc, pathkeys)
6056 	{
6057 		PathKey    *pathkey = (PathKey *) lfirst(lc);
6058 		EquivalenceClass *ec = pathkey->pk_eclass;
6059 		EquivalenceMember *em;
6060 		TargetEntry *tle = NULL;
6061 		Oid			pk_datatype = InvalidOid;
6062 		Oid			eqop;
6063 		ListCell   *j;
6064 
6065 		/* Ignore pathkeys beyond the specified number of columns */
6066 		if (keyno >= numCols)
6067 			break;
6068 
6069 		if (ec->ec_has_volatile)
6070 		{
6071 			/*
6072 			 * If the pathkey's EquivalenceClass is volatile, then it must
6073 			 * have come from an ORDER BY clause, and we have to match it to
6074 			 * that same targetlist entry.
6075 			 */
6076 			if (ec->ec_sortref == 0)	/* can't happen */
6077 				elog(ERROR, "volatile EquivalenceClass has no sortref");
6078 			tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
6079 			Assert(tle);
6080 			Assert(list_length(ec->ec_members) == 1);
6081 			pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
6082 		}
6083 		else
6084 		{
6085 			/*
6086 			 * Otherwise, we can use any non-constant expression listed in the
6087 			 * pathkey's EquivalenceClass.  For now, we take the first tlist
6088 			 * item found in the EC.
6089 			 */
6090 			foreach(j, plan->targetlist)
6091 			{
6092 				tle = (TargetEntry *) lfirst(j);
6093 				em = find_ec_member_for_tle(ec, tle, NULL);
6094 				if (em)
6095 				{
6096 					/* found expr already in tlist */
6097 					pk_datatype = em->em_datatype;
6098 					break;
6099 				}
6100 				tle = NULL;
6101 			}
6102 		}
6103 
6104 		if (!tle)
6105 			elog(ERROR, "could not find pathkey item to sort");
6106 
6107 		/*
6108 		 * Look up the correct equality operator from the PathKey's slightly
6109 		 * abstracted representation.
6110 		 */
6111 		eqop = get_opfamily_member(pathkey->pk_opfamily,
6112 								   pk_datatype,
6113 								   pk_datatype,
6114 								   BTEqualStrategyNumber);
6115 		if (!OidIsValid(eqop))	/* should not happen */
6116 			elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6117 				 BTEqualStrategyNumber, pk_datatype, pk_datatype,
6118 				 pathkey->pk_opfamily);
6119 
6120 		uniqColIdx[keyno] = tle->resno;
6121 		uniqOperators[keyno] = eqop;
6122 
6123 		keyno++;
6124 	}
6125 
6126 	node->numCols = numCols;
6127 	node->uniqColIdx = uniqColIdx;
6128 	node->uniqOperators = uniqOperators;
6129 
6130 	return node;
6131 }
6132 
6133 static Gather *
make_gather(List * qptlist,List * qpqual,int nworkers,int rescan_param,bool single_copy,Plan * subplan)6134 make_gather(List *qptlist,
6135 			List *qpqual,
6136 			int nworkers,
6137 			int rescan_param,
6138 			bool single_copy,
6139 			Plan *subplan)
6140 {
6141 	Gather	   *node = makeNode(Gather);
6142 	Plan	   *plan = &node->plan;
6143 
6144 	plan->targetlist = qptlist;
6145 	plan->qual = qpqual;
6146 	plan->lefttree = subplan;
6147 	plan->righttree = NULL;
6148 	node->num_workers = nworkers;
6149 	node->rescan_param = rescan_param;
6150 	node->single_copy = single_copy;
6151 	node->invisible = false;
6152 
6153 	return node;
6154 }
6155 
6156 /*
6157  * distinctList is a list of SortGroupClauses, identifying the targetlist
6158  * items that should be considered by the SetOp filter.  The input path must
6159  * already be sorted accordingly.
6160  */
6161 static SetOp *
make_setop(SetOpCmd cmd,SetOpStrategy strategy,Plan * lefttree,List * distinctList,AttrNumber flagColIdx,int firstFlag,long numGroups)6162 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
6163 		   List *distinctList, AttrNumber flagColIdx, int firstFlag,
6164 		   long numGroups)
6165 {
6166 	SetOp	   *node = makeNode(SetOp);
6167 	Plan	   *plan = &node->plan;
6168 	int			numCols = list_length(distinctList);
6169 	int			keyno = 0;
6170 	AttrNumber *dupColIdx;
6171 	Oid		   *dupOperators;
6172 	ListCell   *slitem;
6173 
6174 	plan->targetlist = lefttree->targetlist;
6175 	plan->qual = NIL;
6176 	plan->lefttree = lefttree;
6177 	plan->righttree = NULL;
6178 
6179 	/*
6180 	 * convert SortGroupClause list into arrays of attr indexes and equality
6181 	 * operators, as wanted by executor
6182 	 */
6183 	dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
6184 	dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
6185 
6186 	foreach(slitem, distinctList)
6187 	{
6188 		SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
6189 		TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
6190 
6191 		dupColIdx[keyno] = tle->resno;
6192 		dupOperators[keyno] = sortcl->eqop;
6193 		Assert(OidIsValid(dupOperators[keyno]));
6194 		keyno++;
6195 	}
6196 
6197 	node->cmd = cmd;
6198 	node->strategy = strategy;
6199 	node->numCols = numCols;
6200 	node->dupColIdx = dupColIdx;
6201 	node->dupOperators = dupOperators;
6202 	node->flagColIdx = flagColIdx;
6203 	node->firstFlag = firstFlag;
6204 	node->numGroups = numGroups;
6205 
6206 	return node;
6207 }
6208 
6209 /*
6210  * make_lockrows
6211  *	  Build a LockRows plan node
6212  */
6213 static LockRows *
make_lockrows(Plan * lefttree,List * rowMarks,int epqParam)6214 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
6215 {
6216 	LockRows   *node = makeNode(LockRows);
6217 	Plan	   *plan = &node->plan;
6218 
6219 	plan->targetlist = lefttree->targetlist;
6220 	plan->qual = NIL;
6221 	plan->lefttree = lefttree;
6222 	plan->righttree = NULL;
6223 
6224 	node->rowMarks = rowMarks;
6225 	node->epqParam = epqParam;
6226 
6227 	return node;
6228 }
6229 
6230 /*
6231  * make_limit
6232  *	  Build a Limit plan node
6233  */
6234 Limit *
make_limit(Plan * lefttree,Node * limitOffset,Node * limitCount)6235 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount)
6236 {
6237 	Limit	   *node = makeNode(Limit);
6238 	Plan	   *plan = &node->plan;
6239 
6240 	plan->targetlist = lefttree->targetlist;
6241 	plan->qual = NIL;
6242 	plan->lefttree = lefttree;
6243 	plan->righttree = NULL;
6244 
6245 	node->limitOffset = limitOffset;
6246 	node->limitCount = limitCount;
6247 
6248 	return node;
6249 }
6250 
6251 /*
6252  * make_result
6253  *	  Build a Result plan node
6254  */
6255 static Result *
make_result(List * tlist,Node * resconstantqual,Plan * subplan)6256 make_result(List *tlist,
6257 			Node *resconstantqual,
6258 			Plan *subplan)
6259 {
6260 	Result	   *node = makeNode(Result);
6261 	Plan	   *plan = &node->plan;
6262 
6263 	plan->targetlist = tlist;
6264 	plan->qual = NIL;
6265 	plan->lefttree = subplan;
6266 	plan->righttree = NULL;
6267 	node->resconstantqual = resconstantqual;
6268 
6269 	return node;
6270 }
6271 
6272 /*
6273  * make_project_set
6274  *	  Build a ProjectSet plan node
6275  */
6276 static ProjectSet *
make_project_set(List * tlist,Plan * subplan)6277 make_project_set(List *tlist,
6278 				 Plan *subplan)
6279 {
6280 	ProjectSet *node = makeNode(ProjectSet);
6281 	Plan	   *plan = &node->plan;
6282 
6283 	plan->targetlist = tlist;
6284 	plan->qual = NIL;
6285 	plan->lefttree = subplan;
6286 	plan->righttree = NULL;
6287 
6288 	return node;
6289 }
6290 
6291 /*
6292  * make_modifytable
6293  *	  Build a ModifyTable plan node
6294  */
6295 static ModifyTable *
make_modifytable(PlannerInfo * root,CmdType operation,bool canSetTag,Index nominalRelation,List * partitioned_rels,List * resultRelations,List * subplans,List * withCheckOptionLists,List * returningLists,List * rowMarks,OnConflictExpr * onconflict,int epqParam)6296 make_modifytable(PlannerInfo *root,
6297 				 CmdType operation, bool canSetTag,
6298 				 Index nominalRelation, List *partitioned_rels,
6299 				 List *resultRelations, List *subplans,
6300 				 List *withCheckOptionLists, List *returningLists,
6301 				 List *rowMarks, OnConflictExpr *onconflict, int epqParam)
6302 {
6303 	ModifyTable *node = makeNode(ModifyTable);
6304 	List	   *fdw_private_list;
6305 	Bitmapset  *direct_modify_plans;
6306 	ListCell   *lc;
6307 	int			i;
6308 
6309 	Assert(list_length(resultRelations) == list_length(subplans));
6310 	Assert(withCheckOptionLists == NIL ||
6311 		   list_length(resultRelations) == list_length(withCheckOptionLists));
6312 	Assert(returningLists == NIL ||
6313 		   list_length(resultRelations) == list_length(returningLists));
6314 
6315 	node->plan.lefttree = NULL;
6316 	node->plan.righttree = NULL;
6317 	node->plan.qual = NIL;
6318 	/* setrefs.c will fill in the targetlist, if needed */
6319 	node->plan.targetlist = NIL;
6320 
6321 	node->operation = operation;
6322 	node->canSetTag = canSetTag;
6323 	node->nominalRelation = nominalRelation;
6324 	node->partitioned_rels = partitioned_rels;
6325 	node->resultRelations = resultRelations;
6326 	node->resultRelIndex = -1;	/* will be set correctly in setrefs.c */
6327 	node->rootResultRelIndex = -1;	/* will be set correctly in setrefs.c */
6328 	node->plans = subplans;
6329 	if (!onconflict)
6330 	{
6331 		node->onConflictAction = ONCONFLICT_NONE;
6332 		node->onConflictSet = NIL;
6333 		node->onConflictWhere = NULL;
6334 		node->arbiterIndexes = NIL;
6335 		node->exclRelRTI = 0;
6336 		node->exclRelTlist = NIL;
6337 	}
6338 	else
6339 	{
6340 		node->onConflictAction = onconflict->action;
6341 		node->onConflictSet = onconflict->onConflictSet;
6342 		node->onConflictWhere = onconflict->onConflictWhere;
6343 
6344 		/*
6345 		 * If a set of unique index inference elements was provided (an
6346 		 * INSERT...ON CONFLICT "inference specification"), then infer
6347 		 * appropriate unique indexes (or throw an error if none are
6348 		 * available).
6349 		 */
6350 		node->arbiterIndexes = infer_arbiter_indexes(root);
6351 
6352 		node->exclRelRTI = onconflict->exclRelIndex;
6353 		node->exclRelTlist = onconflict->exclRelTlist;
6354 	}
6355 	node->withCheckOptionLists = withCheckOptionLists;
6356 	node->returningLists = returningLists;
6357 	node->rowMarks = rowMarks;
6358 	node->epqParam = epqParam;
6359 
6360 	/*
6361 	 * For each result relation that is a foreign table, allow the FDW to
6362 	 * construct private plan data, and accumulate it all into a list.
6363 	 */
6364 	fdw_private_list = NIL;
6365 	direct_modify_plans = NULL;
6366 	i = 0;
6367 	foreach(lc, resultRelations)
6368 	{
6369 		Index		rti = lfirst_int(lc);
6370 		FdwRoutine *fdwroutine;
6371 		List	   *fdw_private;
6372 		bool		direct_modify;
6373 
6374 		/*
6375 		 * If possible, we want to get the FdwRoutine from our RelOptInfo for
6376 		 * the table.  But sometimes we don't have a RelOptInfo and must get
6377 		 * it the hard way.  (In INSERT, the target relation is not scanned,
6378 		 * so it's not a baserel; and there are also corner cases for
6379 		 * updatable views where the target rel isn't a baserel.)
6380 		 */
6381 		if (rti < root->simple_rel_array_size &&
6382 			root->simple_rel_array[rti] != NULL)
6383 		{
6384 			RelOptInfo *resultRel = root->simple_rel_array[rti];
6385 
6386 			fdwroutine = resultRel->fdwroutine;
6387 		}
6388 		else
6389 		{
6390 			RangeTblEntry *rte = planner_rt_fetch(rti, root);
6391 
6392 			Assert(rte->rtekind == RTE_RELATION);
6393 			if (rte->relkind == RELKIND_FOREIGN_TABLE)
6394 				fdwroutine = GetFdwRoutineByRelId(rte->relid);
6395 			else
6396 				fdwroutine = NULL;
6397 		}
6398 
6399 		/*
6400 		 * Try to modify the foreign table directly if (1) the FDW provides
6401 		 * callback functions needed for that, (2) there are no row-level
6402 		 * triggers on the foreign table, and (3) there are no WITH CHECK
6403 		 * OPTIONs from parent views.
6404 		 */
6405 		direct_modify = false;
6406 		if (fdwroutine != NULL &&
6407 			fdwroutine->PlanDirectModify != NULL &&
6408 			fdwroutine->BeginDirectModify != NULL &&
6409 			fdwroutine->IterateDirectModify != NULL &&
6410 			fdwroutine->EndDirectModify != NULL &&
6411 			withCheckOptionLists == NIL &&
6412 			!has_row_triggers(root, rti, operation))
6413 			direct_modify = fdwroutine->PlanDirectModify(root, node, rti, i);
6414 		if (direct_modify)
6415 			direct_modify_plans = bms_add_member(direct_modify_plans, i);
6416 
6417 		if (!direct_modify &&
6418 			fdwroutine != NULL &&
6419 			fdwroutine->PlanForeignModify != NULL)
6420 			fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
6421 		else
6422 			fdw_private = NIL;
6423 		fdw_private_list = lappend(fdw_private_list, fdw_private);
6424 		i++;
6425 	}
6426 	node->fdwPrivLists = fdw_private_list;
6427 	node->fdwDirectModifyPlans = direct_modify_plans;
6428 
6429 	return node;
6430 }
6431 
6432 /*
6433  * is_projection_capable_path
6434  *		Check whether a given Path node is able to do projection.
6435  */
6436 bool
is_projection_capable_path(Path * path)6437 is_projection_capable_path(Path *path)
6438 {
6439 	/* Most plan types can project, so just list the ones that can't */
6440 	switch (path->pathtype)
6441 	{
6442 		case T_Hash:
6443 		case T_Material:
6444 		case T_Sort:
6445 		case T_Unique:
6446 		case T_SetOp:
6447 		case T_LockRows:
6448 		case T_Limit:
6449 		case T_ModifyTable:
6450 		case T_MergeAppend:
6451 		case T_RecursiveUnion:
6452 			return false;
6453 		case T_Append:
6454 
6455 			/*
6456 			 * Append can't project, but if an AppendPath is being used to
6457 			 * represent a dummy path, what will actually be generated is a
6458 			 * Result which can project.
6459 			 */
6460 			return IS_DUMMY_APPEND(path);
6461 		case T_ProjectSet:
6462 
6463 			/*
6464 			 * Although ProjectSet certainly projects, say "no" because we
6465 			 * don't want the planner to randomly replace its tlist with
6466 			 * something else; the SRFs have to stay at top level.  This might
6467 			 * get relaxed later.
6468 			 */
6469 			return false;
6470 		default:
6471 			break;
6472 	}
6473 	return true;
6474 }
6475 
6476 /*
6477  * is_projection_capable_plan
6478  *		Check whether a given Plan node is able to do projection.
6479  */
6480 bool
is_projection_capable_plan(Plan * plan)6481 is_projection_capable_plan(Plan *plan)
6482 {
6483 	/* Most plan types can project, so just list the ones that can't */
6484 	switch (nodeTag(plan))
6485 	{
6486 		case T_Hash:
6487 		case T_Material:
6488 		case T_Sort:
6489 		case T_Unique:
6490 		case T_SetOp:
6491 		case T_LockRows:
6492 		case T_Limit:
6493 		case T_ModifyTable:
6494 		case T_Append:
6495 		case T_MergeAppend:
6496 		case T_RecursiveUnion:
6497 			return false;
6498 		case T_ProjectSet:
6499 
6500 			/*
6501 			 * Although ProjectSet certainly projects, say "no" because we
6502 			 * don't want the planner to randomly replace its tlist with
6503 			 * something else; the SRFs have to stay at top level.  This might
6504 			 * get relaxed later.
6505 			 */
6506 			return false;
6507 		default:
6508 			break;
6509 	}
6510 	return true;
6511 }
6512