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))
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))
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  {
2973  *qual = lappend(*qual, pred);
2974  *indexqual = lappend(*indexqual, pred);
2975  }
2976  }
2977  subindexECs = NIL;
2978  foreach(l, ipath->indexquals)
2979  {
2980  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2981 
2982  if (rinfo->parent_ec)
2983  subindexECs = lappend(subindexECs, rinfo->parent_ec);
2984  }
2985  *indexECs = subindexECs;
2986  }
2987  else
2988  {
2989  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
2990  plan = NULL; /* keep compiler quiet */
2991  }
2992 
2993  return plan;
2994 }
2995 
2996 /*
2997  * create_tidscan_plan
2998  * Returns a tidscan plan for the base relation scanned by 'best_path'
2999  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3000  */
3001 static TidScan *
3003  List *tlist, List *scan_clauses)
3004 {
3005  TidScan *scan_plan;
3006  Index scan_relid = best_path->path.parent->relid;
3007  List *tidquals = best_path->tidquals;
3008  List *ortidquals;
3009 
3010  /* it should be a base rel... */
3011  Assert(scan_relid > 0);
3012  Assert(best_path->path.parent->rtekind == RTE_RELATION);
3013 
3014  /* Sort clauses into best execution order */
3015  scan_clauses = order_qual_clauses(root, scan_clauses);
3016 
3017  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3018  scan_clauses = extract_actual_clauses(scan_clauses, false);
3019 
3020  /* Replace any outer-relation variables with nestloop params */
3021  if (best_path->path.param_info)
3022  {
3023  tidquals = (List *)
3024  replace_nestloop_params(root, (Node *) tidquals);
3025  scan_clauses = (List *)
3026  replace_nestloop_params(root, (Node *) scan_clauses);
3027  }
3028 
3029  /*
3030  * Remove any clauses that are TID quals. This is a bit tricky since the
3031  * tidquals list has implicit OR semantics.
3032  */
3033  ortidquals = tidquals;
3034  if (list_length(ortidquals) > 1)
3035  ortidquals = list_make1(make_orclause(ortidquals));
3036  scan_clauses = list_difference(scan_clauses, ortidquals);
3037 
3038  scan_plan = make_tidscan(tlist,
3039  scan_clauses,
3040  scan_relid,
3041  tidquals);
3042 
3043  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3044 
3045  return scan_plan;
3046 }
3047 
3048 /*
3049  * create_subqueryscan_plan
3050  * Returns a subqueryscan plan for the base relation scanned by 'best_path'
3051  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3052  */
3053 static SubqueryScan *
3055  List *tlist, List *scan_clauses)
3056 {
3057  SubqueryScan *scan_plan;
3058  RelOptInfo *rel = best_path->path.parent;
3059  Index scan_relid = rel->relid;
3060  Plan *subplan;
3061 
3062  /* it should be a subquery base rel... */
3063  Assert(scan_relid > 0);
3064  Assert(rel->rtekind == RTE_SUBQUERY);
3065 
3066  /*
3067  * Recursively create Plan from Path for subquery. Since we are entering
3068  * a different planner context (subroot), recurse to create_plan not
3069  * create_plan_recurse.
3070  */
3071  subplan = create_plan(rel->subroot, best_path->subpath);
3072 
3073  /* Sort clauses into best execution order */
3074  scan_clauses = order_qual_clauses(root, scan_clauses);
3075 
3076  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3077  scan_clauses = extract_actual_clauses(scan_clauses, false);
3078 
3079  /* Replace any outer-relation variables with nestloop params */
3080  if (best_path->path.param_info)
3081  {
3082  scan_clauses = (List *)
3083  replace_nestloop_params(root, (Node *) scan_clauses);
3085  rel->subplan_params);
3086  }
3087 
3088  scan_plan = make_subqueryscan(tlist,
3089  scan_clauses,
3090  scan_relid,
3091  subplan);
3092 
3093  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3094 
3095  return scan_plan;
3096 }
3097 
3098 /*
3099  * create_functionscan_plan
3100  * Returns a functionscan plan for the base relation scanned by 'best_path'
3101  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3102  */
3103 static FunctionScan *
3105  List *tlist, List *scan_clauses)
3106 {
3107  FunctionScan *scan_plan;
3108  Index scan_relid = best_path->parent->relid;
3109  RangeTblEntry *rte;
3110  List *functions;
3111 
3112  /* it should be a function base rel... */
3113  Assert(scan_relid > 0);
3114  rte = planner_rt_fetch(scan_relid, root);
3115  Assert(rte->rtekind == RTE_FUNCTION);
3116  functions = rte->functions;
3117 
3118  /* Sort clauses into best execution order */
3119  scan_clauses = order_qual_clauses(root, scan_clauses);
3120 
3121  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3122  scan_clauses = extract_actual_clauses(scan_clauses, false);
3123 
3124  /* Replace any outer-relation variables with nestloop params */
3125  if (best_path->param_info)
3126  {
3127  scan_clauses = (List *)
3128  replace_nestloop_params(root, (Node *) scan_clauses);
3129  /* The function expressions could contain nestloop params, too */
3130  functions = (List *) replace_nestloop_params(root, (Node *) functions);
3131  }
3132 
3133  scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
3134  functions, rte->funcordinality);
3135 
3136  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3137 
3138  return scan_plan;
3139 }
3140 
3141 /*
3142  * create_tablefuncscan_plan
3143  * Returns a tablefuncscan plan for the base relation scanned by 'best_path'
3144  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3145  */
3146 static TableFuncScan *
3148  List *tlist, List *scan_clauses)
3149 {
3150  TableFuncScan *scan_plan;
3151  Index scan_relid = best_path->parent->relid;
3152  RangeTblEntry *rte;
3153  TableFunc *tablefunc;
3154 
3155  /* it should be a function base rel... */
3156  Assert(scan_relid > 0);
3157  rte = planner_rt_fetch(scan_relid, root);
3158  Assert(rte->rtekind == RTE_TABLEFUNC);
3159  tablefunc = rte->tablefunc;
3160 
3161  /* Sort clauses into best execution order */
3162  scan_clauses = order_qual_clauses(root, scan_clauses);
3163 
3164  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3165  scan_clauses = extract_actual_clauses(scan_clauses, false);
3166 
3167  /* Replace any outer-relation variables with nestloop params */
3168  if (best_path->param_info)
3169  {
3170  scan_clauses = (List *)
3171  replace_nestloop_params(root, (Node *) scan_clauses);
3172  /* The function expressions could contain nestloop params, too */
3173  tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
3174  }
3175 
3176  scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
3177  tablefunc);
3178 
3179  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3180 
3181  return scan_plan;
3182 }
3183 
3184 /*
3185  * create_valuesscan_plan
3186  * Returns a valuesscan plan for the base relation scanned by 'best_path'
3187  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3188  */
3189 static ValuesScan *
3191  List *tlist, List *scan_clauses)
3192 {
3193  ValuesScan *scan_plan;
3194  Index scan_relid = best_path->parent->relid;
3195  RangeTblEntry *rte;
3196  List *values_lists;
3197 
3198  /* it should be a values base rel... */
3199  Assert(scan_relid > 0);
3200  rte = planner_rt_fetch(scan_relid, root);
3201  Assert(rte->rtekind == RTE_VALUES);
3202  values_lists = rte->values_lists;
3203 
3204  /* Sort clauses into best execution order */
3205  scan_clauses = order_qual_clauses(root, scan_clauses);
3206 
3207  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3208  scan_clauses = extract_actual_clauses(scan_clauses, false);
3209 
3210  /* Replace any outer-relation variables with nestloop params */
3211  if (best_path->param_info)
3212  {
3213  scan_clauses = (List *)
3214  replace_nestloop_params(root, (Node *) scan_clauses);
3215  /* The values lists could contain nestloop params, too */
3216  values_lists = (List *)
3217  replace_nestloop_params(root, (Node *) values_lists);
3218  }
3219 
3220  scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
3221  values_lists);
3222 
3223  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3224 
3225  return scan_plan;
3226 }
3227 
3228 /*
3229  * create_ctescan_plan
3230  * Returns a ctescan plan for the base relation scanned by 'best_path'
3231  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3232  */
3233 static CteScan *
3235  List *tlist, List *scan_clauses)
3236 {
3237  CteScan *scan_plan;
3238  Index scan_relid = best_path->parent->relid;
3239  RangeTblEntry *rte;
3240  SubPlan *ctesplan = NULL;
3241  int plan_id;
3242  int cte_param_id;
3243  PlannerInfo *cteroot;
3244  Index levelsup;
3245  int ndx;
3246  ListCell *lc;
3247 
3248  Assert(scan_relid > 0);
3249  rte = planner_rt_fetch(scan_relid, root);
3250  Assert(rte->rtekind == RTE_CTE);
3251  Assert(!rte->self_reference);
3252 
3253  /*
3254  * Find the referenced CTE, and locate the SubPlan previously made for it.
3255  */
3256  levelsup = rte->ctelevelsup;
3257  cteroot = root;
3258  while (levelsup-- > 0)
3259  {
3260  cteroot = cteroot->parent_root;
3261  if (!cteroot) /* shouldn't happen */
3262  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3263  }
3264 
3265  /*
3266  * Note: cte_plan_ids can be shorter than cteList, if we are still working
3267  * on planning the CTEs (ie, this is a side-reference from another CTE).
3268  * So we mustn't use forboth here.
3269  */
3270  ndx = 0;
3271  foreach(lc, cteroot->parse->cteList)
3272  {
3273  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3274 
3275  if (strcmp(cte->ctename, rte->ctename) == 0)
3276  break;
3277  ndx++;
3278  }
3279  if (lc == NULL) /* shouldn't happen */
3280  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3281  if (ndx >= list_length(cteroot->cte_plan_ids))
3282  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3283  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3284  Assert(plan_id > 0);
3285  foreach(lc, cteroot->init_plans)
3286  {
3287  ctesplan = (SubPlan *) lfirst(lc);
3288  if (ctesplan->plan_id == plan_id)
3289  break;
3290  }
3291  if (lc == NULL) /* shouldn't happen */
3292  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3293 
3294  /*
3295  * We need the CTE param ID, which is the sole member of the SubPlan's
3296  * setParam list.
3297  */
3298  cte_param_id = linitial_int(ctesplan->setParam);
3299 
3300  /* Sort clauses into best execution order */
3301  scan_clauses = order_qual_clauses(root, scan_clauses);
3302 
3303  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3304  scan_clauses = extract_actual_clauses(scan_clauses, false);
3305 
3306  /* Replace any outer-relation variables with nestloop params */
3307  if (best_path->param_info)
3308  {
3309  scan_clauses = (List *)
3310  replace_nestloop_params(root, (Node *) scan_clauses);
3311  }
3312 
3313  scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3314  plan_id, cte_param_id);
3315 
3316  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3317 
3318  return scan_plan;
3319 }
3320 
3321 /*
3322  * create_namedtuplestorescan_plan
3323  * Returns a tuplestorescan plan for the base relation scanned by
3324  * 'best_path' with restriction clauses 'scan_clauses' and targetlist
3325  * 'tlist'.
3326  */
3327 static NamedTuplestoreScan *
3329  List *tlist, List *scan_clauses)
3330 {
3331  NamedTuplestoreScan *scan_plan;
3332  Index scan_relid = best_path->parent->relid;
3333  RangeTblEntry *rte;
3334 
3335  Assert(scan_relid > 0);
3336  rte = planner_rt_fetch(scan_relid, root);
3338 
3339  /* Sort clauses into best execution order */
3340  scan_clauses = order_qual_clauses(root, scan_clauses);
3341 
3342  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3343  scan_clauses = extract_actual_clauses(scan_clauses, false);
3344 
3345  /* Replace any outer-relation variables with nestloop params */
3346  if (best_path->param_info)
3347  {
3348  scan_clauses = (List *)
3349  replace_nestloop_params(root, (Node *) scan_clauses);
3350  }
3351 
3352  scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
3353  rte->enrname);
3354 
3355  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3356 
3357  return scan_plan;
3358 }
3359 
3360 /*
3361  * create_worktablescan_plan
3362  * Returns a worktablescan plan for the base relation scanned by 'best_path'
3363  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3364  */
3365 static WorkTableScan *
3367  List *tlist, List *scan_clauses)
3368 {
3369  WorkTableScan *scan_plan;
3370  Index scan_relid = best_path->parent->relid;
3371  RangeTblEntry *rte;
3372  Index levelsup;
3373  PlannerInfo *cteroot;
3374 
3375  Assert(scan_relid > 0);
3376  rte = planner_rt_fetch(scan_relid, root);
3377  Assert(rte->rtekind == RTE_CTE);
3378  Assert(rte->self_reference);
3379 
3380  /*
3381  * We need to find the worktable param ID, which is in the plan level
3382  * that's processing the recursive UNION, which is one level *below* where
3383  * the CTE comes from.
3384  */
3385  levelsup = rte->ctelevelsup;
3386  if (levelsup == 0) /* shouldn't happen */
3387  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3388  levelsup--;
3389  cteroot = root;
3390  while (levelsup-- > 0)
3391  {
3392  cteroot = cteroot->parent_root;
3393  if (!cteroot) /* shouldn't happen */
3394  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3395  }
3396  if (cteroot->wt_param_id < 0) /* shouldn't happen */
3397  elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
3398 
3399  /* Sort clauses into best execution order */
3400  scan_clauses = order_qual_clauses(root, scan_clauses);
3401 
3402  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3403  scan_clauses = extract_actual_clauses(scan_clauses, false);
3404 
3405  /* Replace any outer-relation variables with nestloop params */
3406  if (best_path->param_info)
3407  {
3408  scan_clauses = (List *)
3409  replace_nestloop_params(root, (Node *) scan_clauses);
3410  }
3411 
3412  scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
3413  cteroot->wt_param_id);
3414 
3415  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3416 
3417  return scan_plan;
3418 }
3419 
3420 /*
3421  * create_foreignscan_plan
3422  * Returns a foreignscan plan for the relation scanned by 'best_path'
3423  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3424  */
3425 static ForeignScan *
3427  List *tlist, List *scan_clauses)
3428 {
3429  ForeignScan *scan_plan;
3430  RelOptInfo *rel = best_path->path.parent;
3431  Index scan_relid = rel->relid;
3432  Oid rel_oid = InvalidOid;
3433  Plan *outer_plan = NULL;
3434 
3435  Assert(rel->fdwroutine != NULL);
3436 
3437  /* transform the child path if any */
3438  if (best_path->fdw_outerpath)
3439  outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3440  CP_EXACT_TLIST);
3441 
3442  /*
3443  * If we're scanning a base relation, fetch its OID. (Irrelevant if
3444  * scanning a join relation.)
3445  */
3446  if (scan_relid > 0)
3447  {
3448  RangeTblEntry *rte;
3449 
3450  Assert(rel->rtekind == RTE_RELATION);
3451  rte = planner_rt_fetch(scan_relid, root);
3452  Assert(rte->rtekind == RTE_RELATION);
3453  rel_oid = rte->relid;
3454  }
3455 
3456  /*
3457  * Sort clauses into best execution order. We do this first since the FDW
3458  * might have more info than we do and wish to adjust the ordering.
3459  */
3460  scan_clauses = order_qual_clauses(root, scan_clauses);
3461 
3462  /*
3463  * Let the FDW perform its processing on the restriction clauses and
3464  * generate the plan node. Note that the FDW might remove restriction
3465  * clauses that it intends to execute remotely, or even add more (if it
3466  * has selected some join clauses for remote use but also wants them
3467  * rechecked locally).
3468  */
3469  scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
3470  best_path,
3471  tlist, scan_clauses,
3472  outer_plan);
3473 
3474  /* Copy cost data from Path to Plan; no need to make FDW do this */
3475  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3476 
3477  /* Copy foreign server OID; likewise, no need to make FDW do this */
3478  scan_plan->fs_server = rel->serverid;
3479 
3480  /*
3481  * Likewise, copy the relids that are represented by this foreign scan. An
3482  * upper rel doesn't have relids set, but it covers all the base relations
3483  * participating in the underlying scan, so use root's all_baserels.
3484  */
3485  if (IS_UPPER_REL(rel))
3486  scan_plan->fs_relids = root->all_baserels;
3487  else
3488  scan_plan->fs_relids = best_path->path.parent->relids;
3489 
3490  /*
3491  * If this is a foreign join, and to make it valid to push down we had to
3492  * assume that the current user is the same as some user explicitly named
3493  * in the query, mark the finished plan as depending on the current user.
3494  */
3495  if (rel->useridiscurrent)
3496  root->glob->dependsOnRole = true;
3497 
3498  /*
3499  * Replace any outer-relation variables with nestloop params in the qual,
3500  * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
3501  * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
3502  * fdw_recheck_quals could have come from join clauses, so doing this
3503  * beforehand on the scan_clauses wouldn't work.) We assume
3504  * fdw_scan_tlist contains no such variables.
3505  */
3506  if (best_path->path.param_info)
3507  {
3508  scan_plan->scan.plan.qual = (List *)
3509  replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
3510  scan_plan->fdw_exprs = (List *)
3511  replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
3512  scan_plan->fdw_recheck_quals = (List *)
3514  (Node *) scan_plan->fdw_recheck_quals);
3515  }
3516 
3517  /*
3518  * If rel is a base relation, detect whether any system columns are
3519  * requested from the rel. (If rel is a join relation, rel->relid will be
3520  * 0, but there can be no Var with relid 0 in the rel's targetlist or the
3521  * restriction clauses, so we skip this in that case. Note that any such
3522  * columns in base relations that were joined are assumed to be contained
3523  * in fdw_scan_tlist.) This is a bit of a kluge and might go away
3524  * someday, so we intentionally leave it out of the API presented to FDWs.
3525  */
3526  scan_plan->fsSystemCol = false;
3527  if (scan_relid > 0)
3528  {
3529  Bitmapset *attrs_used = NULL;
3530  ListCell *lc;
3531  int i;
3532 
3533  /*
3534  * First, examine all the attributes needed for joins or final output.
3535  * Note: we must look at rel's targetlist, not the attr_needed data,
3536  * because attr_needed isn't computed for inheritance child rels.
3537  */
3538  pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
3539 
3540  /* Add all the attributes used by restriction clauses. */
3541  foreach(lc, rel->baserestrictinfo)
3542  {
3543  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3544 
3545  pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
3546  }
3547 
3548  /* Now, are any system columns requested from rel? */
3549  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
3550  {
3552  {
3553  scan_plan->fsSystemCol = true;
3554  break;
3555  }
3556  }
3557 
3558  bms_free(attrs_used);
3559  }
3560 
3561  return scan_plan;
3562 }
3563 
3564 /*
3565  * create_custom_plan
3566  *
3567  * Transform a CustomPath into a Plan.
3568  */
3569 static CustomScan *
3571  List *tlist, List *scan_clauses)
3572 {
3573  CustomScan *cplan;
3574  RelOptInfo *rel = best_path->path.parent;
3575  List *custom_plans = NIL;
3576  ListCell *lc;
3577 
3578  /* Recursively transform child paths. */
3579  foreach(lc, best_path->custom_paths)
3580  {
3581  Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
3582  CP_EXACT_TLIST);
3583 
3584  custom_plans = lappend(custom_plans, plan);
3585  }
3586 
3587  /*
3588  * Sort clauses into the best execution order, although custom-scan
3589  * provider can reorder them again.
3590  */
3591  scan_clauses = order_qual_clauses(root, scan_clauses);
3592 
3593  /*
3594  * Invoke custom plan provider to create the Plan node represented by the
3595  * CustomPath.
3596  */
3597  cplan = castNode(CustomScan,
3598  best_path->methods->PlanCustomPath(root,
3599  rel,
3600  best_path,
3601  tlist,
3602  scan_clauses,
3603  custom_plans));
3604 
3605  /*
3606  * Copy cost data from Path to Plan; no need to make custom-plan providers
3607  * do this
3608  */
3609  copy_generic_path_info(&cplan->scan.plan, &best_path->path);
3610 
3611  /* Likewise, copy the relids that are represented by this custom scan */
3612  cplan->custom_relids = best_path->path.parent->relids;
3613 
3614  /*
3615  * Replace any outer-relation variables with nestloop params in the qual
3616  * and custom_exprs expressions. We do this last so that the custom-plan
3617  * provider doesn't have to be involved. (Note that parts of custom_exprs
3618  * could have come from join clauses, so doing this beforehand on the
3619  * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
3620  * such variables.
3621  */
3622  if (best_path->path.param_info)
3623  {
3624  cplan->scan.plan.qual = (List *)
3625  replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
3626  cplan->custom_exprs = (List *)
3627  replace_nestloop_params(root, (Node *) cplan->custom_exprs);
3628  }
3629 
3630  return cplan;
3631 }
3632 
3633 
3634 /*****************************************************************************
3635  *
3636  * JOIN METHODS
3637  *
3638  *****************************************************************************/
3639 
3640 static NestLoop *
3642  NestPath *best_path)
3643 {
3644  NestLoop *join_plan;
3645  Plan *outer_plan;
3646  Plan *inner_plan;
3647  List *tlist = build_path_tlist(root, &best_path->path);
3648  List *joinrestrictclauses = best_path->joinrestrictinfo;
3649  List *joinclauses;
3650  List *otherclauses;
3651  Relids outerrelids;
3652  List *nestParams;
3653  Relids saveOuterRels = root->curOuterRels;
3654  ListCell *cell;
3655  ListCell *prev;
3656  ListCell *next;
3657 
3658  /* NestLoop can project, so no need to be picky about child tlists */
3659  outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
3660 
3661  /* For a nestloop, include outer relids in curOuterRels for inner side */
3662  root->curOuterRels = bms_union(root->curOuterRels,
3663  best_path->outerjoinpath->parent->relids);
3664 
3665  inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
3666 
3667  /* Restore curOuterRels */
3668  bms_free(root->curOuterRels);
3669  root->curOuterRels = saveOuterRels;
3670 
3671  /* Sort join qual clauses into best execution order */
3672  joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
3673 
3674  /* Get the join qual clauses (in plain expression form) */
3675  /* Any pseudoconstant clauses are ignored here */
3676  if (IS_OUTER_JOIN(best_path->jointype))
3677  {
3678  extract_actual_join_clauses(joinrestrictclauses,
3679  &joinclauses, &otherclauses);
3680  }
3681  else
3682  {
3683  /* We can treat all clauses alike for an inner join */
3684  joinclauses = extract_actual_clauses(joinrestrictclauses, false);
3685  otherclauses = NIL;
3686  }
3687 
3688  /* Replace any outer-relation variables with nestloop params */
3689  if (best_path->path.param_info)
3690  {
3691  joinclauses = (List *)
3692  replace_nestloop_params(root, (Node *) joinclauses);
3693  otherclauses = (List *)
3694  replace_nestloop_params(root, (Node *) otherclauses);
3695  }
3696 
3697  /*
3698  * Identify any nestloop parameters that should be supplied by this join
3699  * node, and move them from root->curOuterParams to the nestParams list.
3700  */
3701  outerrelids = best_path->outerjoinpath->parent->relids;
3702  nestParams = NIL;
3703  prev = NULL;
3704  for (cell = list_head(root->curOuterParams); cell; cell = next)
3705  {
3706  NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
3707 
3708  next = lnext(cell);
3709  if (IsA(nlp->paramval, Var) &&
3710  bms_is_member(nlp->paramval->varno, outerrelids))
3711  {
3713  cell, prev);
3714  nestParams = lappend(nestParams, nlp);
3715  }
3716  else if (IsA(nlp->paramval, PlaceHolderVar) &&
3717  bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
3718  outerrelids) &&
3720  (PlaceHolderVar *) nlp->paramval,
3721  false)->ph_eval_at,
3722  outerrelids))
3723  {
3725  cell, prev);
3726  nestParams = lappend(nestParams, nlp);
3727  }
3728  else
3729  prev = cell;
3730  }
3731 
3732  join_plan = make_nestloop(tlist,
3733  joinclauses,
3734  otherclauses,
3735  nestParams,
3736  outer_plan,
3737  inner_plan,
3738  best_path->jointype,
3739  best_path->inner_unique);
3740 
3741  copy_generic_path_info(&join_plan->join.plan, &best_path->path);
3742 
3743  return join_plan;
3744 }
3745 
3746 static MergeJoin *
3748  MergePath *best_path)
3749 {
3750  MergeJoin *join_plan;
3751  Plan *outer_plan;
3752  Plan *inner_plan;
3753  List *tlist = build_path_tlist(root, &best_path->jpath.path);
3754  List *joinclauses;
3755  List *otherclauses;
3756  List *mergeclauses;
3757  List *outerpathkeys;
3758  List *innerpathkeys;
3759  int nClauses;
3760  Oid *mergefamilies;
3761  Oid *mergecollations;
3762  int *mergestrategies;
3763  bool *mergenullsfirst;
3764  int i;
3765  ListCell *lc;
3766  ListCell *lop;
3767  ListCell *lip;
3768 
3769  /*
3770  * MergeJoin can project, so we don't have to demand exact tlists from the
3771  * inputs. However, if we're intending to sort an input's result, it's
3772  * best to request a small tlist so we aren't sorting more data than
3773  * necessary.
3774  */
3775  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3776  (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3777 
3778  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3779  (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3780 
3781  /* Sort join qual clauses into best execution order */
3782  /* NB: do NOT reorder the mergeclauses */
3783  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3784 
3785  /* Get the join qual clauses (in plain expression form) */
3786  /* Any pseudoconstant clauses are ignored here */
3787  if (IS_OUTER_JOIN(best_path->jpath.jointype))
3788  {
3789  extract_actual_join_clauses(joinclauses,
3790  &joinclauses, &otherclauses);
3791  }
3792  else
3793  {
3794  /* We can treat all clauses alike for an inner join */
3795  joinclauses = extract_actual_clauses(joinclauses, false);
3796  otherclauses = NIL;
3797  }
3798 
3799  /*
3800  * Remove the mergeclauses from the list of join qual clauses, leaving the
3801  * list of quals that must be checked as qpquals.
3802  */
3803  mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
3804  joinclauses = list_difference(joinclauses, mergeclauses);
3805 
3806  /*
3807  * Replace any outer-relation variables with nestloop params. There
3808  * should not be any in the mergeclauses.
3809  */
3810  if (best_path->jpath.path.param_info)
3811  {
3812  joinclauses = (List *)
3813  replace_nestloop_params(root, (Node *) joinclauses);
3814  otherclauses = (List *)
3815  replace_nestloop_params(root, (Node *) otherclauses);
3816  }
3817 
3818  /*
3819  * Rearrange mergeclauses, if needed, so that the outer variable is always
3820  * on the left; mark the mergeclause restrictinfos with correct
3821  * outer_is_left status.
3822  */
3823  mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
3824  best_path->jpath.outerjoinpath->parent->relids);
3825 
3826  /*
3827  * Create explicit sort nodes for the outer and inner paths if necessary.
3828  */
3829  if (best_path->outersortkeys)
3830  {
3831  Sort *sort = make_sort_from_pathkeys(outer_plan,
3832  best_path->outersortkeys);
3833 
3834  label_sort_with_costsize(root, sort, -1.0);
3835  outer_plan = (Plan *) sort;
3836  outerpathkeys = best_path->outersortkeys;
3837  }
3838  else
3839  outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
3840 
3841  if (best_path->innersortkeys)
3842  {
3843  Sort *sort = make_sort_from_pathkeys(inner_plan,
3844  best_path->innersortkeys);
3845 
3846  label_sort_with_costsize(root, sort, -1.0);
3847  inner_plan = (Plan *) sort;
3848  innerpathkeys = best_path->innersortkeys;
3849  }
3850  else
3851  innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
3852 
3853  /*
3854  * If specified, add a materialize node to shield the inner plan from the
3855  * need to handle mark/restore.
3856  */
3857  if (best_path->materialize_inner)
3858  {
3859  Plan *matplan = (Plan *) make_material(inner_plan);
3860 
3861  /*
3862  * We assume the materialize will not spill to disk, and therefore
3863  * charge just cpu_operator_cost per tuple. (Keep this estimate in
3864  * sync with final_cost_mergejoin.)
3865  */
3866  copy_plan_costsize(matplan, inner_plan);
3867  matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
3868 
3869  inner_plan = matplan;
3870  }
3871 
3872  /*
3873  * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
3874  * executor. The information is in the pathkeys for the two inputs, but
3875  * we need to be careful about the possibility of mergeclauses sharing a
3876  * pathkey (compare find_mergeclauses_for_pathkeys()).
3877  */
3878  nClauses = list_length(mergeclauses);
3879  Assert(nClauses == list_length(best_path->path_mergeclauses));
3880  mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
3881  mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
3882  mergestrategies = (int *) palloc(nClauses * sizeof(int));
3883  mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
3884 
3885  lop = list_head(outerpathkeys);
3886  lip = list_head(innerpathkeys);
3887  i = 0;
3888  foreach(lc, best_path->path_mergeclauses)
3889  {
3890  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3891  EquivalenceClass *oeclass;
3892  EquivalenceClass *ieclass;
3893  PathKey *opathkey;
3894  PathKey *ipathkey;
3895  EquivalenceClass *opeclass;
3896  EquivalenceClass *ipeclass;
3897  ListCell *l2;
3898 
3899  /* fetch outer/inner eclass from mergeclause */
3900  if (rinfo->outer_is_left)
3901  {
3902  oeclass = rinfo->left_ec;
3903  ieclass = rinfo->right_ec;
3904  }
3905  else
3906  {
3907  oeclass = rinfo->right_ec;
3908  ieclass = rinfo->left_ec;
3909  }
3910  Assert(oeclass != NULL);
3911  Assert(ieclass != NULL);
3912 
3913  /*
3914  * For debugging purposes, we check that the eclasses match the paths'
3915  * pathkeys. In typical cases the merge clauses are one-to-one with
3916  * the pathkeys, but when dealing with partially redundant query
3917  * conditions, we might have clauses that re-reference earlier path
3918  * keys. The case that we need to reject is where a pathkey is
3919  * entirely skipped over.
3920  *
3921  * lop and lip reference the first as-yet-unused pathkey elements;
3922  * it's okay to match them, or any element before them. If they're
3923  * NULL then we have found all pathkey elements to be used.
3924  */
3925  if (lop)
3926  {
3927  opathkey = (PathKey *) lfirst(lop);
3928  opeclass = opathkey->pk_eclass;
3929  if (oeclass == opeclass)
3930  {
3931  /* fast path for typical case */
3932  lop = lnext(lop);
3933  }
3934  else
3935  {
3936  /* redundant clauses ... must match something before lop */
3937  foreach(l2, outerpathkeys)
3938  {
3939  if (l2 == lop)
3940  break;
3941  opathkey = (PathKey *) lfirst(l2);
3942  opeclass = opathkey->pk_eclass;
3943  if (oeclass == opeclass)
3944  break;
3945  }
3946  if (oeclass != opeclass)
3947  elog(ERROR, "outer pathkeys do not match mergeclauses");
3948  }
3949  }
3950  else
3951  {
3952  /* redundant clauses ... must match some already-used pathkey */
3953  opathkey = NULL;
3954  opeclass = NULL;
3955  foreach(l2, outerpathkeys)
3956  {
3957  opathkey = (PathKey *) lfirst(l2);
3958  opeclass = opathkey->pk_eclass;
3959  if (oeclass == opeclass)
3960  break;
3961  }
3962  if (l2 == NULL)
3963  elog(ERROR, "outer pathkeys do not match mergeclauses");
3964  }
3965 
3966  if (lip)
3967  {
3968  ipathkey = (PathKey *) lfirst(lip);
3969  ipeclass = ipathkey->pk_eclass;
3970  if (ieclass == ipeclass)
3971  {
3972  /* fast path for typical case */
3973  lip = lnext(lip);
3974  }
3975  else
3976  {
3977  /* redundant clauses ... must match something before lip */
3978  foreach(l2, innerpathkeys)
3979  {
3980  if (l2 == lip)
3981  break;
3982  ipathkey = (PathKey *) lfirst(l2);
3983  ipeclass = ipathkey->pk_eclass;
3984  if (ieclass == ipeclass)
3985  break;
3986  }
3987  if (ieclass != ipeclass)
3988  elog(ERROR, "inner pathkeys do not match mergeclauses");
3989  }
3990  }
3991  else
3992  {
3993  /* redundant clauses ... must match some already-used pathkey */
3994  ipathkey = NULL;
3995  ipeclass = NULL;
3996  foreach(l2, innerpathkeys)
3997  {
3998  ipathkey = (PathKey *) lfirst(l2);
3999  ipeclass = ipathkey->pk_eclass;
4000  if (ieclass == ipeclass)
4001  break;
4002  }
4003  if (l2 == NULL)
4004  elog(ERROR, "inner pathkeys do not match mergeclauses");
4005  }
4006 
4007  /* pathkeys should match each other too (more debugging) */
4008  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4009  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
4010  opathkey->pk_strategy != ipathkey->pk_strategy ||
4011  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
4012  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4013 
4014  /* OK, save info for executor */
4015  mergefamilies[i] = opathkey->pk_opfamily;
4016  mergecollations[i] = opathkey->pk_eclass->ec_collation;
4017  mergestrategies[i] = opathkey->pk_strategy;
4018  mergenullsfirst[i] = opathkey->pk_nulls_first;
4019  i++;
4020  }
4021 
4022  /*
4023  * Note: it is not an error if we have additional pathkey elements (i.e.,
4024  * lop or lip isn't NULL here). The input paths might be better-sorted
4025  * than we need for the current mergejoin.
4026  */
4027 
4028  /*
4029  * Now we can build the mergejoin node.
4030  */
4031  join_plan = make_mergejoin(tlist,
4032  joinclauses,
4033  otherclauses,
4034  mergeclauses,
4035  mergefamilies,
4036  mergecollations,
4037  mergestrategies,
4038  mergenullsfirst,
4039  outer_plan,
4040  inner_plan,
4041  best_path->jpath.jointype,
4042  best_path->jpath.inner_unique,
4043  best_path->skip_mark_restore);
4044 
4045  /* Costs of sort and material steps are included in path cost already */
4046  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4047 
4048  return join_plan;
4049 }
4050 
4051 static HashJoin *
4053  HashPath *best_path)
4054 {
4055  HashJoin *join_plan;
4056  Hash *hash_plan;
4057  Plan *outer_plan;
4058  Plan *inner_plan;
4059  List *tlist = build_path_tlist(root, &best_path->jpath.path);
4060  List *joinclauses;
4061  List *otherclauses;
4062  List *hashclauses;
4063  Oid skewTable = InvalidOid;
4064  AttrNumber skewColumn = InvalidAttrNumber;
4065  bool skewInherit = false;
4066 
4067  /*
4068  * HashJoin can project, so we don't have to demand exact tlists from the
4069  * inputs. However, it's best to request a small tlist from the inner
4070  * side, so that we aren't storing more data than necessary. Likewise, if
4071  * we anticipate batching, request a small tlist from the outer side so
4072  * that we don't put extra data in the outer batch files.
4073  */
4074  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4075  (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4076 
4077  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4078  CP_SMALL_TLIST);
4079 
4080  /* Sort join qual clauses into best execution order */
4081  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4082  /* There's no point in sorting the hash clauses ... */
4083 
4084  /* Get the join qual clauses (in plain expression form) */
4085  /* Any pseudoconstant clauses are ignored here */
4086  if (IS_OUTER_JOIN(best_path->jpath.jointype))
4087  {
4088  extract_actual_join_clauses(joinclauses,
4089  &joinclauses, &otherclauses);
4090  }
4091  else
4092  {
4093  /* We can treat all clauses alike for an inner join */
4094  joinclauses = extract_actual_clauses(joinclauses, false);
4095  otherclauses = NIL;
4096  }
4097 
4098  /*
4099  * Remove the hashclauses from the list of join qual clauses, leaving the
4100  * list of quals that must be checked as qpquals.
4101  */
4102  hashclauses = get_actual_clauses(best_path->path_hashclauses);
4103  joinclauses = list_difference(joinclauses, hashclauses);
4104 
4105  /*
4106  * Replace any outer-relation variables with nestloop params. There
4107  * should not be any in the hashclauses.
4108  */
4109  if (best_path->jpath.path.param_info)
4110  {
4111  joinclauses = (List *)
4112  replace_nestloop_params(root, (Node *) joinclauses);
4113  otherclauses = (List *)
4114  replace_nestloop_params(root, (Node *) otherclauses);
4115  }
4116 
4117  /*
4118  * Rearrange hashclauses, if needed, so that the outer variable is always
4119  * on the left.
4120  */
4121  hashclauses = get_switched_clauses(best_path->path_hashclauses,
4122  best_path->jpath.outerjoinpath->parent->relids);
4123 
4124  /*
4125  * If there is a single join clause and we can identify the outer variable
4126  * as a simple column reference, supply its identity for possible use in
4127  * skew optimization. (Note: in principle we could do skew optimization
4128  * with multiple join clauses, but we'd have to be able to determine the
4129  * most common combinations of outer values, which we don't currently have
4130  * enough stats for.)
4131  */
4132  if (list_length(hashclauses) == 1)
4133  {
4134  OpExpr *clause = (OpExpr *) linitial(hashclauses);
4135  Node *node;
4136 
4137  Assert(is_opclause(clause));
4138  node = (Node *) linitial(clause->args);
4139  if (IsA(node, RelabelType))
4140  node = (Node *) ((RelabelType *) node)->arg;
4141  if (IsA(node, Var))
4142  {
4143  Var *var = (Var *) node;
4144  RangeTblEntry *rte;
4145 
4146  rte = root->simple_rte_array[var->varno];
4147  if (rte->rtekind == RTE_RELATION)
4148  {
4149  skewTable = rte->relid;
4150  skewColumn = var->varattno;
4151  skewInherit = rte->inh;
4152  }
4153  }
4154  }
4155 
4156  /*
4157  * Build the hash node and hash join node.
4158  */
4159  hash_plan = make_hash(inner_plan,
4160  skewTable,
4161  skewColumn,
4162  skewInherit);
4163 
4164  /*
4165  * Set Hash node's startup & total costs equal to total cost of input
4166  * plan; this only affects EXPLAIN display not decisions.
4167  */
4168  copy_plan_costsize(&hash_plan->plan, inner_plan);
4169  hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4170 
4171  join_plan = make_hashjoin(tlist,
4172  joinclauses,
4173  otherclauses,
4174  hashclauses,
4175  outer_plan,
4176  (Plan *) hash_plan,
4177  best_path->jpath.jointype,
4178  best_path->jpath.inner_unique);
4179 
4180  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4181 
4182  return join_plan;
4183 }
4184 
4185 
4186 /*****************************************************************************
4187  *
4188  * SUPPORTING ROUTINES
4189  *
4190  *****************************************************************************/
4191 
4192 /*
4193  * replace_nestloop_params
4194  * Replace outer-relation Vars and PlaceHolderVars in the given expression
4195  * with nestloop Params
4196  *
4197  * All Vars and PlaceHolderVars belonging to the relation(s) identified by
4198  * root->curOuterRels are replaced by Params, and entries are added to
4199  * root->curOuterParams if not already present.
4200  */
4201 static Node *
4203 {
4204  /* No setup needed for tree walk, so away we go */
4205  return replace_nestloop_params_mutator(expr, root);
4206 }
4207 
4208 static Node *
4210 {
4211  if (node == NULL)
4212  return NULL;
4213  if (IsA(node, Var))
4214  {
4215  Var *var = (Var *) node;
4216  Param *param;
4217  NestLoopParam *nlp;
4218  ListCell *lc;
4219 
4220  /* Upper-level Vars should be long gone at this point */
4221  Assert(var->varlevelsup == 0);
4222  /* If not to be replaced, we can just return the Var unmodified */
4223  if (!bms_is_member(var->varno, root->curOuterRels))
4224  return node;
4225  /* Create a Param representing the Var */
4226  param = assign_nestloop_param_var(root, var);
4227  /* Is this param already listed in root->curOuterParams? */
4228  foreach(lc, root->curOuterParams)
4229  {
4230  nlp = (NestLoopParam *) lfirst(lc);
4231  if (nlp->paramno == param->paramid)
4232  {
4233  Assert(equal(var, nlp->paramval));
4234  /* Present, so we can just return the Param */
4235  return (Node *) param;
4236  }
4237  }
4238  /* No, so add it */
4239  nlp = makeNode(NestLoopParam);
4240  nlp->paramno = param->paramid;
4241  nlp->paramval = var;
4242  root->curOuterParams = lappend(root->curOuterParams, nlp);
4243  /* And return the replacement Param */
4244  return (Node *) param;
4245  }
4246  if (IsA(node, PlaceHolderVar))
4247  {
4248  PlaceHolderVar *phv = (PlaceHolderVar *) node;
4249  Param *param;
4250  NestLoopParam *nlp;
4251  ListCell *lc;
4252 
4253  /* Upper-level PlaceHolderVars should be long gone at this point */
4254  Assert(phv->phlevelsup == 0);
4255 
4256  /*
4257  * Check whether we need to replace the PHV. We use bms_overlap as a
4258  * cheap/quick test to see if the PHV might be evaluated in the outer
4259  * rels, and then grab its PlaceHolderInfo to tell for sure.
4260  */
4261  if (!bms_overlap(phv->phrels, root->curOuterRels) ||
4262  !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4263  root->curOuterRels))
4264  {
4265  /*
4266  * We can't replace the whole PHV, but we might still need to
4267  * replace Vars or PHVs within its expression, in case it ends up
4268  * actually getting evaluated here. (It might get evaluated in
4269  * this plan node, or some child node; in the latter case we don't
4270  * really need to process the expression here, but we haven't got
4271  * enough info to tell if that's the case.) Flat-copy the PHV
4272  * node and then recurse on its expression.
4273  *
4274  * Note that after doing this, we might have different
4275  * representations of the contents of the same PHV in different
4276  * parts of the plan tree. This is OK because equal() will just
4277  * match on phid/phlevelsup, so setrefs.c will still recognize an
4278  * upper-level reference to a lower-level copy of the same PHV.
4279  */
4281 
4282  memcpy(newphv, phv, sizeof(PlaceHolderVar));
4283  newphv->phexpr = (Expr *)
4285  root);
4286  return (Node *) newphv;
4287  }
4288  /* Create a Param representing the PlaceHolderVar */
4289  param = assign_nestloop_param_placeholdervar(root, phv);
4290  /* Is this param already listed in root->curOuterParams? */
4291  foreach(lc, root->curOuterParams)
4292  {
4293  nlp = (NestLoopParam *) lfirst(lc);
4294  if (nlp->paramno == param->paramid)
4295  {
4296  Assert(equal(phv, nlp->paramval));
4297  /* Present, so we can just return the Param */
4298  return (Node *) param;
4299  }
4300  }
4301  /* No, so add it */
4302  nlp = makeNode(NestLoopParam);
4303  nlp->paramno = param->paramid;
4304  nlp->paramval = (Var *) phv;
4305  root->curOuterParams = lappend(root->curOuterParams, nlp);
4306  /* And return the replacement Param */
4307  return (Node *) param;
4308  }
4309  return expression_tree_mutator(node,
4311  (void *) root);
4312 }
4313 
4314 /*
4315  * process_subquery_nestloop_params
4316  * Handle params of a parameterized subquery that need to be fed
4317  * from an outer nestloop.
4318  *
4319  * Currently, that would be *all* params that a subquery in FROM has demanded
4320  * from the current query level, since they must be LATERAL references.
4321  *
4322  * The subplan's references to the outer variables are already represented
4323  * as PARAM_EXEC Params, so we need not modify the subplan here. What we
4324  * do need to do is add entries to root->curOuterParams to signal the parent
4325  * nestloop plan node that it must provide these values.
4326  */
4327 static void
4329 {
4330  ListCell *ppl;
4331 
4332  foreach(ppl, subplan_params)
4333  {
4334  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
4335 
4336  if (IsA(pitem->item, Var))
4337  {
4338  Var *var = (Var *) pitem->item;
4339  NestLoopParam *nlp;
4340  ListCell *lc;
4341 
4342  /* If not from a nestloop outer rel, complain */
4343  if (!bms_is_member(var->varno, root->curOuterRels))
4344  elog(ERROR, "non-LATERAL parameter required by subquery");
4345  /* Is this param already listed in root->curOuterParams? */
4346  foreach(lc, root->curOuterParams)
4347  {
4348  nlp = (NestLoopParam *) lfirst(lc);
4349  if (nlp->paramno == pitem->paramId)
4350  {
4351  Assert(equal(var, nlp->paramval));
4352  /* Present, so nothing to do */
4353  break;
4354  }
4355  }
4356  if (lc == NULL)
4357  {
4358  /* No, so add it */
4359  nlp = makeNode(NestLoopParam);
4360  nlp->paramno = pitem->paramId;
4361  nlp->paramval = copyObject(var);
4362  root->curOuterParams = lappend(root->curOuterParams, nlp);
4363  }
4364  }
4365  else if (IsA(pitem->item, PlaceHolderVar))
4366  {
4367  PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
4368  NestLoopParam *nlp;
4369  ListCell *lc;
4370 
4371  /* If not from a nestloop outer rel, complain */
4372  if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4373  root->curOuterRels))
4374  elog(ERROR, "non-LATERAL parameter required by subquery");
4375  /* Is this param already listed in root->curOuterParams? */
4376  foreach(lc, root->curOuterParams)
4377  {
4378  nlp = (NestLoopParam *) lfirst(lc);
4379  if (nlp->paramno == pitem->paramId)
4380  {
4381  Assert(equal(phv, nlp->paramval));
4382  /* Present, so nothing to do */
4383  break;
4384  }
4385  }
4386  if (lc == NULL)
4387  {
4388  /* No, so add it */
4389  nlp = makeNode(NestLoopParam);
4390  nlp->paramno = pitem->paramId;
4391  nlp->paramval = (Var *) copyObject(phv);
4392  root->curOuterParams = lappend(root->curOuterParams, nlp);
4393  }
4394  }
4395  else
4396  elog(ERROR, "unexpected type of subquery parameter");
4397  }
4398 }
4399 
4400 /*
4401  * fix_indexqual_references
4402  * Adjust indexqual clauses to the form the executor's indexqual
4403  * machinery needs.
4404  *
4405  * We have four tasks here:
4406  * * Remove RestrictInfo nodes from the input clauses.
4407  * * Replace any outer-relation Var or PHV nodes with nestloop Params.
4408  * (XXX eventually, that responsibility should go elsewhere?)
4409  * * Index keys must be represented by Var nodes with varattno set to the
4410  * index's attribute number, not the attribute number in the original rel.
4411  * * If the index key is on the right, commute the clause to put it on the
4412  * left.
4413  *
4414  * The result is a modified copy of the path's indexquals list --- the
4415  * original is not changed. Note also that the copy shares no substructure
4416  * with the original; this is needed in case there is a subplan in it (we need
4417  * two separate copies of the subplan tree, or things will go awry).
4418  */
4419 static List *
4421 {
4422  IndexOptInfo *index = index_path->indexinfo;
4423  List *fixed_indexquals;
4424  ListCell *lcc,
4425  *lci;
4426 
4427  fixed_indexquals = NIL;
4428 
4429  forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
4430  {
4431  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
4432  int indexcol = lfirst_int(lci);
4433  Node *clause;
4434 
4435  /*
4436  * Replace any outer-relation variables with nestloop params.
4437  *
4438  * This also makes a copy of the clause, so it's safe to modify it
4439  * in-place below.
4440  */
4441  clause = replace_nestloop_params(root, (Node *) rinfo->clause);
4442 
4443  if (IsA(clause, OpExpr))
4444  {
4445  OpExpr *op = (OpExpr *) clause;
4446 
4447  if (list_length(op->args) != 2)
4448  elog(ERROR, "indexqual clause is not binary opclause");
4449 
4450  /*
4451  * Check to see if the indexkey is on the right; if so, commute
4452  * the clause. The indexkey should be the side that refers to
4453  * (only) the base relation.
4454  */
4455  if (!bms_equal(rinfo->left_relids, index->rel->relids))
4456  CommuteOpExpr(op);
4457 
4458  /*
4459  * Now replace the indexkey expression with an index Var.
4460  */
4462  index,
4463  indexcol);
4464  }
4465  else if (IsA(clause, RowCompareExpr))
4466  {
4467  RowCompareExpr *rc = (RowCompareExpr *) clause;
4468  Expr *newrc;
4469  List *indexcolnos;
4470  bool var_on_left;
4471  ListCell *lca,
4472  *lcai;
4473 
4474  /*
4475  * Re-discover which index columns are used in the rowcompare.
4476  */
4477  newrc = adjust_rowcompare_for_index(rc,
4478  index,
4479  indexcol,
4480  &indexcolnos,
4481  &var_on_left);
4482 
4483  /*
4484  * Trouble if adjust_rowcompare_for_index thought the
4485  * RowCompareExpr didn't match the index as-is; the clause should
4486  * have gone through that routine already.
4487  */
4488  if (newrc != (Expr *) rc)
4489  elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
4490 
4491  /*
4492  * Check to see if the indexkey is on the right; if so, commute
4493  * the clause.
4494  */
4495  if (!var_on_left)
4497 
4498  /*
4499  * Now replace the indexkey expressions with index Vars.
4500  */
4501  Assert(list_length(rc->largs) == list_length(indexcolnos));
4502  forboth(lca, rc->largs, lcai, indexcolnos)
4503  {
4504  lfirst(lca) = fix_indexqual_operand(lfirst(lca),
4505  index,
4506  lfirst_int(lcai));
4507  }
4508  }
4509  else if (IsA(clause, ScalarArrayOpExpr))
4510  {
4511  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
4512 
4513  /* Never need to commute... */
4514 
4515  /* Replace the indexkey expression with an index Var. */
4517  index,
4518  indexcol);
4519  }
4520  else if (IsA(clause, NullTest))
4521  {
4522  NullTest *nt = (NullTest *) clause;
4523 
4524  /* Replace the indexkey expression with an index Var. */
4525  nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
4526  index,
4527  indexcol);
4528  }
4529  else
4530  elog(ERROR, "unsupported indexqual type: %d",
4531  (int) nodeTag(clause));
4532 
4533  fixed_indexquals = lappend(fixed_indexquals, clause);
4534  }
4535 
4536  return fixed_indexquals;
4537 }
4538 
4539 /*
4540  * fix_indexorderby_references
4541  * Adjust indexorderby clauses to the form the executor's index
4542  * machinery needs.
4543  *
4544  * This is a simplified version of fix_indexqual_references. The input does
4545  * not have RestrictInfo nodes, and we assume that indxpath.c already
4546  * commuted the clauses to put the index keys on the left. Also, we don't
4547  * bother to support any cases except simple OpExprs, since nothing else
4548  * is allowed for ordering operators.
4549  */
4550 static List *
4552 {
4553  IndexOptInfo *index = index_path->indexinfo;
4554  List *fixed_indexorderbys;
4555  ListCell *lcc,
4556  *lci;
4557 
4558  fixed_indexorderbys = NIL;
4559 
4560  forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
4561  {
4562  Node *clause = (Node *) lfirst(lcc);
4563  int indexcol = lfirst_int(lci);
4564 
4565  /*
4566  * Replace any outer-relation variables with nestloop params.
4567  *
4568  * This also makes a copy of the clause, so it's safe to modify it
4569  * in-place below.
4570  */
4571  clause = replace_nestloop_params(root, clause);
4572 
4573  if (IsA(clause, OpExpr))
4574  {
4575  OpExpr *op = (OpExpr *) clause;
4576 
4577  if (list_length(op->args) != 2)
4578  elog(ERROR, "indexorderby clause is not binary opclause");
4579 
4580  /*
4581  * Now replace the indexkey expression with an index Var.
4582  */
4584  index,
4585  indexcol);
4586  }
4587  else
4588  elog(ERROR, "unsupported indexorderby type: %d",
4589  (int) nodeTag(clause));
4590 
4591  fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
4592  }
4593 
4594  return fixed_indexorderbys;
4595 }
4596 
4597 /*
4598  * fix_indexqual_operand
4599  * Convert an indexqual expression to a Var referencing the index column.
4600  *
4601  * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
4602  * equal to the index's attribute number (index column position).
4603  *
4604  * Most of the code here is just for sanity cross-checking that the given
4605  * expression actually matches the index column it's claimed to.
4606  */
4607 static Node *
4609 {
4610  Var *result;
4611  int pos;
4612  ListCell *indexpr_item;
4613 
4614  /*
4615  * Remove any binary-compatible relabeling of the indexkey
4616  */
4617  if (IsA(node, RelabelType))
4618  node = (Node *) ((RelabelType *) node)->arg;
4619 
4620  Assert(indexcol >= 0 && indexcol < index->ncolumns);
4621 
4622  if (index->indexkeys[indexcol] != 0)
4623  {
4624  /* It's a simple index column */
4625  if (IsA(node, Var) &&
4626  ((Var *) node)->varno == index->rel->relid &&
4627  ((Var *) node)->varattno == index->indexkeys[indexcol])
4628  {
4629  result = (Var *) copyObject(node);
4630  result->varno = INDEX_VAR;
4631  result->varattno = indexcol + 1;
4632  return (Node *) result;
4633  }
4634  else
4635  elog(ERROR, "index key does not match expected index column");
4636  }
4637 
4638  /* It's an index expression, so find and cross-check the expression */
4639  indexpr_item = list_head(index->indexprs);
4640  for (pos = 0; pos < index->ncolumns; pos++)
4641  {
4642  if (index->indexkeys[pos] == 0)
4643  {
4644  if (indexpr_item == NULL)
4645  elog(ERROR, "too few entries in indexprs list");
4646  if (pos == indexcol)
4647  {
4648  Node *indexkey;
4649 
4650  indexkey = (Node *) lfirst(indexpr_item);
4651  if (indexkey && IsA(indexkey, RelabelType))
4652  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4653  if (equal(node, indexkey))
4654  {
4655  result = makeVar(INDEX_VAR, indexcol + 1,
4656  exprType(lfirst(indexpr_item)), -1,
4657  exprCollation(lfirst(indexpr_item)),
4658  0);
4659  return (Node *) result;
4660  }
4661  else
4662  elog(ERROR, "index key does not match expected index column");
4663  }
4664  indexpr_item = lnext(indexpr_item);
4665  }
4666  }
4667 
4668  /* Oops... */
4669  elog(ERROR, "index key does not match expected index column");
4670  return NULL; /* keep compiler quiet */
4671 }
4672 
4673 /*
4674  * get_switched_clauses
4675  * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
4676  * extract the bare clauses, and rearrange the elements within the
4677  * clauses, if needed, so the outer join variable is on the left and
4678  * the inner is on the right. The original clause data structure is not
4679  * touched; a modified list is returned. We do, however, set the transient
4680  * outer_is_left field in each RestrictInfo to show which side was which.
4681  */
4682 static List *
4683 get_switched_clauses(List *clauses, Relids outerrelids)
4684 {
4685  List *t_list = NIL;
4686  ListCell *l;
4687 
4688  foreach(l, clauses)
4689  {
4690  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
4691  OpExpr *clause = (OpExpr *) restrictinfo->clause;
4692 
4693  Assert(is_opclause(clause));
4694  if (bms_is_subset(restrictinfo->right_relids, outerrelids))
4695  {
4696  /*
4697  * Duplicate just enough of the structure to allow commuting the
4698  * clause without changing the original list. Could use
4699  * copyObject, but a complete deep copy is overkill.
4700  */
4701  OpExpr *temp = makeNode(OpExpr);
4702 
4703  temp->opno = clause->opno;
4704  temp->opfuncid = InvalidOid;
4705  temp->opresulttype = clause->opresulttype;
4706  temp->opretset = clause->opretset;
4707  temp->opcollid = clause->opcollid;
4708  temp->inputcollid = clause->inputcollid;
4709  temp->args = list_copy(clause->args);
4710  temp->location = clause->location;
4711  /* Commute it --- note this modifies the temp node in-place. */
4712  CommuteOpExpr(temp);
4713  t_list = lappend(t_list, temp);
4714  restrictinfo->outer_is_left = false;
4715  }
4716  else
4717  {
4718  Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
4719  t_list = lappend(t_list, clause);
4720  restrictinfo->outer_is_left = true;
4721  }
4722  }
4723  return t_list;
4724 }
4725 
4726 /*
4727  * order_qual_clauses
4728  * Given a list of qual clauses that will all be evaluated at the same
4729  * plan node, sort the list into the order we want to check the quals
4730  * in at runtime.
4731  *
4732  * When security barrier quals are used in the query, we may have quals with
4733  * different security levels in the list. Quals of lower security_level
4734  * must go before quals of higher security_level, except that we can grant
4735  * exceptions to move up quals that are leakproof. When security level
4736  * doesn't force the decision, we prefer to order clauses by estimated
4737  * execution cost, cheapest first.
4738  *
4739  * Ideally the order should be driven by a combination of execution cost and
4740  * selectivity, but it's not immediately clear how to account for both,
4741  * and given the uncertainty of the estimates the reliability of the decisions
4742  * would be doubtful anyway. So we just order by security level then
4743  * estimated per-tuple cost, being careful not to change the order when
4744  * (as is often the case) the estimates are identical.
4745  *
4746  * Although this will work on either bare clauses or RestrictInfos, it's
4747  * much faster to apply it to RestrictInfos, since it can re-use cost
4748  * information that is cached in RestrictInfos. XXX in the bare-clause
4749  * case, we are also not able to apply security considerations. That is
4750  * all right for the moment, because the bare-clause case doesn't occur
4751  * anywhere that barrier quals could be present, but it would be better to
4752  * get rid of it.
4753  *
4754  * Note: some callers pass lists that contain entries that will later be
4755  * removed; this is the easiest way to let this routine see RestrictInfos
4756  * instead of bare clauses. This is another reason why trying to consider
4757  * selectivity in the ordering would likely do the wrong thing.
4758  */
4759 static List *
4761 {
4762  typedef struct
4763  {
4764  Node *clause;
4765  Cost cost;
4766  Index security_level;
4767  } QualItem;
4768  int nitems = list_length(clauses);
4769  QualItem *items;
4770  ListCell *lc;
4771  int i;
4772  List *result;
4773 
4774  /* No need to work hard for 0 or 1 clause */
4775  if (nitems <= 1)
4776  return clauses;
4777 
4778  /*
4779  * Collect the items and costs into an array. This is to avoid repeated
4780  * cost_qual_eval work if the inputs aren't RestrictInfos.
4781  */
4782  items = (QualItem *) palloc(nitems * sizeof(QualItem));
4783  i = 0;
4784  foreach(lc, clauses)
4785  {
4786  Node *clause = (Node *) lfirst(lc);
4787  QualCost qcost;
4788 
4789  cost_qual_eval_node(&qcost, clause, root);
4790  items[i].clause = clause;
4791  items[i].cost = qcost.per_tuple;
4792  if (IsA(clause, RestrictInfo))
4793  {
4794  RestrictInfo *rinfo = (RestrictInfo *) clause;
4795 
4796  /*
4797  * If a clause is leakproof, it doesn't have to be constrained by
4798  * its nominal security level. If it's also reasonably cheap
4799  * (here defined as 10X cpu_operator_cost), pretend it has
4800  * security_level 0, which will allow it to go in front of
4801  * more-expensive quals of lower security levels. Of course, that
4802  * will also force it to go in front of cheaper quals of its own
4803  * security level, which is not so great, but we can alleviate
4804  * that risk by applying the cost limit cutoff.
4805  */
4806  if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
4807  items[i].security_level = 0;
4808  else
4809  items[i].security_level = rinfo->security_level;
4810  }
4811  else
4812  items[i].security_level = 0;
4813  i++;
4814  }
4815 
4816  /*
4817  * Sort. We don't use qsort() because it's not guaranteed stable for
4818  * equal keys. The expected number of entries is small enough that a
4819  * simple insertion sort should be good enough.
4820  */
4821  for (i = 1; i < nitems; i++)
4822  {
4823  QualItem newitem = items[i];
4824  int j;
4825 
4826  /* insert newitem into the already-sorted subarray */
4827  for (j = i; j > 0; j--)
4828  {
4829  QualItem *olditem = &items[j - 1];
4830 
4831  if (newitem.security_level > olditem->security_level ||
4832  (newitem.security_level == olditem->security_level &&
4833  newitem.cost >= olditem->cost))
4834  break;
4835  items[j] = *olditem;
4836  }
4837  items[j] = newitem;
4838  }
4839 
4840  /* Convert back to a list */
4841  result = NIL;
4842  for (i = 0; i < nitems; i++)
4843  result = lappend(result, items[i].clause);
4844 
4845  return result;
4846 }
4847 
4848 /*
4849  * Copy cost and size info from a Path node to the Plan node created from it.
4850  * The executor usually won't use this info, but it's needed by EXPLAIN.
4851  * Also copy the parallel-related flags, which the executor *will* use.
4852  */
4853 static void
4855 {
4856  dest->startup_cost = src->startup_cost;
4857  dest->total_cost = src->total_cost;
4858  dest->plan_rows = src->rows;
4859  dest->plan_width = src->pathtarget->width;
4860  dest->parallel_aware = src->parallel_aware;
4861  dest->parallel_safe = src->parallel_safe;
4862 }
4863 
4864 /*
4865  * Copy cost and size info from a lower plan node to an inserted node.
4866  * (Most callers alter the info after copying it.)
4867  */
4868 static void
4870 {
4871  dest->startup_cost = src->startup_cost;
4872  dest->total_cost = src->total_cost;
4873  dest->plan_rows = src->plan_rows;
4874  dest->plan_width = src->plan_width;
4875  /* Assume the inserted node is not parallel-aware. */
4876  dest->parallel_aware = false;
4877  /* Assume the inserted node is parallel-safe, if child plan is. */
4878  dest->parallel_safe = src->parallel_safe;
4879 }
4880 
4881 /*
4882  * Some places in this file build Sort nodes that don't have a directly
4883  * corresponding Path node. The cost of the sort is, or should have been,
4884  * included in the cost of the Path node we're working from, but since it's
4885  * not split out, we have to re-figure it using cost_sort(). This is just
4886  * to label the Sort node nicely for EXPLAIN.
4887  *
4888  * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4889  */
4890 static void
4891 label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
4892 {
4893  Plan *lefttree = plan->plan.lefttree;
4894  Path sort_path; /* dummy for result of cost_sort */
4895 
4896  cost_sort(&sort_path, root, NIL,
4897  lefttree->total_cost,
4898  lefttree->plan_rows,
4899  lefttree->plan_width,
4900  0.0,
4901  work_mem,
4902  limit_tuples);
4903  plan->plan.startup_cost = sort_path.startup_cost;
4904  plan->plan.total_cost = sort_path.total_cost;
4905  plan->plan.plan_rows = lefttree->plan_rows;
4906  plan->plan.plan_width = lefttree->plan_width;
4907  plan->plan.parallel_aware = false;
4908  plan->plan.parallel_safe = lefttree->parallel_safe;
4909 }
4910 
4911 /*
4912  * bitmap_subplan_mark_shared
4913  * Set isshared flag in bitmap subplan so that it will be created in
4914  * shared memory.
4915  */
4916 static void
4918 {
4919  if (IsA(plan, BitmapAnd))
4921  linitial(((BitmapAnd *) plan)->bitmapplans));
4922  else if (IsA(plan, BitmapOr))
4923  ((BitmapOr *) plan)->isshared = true;
4924  else if (IsA(plan, BitmapIndexScan))
4925  ((BitmapIndexScan *) plan)->isshared = true;
4926  else
4927  elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
4928 }
4929 
4930 /*****************************************************************************
4931  *
4932  * PLAN NODE BUILDING ROUTINES
4933  *
4934  * In general, these functions are not passed the original Path and therefore
4935  * leave it to the caller to fill in the cost/width fields from the Path,
4936  * typically by calling copy_generic_path_info(). This convention is
4937  * somewhat historical, but it does support a few places above where we build
4938  * a plan node without having an exactly corresponding Path node. Under no
4939  * circumstances should one of these functions do its own cost calculations,
4940  * as that would be redundant with calculations done while building Paths.
4941  *
4942  *****************************************************************************/
4943 
4944 static SeqScan *
4946  List *qpqual,
4947  Index scanrelid)
4948 {
4949  SeqScan *node = makeNode(SeqScan);
4950  Plan *plan = &node->plan;
4951 
4952  plan->targetlist = qptlist;
4953  plan->qual = qpqual;
4954  plan->lefttree = NULL;
4955  plan->righttree = NULL;
4956  node->scanrelid = scanrelid;
4957 
4958  return node;
4959 }
4960 
4961 static SampleScan *
4963  List *qpqual,
4964  Index scanrelid,
4965  TableSampleClause *tsc)
4966 {
4967  SampleScan *node = makeNode(SampleScan);
4968  Plan *plan = &node->scan.plan;
4969 
4970  plan->targetlist = qptlist;
4971  plan->qual = qpqual;
4972  plan->lefttree = NULL;
4973  plan->righttree = NULL;
4974  node->scan.scanrelid = scanrelid;
4975  node->tablesample = tsc;
4976 
4977  return node;
4978 }
4979 
4980 static IndexScan *
4982  List *qpqual,
4983  Index scanrelid,
4984  Oid indexid,
4985  List *indexqual,
4986  List *indexqualorig,
4987  List *indexorderby,
4988  List *indexorderbyorig,
4989  List *indexorderbyops,
4990  ScanDirection indexscandir)
4991 {
4992  IndexScan *node = makeNode(IndexScan);
4993  Plan *plan = &node->scan.plan;
4994 
4995  plan->targetlist = qptlist;
4996  plan->qual = qpqual;
4997  plan->lefttree = NULL;
4998  plan->righttree = NULL;
4999  node->scan.scanrelid = scanrelid;
5000  node->indexid = indexid;
5001  node->indexqual = indexqual;
5002  node->indexqualorig = indexqualorig;
5003  node->indexorderby = indexorderby;
5004  node->indexorderbyorig = indexorderbyorig;
5005  node->indexorderbyops = indexorderbyops;
5006  node->indexorderdir = indexscandir;
5007 
5008  return node;
5009 }
5010 
5011 static IndexOnlyScan *
5013  List *qpqual,
5014  Index scanrelid,
5015  Oid indexid,
5016  List *indexqual,
5017  List *indexorderby,
5018  List *indextlist,
5019  ScanDirection indexscandir)
5020 {
5022  Plan *plan = &node->scan.plan;
5023 
5024  plan->targetlist = qptlist;
5025  plan->qual = qpqual;
5026  plan->lefttree = NULL;
5027  plan->righttree = NULL;
5028  node->scan.scanrelid = scanrelid;
5029  node->indexid = indexid;
5030  node->indexqual = indexqual;
5031  node->indexorderby = indexorderby;
5032  node->indextlist = indextlist;
5033  node->indexorderdir = indexscandir;
5034 
5035  return node;
5036 }
5037 
5038 static BitmapIndexScan *
5040  Oid indexid,
5041  List *indexqual,
5042  List *indexqualorig)
5043 {
5045  Plan *plan = &node->scan.plan;
5046 
5047  plan->targetlist = NIL; /* not used */
5048  plan->qual = NIL; /* not used */
5049  plan->lefttree = NULL;
5050  plan->righttree = NULL;
5051  node->scan.scanrelid = scanrelid;
5052  node->indexid = indexid;
5053  node->indexqual = indexqual;
5054  node->indexqualorig = indexqualorig;
5055 
5056  return node;
5057 }
5058 
5059 static BitmapHeapScan *
5061  List *qpqual,
5062  Plan *lefttree,
5063  List *bitmapqualorig,
5064  Index scanrelid)
5065 {
5067  Plan *plan = &node->scan.plan;
5068 
5069  plan->targetlist = qptlist;
5070  plan->qual = qpqual;
5071  plan->lefttree = lefttree;
5072  plan->righttree = NULL;
5073  node->scan.scanrelid = scanrelid;
5074  node->bitmapqualorig = bitmapqualorig;
5075 
5076  return node;
5077 }
5078 
5079 static TidScan *
5081  List *qpqual,
5082  Index scanrelid,
5083  List *tidquals)
5084 {
5085  TidScan *node = makeNode(TidScan);
5086  Plan *plan = &node->scan.plan;
5087 
5088  plan->targetlist = qptlist;
5089  plan->qual = qpqual;
5090  plan->lefttree = NULL;
5091  plan->righttree = NULL;
5092  node->scan.scanrelid = scanrelid;
5093  node->tidquals = tidquals;
5094 
5095  return node;
5096 }
5097 
5098 static SubqueryScan *
5100  List *qpqual,
5101  Index scanrelid,
5102  Plan *subplan)
5103 {
5105  Plan *plan = &node->scan.plan;
5106 
5107  plan->targetlist = qptlist;
5108  plan->qual = qpqual;
5109  plan->lefttree = NULL;
5110  plan->righttree = NULL;
5111  node->scan.scanrelid = scanrelid;
5112  node->subplan = subplan;
5113 
5114  return node;
5115 }
5116 
5117 static FunctionScan *
5119  List *qpqual,
5120  Index scanrelid,
5121  List *functions,
5122  bool funcordinality)
5123 {
5125  Plan *plan = &node->scan.plan;
5126 
5127  plan->targetlist = qptlist;
5128  plan->qual = qpqual;
5129  plan->lefttree = NULL;
5130  plan->righttree = NULL;
5131  node->scan.scanrelid = scanrelid;
5132  node->functions = functions;
5133  node->funcordinality = funcordinality;
5134 
5135  return node;
5136 }
5137 
5138 static TableFuncScan *
5140  List *qpqual,
5141  Index scanrelid,
5142  TableFunc *tablefunc)
5143 {
5145  Plan *plan = &node->scan.plan;
5146 
5147  plan->targetlist = qptlist;
5148  plan->qual = qpqual;
5149  plan->lefttree = NULL;
5150  plan->righttree = NULL;
5151  node->scan.scanrelid = scanrelid;
5152  node->tablefunc = tablefunc;
5153 
5154  return node;
5155 }
5156 
5157 static ValuesScan *
5159  List *qpqual,
5160  Index scanrelid,
5161  List *values_lists)
5162 {
5163  ValuesScan *node = makeNode(ValuesScan);
5164  Plan *plan = &node->scan.plan;
5165 
5166  plan->targetlist = qptlist;
5167  plan->qual = qpqual;
5168  plan->lefttree = NULL;
5169  plan->righttree = NULL;
5170  node->scan.scanrelid = scanrelid;
5171  node->values_lists = values_lists;
5172 
5173  return node;
5174 }
5175 
5176 static CteScan *
5178  List *qpqual,
5179  Index scanrelid,
5180  int ctePlanId,
5181  int cteParam)
5182 {
5183  CteScan *node = makeNode(CteScan);
5184  Plan *plan = &node->scan.plan;
5185 
5186  plan->targetlist = qptlist;
5187  plan->qual = qpqual;
5188  plan->lefttree = NULL;
5189  plan->righttree = NULL;
5190  node->scan.scanrelid = scanrelid;
5191  node->ctePlanId = ctePlanId;
5192  node->cteParam = cteParam;
5193 
5194  return node;
5195 }
5196 
5197 static NamedTuplestoreScan *
5199  List *qpqual,
5200  Index scanrelid,
5201  char *enrname)
5202 {
5204  Plan *plan = &node->scan.plan;
5205 
5206  /* cost should be inserted by caller */
5207  plan->targetlist = qptlist;
5208  plan->qual = qpqual;
5209  plan->lefttree = NULL;
5210  plan->righttree = NULL;
5211  node->scan.scanrelid = scanrelid;
5212  node->enrname = enrname;
5213 
5214  return node;
5215 }
5216 
5217 static WorkTableScan *
5219  List *qpqual,
5220  Index scanrelid,
5221  int wtParam)
5222 {
5224  Plan *plan = &node->scan.plan;
5225 
5226  plan->targetlist = qptlist;
5227  plan->qual = qpqual;
5228  plan->lefttree = NULL;
5229  plan->righttree = NULL;
5230  node->scan.scanrelid = scanrelid;
5231  node->wtParam = wtParam;
5232 
5233  return node;
5234 }
5235 
5236 ForeignScan *
5238  List *qpqual,
5239  Index scanrelid,
5240  List *fdw_exprs,
5241  List *fdw_private,
5242  List *fdw_scan_tlist,
5243  List *fdw_recheck_quals,
5244  Plan *outer_plan)
5245 {
5246  ForeignScan *node = makeNode(ForeignScan);
5247  Plan *plan = &node->scan.plan;
5248 
5249  /* cost will be filled in by create_foreignscan_plan */
5250  plan->targetlist = qptlist;
5251  plan->qual = qpqual;
5252  plan->lefttree = outer_plan;
5253  plan->righttree = NULL;
5254  node->scan.scanrelid = scanrelid;
5255  node->operation = CMD_SELECT;
5256  /* fs_server will be filled in by create_foreignscan_plan */
5257  node->fs_server = InvalidOid;
5258  node->fdw_exprs = fdw_exprs;
5259  node->fdw_private = fdw_private;
5260  node->fdw_scan_tlist = fdw_scan_tlist;
5261  node->fdw_recheck_quals = fdw_recheck_quals;
5262  /* fs_relids will be filled in by create_foreignscan_plan */
5263  node->fs_relids = NULL;
5264  /* fsSystemCol will be filled in by create_foreignscan_plan */
5265  node->fsSystemCol = false;
5266 
5267  return node;
5268 }
5269 
5270 static Append *
5271 make_append(List *appendplans, List *tlist, List *partitioned_rels)
5272 {
5273  Append *node = makeNode(Append);
5274  Plan *plan = &node->plan;
5275 
5276  plan->targetlist = tlist;
5277  plan->qual = NIL;
5278  plan->lefttree = NULL;
5279  plan->righttree = NULL;
5280  node->partitioned_rels = partitioned_rels;
5281  node->appendplans = appendplans;
5282 
5283  return node;
5284 }
5285 
5286 static RecursiveUnion *
5288  Plan *lefttree,
5289  Plan *righttree,
5290  int wtParam,
5291  List *distinctList,
5292  long numGroups)
5293 {
5295  Plan *plan = &node->plan;
5296  int numCols = list_length(distinctList);
5297 
5298  plan->targetlist = tlist;
5299  plan->qual = NIL;
5300  plan->lefttree = lefttree;
5301  plan->righttree = righttree;
5302  node->wtParam = wtParam;
5303 
5304  /*
5305  * convert SortGroupClause list into arrays of attr indexes and equality
5306  * operators, as wanted by executor
5307  */
5308  node->numCols = numCols;
5309  if (numCols > 0)
5310  {
5311  int keyno = 0;
5312  AttrNumber *dupColIdx;
5313  Oid *dupOperators;
5314  ListCell *slitem;
5315 
5316  dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5317  dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5318 
5319  foreach(slitem, distinctList)
5320  {
5321  SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
5322  TargetEntry *tle = get_sortgroupclause_tle(sortcl,
5323  plan->targetlist);
5324 
5325  dupColIdx[keyno] = tle->resno;
5326  dupOperators[keyno] = sortcl->eqop;
5327  Assert(OidIsValid(dupOperators[keyno]));
5328  keyno++;
5329  }
5330  node->dupColIdx = dupColIdx;
5331  node->dupOperators = dupOperators;
5332  }
5333  node->numGroups = numGroups;
5334 
5335  return node;
5336 }
5337 
5338 static BitmapAnd *
5339 make_bitmap_and(List *bitmapplans)
5340 {
5341  BitmapAnd *node = makeNode(BitmapAnd);
5342  Plan *plan = &node->plan;
5343 
5344  plan->targetlist = NIL;
5345  plan->qual = NIL;
5346  plan->lefttree = NULL;
5347  plan->righttree = NULL;
5348  node->bitmapplans = bitmapplans;
5349 
5350  return node;
5351 }
5352 
5353 static BitmapOr *
5354 make_bitmap_or(List *bitmapplans)
5355 {
5356  BitmapOr *node = makeNode(BitmapOr);
5357  Plan *plan = &node->plan;
5358 
5359  plan->targetlist = NIL;
5360  plan->qual = NIL;
5361  plan->lefttree = NULL;
5362  plan->righttree = NULL;
5363  node->bitmapplans = bitmapplans;
5364 
5365  return node;
5366 }
5367 
5368 static NestLoop *
5370  List *joinclauses,
5371  List *otherclauses,
5372  List *nestParams,
5373  Plan *lefttree,
5374  Plan *righttree,
5375  JoinType jointype,
5376  bool inner_unique)
5377 {
5378  NestLoop *node = makeNode(NestLoop);
5379  Plan *plan = &node->join.plan;
5380 
5381  plan->targetlist = tlist;
5382  plan->qual = otherclauses;
5383  plan->lefttree = lefttree;
5384  plan->righttree = righttree;
5385  node->join.jointype = jointype;
5386  node->join.inner_unique = inner_unique;
5387  node->join.joinqual = joinclauses;
5388  node->nestParams = nestParams;
5389 
5390  return node;
5391 }
5392 
5393 static HashJoin *
5395  List *joinclauses,
5396  List *otherclauses,
5397  List *hashclauses,
5398  Plan *lefttree,
5399  Plan *righttree,
5400  JoinType jointype,
5401  bool inner_unique)
5402 {
5403  HashJoin *node = makeNode(HashJoin);
5404  Plan *plan = &node->join.plan;
5405 
5406  plan->targetlist = tlist;
5407  plan->qual = otherclauses;
5408  plan->lefttree = lefttree;
5409  plan->righttree = righttree;
5410  node->hashclauses = hashclauses;
5411  node->join.jointype = jointype;
5412  node->join.inner_unique = inner_unique;
5413  node->join.joinqual = joinclauses;
5414 
5415  return node;
5416 }
5417 
5418 static Hash *
5419 make_hash(Plan *lefttree,
5420  Oid skewTable,
5421  AttrNumber skewColumn,
5422  bool skewInherit)
5423 {
5424  Hash *node = makeNode(Hash);
5425  Plan *plan = &node->plan;
5426 
5427  plan->targetlist = lefttree->targetlist;
5428  plan->qual = NIL;
5429  plan->lefttree = lefttree;
5430  plan->righttree = NULL;
5431 
5432  node->skewTable = skewTable;
5433  node->skewColumn = skewColumn;
5434  node->skewInherit = skewInherit;
5435 
5436  return node;
5437 }
5438 
5439 static MergeJoin *
5441  List *joinclauses,
5442  List *otherclauses,
5443  List *mergeclauses,
5444  Oid *mergefamilies,
5445  Oid *mergecollations,
5446  int *mergestrategies,
5447  bool *mergenullsfirst,
5448  Plan *lefttree,
5449  Plan *righttree,
5450  JoinType jointype,
5451  bool inner_unique,
5452  bool skip_mark_restore)
5453 {
5454  MergeJoin *node = makeNode(MergeJoin);
5455  Plan *plan = &node->join.plan;
5456 
5457  plan->targetlist = tlist;
5458  plan->qual = otherclauses;
5459  plan->lefttree = lefttree;
5460  plan->righttree = righttree;
5461  node->skip_mark_restore = skip_mark_restore;
5462  node->mergeclauses = mergeclauses;
5463  node->mergeFamilies = mergefamilies;
5464  node->mergeCollations = mergecollations;
5465  node->mergeStrategies = mergestrategies;
5466  node->mergeNullsFirst = mergenullsfirst;
5467  node->join.jointype = jointype;
5468  node->join.inner_unique = inner_unique;
5469  node->join.joinqual = joinclauses;
5470 
5471  return node;
5472 }
5473 
5474 /*
5475  * make_sort --- basic routine to build a Sort plan node
5476  *
5477  * Caller must have built the sortColIdx, sortOperators, collations, and
5478  * nullsFirst arrays already.
5479  */
5480 static Sort *
5481 make_sort(Plan *lefttree, int numCols,
5482  AttrNumber *sortColIdx, Oid *sortOperators,
5483  Oid *collations, bool *nullsFirst)
5484 {
5485  Sort *node = makeNode(Sort);
5486  Plan *plan = &node->plan;
5487 
5488  plan->targetlist = lefttree->targetlist;
5489  plan->qual = NIL;
5490  plan->lefttree = lefttree;
5491  plan->righttree = NULL;
5492  node->numCols = numCols;
5493  node->sortColIdx = sortColIdx;
5494  node->sortOperators = sortOperators;
5495  node->collations = collations;
5496  node->nullsFirst = nullsFirst;
5497 
5498  return node;
5499 }
5500 
5501 /*
5502  * prepare_sort_from_pathkeys
5503  * Prepare to sort according to given pathkeys
5504  *
5505  * This is used to set up for Sort, MergeAppend, and Gather Merge nodes. It
5506  * calculates the executor's representation of the sort key information, and
5507  * adjusts the plan targetlist if needed to add resjunk sort columns.
5508  *
5509  * Input parameters:
5510  * 'lefttree' is the plan node which yields input tuples
5511  * 'pathkeys' is the list of pathkeys by which the result is to be sorted
5512  * 'relids' identifies the child relation being sorted, if any
5513  * 'reqColIdx' is NULL or an array of required sort key column numbers
5514  * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
5515  *
5516  * We must convert the pathkey information into arrays of sort key column
5517  * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
5518  * which is the representation the executor wants. These are returned into
5519  * the output parameters *p_numsortkeys etc.
5520  *
5521  * When looking for matches to an EquivalenceClass's members, we will only
5522  * consider child EC members if they match 'relids'. This protects against
5523  * possible incorrect matches to child expressions that contain no Vars.
5524  *
5525  * If reqColIdx isn't NULL then it contains sort key column numbers that
5526  * we should match. This is used when making child plans for a MergeAppend;
5527  * it's an error if we can't match the columns.
5528  *
5529  * If the pathkeys include expressions that aren't simple Vars, we will
5530  * usually need to add resjunk items to the input plan's targetlist to
5531  * compute these expressions, since a Sort or MergeAppend node itself won't
5532  * do any such calculations. If the input plan type isn't one that can do
5533  * projections, this means adding a Result node just to do the projection.
5534  * However, the caller can pass adjust_tlist_in_place = TRUE to force the
5535  * lefttree tlist to be modified in-place regardless of whether the node type
5536  * can project --- we use this for fixing the tlist of MergeAppend itself.
5537  *
5538  * Returns the node which is to be the input to the Sort (either lefttree,
5539  * or a Result stacked atop lefttree).
5540  */
5541 static Plan *
5542 prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
5543  Relids relids,
5544  const AttrNumber *reqColIdx,
5545  bool adjust_tlist_in_place,
5546  int *p_numsortkeys,
5547  AttrNumber **p_sortColIdx,
5548  Oid **p_sortOperators,
5549  Oid **p_collations,
5550  bool **p_nullsFirst)
5551 {
5552  List *tlist = lefttree->targetlist;
5553  ListCell *i;
5554  int numsortkeys;
5555  AttrNumber *sortColIdx;
5556  Oid *sortOperators;
5557  Oid *collations;
5558  bool *nullsFirst;
5559 
5560  /*
5561  * We will need at most list_length(pathkeys) sort columns; possibly less
5562  */
5563  numsortkeys = list_length(pathkeys);
5564  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5565  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5566  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5567  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5568 
5569  numsortkeys = 0;
5570 
5571  foreach(i, pathkeys)
5572  {
5573  PathKey *pathkey = (PathKey *) lfirst(i);
5574  EquivalenceClass *ec = pathkey->pk_eclass;
5575  EquivalenceMember *em;
5576  TargetEntry *tle = NULL;
5577  Oid pk_datatype = InvalidOid;
5578  Oid sortop;
5579  ListCell *j;
5580 
5581  if (ec->ec_has_volatile)
5582  {
5583  /*
5584  * If the pathkey's EquivalenceClass is volatile, then it must
5585  * have come from an ORDER BY clause, and we have to match it to
5586  * that same targetlist entry.
5587  */
5588  if (ec->ec_sortref == 0) /* can't happen */
5589  elog(ERROR, "volatile EquivalenceClass has no sortref");
5590  tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
5591  Assert(tle);
5592  Assert(list_length(ec->ec_members) == 1);
5593  pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
5594  }
5595