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