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