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