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