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