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