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, int rescan_param, 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,
1475  best_path->single_copy,
1476  subplan);
1477 
1478  copy_generic_path_info(&gather_plan->plan, &best_path->path);
1479 
1480  /* use parallel mode for parallel plans. */
1481  root->glob->parallelModeNeeded = true;
1482 
1483  return gather_plan;
1484 }
1485 
1486 /*
1487  * create_gather_merge_plan
1488  *
1489  * Create a Gather Merge plan for 'best_path' and (recursively)
1490  * plans for its subpaths.
1491  */
1492 static GatherMerge *
1494 {
1495  GatherMerge *gm_plan;
1496  Plan *subplan;
1497  List *pathkeys = best_path->path.pathkeys;
1498  List *tlist = build_path_tlist(root, &best_path->path);
1499 
1500  /* As with Gather, it's best to project away columns in the workers. */
1501  subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1502 
1503  /* Create a shell for a GatherMerge plan. */
1504  gm_plan = makeNode(GatherMerge);
1505  gm_plan->plan.targetlist = tlist;
1506  gm_plan->num_workers = best_path->num_workers;
1507  copy_generic_path_info(&gm_plan->plan, &best_path->path);
1508 
1509  /* Assign the rescan Param. */
1510  gm_plan->rescan_param = SS_assign_special_param(root);
1511 
1512  /* Gather Merge is pointless with no pathkeys; use Gather instead. */
1513  Assert(pathkeys != NIL);
1514 
1515  /* Compute sort column info, and adjust subplan's tlist as needed */
1516  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1517  best_path->subpath->parent->relids,
1518  gm_plan->sortColIdx,
1519  false,
1520  &gm_plan->numCols,
1521  &gm_plan->sortColIdx,
1522  &gm_plan->sortOperators,
1523  &gm_plan->collations,
1524  &gm_plan->nullsFirst);
1525 
1526 
1527  /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1528  if (!pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys))
1529  subplan = (Plan *) make_sort(subplan, gm_plan->numCols,
1530  gm_plan->sortColIdx,
1531  gm_plan->sortOperators,
1532  gm_plan->collations,
1533  gm_plan->nullsFirst);
1534 
1535  /* Now insert the subplan under GatherMerge. */
1536  gm_plan->plan.lefttree = subplan;
1537 
1538  /* use parallel mode for parallel plans. */
1539  root->glob->parallelModeNeeded = true;
1540 
1541  return gm_plan;
1542 }
1543 
1544 /*
1545  * create_projection_plan
1546  *
1547  * Create a plan tree to do a projection step and (recursively) plans
1548  * for its subpaths. We may need a Result node for the projection,
1549  * but sometimes we can just let the subplan do the work.
1550  */
1551 static Plan *
1553 {
1554  Plan *plan;
1555  Plan *subplan;
1556  List *tlist;
1557 
1558  /* Since we intend to project, we don't need to constrain child tlist */
1559  subplan = create_plan_recurse(root, best_path->subpath, 0);
1560 
1561  tlist = build_path_tlist(root, &best_path->path);
1562 
1563  /*
1564  * We might not really need a Result node here, either because the subplan
1565  * can project or because it's returning the right list of expressions
1566  * anyway. Usually create_projection_path will have detected that and set
1567  * dummypp if we don't need a Result; but its decision can't be final,
1568  * because some createplan.c routines change the tlists of their nodes.
1569  * (An example is that create_merge_append_plan might add resjunk sort
1570  * columns to a MergeAppend.) So we have to recheck here. If we do
1571  * arrive at a different answer than create_projection_path did, we'll
1572  * have made slightly wrong cost estimates; but label the plan with the
1573  * cost estimates we actually used, not "corrected" ones. (XXX this could
1574  * be cleaned up if we moved more of the sortcolumn setup logic into Path
1575  * creation, but that would add expense to creating Paths we might end up
1576  * not using.)
1577  */
1578  if (is_projection_capable_path(best_path->subpath) ||
1579  tlist_same_exprs(tlist, subplan->targetlist))
1580  {
1581  /* Don't need a separate Result, just assign tlist to subplan */
1582  plan = subplan;
1583  plan->targetlist = tlist;
1584 
1585  /* Label plan with the estimated costs we actually used */
1586  plan->startup_cost = best_path->path.startup_cost;
1587  plan->total_cost = best_path->path.total_cost;
1588  plan->plan_rows = best_path->path.rows;
1589  plan->plan_width = best_path->path.pathtarget->width;
1590  plan->parallel_safe = best_path->path.parallel_safe;
1591  /* ... but don't change subplan's parallel_aware flag */
1592  }
1593  else
1594  {
1595  /* We need a Result node */
1596  plan = (Plan *) make_result(tlist, NULL, subplan);
1597 
1598  copy_generic_path_info(plan, (Path *) best_path);
1599  }
1600 
1601  return plan;
1602 }
1603 
1604 /*
1605  * inject_projection_plan
1606  * Insert a Result node to do a projection step.
1607  *
1608  * This is used in a few places where we decide on-the-fly that we need a
1609  * projection step as part of the tree generated for some Path node.
1610  * We should try to get rid of this in favor of doing it more honestly.
1611  *
1612  * One reason it's ugly is we have to be told the right parallel_safe marking
1613  * to apply (since the tlist might be unsafe even if the child plan is safe).
1614  */
1615 static Plan *
1616 inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
1617 {
1618  Plan *plan;
1619 
1620  plan = (Plan *) make_result(tlist, NULL, subplan);
1621 
1622  /*
1623  * In principle, we should charge tlist eval cost plus cpu_per_tuple per
1624  * row for the Result node. But the former has probably been factored in
1625  * already and the latter was not accounted for during Path construction,
1626  * so being formally correct might just make the EXPLAIN output look less
1627  * consistent not more so. Hence, just copy the subplan's cost.
1628  */
1629  copy_plan_costsize(plan, subplan);
1630  plan->parallel_safe = parallel_safe;
1631 
1632  return plan;
1633 }
1634 
1635 /*
1636  * create_sort_plan
1637  *
1638  * Create a Sort plan for 'best_path' and (recursively) plans
1639  * for its subpaths.
1640  */
1641 static Sort *
1642 create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
1643 {
1644  Sort *plan;
1645  Plan *subplan;
1646 
1647  /*
1648  * We don't want any excess columns in the sorted tuples, so request a
1649  * smaller tlist. Otherwise, since Sort doesn't project, tlist
1650  * requirements pass through.
1651  */
1652  subplan = create_plan_recurse(root, best_path->subpath,
1653  flags | CP_SMALL_TLIST);
1654 
1655  plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys);
1656 
1657  copy_generic_path_info(&plan->plan, (Path *) best_path);
1658 
1659  return plan;
1660 }
1661 
1662 /*
1663  * create_group_plan
1664  *
1665  * Create a Group plan for 'best_path' and (recursively) plans
1666  * for its subpaths.
1667  */
1668 static Group *
1670 {
1671  Group *plan;
1672  Plan *subplan;
1673  List *tlist;
1674  List *quals;
1675 
1676  /*
1677  * Group can project, so no need to be terribly picky about child tlist,
1678  * but we do need grouping columns to be available
1679  */
1680  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1681 
1682  tlist = build_path_tlist(root, &best_path->path);
1683 
1684  quals = order_qual_clauses(root, best_path->qual);
1685 
1686  plan = make_group(tlist,
1687  quals,
1688  list_length(best_path->groupClause),
1690  subplan->targetlist),
1691  extract_grouping_ops(best_path->groupClause),
1692  subplan);
1693 
1694  copy_generic_path_info(&plan->plan, (Path *) best_path);
1695 
1696  return plan;
1697 }
1698 
1699 /*
1700  * create_upper_unique_plan
1701  *
1702  * Create a Unique plan for 'best_path' and (recursively) plans
1703  * for its subpaths.
1704  */
1705 static Unique *
1707 {
1708  Unique *plan;
1709  Plan *subplan;
1710 
1711  /*
1712  * Unique doesn't project, so tlist requirements pass through; moreover we
1713  * need grouping columns to be labeled.
1714  */
1715  subplan = create_plan_recurse(root, best_path->subpath,
1716  flags | CP_LABEL_TLIST);
1717 
1718  plan = make_unique_from_pathkeys(subplan,
1719  best_path->path.pathkeys,
1720  best_path->numkeys);
1721 
1722  copy_generic_path_info(&plan->plan, (Path *) best_path);
1723 
1724  return plan;
1725 }
1726 
1727 /*
1728  * create_agg_plan
1729  *
1730  * Create an Agg plan for 'best_path' and (recursively) plans
1731  * for its subpaths.
1732  */
1733 static Agg *
1735 {
1736  Agg *plan;
1737  Plan *subplan;
1738  List *tlist;
1739  List *quals;
1740 
1741  /*
1742  * Agg can project, so no need to be terribly picky about child tlist, but
1743  * we do need grouping columns to be available
1744  */
1745  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1746 
1747  tlist = build_path_tlist(root, &best_path->path);
1748 
1749  quals = order_qual_clauses(root, best_path->qual);
1750 
1751  plan = make_agg(tlist, quals,
1752  best_path->aggstrategy,
1753  best_path->aggsplit,
1754  list_length(best_path->groupClause),
1756  subplan->targetlist),
1757  extract_grouping_ops(best_path->groupClause),
1758  NIL,
1759  NIL,
1760  best_path->numGroups,
1761  subplan);
1762 
1763  copy_generic_path_info(&plan->plan, (Path *) best_path);
1764 
1765  return plan;
1766 }
1767 
1768 /*
1769  * Given a groupclause for a collection of grouping sets, produce the
1770  * corresponding groupColIdx.
1771  *
1772  * root->grouping_map maps the tleSortGroupRef to the actual column position in
1773  * the input tuple. So we get the ref from the entries in the groupclause and
1774  * look them up there.
1775  */
1776 static AttrNumber *
1777 remap_groupColIdx(PlannerInfo *root, List *groupClause)
1778 {
1779  AttrNumber *grouping_map = root->grouping_map;
1780  AttrNumber *new_grpColIdx;
1781  ListCell *lc;
1782  int i;
1783 
1784  Assert(grouping_map);
1785 
1786  new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
1787 
1788  i = 0;
1789  foreach(lc, groupClause)
1790  {
1791  SortGroupClause *clause = lfirst(lc);
1792 
1793  new_grpColIdx[i++] = grouping_map[clause->tleSortGroupRef];
1794  }
1795 
1796  return new_grpColIdx;
1797 }
1798 
1799 /*
1800  * create_groupingsets_plan
1801  * Create a plan for 'best_path' and (recursively) plans
1802  * for its subpaths.
1803  *
1804  * What we emit is an Agg plan with some vestigial Agg and Sort nodes
1805  * hanging off the side. The top Agg implements the last grouping set
1806  * specified in the GroupingSetsPath, and any additional grouping sets
1807  * each give rise to a subsidiary Agg and Sort node in the top Agg's
1808  * "chain" list. These nodes don't participate in the plan directly,
1809  * but they are a convenient way to represent the required data for
1810  * the extra steps.
1811  *
1812  * Returns a Plan node.
1813  */
1814 static Plan *
1816 {
1817  Agg *plan;
1818  Plan *subplan;
1819  List *rollups = best_path->rollups;
1820  AttrNumber *grouping_map;
1821  int maxref;
1822  List *chain;
1823  ListCell *lc;
1824 
1825  /* Shouldn't get here without grouping sets */
1826  Assert(root->parse->groupingSets);
1827  Assert(rollups != NIL);
1828 
1829  /*
1830  * Agg can project, so no need to be terribly picky about child tlist, but
1831  * we do need grouping columns to be available
1832  */
1833  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1834 
1835  /*
1836  * Compute the mapping from tleSortGroupRef to column index in the child's
1837  * tlist. First, identify max SortGroupRef in groupClause, for array
1838  * sizing.
1839  */
1840  maxref = 0;
1841  foreach(lc, root->parse->groupClause)
1842  {
1843  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1844 
1845  if (gc->tleSortGroupRef > maxref)
1846  maxref = gc->tleSortGroupRef;
1847  }
1848 
1849  grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
1850 
1851  /* Now look up the column numbers in the child's tlist */
1852  foreach(lc, root->parse->groupClause)
1853  {
1854  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1855  TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
1856 
1857  grouping_map[gc->tleSortGroupRef] = tle->resno;
1858  }
1859 
1860  /*
1861  * During setrefs.c, we'll need the grouping_map to fix up the cols lists
1862  * in GroupingFunc nodes. Save it for setrefs.c to use.
1863  *
1864  * This doesn't work if we're in an inheritance subtree (see notes in
1865  * create_modifytable_plan). Fortunately we can't be because there would
1866  * never be grouping in an UPDATE/DELETE; but let's Assert that.
1867  */
1868  Assert(!root->hasInheritedTarget);
1869  Assert(root->grouping_map == NULL);
1870  root->grouping_map = grouping_map;
1871 
1872  /*
1873  * Generate the side nodes that describe the other sort and group
1874  * operations besides the top one. Note that we don't worry about putting
1875  * accurate cost estimates in the side nodes; only the topmost Agg node's
1876  * costs will be shown by EXPLAIN.
1877  */
1878  chain = NIL;
1879  if (list_length(rollups) > 1)
1880  {
1881  ListCell *lc2 = lnext(list_head(rollups));
1882  bool is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
1883 
1884  for_each_cell(lc, lc2)
1885  {
1886  RollupData *rollup = lfirst(lc);
1887  AttrNumber *new_grpColIdx;
1888  Plan *sort_plan = NULL;
1889  Plan *agg_plan;
1890  AggStrategy strat;
1891 
1892  new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1893 
1894  if (!rollup->is_hashed && !is_first_sort)
1895  {
1896  sort_plan = (Plan *)
1898  new_grpColIdx,
1899  subplan);
1900  }
1901 
1902  if (!rollup->is_hashed)
1903  is_first_sort = false;
1904 
1905  if (rollup->is_hashed)
1906  strat = AGG_HASHED;
1907  else if (list_length(linitial(rollup->gsets)) == 0)
1908  strat = AGG_PLAIN;
1909  else
1910  strat = AGG_SORTED;
1911 
1912  agg_plan = (Plan *) make_agg(NIL,
1913  NIL,
1914  strat,
1916  list_length((List *) linitial(rollup->gsets)),
1917  new_grpColIdx,
1919  rollup->gsets,
1920  NIL,
1921  rollup->numGroups,
1922  sort_plan);
1923 
1924  /*
1925  * Remove stuff we don't need to avoid bloating debug output.
1926  */
1927  if (sort_plan)
1928  {
1929  sort_plan->targetlist = NIL;
1930  sort_plan->lefttree = NULL;
1931  }
1932 
1933  chain = lappend(chain, agg_plan);
1934  }
1935  }
1936 
1937  /*
1938  * Now make the real Agg node
1939  */
1940  {
1941  RollupData *rollup = linitial(rollups);
1942  AttrNumber *top_grpColIdx;
1943  int numGroupCols;
1944 
1945  top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1946 
1947  numGroupCols = list_length((List *) linitial(rollup->gsets));
1948 
1949  plan = make_agg(build_path_tlist(root, &best_path->path),
1950  best_path->qual,
1951  best_path->aggstrategy,
1953  numGroupCols,
1954  top_grpColIdx,
1956  rollup->gsets,
1957  chain,
1958  rollup->numGroups,
1959  subplan);
1960 
1961  /* Copy cost data from Path to Plan */
1962  copy_generic_path_info(&plan->plan, &best_path->path);
1963  }
1964 
1965  return (Plan *) plan;
1966 }
1967 
1968 /*
1969  * create_minmaxagg_plan
1970  *
1971  * Create a Result plan for 'best_path' and (recursively) plans
1972  * for its subpaths.
1973  */
1974 static Result *
1976 {
1977  Result *plan;
1978  List *tlist;
1979  ListCell *lc;
1980 
1981  /* Prepare an InitPlan for each aggregate's subquery. */
1982  foreach(lc, best_path->mmaggregates)
1983  {
1984  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
1985  PlannerInfo *subroot = mminfo->subroot;
1986  Query *subparse = subroot->parse;
1987  Plan *plan;
1988 
1989  /*
1990  * Generate the plan for the subquery. We already have a Path, but we
1991  * have to convert it to a Plan and attach a LIMIT node above it.
1992  * Since we are entering a different planner context (subroot),
1993  * recurse to create_plan not create_plan_recurse.
1994  */
1995  plan = create_plan(subroot, mminfo->path);
1996 
1997  plan = (Plan *) make_limit(plan,
1998  subparse->limitOffset,
1999  subparse->limitCount);
2000 
2001  /* Must apply correct cost/width data to Limit node */
2002  plan->startup_cost = mminfo->path->startup_cost;
2003  plan->total_cost = mminfo->pathcost;
2004  plan->plan_rows = 1;
2005  plan->plan_width = mminfo->path->pathtarget->width;
2006  plan->parallel_aware = false;
2007  plan->parallel_safe = mminfo->path->parallel_safe;
2008 
2009  /* Convert the plan into an InitPlan in the outer query. */
2010  SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
2011  }
2012 
2013  /* Generate the output plan --- basically just a Result */
2014  tlist = build_path_tlist(root, &best_path->path);
2015 
2016  plan = make_result(tlist, (Node *) best_path->quals, NULL);
2017 
2018  copy_generic_path_info(&plan->plan, (Path *) best_path);
2019 
2020  /*
2021  * During setrefs.c, we'll need to replace references to the Agg nodes
2022  * with InitPlan output params. (We can't just do that locally in the
2023  * MinMaxAgg node, because path nodes above here may have Agg references
2024  * as well.) Save the mmaggregates list to tell setrefs.c to do that.
2025  *
2026  * This doesn't work if we're in an inheritance subtree (see notes in
2027  * create_modifytable_plan). Fortunately we can't be because there would
2028  * never be aggregates in an UPDATE/DELETE; but let's Assert that.
2029  */
2030  Assert(!root->hasInheritedTarget);
2031  Assert(root->minmax_aggs == NIL);
2032  root->minmax_aggs = best_path->mmaggregates;
2033 
2034  return plan;
2035 }
2036 
2037 /*
2038  * create_windowagg_plan
2039  *
2040  * Create a WindowAgg plan for 'best_path' and (recursively) plans
2041  * for its subpaths.
2042  */
2043 static WindowAgg *
2045 {
2046  WindowAgg *plan;
2047  WindowClause *wc = best_path->winclause;
2048  Plan *subplan;
2049  List *tlist;
2050  int numsortkeys;
2051  AttrNumber *sortColIdx;
2052  Oid *sortOperators;
2053  Oid *collations;
2054  bool *nullsFirst;
2055  int partNumCols;
2056  AttrNumber *partColIdx;
2057  Oid *partOperators;
2058  int ordNumCols;
2059  AttrNumber *ordColIdx;
2060  Oid *ordOperators;
2061 
2062  /*
2063  * WindowAgg can project, so no need to be terribly picky about child
2064  * tlist, but we do need grouping columns to be available
2065  */
2066  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2067 
2068  tlist = build_path_tlist(root, &best_path->path);
2069 
2070  /*
2071  * We shouldn't need to actually sort, but it's convenient to use
2072  * prepare_sort_from_pathkeys to identify the input's sort columns.
2073  */
2074  subplan = prepare_sort_from_pathkeys(subplan,
2075  best_path->winpathkeys,
2076  NULL,
2077  NULL,
2078  false,
2079  &numsortkeys,
2080  &sortColIdx,
2081  &sortOperators,
2082  &collations,
2083  &nullsFirst);
2084 
2085  /* Now deconstruct that into partition and ordering portions */
2087  wc,
2088  subplan->targetlist,
2089  numsortkeys,
2090  sortColIdx,
2091  &partNumCols,
2092  &partColIdx,
2093  &partOperators,
2094  &ordNumCols,
2095  &ordColIdx,
2096  &ordOperators);
2097 
2098  /* And finally we can make the WindowAgg node */
2099  plan = make_windowagg(tlist,
2100  wc->winref,
2101  partNumCols,
2102  partColIdx,
2103  partOperators,
2104  ordNumCols,
2105  ordColIdx,
2106  ordOperators,
2107  wc->frameOptions,
2108  wc->startOffset,
2109  wc->endOffset,
2110  subplan);
2111 
2112  copy_generic_path_info(&plan->plan, (Path *) best_path);
2113 
2114  return plan;
2115 }
2116 
2117 /*
2118  * get_column_info_for_window
2119  * Get the partitioning/ordering column numbers and equality operators
2120  * for a WindowAgg node.
2121  *
2122  * This depends on the behavior of planner.c's make_pathkeys_for_window!
2123  *
2124  * We are given the target WindowClause and an array of the input column
2125  * numbers associated with the resulting pathkeys. In the easy case, there
2126  * are the same number of pathkey columns as partitioning + ordering columns
2127  * and we just have to copy some data around. However, it's possible that
2128  * some of the original partitioning + ordering columns were eliminated as
2129  * redundant during the transformation to pathkeys. (This can happen even
2130  * though the parser gets rid of obvious duplicates. A typical scenario is a
2131  * window specification "PARTITION BY x ORDER BY y" coupled with a clause
2132  * "WHERE x = y" that causes the two sort columns to be recognized as
2133  * redundant.) In that unusual case, we have to work a lot harder to
2134  * determine which keys are significant.
2135  *
2136  * The method used here is a bit brute-force: add the sort columns to a list
2137  * one at a time and note when the resulting pathkey list gets longer. But
2138  * it's a sufficiently uncommon case that a faster way doesn't seem worth
2139  * the amount of code refactoring that'd be needed.
2140  */
2141 static void
2143  int numSortCols, AttrNumber *sortColIdx,
2144  int *partNumCols,
2145  AttrNumber **partColIdx,
2146  Oid **partOperators,
2147  int *ordNumCols,
2148  AttrNumber **ordColIdx,
2149  Oid **ordOperators)
2150 {
2151  int numPart = list_length(wc->partitionClause);
2152  int numOrder = list_length(wc->orderClause);
2153 
2154  if (numSortCols == numPart + numOrder)
2155  {
2156  /* easy case */
2157  *partNumCols = numPart;
2158  *partColIdx = sortColIdx;
2159  *partOperators = extract_grouping_ops(wc->partitionClause);
2160  *ordNumCols = numOrder;
2161  *ordColIdx = sortColIdx + numPart;
2162  *ordOperators = extract_grouping_ops(wc->orderClause);
2163  }
2164  else
2165  {
2166  List *sortclauses;
2167  List *pathkeys;
2168  int scidx;
2169  ListCell *lc;
2170 
2171  /* first, allocate what's certainly enough space for the arrays */
2172  *partNumCols = 0;
2173  *partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
2174  *partOperators = (Oid *) palloc(numPart * sizeof(Oid));
2175  *ordNumCols = 0;
2176  *ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
2177  *ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
2178  sortclauses = NIL;
2179  pathkeys = NIL;
2180  scidx = 0;
2181  foreach(lc, wc->partitionClause)
2182  {
2183  SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2184  List *new_pathkeys;
2185 
2186  sortclauses = lappend(sortclauses, sgc);
2187  new_pathkeys = make_pathkeys_for_sortclauses(root,
2188  sortclauses,
2189  tlist);
2190  if (list_length(new_pathkeys) > list_length(pathkeys))
2191  {
2192  /* this sort clause is actually significant */
2193  (*partColIdx)[*partNumCols] = sortColIdx[scidx++];
2194  (*partOperators)[*partNumCols] = sgc->eqop;
2195  (*partNumCols)++;
2196  pathkeys = new_pathkeys;
2197  }
2198  }
2199  foreach(lc, wc->orderClause)
2200  {
2201  SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2202  List *new_pathkeys;
2203 
2204  sortclauses = lappend(sortclauses, sgc);
2205  new_pathkeys = make_pathkeys_for_sortclauses(root,
2206  sortclauses,
2207  tlist);
2208  if (list_length(new_pathkeys) > list_length(pathkeys))
2209  {
2210  /* this sort clause is actually significant */
2211  (*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
2212  (*ordOperators)[*ordNumCols] = sgc->eqop;
2213  (*ordNumCols)++;
2214  pathkeys = new_pathkeys;
2215  }
2216  }
2217  /* complain if we didn't eat exactly the right number of sort cols */
2218  if (scidx != numSortCols)
2219  elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
2220  }
2221 }
2222 
2223 /*
2224  * create_setop_plan
2225  *
2226  * Create a SetOp plan for 'best_path' and (recursively) plans
2227  * for its subpaths.
2228  */
2229 static SetOp *
2230 create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
2231 {
2232  SetOp *plan;
2233  Plan *subplan;
2234  long numGroups;
2235 
2236  /*
2237  * SetOp doesn't project, so tlist requirements pass through; moreover we
2238  * need grouping columns to be labeled.
2239  */
2240  subplan = create_plan_recurse(root, best_path->subpath,
2241  flags | CP_LABEL_TLIST);
2242 
2243  /* Convert numGroups to long int --- but 'ware overflow! */
2244  numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2245 
2246  plan = make_setop(best_path->cmd,
2247  best_path->strategy,
2248  subplan,
2249  best_path->distinctList,
2250  best_path->flagColIdx,
2251  best_path->firstFlag,
2252  numGroups);
2253 
2254  copy_generic_path_info(&plan->plan, (Path *) best_path);
2255 
2256  return plan;
2257 }
2258 
2259 /*
2260  * create_recursiveunion_plan
2261  *
2262  * Create a RecursiveUnion plan for 'best_path' and (recursively) plans
2263  * for its subpaths.
2264  */
2265 static RecursiveUnion *
2267 {
2268  RecursiveUnion *plan;
2269  Plan *leftplan;
2270  Plan *rightplan;
2271  List *tlist;
2272  long numGroups;
2273 
2274  /* Need both children to produce same tlist, so force it */
2275  leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
2276  rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
2277 
2278  tlist = build_path_tlist(root, &best_path->path);
2279 
2280  /* Convert numGroups to long int --- but 'ware overflow! */
2281  numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2282 
2283  plan = make_recursive_union(tlist,
2284  leftplan,
2285  rightplan,
2286  best_path->wtParam,
2287  best_path->distinctList,
2288  numGroups);
2289 
2290  copy_generic_path_info(&plan->plan, (Path *) best_path);
2291 
2292  return plan;
2293 }
2294 
2295 /*
2296  * create_lockrows_plan
2297  *
2298  * Create a LockRows plan for 'best_path' and (recursively) plans
2299  * for its subpaths.
2300  */
2301 static LockRows *
2303  int flags)
2304 {
2305  LockRows *plan;
2306  Plan *subplan;
2307 
2308  /* LockRows doesn't project, so tlist requirements pass through */
2309  subplan = create_plan_recurse(root, best_path->subpath, flags);
2310 
2311  plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2312 
2313  copy_generic_path_info(&plan->plan, (Path *) best_path);
2314 
2315  return plan;
2316 }
2317 
2318 /*
2319  * create_modifytable_plan
2320  * Create a ModifyTable plan for 'best_path'.
2321  *
2322  * Returns a Plan node.
2323  */
2324 static ModifyTable *
2326 {
2327  ModifyTable *plan;
2328  List *subplans = NIL;
2329  ListCell *subpaths,
2330  *subroots;
2331 
2332  /* Build the plan for each input path */
2333  forboth(subpaths, best_path->subpaths,
2334  subroots, best_path->subroots)
2335  {
2336  Path *subpath = (Path *) lfirst(subpaths);
2337  PlannerInfo *subroot = (PlannerInfo *) lfirst(subroots);
2338  Plan *subplan;
2339 
2340  /*
2341  * In an inherited UPDATE/DELETE, reference the per-child modified
2342  * subroot while creating Plans from Paths for the child rel. This is
2343  * a kluge, but otherwise it's too hard to ensure that Plan creation
2344  * functions (particularly in FDWs) don't depend on the contents of
2345  * "root" matching what they saw at Path creation time. The main
2346  * downside is that creation functions for Plans that might appear
2347  * below a ModifyTable cannot expect to modify the contents of "root"
2348  * and have it "stick" for subsequent processing such as setrefs.c.
2349  * That's not great, but it seems better than the alternative.
2350  */
2351  subplan = create_plan_recurse(subroot, subpath, CP_EXACT_TLIST);
2352 
2353  /* Transfer resname/resjunk labeling, too, to keep executor happy */
2354  apply_tlist_labeling(subplan->targetlist, subroot->processed_tlist);
2355 
2356  subplans = lappend(subplans, subplan);
2357  }
2358 
2359  plan = make_modifytable(root,
2360  best_path->operation,
2361  best_path->canSetTag,
2362  best_path->nominalRelation,
2363  best_path->partitioned_rels,
2364  best_path->resultRelations,
2365  subplans,
2366  best_path->withCheckOptionLists,
2367  best_path->returningLists,
2368  best_path->rowMarks,
2369  best_path->onconflict,
2370  best_path->epqParam);
2371 
2372  copy_generic_path_info(&plan->plan, &best_path->path);
2373 
2374  return plan;
2375 }
2376 
2377 /*
2378  * create_limit_plan
2379  *
2380  * Create a Limit plan for 'best_path' and (recursively) plans
2381  * for its subpaths.
2382  */
2383 static Limit *
2384 create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
2385 {
2386  Limit *plan;
2387  Plan *subplan;
2388 
2389  /* Limit doesn't project, so tlist requirements pass through */
2390  subplan = create_plan_recurse(root, best_path->subpath, flags);
2391 
2392  plan = make_limit(subplan,
2393  best_path->limitOffset,
2394  best_path->limitCount);
2395 
2396  copy_generic_path_info(&plan->plan, (Path *) best_path);
2397 
2398  return plan;
2399 }
2400 
2401 
2402 /*****************************************************************************
2403  *
2404  * BASE-RELATION SCAN METHODS
2405  *
2406  *****************************************************************************/
2407 
2408 
2409 /*
2410  * create_seqscan_plan
2411  * Returns a seqscan plan for the base relation scanned by 'best_path'
2412  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2413  */
2414 static SeqScan *
2416  List *tlist, List *scan_clauses)
2417 {
2418  SeqScan *scan_plan;
2419  Index scan_relid = best_path->parent->relid;
2420 
2421  /* it should be a base rel... */
2422  Assert(scan_relid > 0);
2423  Assert(best_path->parent->rtekind == RTE_RELATION);
2424 
2425  /* Sort clauses into best execution order */
2426  scan_clauses = order_qual_clauses(root, scan_clauses);
2427 
2428  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2429  scan_clauses = extract_actual_clauses(scan_clauses, false);
2430 
2431  /* Replace any outer-relation variables with nestloop params */
2432  if (best_path->param_info)
2433  {
2434  scan_clauses = (List *)
2435  replace_nestloop_params(root, (Node *) scan_clauses);
2436  }
2437 
2438  scan_plan = make_seqscan(tlist,
2439  scan_clauses,
2440  scan_relid);
2441 
2442  copy_generic_path_info(&scan_plan->plan, best_path);
2443 
2444  return scan_plan;
2445 }
2446 
2447 /*
2448  * create_samplescan_plan
2449  * Returns a samplescan plan for the base relation scanned by 'best_path'
2450  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2451  */
2452 static SampleScan *
2454  List *tlist, List *scan_clauses)
2455 {
2456  SampleScan *scan_plan;
2457  Index scan_relid = best_path->parent->relid;
2458  RangeTblEntry *rte;
2459  TableSampleClause *tsc;
2460 
2461  /* it should be a base rel with a tablesample clause... */
2462  Assert(scan_relid > 0);
2463  rte = planner_rt_fetch(scan_relid, root);
2464  Assert(rte->rtekind == RTE_RELATION);
2465  tsc = rte->tablesample;
2466  Assert(tsc != NULL);
2467 
2468  /* Sort clauses into best execution order */
2469  scan_clauses = order_qual_clauses(root, scan_clauses);
2470 
2471  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2472  scan_clauses = extract_actual_clauses(scan_clauses, false);
2473 
2474  /* Replace any outer-relation variables with nestloop params */
2475  if (best_path->param_info)
2476  {
2477  scan_clauses = (List *)
2478  replace_nestloop_params(root, (Node *) scan_clauses);
2479  tsc = (TableSampleClause *)
2480  replace_nestloop_params(root, (Node *) tsc);
2481  }
2482 
2483  scan_plan = make_samplescan(tlist,
2484  scan_clauses,
2485  scan_relid,
2486  tsc);
2487 
2488  copy_generic_path_info(&scan_plan->scan.plan, best_path);
2489 
2490  return scan_plan;
2491 }
2492 
2493 /*
2494  * create_indexscan_plan
2495  * Returns an indexscan plan for the base relation scanned by 'best_path'
2496  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2497  *
2498  * We use this for both plain IndexScans and IndexOnlyScans, because the
2499  * qual preprocessing work is the same for both. Note that the caller tells
2500  * us which to build --- we don't look at best_path->path.pathtype, because
2501  * create_bitmap_subplan needs to be able to override the prior decision.
2502  */
2503 static Scan *
2505  IndexPath *best_path,
2506  List *tlist,
2507  List *scan_clauses,
2508  bool indexonly)
2509 {
2510  Scan *scan_plan;
2511  List *indexquals = best_path->indexquals;
2512  List *indexorderbys = best_path->indexorderbys;
2513  Index baserelid = best_path->path.parent->relid;
2514  Oid indexoid = best_path->indexinfo->indexoid;
2515  List *qpqual;
2516  List *stripped_indexquals;
2517  List *fixed_indexquals;
2518  List *fixed_indexorderbys;
2519  List *indexorderbyops = NIL;
2520  ListCell *l;
2521 
2522  /* it should be a base rel... */
2523  Assert(baserelid > 0);
2524  Assert(best_path->path.parent->rtekind == RTE_RELATION);
2525 
2526  /*
2527  * Build "stripped" indexquals structure (no RestrictInfos) to pass to
2528  * executor as indexqualorig
2529  */
2530  stripped_indexquals = get_actual_clauses(indexquals);
2531 
2532  /*
2533  * The executor needs a copy with the indexkey on the left of each clause
2534  * and with index Vars substituted for table ones.
2535  */
2536  fixed_indexquals = fix_indexqual_references(root, best_path);
2537 
2538  /*
2539  * Likewise fix up index attr references in the ORDER BY expressions.
2540  */
2541  fixed_indexorderbys = fix_indexorderby_references(root, best_path);
2542 
2543  /*
2544  * The qpqual list must contain all restrictions not automatically handled
2545  * by the index, other than pseudoconstant clauses which will be handled
2546  * by a separate gating plan node. All the predicates in the indexquals
2547  * will be checked (either by the index itself, or by nodeIndexscan.c),
2548  * but if there are any "special" operators involved then they must be
2549  * included in qpqual. The upshot is that qpqual must contain
2550  * scan_clauses minus whatever appears in indexquals.
2551  *
2552  * In normal cases simple pointer equality checks will be enough to spot
2553  * duplicate RestrictInfos, so we try that first.
2554  *
2555  * Another common case is that a scan_clauses entry is generated from the
2556  * same EquivalenceClass as some indexqual, and is therefore redundant
2557  * with it, though not equal. (This happens when indxpath.c prefers a
2558  * different derived equality than what generate_join_implied_equalities
2559  * picked for a parameterized scan's ppi_clauses.)
2560  *
2561  * In some situations (particularly with OR'd index conditions) we may
2562  * have scan_clauses that are not equal to, but are logically implied by,
2563  * the index quals; so we also try a predicate_implied_by() check to see
2564  * if we can discard quals that way. (predicate_implied_by assumes its
2565  * first input contains only immutable functions, so we have to check
2566  * that.)
2567  *
2568  * Note: if you change this bit of code you should also look at
2569  * extract_nonindex_conditions() in costsize.c.
2570  */
2571  qpqual = NIL;
2572  foreach(l, scan_clauses)
2573  {
2574  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2575 
2576  if (rinfo->pseudoconstant)
2577  continue; /* we may drop pseudoconstants here */
2578  if (list_member_ptr(indexquals, rinfo))
2579  continue; /* simple duplicate */
2580  if (is_redundant_derived_clause(rinfo, indexquals))
2581  continue; /* derived from same EquivalenceClass */
2582  if (!contain_mutable_functions((Node *) rinfo->clause) &&
2583  predicate_implied_by(list_make1(rinfo->clause), indexquals, false))
2584  continue; /* provably implied by indexquals */
2585  qpqual = lappend(qpqual, rinfo);
2586  }
2587 
2588  /* Sort clauses into best execution order */
2589  qpqual = order_qual_clauses(root, qpqual);
2590 
2591  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2592  qpqual = extract_actual_clauses(qpqual, false);
2593 
2594  /*
2595  * We have to replace any outer-relation variables with nestloop params in
2596  * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
2597  * annoying to have to do this separately from the processing in
2598  * fix_indexqual_references --- rethink this when generalizing the inner
2599  * indexscan support. But note we can't really do this earlier because
2600  * it'd break the comparisons to predicates above ... (or would it? Those
2601  * wouldn't have outer refs)
2602  */
2603  if (best_path->path.param_info)
2604  {
2605  stripped_indexquals = (List *)
2606  replace_nestloop_params(root, (Node *) stripped_indexquals);
2607  qpqual = (List *)
2608  replace_nestloop_params(root, (Node *) qpqual);
2609  indexorderbys = (List *)
2610  replace_nestloop_params(root, (Node *) indexorderbys);
2611  }
2612 
2613  /*
2614  * If there are ORDER BY expressions, look up the sort operators for their
2615  * result datatypes.
2616  */
2617  if (indexorderbys)
2618  {
2619  ListCell *pathkeyCell,
2620  *exprCell;
2621 
2622  /*
2623  * PathKey contains OID of the btree opfamily we're sorting by, but
2624  * that's not quite enough because we need the expression's datatype
2625  * to look up the sort operator in the operator family.
2626  */
2627  Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
2628  forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
2629  {
2630  PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
2631  Node *expr = (Node *) lfirst(exprCell);
2632  Oid exprtype = exprType(expr);
2633  Oid sortop;
2634 
2635  /* Get sort operator from opfamily */
2636  sortop = get_opfamily_member(pathkey->pk_opfamily,
2637  exprtype,
2638  exprtype,
2639  pathkey->pk_strategy);
2640  if (!OidIsValid(sortop))
2641  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2642  pathkey->pk_strategy, exprtype, exprtype, pathkey->pk_opfamily);
2643  indexorderbyops = lappend_oid(indexorderbyops, sortop);
2644  }
2645  }
2646 
2647  /* Finally ready to build the plan node */
2648  if (indexonly)
2649  scan_plan = (Scan *) make_indexonlyscan(tlist,
2650  qpqual,
2651  baserelid,
2652  indexoid,
2653  fixed_indexquals,
2654  fixed_indexorderbys,
2655  best_path->indexinfo->indextlist,
2656  best_path->indexscandir);
2657  else
2658  scan_plan = (Scan *) make_indexscan(tlist,
2659  qpqual,
2660  baserelid,
2661  indexoid,
2662  fixed_indexquals,
2663  stripped_indexquals,
2664  fixed_indexorderbys,
2665  indexorderbys,
2666  indexorderbyops,
2667  best_path->indexscandir);
2668 
2669  copy_generic_path_info(&scan_plan->plan, &best_path->path);
2670 
2671  return scan_plan;
2672 }
2673 
2674 /*
2675  * create_bitmap_scan_plan
2676  * Returns a bitmap scan plan for the base relation scanned by 'best_path'
2677  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2678  */
2679 static BitmapHeapScan *
2681  BitmapHeapPath *best_path,
2682  List *tlist,
2683  List *scan_clauses)
2684 {
2685  Index baserelid = best_path->path.parent->relid;
2686  Plan *bitmapqualplan;
2687  List *bitmapqualorig;
2688  List *indexquals;
2689  List *indexECs;
2690  List *qpqual;
2691  ListCell *l;
2692  BitmapHeapScan *scan_plan;
2693 
2694  /* it should be a base rel... */
2695  Assert(baserelid > 0);
2696  Assert(best_path->path.parent->rtekind == RTE_RELATION);
2697 
2698  /* Process the bitmapqual tree into a Plan tree and qual lists */
2699  bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
2700  &bitmapqualorig, &indexquals,
2701  &indexECs);
2702 
2703  if (best_path->path.parallel_aware)
2704  bitmap_subplan_mark_shared(bitmapqualplan);
2705 
2706  /*
2707  * The qpqual list must contain all restrictions not automatically handled
2708  * by the index, other than pseudoconstant clauses which will be handled
2709  * by a separate gating plan node. All the predicates in the indexquals
2710  * will be checked (either by the index itself, or by
2711  * nodeBitmapHeapscan.c), but if there are any "special" operators
2712  * involved then they must be added to qpqual. The upshot is that qpqual
2713  * must contain scan_clauses minus whatever appears in indexquals.
2714  *
2715  * This loop is similar to the comparable code in create_indexscan_plan(),
2716  * but with some differences because it has to compare the scan clauses to
2717  * stripped (no RestrictInfos) indexquals. See comments there for more
2718  * info.
2719  *
2720  * In normal cases simple equal() checks will be enough to spot duplicate
2721  * clauses, so we try that first. We next see if the scan clause is
2722  * redundant with any top-level indexqual by virtue of being generated
2723  * from the same EC. After that, try predicate_implied_by().
2724  *
2725  * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
2726  * useful for getting rid of qpquals that are implied by index predicates,
2727  * because the predicate conditions are included in the "indexquals"
2728  * returned by create_bitmap_subplan(). Bitmap scans have to do it that
2729  * way because predicate conditions need to be rechecked if the scan
2730  * becomes lossy, so they have to be included in bitmapqualorig.
2731  */
2732  qpqual = NIL;
2733  foreach(l, scan_clauses)
2734  {
2735  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2736  Node *clause = (Node *) rinfo->clause;
2737 
2738  if (rinfo->pseudoconstant)
2739  continue; /* we may drop pseudoconstants here */
2740  if (list_member(indexquals, clause))
2741  continue; /* simple duplicate */
2742  if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
2743  continue; /* derived from same EquivalenceClass */
2744  if (!contain_mutable_functions(clause) &&
2745  predicate_implied_by(list_make1(clause), indexquals, false))
2746  continue; /* provably implied by indexquals */
2747  qpqual = lappend(qpqual, rinfo);
2748  }
2749 
2750  /* Sort clauses into best execution order */
2751  qpqual = order_qual_clauses(root, qpqual);
2752 
2753  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2754  qpqual = extract_actual_clauses(qpqual, false);
2755 
2756  /*
2757  * When dealing with special operators, we will at this point have
2758  * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
2759  * 'em from bitmapqualorig, since there's no point in making the tests
2760  * twice.
2761  */
2762  bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
2763 
2764  /*
2765  * We have to replace any outer-relation variables with nestloop params in
2766  * the qpqual and bitmapqualorig expressions. (This was already done for
2767  * expressions attached to plan nodes in the bitmapqualplan tree.)
2768  */
2769  if (best_path->path.param_info)
2770  {
2771  qpqual = (List *)
2772  replace_nestloop_params(root, (Node *) qpqual);
2773  bitmapqualorig = (List *)
2774  replace_nestloop_params(root, (Node *) bitmapqualorig);
2775  }
2776 
2777  /* Finally ready to build the plan node */
2778  scan_plan = make_bitmap_heapscan(tlist,
2779  qpqual,
2780  bitmapqualplan,
2781  bitmapqualorig,
2782  baserelid);
2783 
2784  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2785 
2786  return scan_plan;
2787 }
2788 
2789 /*
2790  * Given a bitmapqual tree, generate the Plan tree that implements it
2791  *
2792  * As byproducts, we also return in *qual and *indexqual the qual lists
2793  * (in implicit-AND form, without RestrictInfos) describing the original index
2794  * conditions and the generated indexqual conditions. (These are the same in
2795  * simple cases, but when special index operators are involved, the former
2796  * list includes the special conditions while the latter includes the actual
2797  * indexable conditions derived from them.) Both lists include partial-index
2798  * predicates, because we have to recheck predicates as well as index
2799  * conditions if the bitmap scan becomes lossy.
2800  *
2801  * In addition, we return a list of EquivalenceClass pointers for all the
2802  * top-level indexquals that were possibly-redundantly derived from ECs.
2803  * This allows removal of scan_clauses that are redundant with such quals.
2804  * (We do not attempt to detect such redundancies for quals that are within
2805  * OR subtrees. This could be done in a less hacky way if we returned the
2806  * indexquals in RestrictInfo form, but that would be slower and still pretty
2807  * messy, since we'd have to build new RestrictInfos in many cases.)
2808  */
2809 static Plan *
2811  List **qual, List **indexqual, List **indexECs)
2812 {
2813  Plan *plan;
2814 
2815  if (IsA(bitmapqual, BitmapAndPath))
2816  {
2817  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2818  List *subplans = NIL;
2819  List *subquals = NIL;
2820  List *subindexquals = NIL;
2821  List *subindexECs = NIL;
2822  ListCell *l;
2823 
2824  /*
2825  * There may well be redundant quals among the subplans, since a
2826  * top-level WHERE qual might have gotten used to form several
2827  * different index quals. We don't try exceedingly hard to eliminate
2828  * redundancies, but we do eliminate obvious duplicates by using
2829  * list_concat_unique.
2830  */
2831  foreach(l, apath->bitmapquals)
2832  {
2833  Plan *subplan;
2834  List *subqual;
2835  List *subindexqual;
2836  List *subindexEC;
2837 
2838  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2839  &subqual, &subindexqual,
2840  &subindexEC);
2841  subplans = lappend(subplans, subplan);
2842  subquals = list_concat_unique(subquals, subqual);
2843  subindexquals = list_concat_unique(subindexquals, subindexqual);
2844  /* Duplicates in indexECs aren't worth getting rid of */
2845  subindexECs = list_concat(subindexECs, subindexEC);
2846  }
2847  plan = (Plan *) make_bitmap_and(subplans);
2848  plan->startup_cost = apath->path.startup_cost;
2849  plan->total_cost = apath->path.total_cost;
2850  plan->plan_rows =
2851  clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
2852  plan->plan_width = 0; /* meaningless */
2853  plan->parallel_aware = false;
2854  plan->parallel_safe = apath->path.parallel_safe;
2855  *qual = subquals;
2856  *indexqual = subindexquals;
2857  *indexECs = subindexECs;
2858  }
2859  else if (IsA(bitmapqual, BitmapOrPath))
2860  {
2861  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2862  List *subplans = NIL;
2863  List *subquals = NIL;
2864  List *subindexquals = NIL;
2865  bool const_true_subqual = false;
2866  bool const_true_subindexqual = false;
2867  ListCell *l;
2868 
2869  /*
2870  * Here, we only detect qual-free subplans. A qual-free subplan would
2871  * cause us to generate "... OR true ..." which we may as well reduce
2872  * to just "true". We do not try to eliminate redundant subclauses
2873  * because (a) it's not as likely as in the AND case, and (b) we might
2874  * well be working with hundreds or even thousands of OR conditions,
2875  * perhaps from a long IN list. The performance of list_append_unique
2876  * would be unacceptable.
2877  */
2878  foreach(l, opath->bitmapquals)
2879  {
2880  Plan *subplan;
2881  List *subqual;
2882  List *subindexqual;
2883  List *subindexEC;
2884 
2885  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2886  &subqual, &subindexqual,
2887  &subindexEC);
2888  subplans = lappend(subplans, subplan);
2889  if (subqual == NIL)
2890  const_true_subqual = true;
2891  else if (!const_true_subqual)
2892  subquals = lappend(subquals,
2893  make_ands_explicit(subqual));
2894  if (subindexqual == NIL)
2895  const_true_subindexqual = true;
2896  else if (!const_true_subindexqual)
2897  subindexquals = lappend(subindexquals,
2898  make_ands_explicit(subindexqual));
2899  }
2900 
2901  /*
2902  * In the presence of ScalarArrayOpExpr quals, we might have built
2903  * BitmapOrPaths with just one subpath; don't add an OR step.
2904  */
2905  if (list_length(subplans) == 1)
2906  {
2907  plan = (Plan *) linitial(subplans);
2908  }
2909  else
2910  {
2911  plan = (Plan *) make_bitmap_or(subplans);
2912  plan->startup_cost = opath->path.startup_cost;
2913  plan->total_cost = opath->path.total_cost;
2914  plan->plan_rows =
2915  clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
2916  plan->plan_width = 0; /* meaningless */
2917  plan->parallel_aware = false;
2918  plan->parallel_safe = opath->path.parallel_safe;
2919  }
2920 
2921  /*
2922  * If there were constant-TRUE subquals, the OR reduces to constant
2923  * TRUE. Also, avoid generating one-element ORs, which could happen
2924  * due to redundancy elimination or ScalarArrayOpExpr quals.
2925  */
2926  if (const_true_subqual)
2927  *qual = NIL;
2928  else if (list_length(subquals) <= 1)
2929  *qual = subquals;
2930  else
2931  *qual = list_make1(make_orclause(subquals));
2932  if (const_true_subindexqual)
2933  *indexqual = NIL;
2934  else if (list_length(subindexquals) <= 1)
2935  *indexqual = subindexquals;
2936  else
2937  *indexqual = list_make1(make_orclause(subindexquals));
2938  *indexECs = NIL;
2939  }
2940  else if (IsA(bitmapqual, IndexPath))
2941  {
2942  IndexPath *ipath = (IndexPath *) bitmapqual;
2943  IndexScan *iscan;
2944  List *subindexECs;
2945  ListCell *l;
2946 
2947  /* Use the regular indexscan plan build machinery... */
2948  iscan = castNode(IndexScan,
2949  create_indexscan_plan(root, ipath,
2950  NIL, NIL, false));
2951  /* then convert to a bitmap indexscan */
2952  plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
2953  iscan->indexid,
2954  iscan->indexqual,
2955  iscan->indexqualorig);
2956  /* and set its cost/width fields appropriately */
2957  plan->startup_cost = 0.0;
2958  plan->total_cost = ipath->indextotalcost;
2959  plan->plan_rows =
2960  clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
2961  plan->plan_width = 0; /* meaningless */
2962  plan->parallel_aware = false;
2963  plan->parallel_safe = ipath->path.parallel_safe;
2964  *qual = get_actual_clauses(ipath->indexclauses);
2965  *indexqual = get_actual_clauses(ipath->indexquals);
2966  foreach(l, ipath->indexinfo->indpred)
2967  {
2968  Expr *pred = (Expr *) lfirst(l);
2969 
2970  /*
2971  * We know that the index predicate must have been implied by the
2972  * query condition as a whole, but it may or may not be implied by
2973  * the conditions that got pushed into the bitmapqual. Avoid
2974  * generating redundant conditions.
2975  */
2976  if (!predicate_implied_by(list_make1(pred), ipath->indexclauses,
2977  false))
2978  {
2979  *qual = lappend(*qual, pred);
2980  *indexqual = lappend(*indexqual, pred);
2981  }
2982  }
2983  subindexECs = NIL;
2984  foreach(l, ipath->indexquals)
2985  {
2986  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2987 
2988  if (rinfo->parent_ec)
2989  subindexECs = lappend(subindexECs, rinfo->parent_ec);
2990  }
2991  *indexECs = subindexECs;
2992  }
2993  else
2994  {
2995  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
2996  plan = NULL; /* keep compiler quiet */
2997  }
2998 
2999  return plan;
3000 }
3001 
3002 /*
3003  * create_tidscan_plan
3004  * Returns a tidscan plan for the base relation scanned by 'best_path'
3005  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3006  */
3007 static TidScan *
3009  List *tlist, List *scan_clauses)
3010 {
3011  TidScan *scan_plan;
3012  Index scan_relid = best_path->path.parent->relid;
3013  List *tidquals = best_path->tidquals;
3014  List *ortidquals;
3015 
3016  /* it should be a base rel... */
3017  Assert(scan_relid > 0);
3018  Assert(best_path->path.parent->rtekind == RTE_RELATION);
3019 
3020  /* Sort clauses into best execution order */
3021  scan_clauses = order_qual_clauses(root, scan_clauses);
3022 
3023  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3024  scan_clauses = extract_actual_clauses(scan_clauses, false);
3025 
3026  /* Replace any outer-relation variables with nestloop params */
3027  if (best_path->path.param_info)
3028  {
3029  tidquals = (List *)
3030  replace_nestloop_params(root, (Node *) tidquals);
3031  scan_clauses = (List *)
3032  replace_nestloop_params(root, (Node *) scan_clauses);
3033  }
3034 
3035  /*
3036  * Remove any clauses that are TID quals. This is a bit tricky since the
3037  * tidquals list has implicit OR semantics.
3038  */
3039  ortidquals = tidquals;
3040  if (list_length(ortidquals) > 1)
3041  ortidquals = list_make1(make_orclause(ortidquals));
3042  scan_clauses = list_difference(scan_clauses, ortidquals);
3043 
3044  scan_plan = make_tidscan(tlist,
3045  scan_clauses,
3046  scan_relid,
3047  tidquals);
3048 
3049  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3050 
3051  return scan_plan;
3052 }
3053 
3054 /*
3055  * create_subqueryscan_plan
3056  * Returns a subqueryscan plan for the base relation scanned by 'best_path'
3057  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3058  */
3059 static SubqueryScan *
3061  List *tlist, List *scan_clauses)
3062 {
3063  SubqueryScan *scan_plan;
3064  RelOptInfo *rel = best_path->path.parent;
3065  Index scan_relid = rel->relid;
3066  Plan *subplan;
3067 
3068  /* it should be a subquery base rel... */
3069  Assert(scan_relid > 0);
3070  Assert(rel->rtekind == RTE_SUBQUERY);
3071 
3072  /*
3073  * Recursively create Plan from Path for subquery. Since we are entering
3074  * a different planner context (subroot), recurse to create_plan not
3075  * create_plan_recurse.
3076  */
3077  subplan = create_plan(rel->subroot, best_path->subpath);
3078 
3079  /* Sort clauses into best execution order */
3080  scan_clauses = order_qual_clauses(root, scan_clauses);
3081 
3082  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3083  scan_clauses = extract_actual_clauses(scan_clauses, false);
3084 
3085  /* Replace any outer-relation variables with nestloop params */
3086  if (best_path->path.param_info)
3087  {
3088  scan_clauses = (List *)
3089  replace_nestloop_params(root, (Node *) scan_clauses);
3091  rel->subplan_params);
3092  }
3093 
3094  scan_plan = make_subqueryscan(tlist,
3095  scan_clauses,
3096  scan_relid,
3097  subplan);
3098 
3099  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3100 
3101  return scan_plan;
3102 }
3103 
3104 /*
3105  * create_functionscan_plan
3106  * Returns a functionscan plan for the base relation scanned by 'best_path'
3107  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3108  */
3109 static FunctionScan *
3111  List *tlist, List *scan_clauses)
3112 {
3113  FunctionScan *scan_plan;
3114  Index scan_relid = best_path->parent->relid;
3115  RangeTblEntry *rte;
3116  List *functions;
3117 
3118  /* it should be a function base rel... */
3119  Assert(scan_relid > 0);
3120  rte = planner_rt_fetch(scan_relid, root);
3121  Assert(rte->rtekind == RTE_FUNCTION);
3122  functions = rte->functions;
3123 
3124  /* Sort clauses into best execution order */
3125  scan_clauses = order_qual_clauses(root, scan_clauses);
3126 
3127  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3128  scan_clauses = extract_actual_clauses(scan_clauses, false);
3129 
3130  /* Replace any outer-relation variables with nestloop params */
3131  if (best_path->param_info)
3132  {
3133  scan_clauses = (List *)
3134  replace_nestloop_params(root, (Node *) scan_clauses);
3135  /* The function expressions could contain nestloop params, too */
3136  functions = (List *) replace_nestloop_params(root, (Node *) functions);
3137  }
3138 
3139  scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
3140  functions, rte->funcordinality);
3141 
3142  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3143 
3144  return scan_plan;
3145 }
3146 
3147 /*
3148  * create_tablefuncscan_plan
3149  * Returns a tablefuncscan plan for the base relation scanned by 'best_path'
3150  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3151  */
3152 static TableFuncScan *
3154  List *tlist, List *scan_clauses)
3155 {
3156  TableFuncScan *scan_plan;
3157  Index scan_relid = best_path->parent->relid;
3158  RangeTblEntry *rte;
3159  TableFunc *tablefunc;
3160 
3161  /* it should be a function base rel... */
3162  Assert(scan_relid > 0);
3163  rte = planner_rt_fetch(scan_relid, root);
3164  Assert(rte->rtekind == RTE_TABLEFUNC);
3165  tablefunc = rte->tablefunc;
3166 
3167  /* Sort clauses into best execution order */
3168  scan_clauses = order_qual_clauses(root, scan_clauses);
3169 
3170  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3171  scan_clauses = extract_actual_clauses(scan_clauses, false);
3172 
3173  /* Replace any outer-relation variables with nestloop params */
3174  if (best_path->param_info)
3175  {
3176  scan_clauses = (List *)
3177  replace_nestloop_params(root, (Node *) scan_clauses);
3178  /* The function expressions could contain nestloop params, too */
3179  tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
3180  }
3181 
3182  scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
3183  tablefunc);
3184 
3185  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3186 
3187  return scan_plan;
3188 }
3189 
3190 /*
3191  * create_valuesscan_plan
3192  * Returns a valuesscan plan for the base relation scanned by 'best_path'
3193  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3194  */
3195 static ValuesScan *
3197  List *tlist, List *scan_clauses)
3198 {
3199  ValuesScan *scan_plan;
3200  Index scan_relid = best_path->parent->relid;
3201  RangeTblEntry *rte;
3202  List *values_lists;
3203 
3204  /* it should be a values base rel... */
3205  Assert(scan_relid > 0);
3206  rte = planner_rt_fetch(scan_relid, root);
3207  Assert(rte->rtekind == RTE_VALUES);
3208  values_lists = rte->values_lists;
3209 
3210  /* Sort clauses into best execution order */
3211  scan_clauses = order_qual_clauses(root, scan_clauses);
3212 
3213  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3214  scan_clauses = extract_actual_clauses(scan_clauses, false);
3215 
3216  /* Replace any outer-relation variables with nestloop params */
3217  if (best_path->param_info)
3218  {
3219  scan_clauses = (List *)
3220  replace_nestloop_params(root, (Node *) scan_clauses);
3221  /* The values lists could contain nestloop params, too */
3222  values_lists = (List *)
3223  replace_nestloop_params(root, (Node *) values_lists);
3224  }
3225 
3226  scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
3227  values_lists);
3228 
3229  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3230 
3231  return scan_plan;
3232 }
3233 
3234 /*
3235  * create_ctescan_plan
3236  * Returns a ctescan plan for the base relation scanned by 'best_path'
3237  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3238  */
3239 static CteScan *
3241  List *tlist, List *scan_clauses)
3242 {
3243  CteScan *scan_plan;
3244  Index scan_relid = best_path->parent->relid;
3245  RangeTblEntry *rte;
3246  SubPlan *ctesplan = NULL;
3247  int plan_id;
3248  int cte_param_id;
3249  PlannerInfo *cteroot;
3250  Index levelsup;
3251  int ndx;
3252  ListCell *lc;
3253 
3254  Assert(scan_relid > 0);
3255  rte = planner_rt_fetch(scan_relid, root);
3256  Assert(rte->rtekind == RTE_CTE);
3257  Assert(!rte->self_reference);
3258 
3259  /*
3260  * Find the referenced CTE, and locate the SubPlan previously made for it.
3261  */
3262  levelsup = rte->ctelevelsup;
3263  cteroot = root;
3264  while (levelsup-- > 0)
3265  {
3266  cteroot = cteroot->parent_root;
3267  if (!cteroot) /* shouldn't happen */
3268  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3269  }
3270 
3271  /*
3272  * Note: cte_plan_ids can be shorter than cteList, if we are still working
3273  * on planning the CTEs (ie, this is a side-reference from another CTE).
3274  * So we mustn't use forboth here.
3275  */
3276  ndx = 0;
3277  foreach(lc, cteroot->parse->cteList)
3278  {
3279  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3280 
3281  if (strcmp(cte->ctename, rte->ctename) == 0)
3282  break;
3283  ndx++;
3284  }
3285  if (lc == NULL) /* shouldn't happen */
3286  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3287  if (ndx >= list_length(cteroot->cte_plan_ids))
3288  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3289  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3290  Assert(plan_id > 0);
3291  foreach(lc, cteroot->init_plans)
3292  {
3293  ctesplan = (SubPlan *) lfirst(lc);
3294  if (ctesplan->plan_id == plan_id)
3295  break;
3296  }
3297  if (lc == NULL) /* shouldn't happen */
3298  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3299 
3300  /*
3301  * We need the CTE param ID, which is the sole member of the SubPlan's
3302  * setParam list.
3303  */
3304  cte_param_id = linitial_int(ctesplan->setParam);
3305 
3306  /* Sort clauses into best execution order */
3307  scan_clauses = order_qual_clauses(root, scan_clauses);
3308 
3309  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3310  scan_clauses = extract_actual_clauses(scan_clauses, false);
3311 
3312  /* Replace any outer-relation variables with nestloop params */
3313  if (best_path->param_info)
3314  {
3315  scan_clauses = (List *)
3316  replace_nestloop_params(root, (Node *) scan_clauses);
3317  }
3318 
3319  scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3320  plan_id, cte_param_id);
3321 
3322  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3323 
3324  return scan_plan;
3325 }
3326 
3327 /*
3328  * create_namedtuplestorescan_plan
3329  * Returns a tuplestorescan plan for the base relation scanned by
3330  * 'best_path' with restriction clauses 'scan_clauses' and targetlist
3331  * 'tlist'.
3332  */
3333 static NamedTuplestoreScan *
3335  List *tlist, List *scan_clauses)
3336 {
3337  NamedTuplestoreScan *scan_plan;
3338  Index scan_relid = best_path->parent->relid;
3339  RangeTblEntry *rte;
3340 
3341  Assert(scan_relid > 0);
3342  rte = planner_rt_fetch(scan_relid, root);
3344 
3345  /* Sort clauses into best execution order */
3346  scan_clauses = order_qual_clauses(root, scan_clauses);
3347 
3348  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3349  scan_clauses = extract_actual_clauses(scan_clauses, false);
3350 
3351  /* Replace any outer-relation variables with nestloop params */
3352  if (best_path->param_info)
3353  {
3354  scan_clauses = (List *)
3355  replace_nestloop_params(root, (Node *) scan_clauses);
3356  }
3357 
3358  scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
3359  rte->enrname);
3360 
3361  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3362 
3363  return scan_plan;
3364 }
3365 
3366 /*
3367  * create_worktablescan_plan
3368  * Returns a worktablescan plan for the base relation scanned by 'best_path'
3369  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3370  */
3371 static WorkTableScan *
3373  List *tlist, List *scan_clauses)
3374 {
3375  WorkTableScan *scan_plan;
3376  Index scan_relid = best_path->parent->relid;
3377  RangeTblEntry *rte;
3378  Index levelsup;
3379  PlannerInfo *cteroot;
3380 
3381  Assert(scan_relid > 0);
3382  rte = planner_rt_fetch(scan_relid, root);
3383  Assert(rte->rtekind == RTE_CTE);
3384  Assert(rte->self_reference);
3385 
3386  /*
3387  * We need to find the worktable param ID, which is in the plan level
3388  * that's processing the recursive UNION, which is one level *below* where
3389  * the CTE comes from.
3390  */
3391  levelsup = rte->ctelevelsup;
3392  if (levelsup == 0) /* shouldn't happen */
3393  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3394  levelsup--;
3395  cteroot = root;
3396  while (levelsup-- > 0)
3397  {
3398  cteroot = cteroot->parent_root;
3399  if (!cteroot) /* shouldn't happen */
3400  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3401  }
3402  if (cteroot->wt_param_id < 0) /* shouldn't happen */
3403  elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
3404 
3405  /* Sort clauses into best execution order */
3406  scan_clauses = order_qual_clauses(root, scan_clauses);
3407 
3408  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3409  scan_clauses = extract_actual_clauses(scan_clauses, false);
3410 
3411  /* Replace any outer-relation variables with nestloop params */
3412  if (best_path->param_info)
3413  {
3414  scan_clauses = (List *)
3415  replace_nestloop_params(root, (Node *) scan_clauses);
3416  }
3417 
3418  scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
3419  cteroot->wt_param_id);
3420 
3421  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3422 
3423  return scan_plan;
3424 }
3425 
3426 /*
3427  * create_foreignscan_plan
3428  * Returns a foreignscan plan for the relation scanned by 'best_path'
3429  * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3430  */
3431 static ForeignScan *
3433  List *tlist, List *scan_clauses)
3434 {
3435  ForeignScan *scan_plan;
3436  RelOptInfo *rel = best_path->path.parent;
3437  Index scan_relid = rel->relid;
3438  Oid rel_oid = InvalidOid;
3439  Plan *outer_plan = NULL;
3440 
3441  Assert(rel->fdwroutine != NULL);
3442 
3443  /* transform the child path if any */
3444  if (best_path->fdw_outerpath)
3445  outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3446  CP_EXACT_TLIST);
3447 
3448  /*
3449  * If we're scanning a base relation, fetch its OID. (Irrelevant if
3450  * scanning a join relation.)
3451  */
3452  if (scan_relid > 0)
3453  {
3454  RangeTblEntry *rte;
3455 
3456  Assert(rel->rtekind == RTE_RELATION);
3457  rte = planner_rt_fetch(scan_relid, root);
3458  Assert(rte->rtekind == RTE_RELATION);
3459  rel_oid = rte->relid;
3460  }
3461 
3462  /*
3463  * Sort clauses into best execution order. We do this first since the FDW
3464  * might have more info than we do and wish to adjust the ordering.
3465  */
3466  scan_clauses = order_qual_clauses(root, scan_clauses);
3467 
3468  /*
3469  * Let the FDW perform its processing on the restriction clauses and
3470  * generate the plan node. Note that the FDW might remove restriction
3471  * clauses that it intends to execute remotely, or even add more (if it
3472  * has selected some join clauses for remote use but also wants them
3473  * rechecked locally).
3474  */
3475  scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
3476  best_path,
3477  tlist, scan_clauses,
3478  outer_plan);
3479 
3480  /* Copy cost data from Path to Plan; no need to make FDW do this */
3481  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3482 
3483  /* Copy foreign server OID; likewise, no need to make FDW do this */
3484  scan_plan->fs_server = rel->serverid;
3485 
3486  /*
3487  * Likewise, copy the relids that are represented by this foreign scan. An
3488  * upper rel doesn't have relids set, but it covers all the base relations
3489  * participating in the underlying scan, so use root's all_baserels.
3490  */
3491  if (IS_UPPER_REL(rel))
3492  scan_plan->fs_relids = root->all_baserels;
3493  else
3494  scan_plan->fs_relids = best_path->path.parent->relids;
3495 
3496  /*
3497  * If this is a foreign join, and to make it valid to push down we had to
3498  * assume that the current user is the same as some user explicitly named
3499  * in the query, mark the finished plan as depending on the current user.
3500  */
3501  if (rel->useridiscurrent)
3502  root->glob->dependsOnRole = true;
3503 
3504  /*
3505  * Replace any outer-relation variables with nestloop params in the qual,
3506  * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
3507  * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
3508  * fdw_recheck_quals could have come from join clauses, so doing this
3509  * beforehand on the scan_clauses wouldn't work.) We assume
3510  * fdw_scan_tlist contains no such variables.
3511  */
3512  if (best_path->path.param_info)
3513  {
3514  scan_plan->scan.plan.qual = (List *)
3515  replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
3516  scan_plan->fdw_exprs = (List *)
3517  replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
3518  scan_plan->fdw_recheck_quals = (List *)
3520  (Node *) scan_plan->fdw_recheck_quals);
3521  }
3522 
3523  /*
3524  * If rel is a base relation, detect whether any system columns are
3525  * requested from the rel. (If rel is a join relation, rel->relid will be
3526  * 0, but there can be no Var with relid 0 in the rel's targetlist or the
3527  * restriction clauses, so we skip this in that case. Note that any such
3528  * columns in base relations that were joined are assumed to be contained
3529  * in fdw_scan_tlist.) This is a bit of a kluge and might go away
3530  * someday, so we intentionally leave it out of the API presented to FDWs.
3531  */
3532  scan_plan->fsSystemCol = false;
3533  if (scan_relid > 0)
3534  {
3535  Bitmapset *attrs_used = NULL;
3536  ListCell *lc;
3537  int i;
3538 
3539  /*
3540  * First, examine all the attributes needed for joins or final output.
3541  * Note: we must look at rel's targetlist, not the attr_needed data,
3542  * because attr_needed isn't computed for inheritance child rels.
3543  */
3544  pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
3545 
3546  /* Add all the attributes used by restriction clauses. */
3547  foreach(lc, rel->baserestrictinfo)
3548  {
3549  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3550 
3551  pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
3552  }
3553 
3554  /* Now, are any system columns requested from rel? */
3555  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
3556  {
3558  {
3559  scan_plan->fsSystemCol = true;
3560  break;
3561  }
3562  }
3563 
3564  bms_free(attrs_used);
3565  }
3566 
3567  return scan_plan;
3568 }
3569 
3570 /*
3571  * create_custom_plan
3572  *
3573  * Transform a CustomPath into a Plan.
3574  */
3575 static CustomScan *
3577  List *tlist, List *scan_clauses)
3578 {
3579  CustomScan *cplan;
3580  RelOptInfo *rel = best_path->path.parent;
3581  List *custom_plans = NIL;
3582  ListCell *lc;
3583 
3584  /* Recursively transform child paths. */
3585  foreach(lc, best_path->custom_paths)
3586  {
3587  Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
3588  CP_EXACT_TLIST);
3589 
3590  custom_plans = lappend(custom_plans, plan);
3591  }
3592 
3593  /*
3594  * Sort clauses into the best execution order, although custom-scan
3595  * provider can reorder them again.
3596  */
3597  scan_clauses = order_qual_clauses(root, scan_clauses);
3598 
3599  /*
3600  * Invoke custom plan provider to create the Plan node represented by the
3601  * CustomPath.
3602  */
3603  cplan = castNode(CustomScan,
3604  best_path->methods->PlanCustomPath(root,
3605  rel,
3606  best_path,
3607  tlist,
3608  scan_clauses,
3609  custom_plans));
3610 
3611  /*
3612  * Copy cost data from Path to Plan; no need to make custom-plan providers
3613  * do this
3614  */
3615  copy_generic_path_info(&cplan->scan.plan, &best_path->path);
3616 
3617  /* Likewise, copy the relids that are represented by this custom scan */
3618  cplan->custom_relids = best_path->path.parent->relids;
3619 
3620  /*
3621  * Replace any outer-relation variables with nestloop params in the qual
3622  * and custom_exprs expressions. We do this last so that the custom-plan
3623  * provider doesn't have to be involved. (Note that parts of custom_exprs
3624  * could have come from join clauses, so doing this beforehand on the
3625  * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
3626  * such variables.
3627  */
3628  if (best_path->path.param_info)
3629  {
3630  cplan->scan.plan.qual = (List *)
3631  replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
3632  cplan->custom_exprs = (List *)
3633  replace_nestloop_params(root, (Node *) cplan->custom_exprs);
3634  }
3635 
3636  return cplan;
3637 }
3638 
3639 
3640 /*****************************************************************************
3641  *
3642  * JOIN METHODS
3643  *
3644  *****************************************************************************/
3645 
3646 static NestLoop *
3648  NestPath *best_path)
3649 {
3650  NestLoop *join_plan;
3651  Plan *outer_plan;
3652  Plan *inner_plan;
3653  List *tlist = build_path_tlist(root, &best_path->path);
3654  List *joinrestrictclauses = best_path->joinrestrictinfo;
3655  List *joinclauses;
3656  List *otherclauses;
3657  Relids outerrelids;
3658  List *nestParams;
3659  Relids saveOuterRels = root->curOuterRels;
3660  ListCell *cell;
3661  ListCell *prev;
3662  ListCell *next;
3663 
3664  /* NestLoop can project, so no need to be picky about child tlists */
3665  outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
3666 
3667  /* For a nestloop, include outer relids in curOuterRels for inner side */
3668  root->curOuterRels = bms_union(root->curOuterRels,
3669  best_path->outerjoinpath->parent->relids);
3670 
3671  inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
3672 
3673  /* Restore curOuterRels */
3674  bms_free(root->curOuterRels);
3675  root->curOuterRels = saveOuterRels;
3676 
3677  /* Sort join qual clauses into best execution order */
3678  joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
3679 
3680  /* Get the join qual clauses (in plain expression form) */
3681  /* Any pseudoconstant clauses are ignored here */
3682  if (IS_OUTER_JOIN(best_path->jointype))
3683  {
3684  extract_actual_join_clauses(joinrestrictclauses,
3685  &joinclauses, &otherclauses);
3686  }
3687  else
3688  {
3689  /* We can treat all clauses alike for an inner join */
3690  joinclauses = extract_actual_clauses(joinrestrictclauses, false);
3691  otherclauses = NIL;
3692  }
3693 
3694  /* Replace any outer-relation variables with nestloop params */
3695  if (best_path->path.param_info)
3696  {
3697  joinclauses = (List *)
3698  replace_nestloop_params(root, (Node *) joinclauses);
3699  otherclauses = (List *)
3700  replace_nestloop_params(root, (Node *) otherclauses);
3701  }
3702 
3703  /*
3704  * Identify any nestloop parameters that should be supplied by this join
3705  * node, and move them from root->curOuterParams to the nestParams list.
3706  */
3707  outerrelids = best_path->outerjoinpath->parent->relids;
3708  nestParams = NIL;
3709  prev = NULL;
3710  for (cell = list_head(root->curOuterParams); cell; cell = next)
3711  {
3712  NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
3713 
3714  next = lnext(cell);
3715  if (IsA(nlp->paramval, Var) &&
3716  bms_is_member(nlp->paramval->varno, outerrelids))
3717  {
3719  cell, prev);
3720  nestParams = lappend(nestParams, nlp);
3721  }
3722  else if (IsA(nlp->paramval, PlaceHolderVar) &&
3723  bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
3724  outerrelids) &&
3726  (PlaceHolderVar *) nlp->paramval,
3727  false)->ph_eval_at,
3728  outerrelids))
3729  {
3731  cell, prev);
3732  nestParams = lappend(nestParams, nlp);
3733  }
3734  else
3735  prev = cell;
3736  }
3737 
3738  join_plan = make_nestloop(tlist,
3739  joinclauses,
3740  otherclauses,
3741  nestParams,
3742  outer_plan,
3743  inner_plan,
3744  best_path->jointype,
3745  best_path->inner_unique);
3746 
3747  copy_generic_path_info(&join_plan->join.plan, &best_path->path);
3748 
3749  return join_plan;
3750 }
3751 
3752 static MergeJoin *
3754  MergePath *best_path)
3755 {
3756  MergeJoin *join_plan;
3757  Plan *outer_plan;
3758  Plan *inner_plan;
3759  List *tlist = build_path_tlist(root, &best_path->jpath.path);
3760  List *joinclauses;
3761  List *otherclauses;
3762  List *mergeclauses;
3763  List *outerpathkeys;
3764  List *innerpathkeys;
3765  int nClauses;
3766  Oid *mergefamilies;
3767  Oid *mergecollations;
3768  int *mergestrategies;
3769  bool *mergenullsfirst;
3770  int i;
3771  ListCell *lc;
3772  ListCell *lop;
3773  ListCell *lip;
3774 
3775  /*
3776  * MergeJoin can project, so we don't have to demand exact tlists from the
3777  * inputs. However, if we're intending to sort an input's result, it's
3778  * best to request a small tlist so we aren't sorting more data than
3779  * necessary.
3780  */
3781  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3782  (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3783 
3784  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3785  (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3786 
3787  /* Sort join qual clauses into best execution order */
3788  /* NB: do NOT reorder the mergeclauses */
3789  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3790 
3791  /* Get the join qual clauses (in plain expression form) */
3792  /* Any pseudoconstant clauses are ignored here */
3793  if (IS_OUTER_JOIN(best_path->jpath.jointype))
3794  {
3795  extract_actual_join_clauses(joinclauses,
3796  &joinclauses, &otherclauses);
3797  }
3798  else
3799  {
3800  /* We can treat all clauses alike for an inner join */
3801  joinclauses = extract_actual_clauses(joinclauses, false);
3802  otherclauses = NIL;
3803  }
3804 
3805  /*
3806  * Remove the mergeclauses from the list of join qual clauses, leaving the
3807  * list of quals that must be checked as qpquals.
3808  */
3809  mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
3810  joinclauses = list_difference(joinclauses, mergeclauses);
3811 
3812  /*
3813  * Replace any outer-relation variables with nestloop params. There
3814  * should not be any in the mergeclauses.
3815  */
3816  if (best_path->jpath.path.param_info)
3817  {
3818  joinclauses = (List *)
3819  replace_nestloop_params(root, (Node *) joinclauses);
3820  otherclauses = (List *)
3821  replace_nestloop_params(root, (Node *) otherclauses);
3822  }
3823 
3824  /*
3825  * Rearrange mergeclauses, if needed, so that the outer variable is always
3826  * on the left; mark the mergeclause restrictinfos with correct
3827  * outer_is_left status.
3828  */
3829  mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
3830  best_path->jpath.outerjoinpath->parent->relids);
3831 
3832  /*
3833  * Create explicit sort nodes for the outer and inner paths if necessary.
3834  */
3835  if (best_path->outersortkeys)
3836  {
3837  Sort *sort = make_sort_from_pathkeys(outer_plan,
3838  best_path->outersortkeys);
3839 
3840  label_sort_with_costsize(root, sort, -1.0);
3841  outer_plan = (Plan *) sort;
3842  outerpathkeys = best_path->outersortkeys;
3843  }
3844  else
3845  outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
3846 
3847  if (best_path->innersortkeys)
3848  {
3849  Sort *sort = make_sort_from_pathkeys(inner_plan,
3850  best_path->innersortkeys);
3851 
3852  label_sort_with_costsize(root, sort, -1.0);
3853  inner_plan = (Plan *) sort;
3854  innerpathkeys = best_path->innersortkeys;
3855  }
3856  else
3857  innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
3858 
3859  /*
3860  * If specified, add a materialize node to shield the inner plan from the
3861  * need to handle mark/restore.
3862  */
3863  if (best_path->materialize_inner)
3864  {
3865  Plan *matplan = (Plan *) make_material(inner_plan);
3866 
3867  /*
3868  * We assume the materialize will not spill to disk, and therefore
3869  * charge just cpu_operator_cost per tuple. (Keep this estimate in
3870  * sync with final_cost_mergejoin.)
3871  */
3872  copy_plan_costsize(matplan, inner_plan);
3873  matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
3874 
3875  inner_plan = matplan;
3876  }
3877 
3878  /*
3879  * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
3880  * executor. The information is in the pathkeys for the two inputs, but
3881  * we need to be careful about the possibility of mergeclauses sharing a
3882  * pathkey (compare find_mergeclauses_for_pathkeys()).
3883  */
3884  nClauses = list_length(mergeclauses);
3885  Assert(nClauses == list_length(best_path->path_mergeclauses));
3886  mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
3887  mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
3888  mergestrategies = (int *) palloc(nClauses * sizeof(int));
3889  mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
3890 
3891  lop = list_head(outerpathkeys);
3892  lip = list_head(innerpathkeys);
3893  i = 0;
3894  foreach(lc, best_path->path_mergeclauses)
3895  {
3896  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3897  EquivalenceClass *oeclass;
3898  EquivalenceClass *ieclass;
3899  PathKey *opathkey;
3900  PathKey *ipathkey;
3901  EquivalenceClass *opeclass;
3902  EquivalenceClass *ipeclass;
3903  ListCell *l2;
3904 
3905  /* fetch outer/inner eclass from mergeclause */
3906  if (rinfo->outer_is_left)
3907  {
3908  oeclass = rinfo->left_ec;
3909  ieclass = rinfo->right_ec;
3910  }
3911  else
3912  {
3913  oeclass = rinfo->right_ec;
3914  ieclass = rinfo->left_ec;
3915  }
3916  Assert(oeclass != NULL);
3917  Assert(ieclass != NULL);
3918 
3919  /*
3920  * For debugging purposes, we check that the eclasses match the paths'
3921  * pathkeys. In typical cases the merge clauses are one-to-one with
3922  * the pathkeys, but when dealing with partially redundant query
3923  * conditions, we might have clauses that re-reference earlier path
3924  * keys. The case that we need to reject is where a pathkey is
3925  * entirely skipped over.
3926  *
3927  * lop and lip reference the first as-yet-unused pathkey elements;
3928  * it's okay to match them, or any element before them. If they're
3929  * NULL then we have found all pathkey elements to be used.
3930  */
3931  if (lop)
3932  {
3933  opathkey = (PathKey *) lfirst(lop);
3934  opeclass = opathkey->pk_eclass;
3935  if (oeclass == opeclass)
3936  {
3937  /* fast path for typical case */
3938  lop = lnext(lop);
3939  }
3940  else
3941  {
3942  /* redundant clauses ... must match something before lop */
3943  foreach(l2, outerpathkeys)
3944  {
3945  if (l2 == lop)
3946  break;
3947  opathkey = (PathKey *) lfirst(l2);
3948  opeclass = opathkey->pk_eclass;
3949  if (oeclass == opeclass)
3950  break;
3951  }
3952  if (oeclass != opeclass)
3953  elog(ERROR, "outer pathkeys do not match mergeclauses");
3954  }
3955  }
3956  else
3957  {
3958  /* redundant clauses ... must match some already-used pathkey */
3959  opathkey = NULL;
3960  opeclass = NULL;
3961  foreach(l2, outerpathkeys)
3962  {
3963  opathkey = (PathKey *) lfirst(l2);
3964  opeclass = opathkey->pk_eclass;
3965  if (oeclass == opeclass)
3966  break;
3967  }
3968  if (l2 == NULL)
3969  elog(ERROR, "outer pathkeys do not match mergeclauses");
3970  }
3971 
3972  if (lip)
3973  {
3974  ipathkey = (PathKey *) lfirst(lip);
3975  ipeclass = ipathkey->pk_eclass;
3976  if (ieclass == ipeclass)
3977  {
3978  /* fast path for typical case */
3979  lip = lnext(lip);
3980  }
3981  else
3982  {
3983  /* redundant clauses ... must match something before lip */
3984  foreach(l2, innerpathkeys)
3985  {
3986  if (l2 == lip)
3987  break;
3988  ipathkey = (PathKey *) lfirst(l2);
3989  ipeclass = ipathkey->pk_eclass;
3990  if (ieclass == ipeclass)
3991  break;
3992  }
3993  if (ieclass != ipeclass)
3994  elog(ERROR, "inner pathkeys do not match mergeclauses");
3995  }
3996  }
3997  else
3998  {
3999  /* redundant clauses ... must match some already-used pathkey */
4000  ipathkey = NULL;
4001  ipeclass = NULL;
4002  foreach(l2, innerpathkeys)
4003  {
4004  ipathkey = (PathKey *) lfirst(l2);
4005  ipeclass = ipathkey->pk_eclass;
4006  if (ieclass == ipeclass)
4007  break;
4008  }
4009  if (l2 == NULL)
4010  elog(ERROR, "inner pathkeys do not match mergeclauses");
4011  }
4012 
4013  /* pathkeys should match each other too (more debugging) */
4014  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4015  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
4016  opathkey->pk_strategy != ipathkey->pk_strategy ||
4017  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
4018  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4019 
4020  /* OK, save info for executor */
4021  mergefamilies[i] = opathkey->pk_opfamily;
4022  mergecollations[i] = opathkey->pk_eclass->ec_collation;
4023  mergestrategies[i] = opathkey->pk_strategy;
4024  mergenullsfirst[i] = opathkey->pk_nulls_first;
4025  i++;
4026  }
4027 
4028  /*
4029  * Note: it is not an error if we have additional pathkey elements (i.e.,
4030  * lop or lip isn't NULL here). The input paths might be better-sorted
4031  * than we need for the current mergejoin.
4032  */
4033 
4034  /*
4035  * Now we can build the mergejoin node.
4036  */
4037  join_plan = make_mergejoin(tlist,
4038  joinclauses,
4039  otherclauses,
4040  mergeclauses,
4041  mergefamilies,
4042  mergecollations,
4043  mergestrategies,
4044  mergenullsfirst,
4045  outer_plan,
4046  inner_plan,
4047  best_path->jpath.jointype,
4048  best_path->jpath.inner_unique,
4049  best_path->skip_mark_restore);
4050 
4051  /* Costs of sort and material steps are included in path cost already */
4052  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4053 
4054  return join_plan;
4055 }
4056 
4057 static HashJoin *
4059  HashPath *best_path)
4060 {
4061  HashJoin *join_plan;
4062  Hash *hash_plan;
4063  Plan *outer_plan;
4064  Plan *inner_plan;
4065  List *tlist = build_path_tlist(root, &best_path->jpath.path);
4066  List *joinclauses;
4067  List *otherclauses;
4068  List *hashclauses;
4069  Oid skewTable = InvalidOid;
4070  AttrNumber skewColumn = InvalidAttrNumber;
4071  bool skewInherit = false;
4072 
4073  /*
4074  * HashJoin can project, so we don't have to demand exact tlists from the
4075  * inputs. However, it's best to request a small tlist from the inner
4076  * side, so that we aren't storing more data than necessary. Likewise, if
4077  * we anticipate batching, request a small tlist from the outer side so
4078  * that we don't put extra data in the outer batch files.
4079  */
4080  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4081  (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4082 
4083  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4084  CP_SMALL_TLIST);
4085 
4086  /* Sort join qual clauses into best execution order */
4087  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4088  /* There's no point in sorting the hash clauses ... */
4089 
4090  /* Get the join qual clauses (in plain expression form) */
4091  /* Any pseudoconstant clauses are ignored here */
4092  if (IS_OUTER_JOIN(best_path->jpath.jointype))
4093  {
4094  extract_actual_join_clauses(joinclauses,
4095  &joinclauses, &otherclauses);
4096  }
4097  else
4098  {
4099  /* We can treat all clauses alike for an inner join */
4100  joinclauses = extract_actual_clauses(joinclauses, false);
4101  otherclauses = NIL;
4102  }
4103 
4104  /*
4105  * Remove the hashclauses from the list of join qual clauses, leaving the
4106  * list of quals that must be checked as qpquals.
4107  */
4108  hashclauses = get_actual_clauses(best_path->path_hashclauses);
4109  joinclauses = list_difference(joinclauses, hashclauses);
4110 
4111  /*
4112  * Replace any outer-relation variables with nestloop params. There
4113  * should not be any in the hashclauses.
4114  */
4115  if (best_path->jpath.path.param_info)
4116  {
4117  joinclauses = (List *)
4118  replace_nestloop_params(root, (Node *) joinclauses);
4119  otherclauses = (List *)
4120  replace_nestloop_params(root, (Node *) otherclauses);
4121  }
4122 
4123  /*
4124  * Rearrange hashclauses, if needed, so that the outer variable is always
4125  * on the left.
4126  */
4127  hashclauses = get_switched_clauses(best_path->path_hashclauses,
4128  best_path->jpath.outerjoinpath->parent->relids);
4129 
4130  /*
4131  * If there is a single join clause and we can identify the outer variable
4132  * as a simple column reference, supply its identity for possible use in
4133  * skew optimization. (Note: in principle we could do skew optimization
4134  * with multiple join clauses, but we'd have to be able to determine the
4135  * most common combinations of outer values, which we don't currently have
4136  * enough stats for.)
4137  */
4138  if (list_length(hashclauses) == 1)
4139  {
4140  OpExpr *clause = (OpExpr *) linitial(hashclauses);
4141  Node *node;
4142 
4143  Assert(is_opclause(clause));
4144  node = (Node *) linitial(clause->args);
4145  if (IsA(node, RelabelType))
4146  node = (Node *) ((RelabelType *) node)->arg;
4147  if (IsA(node, Var))
4148  {
4149  Var *var = (Var *) node;
4150  RangeTblEntry *rte;
4151 
4152  rte = root->simple_rte_array[var->varno];
4153  if (rte->rtekind == RTE_RELATION)
4154  {
4155  skewTable = rte->relid;
4156  skewColumn = var->varattno;
4157  skewInherit = rte->inh;
4158  }
4159  }
4160  }
4161 
4162  /*
4163  * Build the hash node and hash join node.
4164  */
4165  hash_plan = make_hash(inner_plan,
4166  skewTable,
4167  skewColumn,
4168  skewInherit);
4169 
4170  /*
4171  * Set Hash node's startup & total costs equal to total cost of input
4172  * plan; this only affects EXPLAIN display not decisions.
4173  */
4174  copy_plan_costsize(&hash_plan->plan, inner_plan);
4175  hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4176 
4177  join_plan = make_hashjoin(tlist,
4178  joinclauses,
4179  otherclauses,
4180  hashclauses,
4181  outer_plan,
4182  (Plan *) hash_plan,
4183  best_path->jpath.jointype,
4184  best_path->jpath.inner_unique);
4185 
4186  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4187 
4188  return join_plan;
4189 }
4190 
4191 
4192 /*****************************************************************************
4193  *
4194  * SUPPORTING ROUTINES
4195  *
4196  *****************************************************************************/
4197 
4198 /*
4199  * replace_nestloop_params
4200  * Replace outer-relation Vars and PlaceHolderVars in the given expression
4201  * with nestloop Params
4202  *
4203  * All Vars and PlaceHolderVars belonging to the relation(s) identified by
4204  * root->curOuterRels are replaced by Params, and entries are added to
4205  * root->curOuterParams if not already present.
4206  */
4207 static Node *
4209 {
4210  /* No setup needed for tree walk, so away we go */
4211  return replace_nestloop_params_mutator(expr, root);
4212 }
4213 
4214 static Node *
4216 {
4217  if (node == NULL)
4218  return NULL;
4219  if (IsA(node, Var))
4220  {
4221  Var *var = (Var *) node;
4222  Param *param;
4223  NestLoopParam *nlp;
4224  ListCell *lc;
4225 
4226  /* Upper-level Vars should be long gone at this point */
4227  Assert(var->varlevelsup == 0);
4228  /* If not to be replaced, we can just return the Var unmodified */
4229  if (!bms_is_member(var->varno, root->curOuterRels))
4230  return node;
4231  /* Create a Param representing the Var */
4232  param = assign_nestloop_param_var(root, var);
4233  /* Is this param already listed in root->curOuterParams? */
4234  foreach(lc, root->curOuterParams)
4235  {
4236  nlp = (NestLoopParam *) lfirst(lc);
4237  if (nlp->paramno == param->paramid)
4238  {
4239  Assert(equal(var, nlp->paramval));
4240  /* Present, so we can just return the Param */
4241  return (Node *) param;
4242  }
4243  }
4244  /* No, so add it */
4245  nlp = makeNode(NestLoopParam);
4246  nlp->paramno = param->paramid;
4247  nlp->paramval = var;
4248  root->curOuterParams = lappend(root->curOuterParams, nlp);
4249  /* And return the replacement Param */
4250  return (Node *) param;
4251  }
4252  if (IsA(node, PlaceHolderVar))
4253  {
4254  PlaceHolderVar *phv = (PlaceHolderVar *) node;
4255  Param *param;
4256  NestLoopParam *nlp;
4257  ListCell *lc;
4258 
4259  /* Upper-level PlaceHolderVars should be long gone at this point */
4260  Assert(phv->phlevelsup == 0);
4261 
4262  /*
4263  * Check whether we need to replace the PHV. We use bms_overlap as a
4264  * cheap/quick test to see if the PHV might be evaluated in the outer
4265  * rels, and then grab its PlaceHolderInfo to tell for sure.
4266  */
4267  if (!bms_overlap(phv->phrels, root->curOuterRels) ||
4268  !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4269  root->curOuterRels))
4270  {
4271  /*
4272  * We can't replace the whole PHV, but we might still need to
4273  * replace Vars or PHVs within its expression, in case it ends up
4274  * actually getting evaluated here. (It might get evaluated in
4275  * this plan node, or some child node; in the latter case we don't
4276  * really need to process the expression here, but we haven't got
4277  * enough info to tell if that's the case.) Flat-copy the PHV
4278  * node and then recurse on its expression.
4279  *
4280  * Note that after doing this, we might have different
4281  * representations of the contents of the same PHV in different
4282  * parts of the plan tree. This is OK because equal() will just
4283  * match on phid/phlevelsup, so setrefs.c will still recognize an
4284  * upper-level reference to a lower-level copy of the same PHV.
4285  */
4287 
4288  memcpy(newphv, phv, sizeof(PlaceHolderVar));
4289  newphv->phexpr = (Expr *)
4291  root);
4292  return (Node *) newphv;
4293  }
4294  /* Create a Param representing the PlaceHolderVar */
4295  param = assign_nestloop_param_placeholdervar(root, phv);
4296  /* Is this param already listed in root->curOuterParams? */
4297  foreach(lc, root->curOuterParams)
4298  {
4299  nlp = (NestLoopParam *) lfirst(lc);
4300  if (nlp->paramno == param->paramid)
4301  {
4302  Assert(equal(phv, nlp->paramval));
4303  /* Present, so we can just return the Param */
4304  return (Node *) param;
4305  }
4306  }
4307  /* No, so add it */
4308  nlp = makeNode(NestLoopParam);
4309  nlp->paramno = param->paramid;
4310  nlp->paramval = (Var *) phv;
4311  root->curOuterParams = lappend(root->curOuterParams, nlp);
4312  /* And return the replacement Param */
4313  return (Node *) param;
4314  }
4315  return expression_tree_mutator(node,
4317  (void *) root);
4318 }
4319 
4320 /*
4321  * process_subquery_nestloop_params
4322  * Handle params of a parameterized subquery that need to be fed
4323  * from an outer nestloop.
4324  *
4325  * Currently, that would be *all* params that a subquery in FROM has demanded
4326  * from the current query level, since they must be LATERAL references.
4327  *
4328  * The subplan's references to the outer variables are already represented
4329  * as PARAM_EXEC Params, so we need not modify the subplan here. What we
4330  * do need to do is add entries to root->curOuterParams to signal the parent
4331  * nestloop plan node that it must provide these values.
4332  */
4333 static void
4335 {
4336  ListCell *ppl;
4337 
4338  foreach(ppl, subplan_params)
4339  {
4340  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
4341 
4342  if (IsA(pitem->item, Var))
4343  {
4344  Var *var = (Var *) pitem->item;
4345  NestLoopParam *nlp;
4346  ListCell *lc;
4347 
4348  /* If not from a nestloop outer rel, complain */
4349  if (!bms_is_member(var->varno, root->curOuterRels))
4350  elog(ERROR, "non-LATERAL parameter required by subquery");
4351  /* Is this param already listed in root->curOuterParams? */
4352  foreach(lc, root->curOuterParams)
4353  {
4354  nlp = (NestLoopParam *) lfirst(lc);
4355  if (nlp->paramno == pitem->paramId)
4356  {
4357  Assert(equal(var, nlp->paramval));
4358  /* Present, so nothing to do */
4359  break;
4360  }
4361  }
4362  if (lc == NULL)
4363  {
4364  /* No, so add it */
4365  nlp = makeNode(NestLoopParam);
4366  nlp->paramno = pitem->paramId;
4367  nlp->paramval = copyObject(var);
4368  root->curOuterParams = lappend(root->curOuterParams, nlp);
4369  }
4370  }
4371  else if (IsA(pitem->item, PlaceHolderVar))
4372  {
4373  PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
4374  NestLoopParam *nlp;
4375  ListCell *lc;
4376 
4377  /* If not from a nestloop outer rel, complain */
4378  if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4379  root->curOuterRels))
4380  elog(ERROR, "non-LATERAL parameter required by subquery");
4381  /* Is this param already listed in root->curOuterParams? */
4382  foreach(lc, root->curOuterParams)
4383  {
4384  nlp = (NestLoopParam *) lfirst(lc);
4385  if (nlp->paramno == pitem->paramId)
4386  {
4387  Assert(equal(phv, nlp->paramval));
4388  /* Present, so nothing to do */
4389  break;
4390  }
4391  }
4392  if (lc == NULL)
4393  {
4394  /* No, so add it */
4395  nlp = makeNode(NestLoopParam);
4396  nlp->paramno = pitem->paramId;
4397  nlp->paramval = (Var *) copyObject(phv);
4398  root->curOuterParams = lappend(root->curOuterParams, nlp);
4399  }
4400  }
4401  else
4402  elog(ERROR, "unexpected type of subquery parameter");
4403  }
4404 }
4405 
4406 /*
4407  * fix_indexqual_references
4408  * Adjust indexqual clauses to the form the executor's indexqual
4409  * machinery needs.
4410  *
4411  * We have four tasks here:
4412  * * Remove RestrictInfo nodes from the input clauses.
4413  * * Replace any outer-relation Var or PHV nodes with nestloop Params.
4414  * (XXX eventually, that responsibility should go elsewhere?)
4415  * * Index keys must be represented by Var nodes with varattno set to the
4416  * index's attribute number, not the attribute number in the original rel.
4417  * * If the index key is on the right, commute the clause to put it on the
4418  * left.
4419  *
4420  * The result is a modified copy of the path's indexquals list --- the
4421  * original is not changed. Note also that the copy shares no substructure
4422  * with the original; this is needed in case there is a subplan in it (we need
4423  * two separate copies of the subplan tree, or things will go awry).
4424  */
4425 static List *
4427 {
4428  IndexOptInfo *index = index_path->indexinfo;
4429  List *fixed_indexquals;
4430  ListCell *lcc,
4431  *lci;
4432 
4433  fixed_indexquals = NIL;
4434 
4435  forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
4436  {
4437  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
4438  int indexcol = lfirst_int(lci);
4439  Node *clause;
4440 
4441  /*
4442  * Replace any outer-relation variables with nestloop params.
4443  *
4444  * This also makes a copy of the clause, so it's safe to modify it
4445  * in-place below.
4446  */
4447  clause = replace_nestloop_params(root, (Node *) rinfo->clause);
4448 
4449  if (IsA(clause, OpExpr))
4450  {
4451  OpExpr *op = (OpExpr *) clause;
4452 
4453  if (list_length(op->args) != 2)
4454  elog(ERROR, "indexqual clause is not binary opclause");
4455 
4456  /*
4457  * Check to see if the indexkey is on the right; if so, commute
4458  * the clause. The indexkey should be the side that refers to
4459  * (only) the base relation.
4460  */
4461  if (!bms_equal(rinfo->left_relids, index->rel->relids))
4462  CommuteOpExpr(op);
4463 
4464  /*
4465  * Now replace the indexkey expression with an index Var.
4466  */
4468  index,
4469  indexcol);
4470  }
4471  else if (IsA(clause, RowCompareExpr))
4472  {
4473  RowCompareExpr *rc = (RowCompareExpr *) clause;
4474  Expr *newrc;
4475  List *indexcolnos;
4476  bool var_on_left;
4477  ListCell *lca,
4478  *lcai;
4479 
4480  /*
4481  * Re-discover which index columns are used in the rowcompare.
4482  */
4483  newrc = adjust_rowcompare_for_index(rc,
4484  index,
4485  indexcol,
4486  &indexcolnos,
4487  &var_on_left);
4488 
4489  /*
4490  * Trouble if adjust_rowcompare_for_index thought the
4491  * RowCompareExpr didn't match the index as-is; the clause should
4492  * have gone through that routine already.
4493  */
4494  if (newrc != (Expr *) rc)
4495  elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
4496 
4497  /*
4498  * Check to see if the indexkey is on the right; if so, commute
4499  * the clause.
4500  */
4501  if (!var_on_left)
4503 
4504  /*
4505  * Now replace the indexkey expressions with index Vars.
4506  */
4507  Assert(list_length(rc->largs) == list_length(indexcolnos));
4508  forboth(lca, rc->largs, lcai, indexcolnos)
4509  {
4510  lfirst(lca) = fix_indexqual_operand(lfirst(lca),
4511  index,
4512  lfirst_int(lcai));
4513  }
4514  }
4515  else if (IsA(clause, ScalarArrayOpExpr))
4516  {
4517  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
4518 
4519  /* Never need to commute... */
4520 
4521  /* Replace the indexkey expression with an index Var. */
4523  index,
4524  indexcol);
4525  }
4526  else if (IsA(clause, NullTest))
4527  {
4528  NullTest *nt = (NullTest *) clause;
4529 
4530  /* Replace the indexkey expression with an index Var. */
4531  nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
4532  index,
4533  indexcol);
4534  }
4535  else
4536  elog(ERROR, "unsupported indexqual type: %d",
4537  (int) nodeTag(clause));
4538 
4539  fixed_indexquals = lappend(fixed_indexquals, clause);
4540  }
4541 
4542  return fixed_indexquals;
4543 }
4544 
4545 /*
4546  * fix_indexorderby_references
4547  * Adjust indexorderby clauses to the form the executor's index
4548  * machinery needs.
4549  *
4550  * This is a simplified version of fix_indexqual_references. The input does
4551  * not have RestrictInfo nodes, and we assume that indxpath.c already
4552  * commuted the clauses to put the index keys on the left. Also, we don't
4553  * bother to support any cases except simple OpExprs, since nothing else
4554  * is allowed for ordering operators.
4555  */
4556 static List *
4558 {
4559  IndexOptInfo *index = index_path->indexinfo;
4560  List *fixed_indexorderbys;
4561  ListCell *lcc,
4562  *lci;
4563 
4564  fixed_indexorderbys = NIL;
4565 
4566  forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
4567  {
4568  Node *clause = (Node *) lfirst(lcc);
4569  int indexcol = lfirst_int(lci);
4570 
4571  /*
4572  * Replace any outer-relation variables with nestloop params.
4573  *
4574  * This also makes a copy of the clause, so it's safe to modify it
4575  * in-place below.
4576  */
4577  clause = replace_nestloop_params(root, clause);
4578 
4579  if (IsA(clause, OpExpr))
4580  {
4581  OpExpr *op = (OpExpr *) clause;
4582 
4583  if (list_length(op->args) != 2)
4584  elog(ERROR, "indexorderby clause is not binary opclause");
4585 
4586  /*
4587  * Now replace the indexkey expression with an index Var.
4588  */
4590  index,
4591  indexcol);
4592  }
4593  else
4594  elog(ERROR, "unsupported indexorderby type: %d",
4595  (int) nodeTag(clause));
4596 
4597  fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
4598  }
4599 
4600  return fixed_indexorderbys;
4601 }
4602 
4603 /*
4604  * fix_indexqual_operand
4605  * Convert an indexqual expression to a Var referencing the index column.
4606  *
4607  * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
4608  * equal to the index's attribute number (index column position).
4609  *
4610  * Most of the code here is just for sanity cross-checking that the given
4611  * expression actually matches the index column it's claimed to.
4612  */
4613 static Node *
4615 {
4616  Var *result;
4617  int pos;
4618  ListCell *indexpr_item;
4619 
4620  /*
4621  * Remove any binary-compatible relabeling of the indexkey
4622  */
4623  if (IsA(node, RelabelType))
4624  node = (Node *) ((RelabelType *) node)->arg;
4625 
4626  Assert(indexcol >= 0 && indexcol < index->ncolumns);
4627 
4628  if (index->indexkeys[indexcol] != 0)
4629  {
4630  /* It's a simple index column */
4631  if (IsA(node, Var) &&
4632  ((Var *) node)->varno == index->rel->relid &&
4633  ((Var *) node)->varattno == index->indexkeys[indexcol])
4634  {
4635  result = (Var *) copyObject(node);
4636  result->varno = INDEX_VAR;
4637  result->varattno = indexcol + 1;
4638  return (Node *) result;
4639  }
4640  else
4641  elog(ERROR, "index key does not match expected index column");
4642  }
4643 
4644  /* It's an index expression, so find and cross-check the expression */
4645  indexpr_item = list_head(index->indexprs);
4646  for (pos = 0; pos < index->ncolumns; pos++)
4647  {
4648  if (index->indexkeys[pos] == 0)
4649  {
4650  if (indexpr_item == NULL)
4651  elog(ERROR, "too few entries in indexprs list");
4652  if (pos == indexcol)
4653  {
4654  Node *indexkey;
4655 
4656  indexkey = (Node *) lfirst(indexpr_item);
4657  if (indexkey && IsA(indexkey, RelabelType))
4658  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4659  if (equal(node, indexkey))
4660  {
4661  result = makeVar(INDEX_VAR, indexcol + 1,
4662  exprType(lfirst(indexpr_item)), -1,
4663  exprCollation(lfirst(indexpr_item)),
4664  0);
4665  return (Node *) result;
4666  }
4667  else
4668  elog(ERROR, "index key does not match expected index column");
4669  }
4670  indexpr_item = lnext(indexpr_item);
4671  }
4672  }
4673 
4674  /* Oops... */
4675  elog(ERROR, "index key does not match expected index column");
4676  return NULL; /* keep compiler quiet */
4677 }
4678 
4679 /*
4680  * get_switched_clauses
4681  * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
4682  * extract the bare clauses, and rearrange the elements within the
4683  * clauses, if needed, so the outer join variable is on the left and
4684  * the inner is on the right. The original clause data structure is not
4685  * touched; a modified list is returned. We do, however, set the transient
4686  * outer_is_left field in each RestrictInfo to show which side was which.
4687  */
4688 static List *
4689 get_switched_clauses(List *clauses, Relids outerrelids)
4690 {
4691  List *t_list = NIL;
4692  ListCell *l;
4693 
4694  foreach(l, clauses)
4695  {
4696  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
4697  OpExpr *clause = (OpExpr *) restrictinfo->clause;
4698 
4699  Assert(is_opclause(clause));
4700  if (bms_is_subset(restrictinfo->right_relids, outerrelids))
4701  {
4702  /*
4703  * Duplicate just enough of the structure to allow commuting the
4704  * clause without changing the original list. Could use
4705  * copyObject, but a complete deep copy is overkill.
4706  */
4707  OpExpr *temp = makeNode(OpExpr);
4708 
4709  temp->opno = clause->opno;
4710  temp->opfuncid = InvalidOid;
4711  temp->opresulttype = clause->opresulttype;
4712  temp->opretset = clause->opretset;
4713  temp->opcollid = clause->opcollid;
4714  temp->inputcollid = clause->inputcollid;
4715  temp->args = list_copy(clause->args);
4716  temp->location = clause->location;
4717  /* Commute it --- note this modifies the temp node in-place. */
4718  CommuteOpExpr(temp);
4719  t_list = lappend(t_list, temp);
4720  restrictinfo->outer_is_left = false;
4721  }
4722  else
4723  {
4724  Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
4725  t_list = lappend(t_list, clause);
4726  restrictinfo->outer_is_left = true;
4727  }
4728  }
4729  return t_list;
4730 }
4731 
4732 /*
4733  * order_qual_clauses
4734  * Given a list of qual clauses that will all be evaluated at the same
4735  * plan node, sort the list into the order we want to check the quals
4736  * in at runtime.
4737  *
4738  * When security barrier quals are used in the query, we may have quals with
4739  * different security levels in the list. Quals of lower security_level
4740  * must go before quals of higher security_level, except that we can grant
4741  * exceptions to move up quals that are leakproof. When security level
4742  * doesn't force the decision, we prefer to order clauses by estimated
4743  * execution cost, cheapest first.
4744  *
4745  * Ideally the order should be driven by a combination of execution cost and
4746  * selectivity, but it's not immediately clear how to account for both,
4747  * and given the uncertainty of the estimates the reliability of the decisions
4748  * would be doubtful anyway. So we just order by security level then
4749  * estimated per-tuple cost, being careful not to change the order when
4750  * (as is often the case) the estimates are identical.
4751  *
4752  * Although this will work on either bare clauses or RestrictInfos, it's
4753  * much faster to apply it to RestrictInfos, since it can re-use cost
4754  * information that is cached in RestrictInfos. XXX in the bare-clause
4755  * case, we are also not able to apply security considerations. That is
4756  * all right for the moment, because the bare-clause case doesn't occur
4757  * anywhere that barrier quals could be present, but it would be better to
4758  * get rid of it.
4759  *
4760  * Note: some callers pass lists that contain entries that will later be
4761  * removed; this is the easiest way to let this routine see RestrictInfos
4762  * instead of bare clauses. This is another reason why trying to consider
4763  * selectivity in the ordering would likely do the wrong thing.
4764  */
4765 static List *
4767 {
4768  typedef struct
4769  {
4770  Node *clause;
4771  Cost cost;
4772  Index security_level;
4773  } QualItem;
4774  int nitems = list_length(clauses);
4775  QualItem *items;
4776  ListCell *lc;
4777  int i;
4778  List *result;
4779 
4780  /* No need to work hard for 0 or 1 clause */
4781  if (nitems <= 1)
4782  return clauses;
4783 
4784  /*
4785  * Collect the items and costs into an array. This is to avoid repeated
4786  * cost_qual_eval work if the inputs aren't RestrictInfos.
4787  */
4788  items = (QualItem *) palloc(nitems * sizeof(QualItem));
4789  i = 0;
4790  foreach(lc, clauses)
4791  {
4792  Node *clause = (Node *) lfirst(lc);
4793  QualCost qcost;
4794 
4795  cost_qual_eval_node(&qcost, clause, root);
4796  items[i].clause = clause;
4797  items[i].cost = qcost.per_tuple;
4798  if (IsA(clause, RestrictInfo))
4799  {
4800  RestrictInfo *rinfo = (RestrictInfo *) clause;
4801 
4802  /*
4803  * If a clause is leakproof, it doesn't have to be constrained by
4804  * its nominal security level. If it's also reasonably cheap
4805  * (here defined as 10X cpu_operator_cost), pretend it has
4806  * security_level 0, which will allow it to go in front of
4807  * more-expensive quals of lower security levels. Of course, that
4808  * will also force it to go in front of cheaper quals of its own
4809  * security level, which is not so great, but we can alleviate
4810  * that risk by applying the cost limit cutoff.
4811  */
4812  if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
4813  items[i].security_level = 0;
4814  else
4815  items[i].security_level = rinfo->security_level;
4816  }
4817  else
4818  items[i].security_level = 0;
4819  i++;
4820  }
4821 
4822  /*
4823  * Sort. We don't use qsort() because it's not guaranteed stable for
4824  * equal keys. The expected number of entries is small enough that a
4825  * simple insertion sort should be good enough.
4826  */
4827  for (i = 1; i < nitems; i++)
4828  {
4829  QualItem newitem = items[i];
4830  int j;
4831 
4832  /* insert newitem into the already-sorted subarray */
4833  for (j = i; j > 0; j--)
4834  {
4835  QualItem *olditem = &items[j - 1];
4836 
4837  if (newitem.security_level > olditem->security_level ||
4838  (newitem.security_level == olditem->security_level &&
4839  newitem.cost >= olditem->cost))
4840  break;
4841  items[j] = *olditem;
4842  }
4843  items[j] = newitem;
4844  }
4845 
4846  /* Convert back to a list */
4847  result = NIL;
4848  for (i = 0; i < nitems; i++)
4849  result = lappend(result, items[i].clause);
4850 
4851  return result;
4852 }
4853 
4854 /*
4855  * Copy cost and size info from a Path node to the Plan node created from it.
4856  * The executor usually won't use this info, but it's needed by EXPLAIN.
4857  * Also copy the parallel-related flags, which the executor *will* use.
4858  */
4859 static void
4861 {
4862  dest->startup_cost = src->startup_cost;
4863  dest->total_cost = src->total_cost;
4864  dest->plan_rows = src->rows;
4865  dest->plan_width = src->pathtarget->width;
4866  dest->parallel_aware = src->parallel_aware;
4867  dest->parallel_safe = src->parallel_safe;
4868 }
4869 
4870 /*
4871  * Copy cost and size info from a lower plan node to an inserted node.
4872  * (Most callers alter the info after copying it.)
4873  */
4874 static void
4876 {
4877  dest->startup_cost = src->startup_cost;
4878  dest->total_cost = src->total_cost;
4879  dest->plan_rows = src->plan_rows;
4880  dest->plan_width = src->plan_width;
4881  /* Assume the inserted node is not parallel-aware. */
4882  dest->parallel_aware = false;
4883  /* Assume the inserted node is parallel-safe, if child plan is. */
4884  dest->parallel_safe = src->parallel_safe;
4885 }
4886 
4887 /*
4888  * Some places in this file build Sort nodes that don't have a directly
4889  * corresponding Path node. The cost of the sort is, or should have been,
4890  * included in the cost of the Path node we're working from, but since it's
4891  * not split out, we have to re-figure it using cost_sort(). This is just
4892  * to label the Sort node nicely for EXPLAIN.
4893  *
4894  * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4895  */
4896 static void
4897 label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
4898 {
4899  Plan *lefttree = plan->plan.lefttree;
4900  Path sort_path; /* dummy for result of cost_sort */
4901 
4902  cost_sort(&sort_path, root, NIL,
4903  lefttree->total_cost,
4904  lefttree->plan_rows,
4905  lefttree->plan_width,
4906  0.0,
4907  work_mem,
4908  limit_tuples);
4909  plan->plan.startup_cost = sort_path.startup_cost;
4910  plan->plan.total_cost = sort_path.total_cost;
4911  plan->plan.plan_rows = lefttree->plan_rows;
4912  plan->plan.plan_width = lefttree->plan_width;
4913  plan->plan.parallel_aware = false;
4914  plan->plan.parallel_safe = lefttree->parallel_safe;
4915 }
4916 
4917 /*
4918  * bitmap_subplan_mark_shared
4919  * Set isshared flag in bitmap subplan so that it will be created in
4920  * shared memory.
4921  */
4922 static void
4924 {
4925  if (IsA(plan, BitmapAnd))
4927  linitial(((BitmapAnd *) plan)->bitmapplans));
4928  else if (IsA(plan, BitmapOr))
4929  ((BitmapOr *) plan)->isshared = true;
4930  else if (IsA(plan, BitmapIndexScan))
4931  ((BitmapIndexScan *) plan)->isshared = true;
4932  else
4933  elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
4934 }
4935 
4936 /*****************************************************************************
4937  *
4938  * PLAN NODE BUILDING ROUTINES
4939  *
4940  * In general, these functions are not passed the original Path and therefore
4941  * leave it to the caller to fill in the cost/width fields from the Path,
4942  * typically by calling copy_generic_path_info(). This convention is
4943  * somewhat historical, but it does support a few places above where we build
4944  * a plan node without having an exactly corresponding Path node. Under no
4945  * circumstances should one of these functions do its own cost calculations,
4946  * as that would be redundant with calculations done while building Paths.
4947  *
4948  *****************************************************************************/
4949 
4950 static SeqScan *
4952  List *qpqual,
4953  Index scanrelid)
4954 {
4955  SeqScan *node = makeNode(SeqScan);
4956  Plan *plan = &node->plan;
4957 
4958  plan->targetlist = qptlist;
4959  plan->qual = qpqual;
4960  plan->lefttree = NULL;
4961  plan->righttree = NULL;
4962  node->scanrelid = scanrelid;
4963 
4964  return node;
4965 }
4966 
4967 static SampleScan *
4969  List *qpqual,
4970  Index scanrelid,
4971  TableSampleClause *tsc)
4972 {
4973  SampleScan *node = makeNode(SampleScan);
4974  Plan *plan = &node->scan.plan;
4975 
4976  plan->targetlist = qptlist;
4977  plan->qual = qpqual;
4978  plan->lefttree = NULL;
4979  plan->righttree = NULL;
4980  node->scan.scanrelid = scanrelid;
4981  node->tablesample = tsc;
4982 
4983  return node;
4984 }
4985 
4986 static IndexScan *
4988  List *qpqual,
4989  Index scanrelid,
4990  Oid indexid,
4991  List *indexqual,
4992  List *indexqualorig,
4993  List *indexorderby,
4994  List *indexorderbyorig,
4995  List *indexorderbyops,
4996  ScanDirection indexscandir)
4997 {
4998  IndexScan *node = makeNode(IndexScan);
4999  Plan *plan = &node->scan.plan;
5000 
5001  plan->targetlist = qptlist;
5002  plan->qual = qpqual;
5003  plan->lefttree = NULL;
5004  plan->righttree = NULL;
5005  node->scan.scanrelid = scanrelid;
5006  node->indexid = indexid;
5007  node->indexqual = indexqual;
5008  node->indexqualorig = indexqualorig;
5009  node->indexorderby = indexorderby;
5010  node->indexorderbyorig = indexorderbyorig;
5011  node->indexorderbyops = indexorderbyops;
5012  node->indexorderdir = indexscandir;
5013 
5014  return node;
5015 }
5016 
5017 static IndexOnlyScan *
5019  List *qpqual,
5020  Index scanrelid,
5021  Oid indexid,
5022  List *indexqual,
5023  List *indexorderby,
5024  List *indextlist,
5025  ScanDirection indexscandir)
5026 {
5028  Plan *plan = &node->scan.plan;
5029 
5030  plan->targetlist = qptlist;
5031  plan->qual = qpqual;
5032  plan->lefttree = NULL;
5033  plan->righttree = NULL;
5034  node->scan.scanrelid = scanrelid;
5035  node->indexid = indexid;
5036  node->indexqual = indexqual;
5037  node->indexorderby = indexorderby;
5038  node->indextlist = indextlist;
5039  node->indexorderdir = indexscandir;
5040 
5041  return node;
5042 }
5043 
5044 static BitmapIndexScan *
5046  Oid indexid,
5047  List *indexqual,
5048  List *indexqualorig)
5049 {
5051  Plan *plan = &node->scan.plan;
5052 
5053  plan->targetlist = NIL; /* not used */
5054  plan->qual = NIL; /* not used */
5055  plan->lefttree = NULL;
5056  plan->righttree = NULL;
5057  node->scan.scanrelid = scanrelid;
5058  node->indexid = indexid;
5059  node->indexqual = indexqual;
5060  node->indexqualorig = indexqualorig;
5061 
5062  return node;
5063 }
5064 
5065 static BitmapHeapScan *
5067  List *qpqual,
5068  Plan *lefttree,
5069  List *bitmapqualorig,
5070  Index scanrelid)
5071 {
5073  Plan *plan = &node->scan.plan;
5074 
5075  plan->targetlist = qptlist;
5076  plan->qual = qpqual;
5077  plan->lefttree = lefttree;
5078  plan->righttree = NULL;
5079  node->scan.scanrelid = scanrelid;
5080  node->bitmapqualorig = bitmapqualorig;
5081 
5082  return node;
5083 }
5084 
5085 static TidScan *
5087  List *qpqual,
5088  Index scanrelid,
5089  List *tidquals)
5090 {
5091  TidScan *node = makeNode(TidScan);
5092  Plan *plan = &node->scan.plan;
5093 
5094  plan->targetlist = qptlist;
5095  plan->qual = qpqual;
5096  plan->lefttree = NULL;
5097  plan->righttree = NULL;
5098  node->scan.scanrelid = scanrelid;
5099  node->tidquals = tidquals;
5100 
5101  return node;
5102 }
5103 
5104 static SubqueryScan *
5106  List *qpqual,
5107  Index scanrelid,
5108  Plan *subplan)
5109 {
5111  Plan *plan = &node->scan.plan;
5112 
5113  plan->targetlist = qptlist;
5114  plan->qual = qpqual;
5115  plan->lefttree = NULL;
5116  plan->righttree = NULL;
5117  node->scan.scanrelid = scanrelid;
5118  node->subplan = subplan;
5119 
5120  return node;
5121 }
5122 
5123 static FunctionScan *
5125  List *qpqual,
5126  Index scanrelid,
5127  List *functions,
5128  bool funcordinality)
5129 {
5131  Plan *plan = &node->scan.plan;
5132 
5133  plan->targetlist = qptlist;
5134  plan->qual = qpqual;
5135  plan->lefttree = NULL;
5136  plan->righttree = NULL;
5137  node->scan.scanrelid = scanrelid;
5138  node->functions = functions;
5139  node->funcordinality = funcordinality;
5140 
5141  return node;
5142 }
5143 
5144 static TableFuncScan *
5146  List *qpqual,
5147  Index scanrelid,
5148  TableFunc *tablefunc)
5149 {
5151  Plan *plan = &node->scan.plan;
5152 
5153  plan->targetlist = qptlist;
5154  plan->qual = qpqual;
5155  plan->lefttree = NULL;
5156  plan->righttree = NULL;
5157  node->scan.scanrelid = scanrelid;
5158  node->tablefunc = tablefunc;
5159 
5160  return node;
5161 }
5162 
5163 static ValuesScan *
5165  List *qpqual,
5166  Index scanrelid,
5167  List *values_lists)
5168 {
5169  ValuesScan *node = makeNode(ValuesScan);
5170  Plan *plan = &node->scan.plan;
5171 
5172  plan->targetlist = qptlist;
5173  plan->qual = qpqual;
5174  plan->lefttree = NULL;
5175  plan->righttree = NULL;
5176  node->scan.scanrelid = scanrelid;
5177  node->values_lists = values_lists;
5178 
5179  return node;
5180 }
5181 
5182 static CteScan *
5184  List *qpqual,
5185  Index scanrelid,
5186  int ctePlanId,
5187  int cteParam)
5188 {
5189  CteScan *node = makeNode(CteScan);
5190  Plan *plan = &node->scan.plan;
5191 
5192  plan->targetlist = qptlist;
5193  plan->qual = qpqual;
5194  plan->lefttree = NULL;
5195  plan->righttree = NULL;
5196  node->scan.scanrelid = scanrelid;
5197  node->ctePlanId = ctePlanId;
5198  node->cteParam = cteParam;
5199 
5200  return node;
5201 }
5202 
5203 static NamedTuplestoreScan *
5205  List *qpqual,
5206  Index scanrelid,
5207  char *enrname)
5208 {
5210  Plan *plan = &node->scan.plan;
5211 
5212  /* cost should be inserted by caller */
5213  plan->targetlist = qptlist;
5214  plan->qual = qpqual;
5215  plan->lefttree = NULL;
5216  plan->righttree = NULL;
5217  node->scan.scanrelid = scanrelid;
5218  node->enrname = enrname;
5219 
5220  return node;
5221 }
5222 
5223 static WorkTableScan *
5225  List *qpqual,
5226  Index scanrelid,
5227  int wtParam)
5228 {
5230  Plan *plan = &node->scan.plan;
5231 
5232  plan->targetlist = qptlist;
5233  plan->qual = qpqual;
5234  plan->lefttree = NULL;
5235  plan->righttree = NULL;
5236  node->scan.scanrelid = scanrelid;
5237  node->wtParam = wtParam;
5238 
5239  return node;
5240 }
5241 
5242 ForeignScan *
5244  List *qpqual,
5245  Index scanrelid,
5246  List *fdw_exprs,
5247  List *fdw_private,
5248  List *fdw_scan_tlist,
5249  List *fdw_recheck_quals,
5250  Plan *outer_plan)
5251 {
5252  ForeignScan *node = makeNode(ForeignScan);
5253  Plan *plan = &node->scan.plan;
5254 
5255  /* cost will be filled in by create_foreignscan_plan */
5256  plan->targetlist = qptlist;
5257  plan->qual = qpqual;
5258  plan->lefttree = outer_plan;
5259  plan->righttree = NULL;
5260  node->scan.scanrelid = scanrelid;
5261  node->operation = CMD_SELECT;
5262  /* fs_server will be filled in by create_foreignscan_plan */
5263  node->fs_server = InvalidOid;
5264  node->fdw_exprs = fdw_exprs;
5265  node->fdw_private = fdw_private;
5266  node->fdw_scan_tlist = fdw_scan_tlist;
5267  node->fdw_recheck_quals = fdw_recheck_quals;
5268  /* fs_relids will be filled in by create_foreignscan_plan */
5269  node->fs_relids = NULL;
5270  /* fsSystemCol will be filled in by create_foreignscan_plan */
5271  node->fsSystemCol = false;
5272 
5273  return node;
5274 }
5275 
5276 static Append *
5277 make_append(List *appendplans, List *tlist, List *partitioned_rels)
5278 {
5279  Append *node = makeNode(Append);
5280  Plan *plan = &node->plan;
5281 
5282  plan->targetlist = tlist;
5283  plan->qual = NIL;
5284  plan->lefttree = NULL;
5285  plan->righttree = NULL;
5286  node->partitioned_rels = partitioned_rels;
5287  node->appendplans = appendplans;
5288 
5289  return node;
5290 }
5291 
5292 static RecursiveUnion *
5294  Plan *lefttree,
5295  Plan *righttree,
5296  int wtParam,
5297  List *distinctList,
5298  long numGroups)
5299 {
5301  Plan *plan = &node->plan;
5302  int numCols = list_length(distinctList);
5303 
5304  plan->targetlist = tlist;
5305  plan->qual = NIL;
5306  plan->lefttree = lefttree;
5307  plan->righttree = righttree;
5308  node->wtParam = wtParam;
5309 
5310  /*
5311  * convert SortGroupClause list into arrays of attr indexes and equality
5312  * operators, as wanted by executor
5313  */
5314  node->numCols = numCols;
5315  if (numCols > 0)
5316  {
5317  int keyno = 0;
5318  AttrNumber *dupColIdx;
5319  Oid *dupOperators;
5320  ListCell *slitem;
5321 
5322  dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5323  dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5324 
5325  foreach(slitem, distinctList)
5326  {
5327  SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
5328  TargetEntry *tle = get_sortgroupclause_tle(sortcl,
5329  plan->targetlist);
5330 
5331  dupColIdx[keyno] = tle->resno;
5332  dupOperators[keyno] = sortcl->eqop;
5333  Assert(OidIsValid(dupOperators[keyno]));
5334  keyno++;
5335  }
5336  node->dupColIdx = dupColIdx;
5337  node->dupOperators = dupOperators;
5338  }
5339  node->numGroups = numGroups;
5340 
5341  return node;
5342 }
5343 
5344 static BitmapAnd *
5345 make_bitmap_and(List *bitmapplans)
5346 {
5347  BitmapAnd *node = makeNode(BitmapAnd);
5348  Plan *plan = &node->plan;
5349 
5350  plan->targetlist = NIL;
5351  plan->qual = NIL;
5352  plan->lefttree = NULL;
5353  plan->righttree = NULL;
5354  node->bitmapplans = bitmapplans;
5355 
5356  return node;
5357 }
5358 
5359 static BitmapOr *
5360 make_bitmap_or(List *bitmapplans)
5361 {
5362  BitmapOr *node = makeNode(BitmapOr);
5363  Plan *plan = &node->plan;
5364 
5365  plan->targetlist = NIL;
5366  plan->qual = NIL;
5367  plan->lefttree = NULL;
5368  plan->righttree = NULL;
5369  node->bitmapplans = bitmapplans;
5370 
5371  return node;
5372 }
5373 
5374 static NestLoop *
5376  List *joinclauses,
5377  List *otherclauses,
5378  List *nestParams,
5379  Plan *lefttree,
5380  Plan *righttree,
5381  JoinType jointype,
5382  bool inner_unique)
5383 {
5384  NestLoop *node = makeNode(NestLoop);
5385  Plan *plan = &node->join.plan;
5386 
5387  plan->targetlist = tlist;
5388  plan->qual = otherclauses;
5389  plan->lefttree = lefttree;
5390  plan->righttree = righttree;
5391  node->join.jointype = jointype;
5392  node->join.inner_unique = inner_unique;
5393  node->join.joinqual = joinclauses;
5394  node->nestParams = nestParams;
5395 
5396  return node;
5397 }
5398 
5399 static HashJoin *
5401  List *joinclauses,
5402  List *otherclauses,
5403  List *hashclauses,
5404  Plan *lefttree,
5405  Plan *righttree,
5406  JoinType jointype,
5407  bool inner_unique)
5408 {
5409  HashJoin *node = makeNode(HashJoin);
5410  Plan *plan = &node->join.plan;
5411 
5412  plan->targetlist = tlist;
5413  plan->qual = otherclauses;
5414  plan->lefttree = lefttree;
5415  plan->righttree = righttree;
5416  node->hashclauses = hashclauses;
5417  node->join.jointype = jointype;
5418  node->join.inner_unique = inner_unique;
5419  node->join.joinqual = joinclauses;
5420 
5421  return node;
5422 }
5423 
5424 static Hash *
5425 make_hash(Plan *lefttree,
5426  Oid skewTable,
5427  AttrNumber skewColumn,
5428  bool skewInherit)
5429 {
5430  Hash *node = makeNode(Hash);
5431  Plan *plan = &node->plan;
5432 
5433  plan->targetlist = lefttree->targetlist;
5434  plan->qual = NIL;
5435  plan->lefttree = lefttree;
5436  plan->righttree = NULL;
5437 
5438  node->skewTable = skewTable;
5439  node->skewColumn = skewColumn;
5440  node->skewInherit = skewInherit;
5441 
5442  return node;
5443 }
5444 
5445 static MergeJoin *
5447  List *joinclauses,
5448  List *otherclauses,
5449  List *mergeclauses,
5450  Oid *mergefamilies,
5451  Oid *mergecollations,
5452  int *mergestrategies,
5453  bool *mergenullsfirst,
5454  Plan *lefttree,
5455  Plan *righttree,
5456  JoinType jointype,
5457  bool inner_unique,
5458  bool skip_mark_restore)
5459 {
5460  MergeJoin *node = makeNode(MergeJoin);
5461  Plan *plan = &node->join.plan;
5462 
5463  plan->targetlist = tlist;
5464  plan->qual = otherclauses;
5465  plan->lefttree = lefttree;
5466  plan->righttree = righttree;
5467  node->skip_mark_restore = skip_mark_restore;
5468  node->mergeclauses = mergeclauses;
5469  node->mergeFamilies = mergefamilies;
5470  node->mergeCollations = mergecollations;
5471  node->mergeStrategies = mergestrategies;
5472  node->mergeNullsFirst = mergenullsfirst;
5473  node->join.jointype = jointype;
5474  node->join.inner_unique = inner_unique;
5475  node->join.joinqual = joinclauses;
5476 
5477  return node;
5478 }
5479 
5480 /*
5481  * make_sort --- basic routine to build a Sort plan node
5482  *
5483  * Caller must have built the sortColIdx, sortOperators, collations, and
5484  * nullsFirst arrays already.
5485  */
5486 static Sort *
5487 make_sort(Plan *lefttree, int numCols,
5488  AttrNumber *sortColIdx, Oid *sortOperators,
5489  Oid *collations, bool *nullsFirst)
5490 {
5491  Sort *node = makeNode(Sort);
5492  Plan *plan = &node->plan;
5493 
5494  plan->targetlist = lefttree->targetlist;
5495  plan->qual = NIL;
5496  plan->lefttree = lefttree;
5497  plan->righttree = NULL;
5498  node->numCols = numCols;
5499  node->sortColIdx = sortColIdx;
5500  node->sortOperators = sortOperators;
5501  node->collations = collations;
5502  node->nullsFirst = nullsFirst;
5503 
5504  return node;
5505 }
5506 
5507 /*
5508  * prepare_sort_from_pathkeys
5509  * Prepare to sort according to given pathkeys
5510  *
5511  * This is used to set up for Sort, MergeAppend, and Gather Merge nodes. It
5512  * calculates the executor's representation of the sort key information, and
5513  * adjusts the plan targetlist if needed to add resjunk sort columns.
5514  *
5515  * Input parameters:
5516  * 'lefttree' is the plan node which yields input tuples
5517  * 'pathkeys' is the list of pathkeys by which the result is to be sorted
5518  * 'relids' identifies the child relation being sorted, if any
5519  * 'reqColIdx' is NULL or an array of required sort key column numbers
5520  * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
5521  *
5522  * We must convert the pathkey information into arrays of sort key column
5523  * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
5524  * which is the representation the executor wants. These are returned into
5525  * the output parameters *p_numsortkeys etc.
5526  *
5527  * When looking for matches to an EquivalenceClass's members, we will only
5528  * consider child EC members if they match 'relids'. This protects against
5529  * possible incorrect matches to child expressions that contain no Vars.
5530  *
5531  * If reqColIdx isn't NULL then it contains sort key column numbers that
5532  * we should match. This is used when making child plans for a MergeAppend;
5533  * it's an error if we can't match the columns.
5534  *
5535  * If the pathkeys include expressions that aren't simple Vars, we will
5536  * usually need to add resjunk items to the input plan's targetlist to
5537  * compute these expressions, since a Sort or MergeAppend node itself won't
5538  * do any such calculations. If the input plan type isn't one that can do
5539  * projections, this means adding a Result node just to do the projection.
5540  * However, the caller can pass adjust_tlist_in_place = TRUE to force the
5541  * lefttree tlist to be modified in-place regardless of whether the node type
5542  * can project --- we use this for fixing the tlist of MergeAppend itself.
5543  *
5544  * Returns the node which is to be the input to the Sort (either lefttree,
5545  * or a Result stacked atop lefttree).
5546  */
5547 static Plan *
5548 prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
5549  Relids relids,
5550  const AttrNumber *reqColIdx,
5551  bool adjust_tlist_in_place,
5552  int *p_numsortkeys,
5553  AttrNumber **p_sortColIdx,
5554  Oid **p_sortOperators,
5555  Oid **p_collations,
5556  bool **p_nullsFirst)
5557 {
5558  List *tlist = lefttree->targetlist;
5559  ListCell *i;
5560  int numsortkeys;
5561  AttrNumber *sortColIdx;
5562  Oid *sortOperators;
5563  Oid *collations;
5564  bool *nullsFirst;
5565 
5566  /*
5567  * We will need at most list_length(pathkeys) sort columns; possibly less
5568  */
5569  numsortkeys = list_length(pathkeys);
5570  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5571  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5572  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5573  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5574 
5575  numsortkeys = 0;
5576 
5577  foreach(i, pathkeys)
5578  {
5579  PathKey *pathkey = (PathKey *) lfirst(i);
5580  EquivalenceClass *ec = pathkey->pk_eclass;
5581  EquivalenceMember *em;
5582  TargetEntry *tle = NULL;
5583  Oid pk_datatype = InvalidOid;
5584  Oid sortop;
5585  ListCell *j;
5586 
5587  if (ec->ec_has_volatile)
5588  {
5589  /*
5590  * If the pathkey's EquivalenceClass is volatile, then it must
5591  * have come from an ORDER BY clause, and we have to match it to
5592  * that same targetlist entry.
5593  */
5594  if (ec->ec_sortref == 0) /* can't happen */
5595  elog(ERROR, "volatile EquivalenceClass has no sortref");
5596  tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
5597  Assert(tle);
5598  Assert(list_length(ec->ec_members) == 1);
5599  pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
5600  }
5601  else if (reqColIdx != NULL)
5602  {
5603  /*
5604  * If we are given a sort column number to match, only consider
5605  * the single TLE at that position. It's possible that there is
5606  * no such TLE, in which case fall through and generate a resjunk
5607  * targetentry (we assume this must have happened in the parent
5608  * plan as well). If there is a TLE but it doesn't match the
5609  * pathkey's EC, we do the same, which is probably the wrong thing
5610  * but we'll leave it to caller to complain about the mismatch.
5611  */
5612  tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
5613  if (tle)
5614  {
5615  em = find_ec_member_for_tle(ec, tle, relids);
5616  if (em)
5617  {
5618  /* found expr at right place in tlist */
5619  pk_datatype = em->em_datatype;
5620  }
5621  else
5622  tle = NULL;
5623  }
5624  }
5625  else
5626  {
5627  /*
5628  * Otherwise, we can sort by any non-constant expression listed in
5629  * the pathkey's EquivalenceClass. For now, we take the first