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