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