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