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