PostgreSQL Source Code  git master
allpaths.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * allpaths.c
4  * Routines to find possible search paths for processing a query
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/optimizer/path/allpaths.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include <limits.h>
19 #include <math.h>
20 
21 #include "access/sysattr.h"
22 #include "access/tsmapi.h"
23 #include "catalog/pg_class.h"
24 #include "catalog/pg_operator.h"
25 #include "catalog/pg_proc.h"
26 #include "foreign/fdwapi.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #ifdef OPTIMIZER_DEBUG
31 #include "nodes/print.h"
32 #endif
33 #include "optimizer/appendinfo.h"
34 #include "optimizer/clauses.h"
35 #include "optimizer/cost.h"
36 #include "optimizer/geqo.h"
37 #include "optimizer/inherit.h"
38 #include "optimizer/optimizer.h"
39 #include "optimizer/pathnode.h"
40 #include "optimizer/paths.h"
41 #include "optimizer/plancat.h"
42 #include "optimizer/planner.h"
43 #include "optimizer/restrictinfo.h"
44 #include "optimizer/tlist.h"
45 #include "parser/parse_clause.h"
46 #include "parser/parsetree.h"
48 #include "partitioning/partprune.h"
49 #include "rewrite/rewriteManip.h"
50 #include "utils/lsyscache.h"
51 
52 
53 /* results of subquery_is_pushdown_safe */
54 typedef struct pushdown_safety_info
55 {
56  bool *unsafeColumns; /* which output columns are unsafe to use */
57  bool unsafeVolatile; /* don't push down volatile quals */
58  bool unsafeLeaky; /* don't push down leaky quals */
60 
61 /* These parameters are set by GUC */
62 bool enable_geqo = false; /* just in case GUC doesn't set it */
66 
67 /* Hook for plugins to get control in set_rel_pathlist() */
69 
70 /* Hook for plugins to replace standard_join_search() */
72 
73 
75 static void set_base_rel_sizes(PlannerInfo *root);
76 static void set_base_rel_pathlists(PlannerInfo *root);
77 static void set_rel_size(PlannerInfo *root, RelOptInfo *rel,
78  Index rti, RangeTblEntry *rte);
79 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
80  Index rti, RangeTblEntry *rte);
81 static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel,
82  RangeTblEntry *rte);
83 static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel);
84 static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel,
85  RangeTblEntry *rte);
86 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
87  RangeTblEntry *rte);
88 static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel,
89  RangeTblEntry *rte);
91  RangeTblEntry *rte);
92 static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel,
93  RangeTblEntry *rte);
94 static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel,
95  RangeTblEntry *rte);
96 static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
97  Index rti, RangeTblEntry *rte);
98 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
99  Index rti, RangeTblEntry *rte);
100 static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel,
101  List *live_childrels,
102  List *all_child_pathkeys);
104  RelOptInfo *rel,
105  Relids required_outer);
106 static void accumulate_append_subpath(Path *path,
107  List **subpaths,
108  List **special_subpaths);
109 static Path *get_singleton_append_subpath(Path *path);
110 static void set_dummy_rel_pathlist(RelOptInfo *rel);
111 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
112  Index rti, RangeTblEntry *rte);
113 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
114  RangeTblEntry *rte);
115 static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
116  RangeTblEntry *rte);
117 static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel,
118  RangeTblEntry *rte);
119 static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel,
120  RangeTblEntry *rte);
121 static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel,
122  RangeTblEntry *rte);
123 static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel,
124  RangeTblEntry *rte);
125 static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel,
126  RangeTblEntry *rte);
127 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
128 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
129  pushdown_safety_info *safetyInfo);
130 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
131  pushdown_safety_info *safetyInfo);
132 static void check_output_expressions(Query *subquery,
133  pushdown_safety_info *safetyInfo);
134 static void compare_tlist_datatypes(List *tlist, List *colTypes,
135  pushdown_safety_info *safetyInfo);
136 static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query);
137 static bool qual_is_pushdown_safe(Query *subquery, Index rti,
138  RestrictInfo *rinfo,
139  pushdown_safety_info *safetyInfo);
140 static void subquery_push_qual(Query *subquery,
141  RangeTblEntry *rte, Index rti, Node *qual);
142 static void recurse_push_qual(Node *setOp, Query *topquery,
143  RangeTblEntry *rte, Index rti, Node *qual);
144 static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel);
145 
146 
147 /*
148  * make_one_rel
149  * Finds all possible access paths for executing a query, returning a
150  * single rel that represents the join of all base rels in the query.
151  */
152 RelOptInfo *
153 make_one_rel(PlannerInfo *root, List *joinlist)
154 {
155  RelOptInfo *rel;
156  Index rti;
157  double total_pages;
158 
159  /*
160  * Construct the all_baserels Relids set.
161  */
162  root->all_baserels = NULL;
163  for (rti = 1; rti < root->simple_rel_array_size; rti++)
164  {
165  RelOptInfo *brel = root->simple_rel_array[rti];
166 
167  /* there may be empty slots corresponding to non-baserel RTEs */
168  if (brel == NULL)
169  continue;
170 
171  Assert(brel->relid == rti); /* sanity check on array */
172 
173  /* ignore RTEs that are "other rels" */
174  if (brel->reloptkind != RELOPT_BASEREL)
175  continue;
176 
177  root->all_baserels = bms_add_member(root->all_baserels, brel->relid);
178  }
179 
180  /* Mark base rels as to whether we care about fast-start plans */
182 
183  /*
184  * Compute size estimates and consider_parallel flags for each base rel.
185  */
186  set_base_rel_sizes(root);
187 
188  /*
189  * We should now have size estimates for every actual table involved in
190  * the query, and we also know which if any have been deleted from the
191  * query by join removal, pruned by partition pruning, or eliminated by
192  * constraint exclusion. So we can now compute total_table_pages.
193  *
194  * Note that appendrels are not double-counted here, even though we don't
195  * bother to distinguish RelOptInfos for appendrel parents, because the
196  * parents will have pages = 0.
197  *
198  * XXX if a table is self-joined, we will count it once per appearance,
199  * which perhaps is the wrong thing ... but that's not completely clear,
200  * and detecting self-joins here is difficult, so ignore it for now.
201  */
202  total_pages = 0;
203  for (rti = 1; rti < root->simple_rel_array_size; rti++)
204  {
205  RelOptInfo *brel = root->simple_rel_array[rti];
206 
207  if (brel == NULL)
208  continue;
209 
210  Assert(brel->relid == rti); /* sanity check on array */
211 
212  if (IS_DUMMY_REL(brel))
213  continue;
214 
215  if (IS_SIMPLE_REL(brel))
216  total_pages += (double) brel->pages;
217  }
218  root->total_table_pages = total_pages;
219 
220  /*
221  * Generate access paths for each base rel.
222  */
224 
225  /*
226  * Generate access paths for the entire join tree.
227  */
228  rel = make_rel_from_joinlist(root, joinlist);
229 
230  /*
231  * The result should join all and only the query's base rels.
232  */
233  Assert(bms_equal(rel->relids, root->all_baserels));
234 
235  return rel;
236 }
237 
238 /*
239  * set_base_rel_consider_startup
240  * Set the consider_[param_]startup flags for each base-relation entry.
241  *
242  * For the moment, we only deal with consider_param_startup here; because the
243  * logic for consider_startup is pretty trivial and is the same for every base
244  * relation, we just let build_simple_rel() initialize that flag correctly to
245  * start with. If that logic ever gets more complicated it would probably
246  * be better to move it here.
247  */
248 static void
250 {
251  /*
252  * Since parameterized paths can only be used on the inside of a nestloop
253  * join plan, there is usually little value in considering fast-start
254  * plans for them. However, for relations that are on the RHS of a SEMI
255  * or ANTI join, a fast-start plan can be useful because we're only going
256  * to care about fetching one tuple anyway.
257  *
258  * To minimize growth of planning time, we currently restrict this to
259  * cases where the RHS is a single base relation, not a join; there is no
260  * provision for consider_param_startup to get set at all on joinrels.
261  * Also we don't worry about appendrels. costsize.c's costing rules for
262  * nestloop semi/antijoins don't consider such cases either.
263  */
264  ListCell *lc;
265 
266  foreach(lc, root->join_info_list)
267  {
268  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
269  int varno;
270 
271  if ((sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) &&
272  bms_get_singleton_member(sjinfo->syn_righthand, &varno))
273  {
274  RelOptInfo *rel = find_base_rel(root, varno);
275 
276  rel->consider_param_startup = true;
277  }
278  }
279 }
280 
281 /*
282  * set_base_rel_sizes
283  * Set the size estimates (rows and widths) for each base-relation entry.
284  * Also determine whether to consider parallel paths for base relations.
285  *
286  * We do this in a separate pass over the base rels so that rowcount
287  * estimates are available for parameterized path generation, and also so
288  * that each rel's consider_parallel flag is set correctly before we begin to
289  * generate paths.
290  */
291 static void
293 {
294  Index rti;
295 
296  for (rti = 1; rti < root->simple_rel_array_size; rti++)
297  {
298  RelOptInfo *rel = root->simple_rel_array[rti];
299  RangeTblEntry *rte;
300 
301  /* there may be empty slots corresponding to non-baserel RTEs */
302  if (rel == NULL)
303  continue;
304 
305  Assert(rel->relid == rti); /* sanity check on array */
306 
307  /* ignore RTEs that are "other rels" */
308  if (rel->reloptkind != RELOPT_BASEREL)
309  continue;
310 
311  rte = root->simple_rte_array[rti];
312 
313  /*
314  * If parallelism is allowable for this query in general, see whether
315  * it's allowable for this rel in particular. We have to do this
316  * before set_rel_size(), because (a) if this rel is an inheritance
317  * parent, set_append_rel_size() will use and perhaps change the rel's
318  * consider_parallel flag, and (b) for some RTE types, set_rel_size()
319  * goes ahead and makes paths immediately.
320  */
321  if (root->glob->parallelModeOK)
322  set_rel_consider_parallel(root, rel, rte);
323 
324  set_rel_size(root, rel, rti, rte);
325  }
326 }
327 
328 /*
329  * set_base_rel_pathlists
330  * Finds all paths available for scanning each base-relation entry.
331  * Sequential scan and any available indices are considered.
332  * Each useful path is attached to its relation's 'pathlist' field.
333  */
334 static void
336 {
337  Index rti;
338 
339  for (rti = 1; rti < root->simple_rel_array_size; rti++)
340  {
341  RelOptInfo *rel = root->simple_rel_array[rti];
342 
343  /* there may be empty slots corresponding to non-baserel RTEs */
344  if (rel == NULL)
345  continue;
346 
347  Assert(rel->relid == rti); /* sanity check on array */
348 
349  /* ignore RTEs that are "other rels" */
350  if (rel->reloptkind != RELOPT_BASEREL)
351  continue;
352 
353  set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
354  }
355 }
356 
357 /*
358  * set_rel_size
359  * Set size estimates for a base relation
360  */
361 static void
363  Index rti, RangeTblEntry *rte)
364 {
365  if (rel->reloptkind == RELOPT_BASEREL &&
366  relation_excluded_by_constraints(root, rel, rte))
367  {
368  /*
369  * We proved we don't need to scan the rel via constraint exclusion,
370  * so set up a single dummy path for it. Here we only check this for
371  * regular baserels; if it's an otherrel, CE was already checked in
372  * set_append_rel_size().
373  *
374  * In this case, we go ahead and set up the relation's path right away
375  * instead of leaving it for set_rel_pathlist to do. This is because
376  * we don't have a convention for marking a rel as dummy except by
377  * assigning a dummy path to it.
378  */
380  }
381  else if (rte->inh)
382  {
383  /* It's an "append relation", process accordingly */
384  set_append_rel_size(root, rel, rti, rte);
385  }
386  else
387  {
388  switch (rel->rtekind)
389  {
390  case RTE_RELATION:
391  if (rte->relkind == RELKIND_FOREIGN_TABLE)
392  {
393  /* Foreign table */
394  set_foreign_size(root, rel, rte);
395  }
396  else if (rte->relkind == RELKIND_PARTITIONED_TABLE)
397  {
398  /*
399  * We could get here if asked to scan a partitioned table
400  * with ONLY. In that case we shouldn't scan any of the
401  * partitions, so mark it as a dummy rel.
402  */
404  }
405  else if (rte->tablesample != NULL)
406  {
407  /* Sampled relation */
408  set_tablesample_rel_size(root, rel, rte);
409  }
410  else
411  {
412  /* Plain relation */
413  set_plain_rel_size(root, rel, rte);
414  }
415  break;
416  case RTE_SUBQUERY:
417 
418  /*
419  * Subqueries don't support making a choice between
420  * parameterized and unparameterized paths, so just go ahead
421  * and build their paths immediately.
422  */
423  set_subquery_pathlist(root, rel, rti, rte);
424  break;
425  case RTE_FUNCTION:
426  set_function_size_estimates(root, rel);
427  break;
428  case RTE_TABLEFUNC:
429  set_tablefunc_size_estimates(root, rel);
430  break;
431  case RTE_VALUES:
432  set_values_size_estimates(root, rel);
433  break;
434  case RTE_CTE:
435 
436  /*
437  * CTEs don't support making a choice between parameterized
438  * and unparameterized paths, so just go ahead and build their
439  * paths immediately.
440  */
441  if (rte->self_reference)
442  set_worktable_pathlist(root, rel, rte);
443  else
444  set_cte_pathlist(root, rel, rte);
445  break;
446  case RTE_NAMEDTUPLESTORE:
447  /* Might as well just build the path immediately */
448  set_namedtuplestore_pathlist(root, rel, rte);
449  break;
450  case RTE_RESULT:
451  /* Might as well just build the path immediately */
452  set_result_pathlist(root, rel, rte);
453  break;
454  default:
455  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
456  break;
457  }
458  }
459 
460  /*
461  * We insist that all non-dummy rels have a nonzero rowcount estimate.
462  */
463  Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
464 }
465 
466 /*
467  * set_rel_pathlist
468  * Build access paths for a base relation
469  */
470 static void
472  Index rti, RangeTblEntry *rte)
473 {
474  if (IS_DUMMY_REL(rel))
475  {
476  /* We already proved the relation empty, so nothing more to do */
477  }
478  else if (rte->inh)
479  {
480  /* It's an "append relation", process accordingly */
481  set_append_rel_pathlist(root, rel, rti, rte);
482  }
483  else
484  {
485  switch (rel->rtekind)
486  {
487  case RTE_RELATION:
488  if (rte->relkind == RELKIND_FOREIGN_TABLE)
489  {
490  /* Foreign table */
491  set_foreign_pathlist(root, rel, rte);
492  }
493  else if (rte->tablesample != NULL)
494  {
495  /* Sampled relation */
496  set_tablesample_rel_pathlist(root, rel, rte);
497  }
498  else
499  {
500  /* Plain relation */
501  set_plain_rel_pathlist(root, rel, rte);
502  }
503  break;
504  case RTE_SUBQUERY:
505  /* Subquery --- fully handled during set_rel_size */
506  break;
507  case RTE_FUNCTION:
508  /* RangeFunction */
509  set_function_pathlist(root, rel, rte);
510  break;
511  case RTE_TABLEFUNC:
512  /* Table Function */
513  set_tablefunc_pathlist(root, rel, rte);
514  break;
515  case RTE_VALUES:
516  /* Values list */
517  set_values_pathlist(root, rel, rte);
518  break;
519  case RTE_CTE:
520  /* CTE reference --- fully handled during set_rel_size */
521  break;
522  case RTE_NAMEDTUPLESTORE:
523  /* tuplestore reference --- fully handled during set_rel_size */
524  break;
525  case RTE_RESULT:
526  /* simple Result --- fully handled during set_rel_size */
527  break;
528  default:
529  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
530  break;
531  }
532  }
533 
534  /*
535  * Allow a plugin to editorialize on the set of Paths for this base
536  * relation. It could add new paths (such as CustomPaths) by calling
537  * add_path(), or add_partial_path() if parallel aware. It could also
538  * delete or modify paths added by the core code.
539  */
541  (*set_rel_pathlist_hook) (root, rel, rti, rte);
542 
543  /*
544  * If this is a baserel, we should normally consider gathering any partial
545  * paths we may have created for it. We have to do this after calling the
546  * set_rel_pathlist_hook, else it cannot add partial paths to be included
547  * here.
548  *
549  * However, if this is an inheritance child, skip it. Otherwise, we could
550  * end up with a very large number of gather nodes, each trying to grab
551  * its own pool of workers. Instead, we'll consider gathering partial
552  * paths for the parent appendrel.
553  *
554  * Also, if this is the topmost scan/join rel (that is, the only baserel),
555  * we postpone gathering until the final scan/join targetlist is available
556  * (see grouping_planner).
557  */
558  if (rel->reloptkind == RELOPT_BASEREL &&
560  generate_useful_gather_paths(root, rel, false);
561 
562  /* Now find the cheapest of the paths for this rel */
563  set_cheapest(rel);
564 
565 #ifdef OPTIMIZER_DEBUG
566  debug_print_rel(root, rel);
567 #endif
568 }
569 
570 /*
571  * set_plain_rel_size
572  * Set size estimates for a plain relation (no subquery, no inheritance)
573  */
574 static void
576 {
577  /*
578  * Test any partial indexes of rel for applicability. We must do this
579  * first since partial unique indexes can affect size estimates.
580  */
581  check_index_predicates(root, rel);
582 
583  /* Mark rel with estimated output rows, width, etc */
584  set_baserel_size_estimates(root, rel);
585 }
586 
587 /*
588  * If this relation could possibly be scanned from within a worker, then set
589  * its consider_parallel flag.
590  */
591 static void
593  RangeTblEntry *rte)
594 {
595  /*
596  * The flag has previously been initialized to false, so we can just
597  * return if it becomes clear that we can't safely set it.
598  */
599  Assert(!rel->consider_parallel);
600 
601  /* Don't call this if parallelism is disallowed for the entire query. */
602  Assert(root->glob->parallelModeOK);
603 
604  /* This should only be called for baserels and appendrel children. */
605  Assert(IS_SIMPLE_REL(rel));
606 
607  /* Assorted checks based on rtekind. */
608  switch (rte->rtekind)
609  {
610  case RTE_RELATION:
611 
612  /*
613  * Currently, parallel workers can't access the leader's temporary
614  * tables. We could possibly relax this if we wrote all of its
615  * local buffers at the start of the query and made no changes
616  * thereafter (maybe we could allow hint bit changes), and if we
617  * taught the workers to read them. Writing a large number of
618  * temporary buffers could be expensive, though, and we don't have
619  * the rest of the necessary infrastructure right now anyway. So
620  * for now, bail out if we see a temporary table.
621  */
622  if (get_rel_persistence(rte->relid) == RELPERSISTENCE_TEMP)
623  return;
624 
625  /*
626  * Table sampling can be pushed down to workers if the sample
627  * function and its arguments are safe.
628  */
629  if (rte->tablesample != NULL)
630  {
631  char proparallel = func_parallel(rte->tablesample->tsmhandler);
632 
633  if (proparallel != PROPARALLEL_SAFE)
634  return;
635  if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
636  return;
637  }
638 
639  /*
640  * Ask FDWs whether they can support performing a ForeignScan
641  * within a worker. Most often, the answer will be no. For
642  * example, if the nature of the FDW is such that it opens a TCP
643  * connection with a remote server, each parallel worker would end
644  * up with a separate connection, and these connections might not
645  * be appropriately coordinated between workers and the leader.
646  */
647  if (rte->relkind == RELKIND_FOREIGN_TABLE)
648  {
649  Assert(rel->fdwroutine);
651  return;
652  if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
653  return;
654  }
655 
656  /*
657  * There are additional considerations for appendrels, which we'll
658  * deal with in set_append_rel_size and set_append_rel_pathlist.
659  * For now, just set consider_parallel based on the rel's own
660  * quals and targetlist.
661  */
662  break;
663 
664  case RTE_SUBQUERY:
665 
666  /*
667  * There's no intrinsic problem with scanning a subquery-in-FROM
668  * (as distinct from a SubPlan or InitPlan) in a parallel worker.
669  * If the subquery doesn't happen to have any parallel-safe paths,
670  * then flagging it as consider_parallel won't change anything,
671  * but that's true for plain tables, too. We must set
672  * consider_parallel based on the rel's own quals and targetlist,
673  * so that if a subquery path is parallel-safe but the quals and
674  * projection we're sticking onto it are not, we correctly mark
675  * the SubqueryScanPath as not parallel-safe. (Note that
676  * set_subquery_pathlist() might push some of these quals down
677  * into the subquery itself, but that doesn't change anything.)
678  *
679  * We can't push sub-select containing LIMIT/OFFSET to workers as
680  * there is no guarantee that the row order will be fully
681  * deterministic, and applying LIMIT/OFFSET will lead to
682  * inconsistent results at the top-level. (In some cases, where
683  * the result is ordered, we could relax this restriction. But it
684  * doesn't currently seem worth expending extra effort to do so.)
685  */
686  {
687  Query *subquery = castNode(Query, rte->subquery);
688 
689  if (limit_needed(subquery))
690  return;
691  }
692  break;
693 
694  case RTE_JOIN:
695  /* Shouldn't happen; we're only considering baserels here. */
696  Assert(false);
697  return;
698 
699  case RTE_FUNCTION:
700  /* Check for parallel-restricted functions. */
701  if (!is_parallel_safe(root, (Node *) rte->functions))
702  return;
703  break;
704 
705  case RTE_TABLEFUNC:
706  /* not parallel safe */
707  return;
708 
709  case RTE_VALUES:
710  /* Check for parallel-restricted functions. */
711  if (!is_parallel_safe(root, (Node *) rte->values_lists))
712  return;
713  break;
714 
715  case RTE_CTE:
716 
717  /*
718  * CTE tuplestores aren't shared among parallel workers, so we
719  * force all CTE scans to happen in the leader. Also, populating
720  * the CTE would require executing a subplan that's not available
721  * in the worker, might be parallel-restricted, and must get
722  * executed only once.
723  */
724  return;
725 
726  case RTE_NAMEDTUPLESTORE:
727 
728  /*
729  * tuplestore cannot be shared, at least without more
730  * infrastructure to support that.
731  */
732  return;
733 
734  case RTE_RESULT:
735  /* RESULT RTEs, in themselves, are no problem. */
736  break;
737  }
738 
739  /*
740  * If there's anything in baserestrictinfo that's parallel-restricted, we
741  * give up on parallelizing access to this relation. We could consider
742  * instead postponing application of the restricted quals until we're
743  * above all the parallelism in the plan tree, but it's not clear that
744  * that would be a win in very many cases, and it might be tricky to make
745  * outer join clauses work correctly. It would likely break equivalence
746  * classes, too.
747  */
748  if (!is_parallel_safe(root, (Node *) rel->baserestrictinfo))
749  return;
750 
751  /*
752  * Likewise, if the relation's outputs are not parallel-safe, give up.
753  * (Usually, they're just Vars, but sometimes they're not.)
754  */
755  if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
756  return;
757 
758  /* We have a winner. */
759  rel->consider_parallel = true;
760 }
761 
762 /*
763  * set_plain_rel_pathlist
764  * Build access paths for a plain relation (no subquery, no inheritance)
765  */
766 static void
768 {
769  Relids required_outer;
770 
771  /*
772  * We don't support pushing join clauses into the quals of a seqscan, but
773  * it could still have required parameterization due to LATERAL refs in
774  * its tlist.
775  */
776  required_outer = rel->lateral_relids;
777 
778  /* Consider sequential scan */
779  add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
780 
781  /* If appropriate, consider parallel sequential scan */
782  if (rel->consider_parallel && required_outer == NULL)
783  create_plain_partial_paths(root, rel);
784 
785  /* Consider index scans */
786  create_index_paths(root, rel);
787 
788  /* Consider TID scans */
789  create_tidscan_paths(root, rel);
790 }
791 
792 /*
793  * create_plain_partial_paths
794  * Build partial access paths for parallel scan of a plain relation
795  */
796 static void
798 {
799  int parallel_workers;
800 
801  parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
803 
804  /* If any limit was set to zero, the user doesn't want a parallel scan. */
805  if (parallel_workers <= 0)
806  return;
807 
808  /* Add an unordered partial path based on a parallel sequential scan. */
809  add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
810 }
811 
812 /*
813  * set_tablesample_rel_size
814  * Set size estimates for a sampled relation
815  */
816 static void
818 {
819  TableSampleClause *tsc = rte->tablesample;
820  TsmRoutine *tsm;
821  BlockNumber pages;
822  double tuples;
823 
824  /*
825  * Test any partial indexes of rel for applicability. We must do this
826  * first since partial unique indexes can affect size estimates.
827  */
828  check_index_predicates(root, rel);
829 
830  /*
831  * Call the sampling method's estimation function to estimate the number
832  * of pages it will read and the number of tuples it will return. (Note:
833  * we assume the function returns sane values.)
834  */
835  tsm = GetTsmRoutine(tsc->tsmhandler);
836  tsm->SampleScanGetSampleSize(root, rel, tsc->args,
837  &pages, &tuples);
838 
839  /*
840  * For the moment, because we will only consider a SampleScan path for the
841  * rel, it's okay to just overwrite the pages and tuples estimates for the
842  * whole relation. If we ever consider multiple path types for sampled
843  * rels, we'll need more complication.
844  */
845  rel->pages = pages;
846  rel->tuples = tuples;
847 
848  /* Mark rel with estimated output rows, width, etc */
849  set_baserel_size_estimates(root, rel);
850 }
851 
852 /*
853  * set_tablesample_rel_pathlist
854  * Build access paths for a sampled relation
855  */
856 static void
858 {
859  Relids required_outer;
860  Path *path;
861 
862  /*
863  * We don't support pushing join clauses into the quals of a samplescan,
864  * but it could still have required parameterization due to LATERAL refs
865  * in its tlist or TABLESAMPLE arguments.
866  */
867  required_outer = rel->lateral_relids;
868 
869  /* Consider sampled scan */
870  path = create_samplescan_path(root, rel, required_outer);
871 
872  /*
873  * If the sampling method does not support repeatable scans, we must avoid
874  * plans that would scan the rel multiple times. Ideally, we'd simply
875  * avoid putting the rel on the inside of a nestloop join; but adding such
876  * a consideration to the planner seems like a great deal of complication
877  * to support an uncommon usage of second-rate sampling methods. Instead,
878  * if there is a risk that the query might perform an unsafe join, just
879  * wrap the SampleScan in a Materialize node. We can check for joins by
880  * counting the membership of all_baserels (note that this correctly
881  * counts inheritance trees as single rels). If we're inside a subquery,
882  * we can't easily check whether a join might occur in the outer query, so
883  * just assume one is possible.
884  *
885  * GetTsmRoutine is relatively expensive compared to the other tests here,
886  * so check repeatable_across_scans last, even though that's a bit odd.
887  */
888  if ((root->query_level > 1 ||
891  {
892  path = (Path *) create_material_path(rel, path);
893  }
894 
895  add_path(rel, path);
896 
897  /* For the moment, at least, there are no other paths to consider */
898 }
899 
900 /*
901  * set_foreign_size
902  * Set size estimates for a foreign table RTE
903  */
904 static void
906 {
907  /* Mark rel with estimated output rows, width, etc */
908  set_foreign_size_estimates(root, rel);
909 
910  /* Let FDW adjust the size estimates, if it can */
911  rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
912 
913  /* ... but do not let it set the rows estimate to zero */
914  rel->rows = clamp_row_est(rel->rows);
915 
916  /*
917  * Also, make sure rel->tuples is not insane relative to rel->rows.
918  * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
919  * FDW doesn't do anything to replace that.
920  */
921  rel->tuples = Max(rel->tuples, rel->rows);
922 }
923 
924 /*
925  * set_foreign_pathlist
926  * Build access paths for a foreign table RTE
927  */
928 static void
930 {
931  /* Call the FDW's GetForeignPaths function to generate path(s) */
932  rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
933 }
934 
935 /*
936  * set_append_rel_size
937  * Set size estimates for a simple "append relation"
938  *
939  * The passed-in rel and RTE represent the entire append relation. The
940  * relation's contents are computed by appending together the output of the
941  * individual member relations. Note that in the non-partitioned inheritance
942  * case, the first member relation is actually the same table as is mentioned
943  * in the parent RTE ... but it has a different RTE and RelOptInfo. This is
944  * a good thing because their outputs are not the same size.
945  */
946 static void
948  Index rti, RangeTblEntry *rte)
949 {
950  int parentRTindex = rti;
951  bool has_live_children;
952  double parent_rows;
953  double parent_size;
954  double *parent_attrsizes;
955  int nattrs;
956  ListCell *l;
957 
958  /* Guard against stack overflow due to overly deep inheritance tree. */
960 
961  Assert(IS_SIMPLE_REL(rel));
962 
963  /*
964  * If this is a partitioned baserel, set the consider_partitionwise_join
965  * flag; currently, we only consider partitionwise joins with the baserel
966  * if its targetlist doesn't contain a whole-row Var.
967  */
969  rel->reloptkind == RELOPT_BASEREL &&
970  rte->relkind == RELKIND_PARTITIONED_TABLE &&
971  rel->attr_needed[InvalidAttrNumber - rel->min_attr] == NULL)
972  rel->consider_partitionwise_join = true;
973 
974  /*
975  * Initialize to compute size estimates for whole append relation.
976  *
977  * We handle width estimates by weighting the widths of different child
978  * rels proportionally to their number of rows. This is sensible because
979  * the use of width estimates is mainly to compute the total relation
980  * "footprint" if we have to sort or hash it. To do this, we sum the
981  * total equivalent size (in "double" arithmetic) and then divide by the
982  * total rowcount estimate. This is done separately for the total rel
983  * width and each attribute.
984  *
985  * Note: if you consider changing this logic, beware that child rels could
986  * have zero rows and/or width, if they were excluded by constraints.
987  */
988  has_live_children = false;
989  parent_rows = 0;
990  parent_size = 0;
991  nattrs = rel->max_attr - rel->min_attr + 1;
992  parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
993 
994  foreach(l, root->append_rel_list)
995  {
996  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
997  int childRTindex;
998  RangeTblEntry *childRTE;
999  RelOptInfo *childrel;
1000  ListCell *parentvars;
1001  ListCell *childvars;
1002 
1003  /* append_rel_list contains all append rels; ignore others */
1004  if (appinfo->parent_relid != parentRTindex)
1005  continue;
1006 
1007  childRTindex = appinfo->child_relid;
1008  childRTE = root->simple_rte_array[childRTindex];
1009 
1010  /*
1011  * The child rel's RelOptInfo was already created during
1012  * add_other_rels_to_query.
1013  */
1014  childrel = find_base_rel(root, childRTindex);
1016 
1017  /* We may have already proven the child to be dummy. */
1018  if (IS_DUMMY_REL(childrel))
1019  continue;
1020 
1021  /*
1022  * We have to copy the parent's targetlist and quals to the child,
1023  * with appropriate substitution of variables. However, the
1024  * baserestrictinfo quals were already copied/substituted when the
1025  * child RelOptInfo was built. So we don't need any additional setup
1026  * before applying constraint exclusion.
1027  */
1028  if (relation_excluded_by_constraints(root, childrel, childRTE))
1029  {
1030  /*
1031  * This child need not be scanned, so we can omit it from the
1032  * appendrel.
1033  */
1034  set_dummy_rel_pathlist(childrel);
1035  continue;
1036  }
1037 
1038  /*
1039  * Constraint exclusion failed, so copy the parent's join quals and
1040  * targetlist to the child, with appropriate variable substitutions.
1041  *
1042  * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1043  * expressions, which otherwise would not occur in a rel's targetlist.
1044  * Code that might be looking at an appendrel child must cope with
1045  * such. (Normally, a rel's targetlist would only include Vars and
1046  * PlaceHolderVars.) XXX we do not bother to update the cost or width
1047  * fields of childrel->reltarget; not clear if that would be useful.
1048  */
1049  childrel->joininfo = (List *)
1051  (Node *) rel->joininfo,
1052  1, &appinfo);
1053  childrel->reltarget->exprs = (List *)
1055  (Node *) rel->reltarget->exprs,
1056  1, &appinfo);
1057 
1058  /*
1059  * We have to make child entries in the EquivalenceClass data
1060  * structures as well. This is needed either if the parent
1061  * participates in some eclass joins (because we will want to consider
1062  * inner-indexscan joins on the individual children) or if the parent
1063  * has useful pathkeys (because we should try to build MergeAppend
1064  * paths that produce those sort orderings).
1065  */
1066  if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1067  add_child_rel_equivalences(root, appinfo, rel, childrel);
1068  childrel->has_eclass_joins = rel->has_eclass_joins;
1069 
1070  /*
1071  * Note: we could compute appropriate attr_needed data for the child's
1072  * variables, by transforming the parent's attr_needed through the
1073  * translated_vars mapping. However, currently there's no need
1074  * because attr_needed is only examined for base relations not
1075  * otherrels. So we just leave the child's attr_needed empty.
1076  */
1077 
1078  /*
1079  * If we consider partitionwise joins with the parent rel, do the same
1080  * for partitioned child rels.
1081  *
1082  * Note: here we abuse the consider_partitionwise_join flag by setting
1083  * it for child rels that are not themselves partitioned. We do so to
1084  * tell try_partitionwise_join() that the child rel is sufficiently
1085  * valid to be used as a per-partition input, even if it later gets
1086  * proven to be dummy. (It's not usable until we've set up the
1087  * reltarget and EC entries, which we just did.)
1088  */
1089  if (rel->consider_partitionwise_join)
1090  childrel->consider_partitionwise_join = true;
1091 
1092  /*
1093  * If parallelism is allowable for this query in general, see whether
1094  * it's allowable for this childrel in particular. But if we've
1095  * already decided the appendrel is not parallel-safe as a whole,
1096  * there's no point in considering parallelism for this child. For
1097  * consistency, do this before calling set_rel_size() for the child.
1098  */
1099  if (root->glob->parallelModeOK && rel->consider_parallel)
1100  set_rel_consider_parallel(root, childrel, childRTE);
1101 
1102  /*
1103  * Compute the child's size.
1104  */
1105  set_rel_size(root, childrel, childRTindex, childRTE);
1106 
1107  /*
1108  * It is possible that constraint exclusion detected a contradiction
1109  * within a child subquery, even though we didn't prove one above. If
1110  * so, we can skip this child.
1111  */
1112  if (IS_DUMMY_REL(childrel))
1113  continue;
1114 
1115  /* We have at least one live child. */
1116  has_live_children = true;
1117 
1118  /*
1119  * If any live child is not parallel-safe, treat the whole appendrel
1120  * as not parallel-safe. In future we might be able to generate plans
1121  * in which some children are farmed out to workers while others are
1122  * not; but we don't have that today, so it's a waste to consider
1123  * partial paths anywhere in the appendrel unless it's all safe.
1124  * (Child rels visited before this one will be unmarked in
1125  * set_append_rel_pathlist().)
1126  */
1127  if (!childrel->consider_parallel)
1128  rel->consider_parallel = false;
1129 
1130  /*
1131  * Accumulate size information from each live child.
1132  */
1133  Assert(childrel->rows > 0);
1134 
1135  parent_rows += childrel->rows;
1136  parent_size += childrel->reltarget->width * childrel->rows;
1137 
1138  /*
1139  * Accumulate per-column estimates too. We need not do anything for
1140  * PlaceHolderVars in the parent list. If child expression isn't a
1141  * Var, or we didn't record a width estimate for it, we have to fall
1142  * back on a datatype-based estimate.
1143  *
1144  * By construction, child's targetlist is 1-to-1 with parent's.
1145  */
1146  forboth(parentvars, rel->reltarget->exprs,
1147  childvars, childrel->reltarget->exprs)
1148  {
1149  Var *parentvar = (Var *) lfirst(parentvars);
1150  Node *childvar = (Node *) lfirst(childvars);
1151 
1152  if (IsA(parentvar, Var) && parentvar->varno == parentRTindex)
1153  {
1154  int pndx = parentvar->varattno - rel->min_attr;
1155  int32 child_width = 0;
1156 
1157  if (IsA(childvar, Var) &&
1158  ((Var *) childvar)->varno == childrel->relid)
1159  {
1160  int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1161 
1162  child_width = childrel->attr_widths[cndx];
1163  }
1164  if (child_width <= 0)
1165  child_width = get_typavgwidth(exprType(childvar),
1166  exprTypmod(childvar));
1167  Assert(child_width > 0);
1168  parent_attrsizes[pndx] += child_width * childrel->rows;
1169  }
1170  }
1171  }
1172 
1173  if (has_live_children)
1174  {
1175  /*
1176  * Save the finished size estimates.
1177  */
1178  int i;
1179 
1180  Assert(parent_rows > 0);
1181  rel->rows = parent_rows;
1182  rel->reltarget->width = rint(parent_size / parent_rows);
1183  for (i = 0; i < nattrs; i++)
1184  rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1185 
1186  /*
1187  * Set "raw tuples" count equal to "rows" for the appendrel; needed
1188  * because some places assume rel->tuples is valid for any baserel.
1189  */
1190  rel->tuples = parent_rows;
1191 
1192  /*
1193  * Note that we leave rel->pages as zero; this is important to avoid
1194  * double-counting the appendrel tree in total_table_pages.
1195  */
1196  }
1197  else
1198  {
1199  /*
1200  * All children were excluded by constraints, so mark the whole
1201  * appendrel dummy. We must do this in this phase so that the rel's
1202  * dummy-ness is visible when we generate paths for other rels.
1203  */
1205  }
1206 
1207  pfree(parent_attrsizes);
1208 }
1209 
1210 /*
1211  * set_append_rel_pathlist
1212  * Build access paths for an "append relation"
1213  */
1214 static void
1216  Index rti, RangeTblEntry *rte)
1217 {
1218  int parentRTindex = rti;
1219  List *live_childrels = NIL;
1220  ListCell *l;
1221 
1222  /*
1223  * Generate access paths for each member relation, and remember the
1224  * non-dummy children.
1225  */
1226  foreach(l, root->append_rel_list)
1227  {
1228  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1229  int childRTindex;
1230  RangeTblEntry *childRTE;
1231  RelOptInfo *childrel;
1232 
1233  /* append_rel_list contains all append rels; ignore others */
1234  if (appinfo->parent_relid != parentRTindex)
1235  continue;
1236 
1237  /* Re-locate the child RTE and RelOptInfo */
1238  childRTindex = appinfo->child_relid;
1239  childRTE = root->simple_rte_array[childRTindex];
1240  childrel = root->simple_rel_array[childRTindex];
1241 
1242  /*
1243  * If set_append_rel_size() decided the parent appendrel was
1244  * parallel-unsafe at some point after visiting this child rel, we
1245  * need to propagate the unsafety marking down to the child, so that
1246  * we don't generate useless partial paths for it.
1247  */
1248  if (!rel->consider_parallel)
1249  childrel->consider_parallel = false;
1250 
1251  /*
1252  * Compute the child's access paths.
1253  */
1254  set_rel_pathlist(root, childrel, childRTindex, childRTE);
1255 
1256  /*
1257  * If child is dummy, ignore it.
1258  */
1259  if (IS_DUMMY_REL(childrel))
1260  continue;
1261 
1262  /*
1263  * Child is live, so add it to the live_childrels list for use below.
1264  */
1265  live_childrels = lappend(live_childrels, childrel);
1266  }
1267 
1268  /* Add paths to the append relation. */
1269  add_paths_to_append_rel(root, rel, live_childrels);
1270 }
1271 
1272 
1273 /*
1274  * add_paths_to_append_rel
1275  * Generate paths for the given append relation given the set of non-dummy
1276  * child rels.
1277  *
1278  * The function collects all parameterizations and orderings supported by the
1279  * non-dummy children. For every such parameterization or ordering, it creates
1280  * an append path collecting one path from each non-dummy child with given
1281  * parameterization or ordering. Similarly it collects partial paths from
1282  * non-dummy children to create partial append paths.
1283  */
1284 void
1286  List *live_childrels)
1287 {
1288  List *subpaths = NIL;
1289  bool subpaths_valid = true;
1290  List *partial_subpaths = NIL;
1291  List *pa_partial_subpaths = NIL;
1292  List *pa_nonpartial_subpaths = NIL;
1293  bool partial_subpaths_valid = true;
1294  bool pa_subpaths_valid;
1295  List *all_child_pathkeys = NIL;
1296  List *all_child_outers = NIL;
1297  ListCell *l;
1298  double partial_rows = -1;
1299 
1300  /* If appropriate, consider parallel append */
1301  pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1302 
1303  /*
1304  * For every non-dummy child, remember the cheapest path. Also, identify
1305  * all pathkeys (orderings) and parameterizations (required_outer sets)
1306  * available for the non-dummy member relations.
1307  */
1308  foreach(l, live_childrels)
1309  {
1310  RelOptInfo *childrel = lfirst(l);
1311  ListCell *lcp;
1312  Path *cheapest_partial_path = NULL;
1313 
1314  /*
1315  * If child has an unparameterized cheapest-total path, add that to
1316  * the unparameterized Append path we are constructing for the parent.
1317  * If not, there's no workable unparameterized path.
1318  *
1319  * With partitionwise aggregates, the child rel's pathlist may be
1320  * empty, so don't assume that a path exists here.
1321  */
1322  if (childrel->pathlist != NIL &&
1323  childrel->cheapest_total_path->param_info == NULL)
1325  &subpaths, NULL);
1326  else
1327  subpaths_valid = false;
1328 
1329  /* Same idea, but for a partial plan. */
1330  if (childrel->partial_pathlist != NIL)
1331  {
1332  cheapest_partial_path = linitial(childrel->partial_pathlist);
1333  accumulate_append_subpath(cheapest_partial_path,
1334  &partial_subpaths, NULL);
1335  }
1336  else
1337  partial_subpaths_valid = false;
1338 
1339  /*
1340  * Same idea, but for a parallel append mixing partial and non-partial
1341  * paths.
1342  */
1343  if (pa_subpaths_valid)
1344  {
1345  Path *nppath = NULL;
1346 
1347  nppath =
1349 
1350  if (cheapest_partial_path == NULL && nppath == NULL)
1351  {
1352  /* Neither a partial nor a parallel-safe path? Forget it. */
1353  pa_subpaths_valid = false;
1354  }
1355  else if (nppath == NULL ||
1356  (cheapest_partial_path != NULL &&
1357  cheapest_partial_path->total_cost < nppath->total_cost))
1358  {
1359  /* Partial path is cheaper or the only option. */
1360  Assert(cheapest_partial_path != NULL);
1361  accumulate_append_subpath(cheapest_partial_path,
1362  &pa_partial_subpaths,
1363  &pa_nonpartial_subpaths);
1364  }
1365  else
1366  {
1367  /*
1368  * Either we've got only a non-partial path, or we think that
1369  * a single backend can execute the best non-partial path
1370  * faster than all the parallel backends working together can
1371  * execute the best partial path.
1372  *
1373  * It might make sense to be more aggressive here. Even if
1374  * the best non-partial path is more expensive than the best
1375  * partial path, it could still be better to choose the
1376  * non-partial path if there are several such paths that can
1377  * be given to different workers. For now, we don't try to
1378  * figure that out.
1379  */
1381  &pa_nonpartial_subpaths,
1382  NULL);
1383  }
1384  }
1385 
1386  /*
1387  * Collect lists of all the available path orderings and
1388  * parameterizations for all the children. We use these as a
1389  * heuristic to indicate which sort orderings and parameterizations we
1390  * should build Append and MergeAppend paths for.
1391  */
1392  foreach(lcp, childrel->pathlist)
1393  {
1394  Path *childpath = (Path *) lfirst(lcp);
1395  List *childkeys = childpath->pathkeys;
1396  Relids childouter = PATH_REQ_OUTER(childpath);
1397 
1398  /* Unsorted paths don't contribute to pathkey list */
1399  if (childkeys != NIL)
1400  {
1401  ListCell *lpk;
1402  bool found = false;
1403 
1404  /* Have we already seen this ordering? */
1405  foreach(lpk, all_child_pathkeys)
1406  {
1407  List *existing_pathkeys = (List *) lfirst(lpk);
1408 
1409  if (compare_pathkeys(existing_pathkeys,
1410  childkeys) == PATHKEYS_EQUAL)
1411  {
1412  found = true;
1413  break;
1414  }
1415  }
1416  if (!found)
1417  {
1418  /* No, so add it to all_child_pathkeys */
1419  all_child_pathkeys = lappend(all_child_pathkeys,
1420  childkeys);
1421  }
1422  }
1423 
1424  /* Unparameterized paths don't contribute to param-set list */
1425  if (childouter)
1426  {
1427  ListCell *lco;
1428  bool found = false;
1429 
1430  /* Have we already seen this param set? */
1431  foreach(lco, all_child_outers)
1432  {
1433  Relids existing_outers = (Relids) lfirst(lco);
1434 
1435  if (bms_equal(existing_outers, childouter))
1436  {
1437  found = true;
1438  break;
1439  }
1440  }
1441  if (!found)
1442  {
1443  /* No, so add it to all_child_outers */
1444  all_child_outers = lappend(all_child_outers,
1445  childouter);
1446  }
1447  }
1448  }
1449  }
1450 
1451  /*
1452  * If we found unparameterized paths for all children, build an unordered,
1453  * unparameterized Append path for the rel. (Note: this is correct even
1454  * if we have zero or one live subpath due to constraint exclusion.)
1455  */
1456  if (subpaths_valid)
1457  add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1458  NIL, NULL, 0, false,
1459  -1));
1460 
1461  /*
1462  * Consider an append of unordered, unparameterized partial paths. Make
1463  * it parallel-aware if possible.
1464  */
1465  if (partial_subpaths_valid && partial_subpaths != NIL)
1466  {
1467  AppendPath *appendpath;
1468  ListCell *lc;
1469  int parallel_workers = 0;
1470 
1471  /* Find the highest number of workers requested for any subpath. */
1472  foreach(lc, partial_subpaths)
1473  {
1474  Path *path = lfirst(lc);
1475 
1476  parallel_workers = Max(parallel_workers, path->parallel_workers);
1477  }
1478  Assert(parallel_workers > 0);
1479 
1480  /*
1481  * If the use of parallel append is permitted, always request at least
1482  * log2(# of children) workers. We assume it can be useful to have
1483  * extra workers in this case because they will be spread out across
1484  * the children. The precise formula is just a guess, but we don't
1485  * want to end up with a radically different answer for a table with N
1486  * partitions vs. an unpartitioned table with the same data, so the
1487  * use of some kind of log-scaling here seems to make some sense.
1488  */
1490  {
1491  parallel_workers = Max(parallel_workers,
1492  fls(list_length(live_childrels)));
1493  parallel_workers = Min(parallel_workers,
1495  }
1496  Assert(parallel_workers > 0);
1497 
1498  /* Generate a partial append path. */
1499  appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1500  NIL, NULL, parallel_workers,
1502  -1);
1503 
1504  /*
1505  * Make sure any subsequent partial paths use the same row count
1506  * estimate.
1507  */
1508  partial_rows = appendpath->path.rows;
1509 
1510  /* Add the path. */
1511  add_partial_path(rel, (Path *) appendpath);
1512  }
1513 
1514  /*
1515  * Consider a parallel-aware append using a mix of partial and non-partial
1516  * paths. (This only makes sense if there's at least one child which has
1517  * a non-partial path that is substantially cheaper than any partial path;
1518  * otherwise, we should use the append path added in the previous step.)
1519  */
1520  if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1521  {
1522  AppendPath *appendpath;
1523  ListCell *lc;
1524  int parallel_workers = 0;
1525 
1526  /*
1527  * Find the highest number of workers requested for any partial
1528  * subpath.
1529  */
1530  foreach(lc, pa_partial_subpaths)
1531  {
1532  Path *path = lfirst(lc);
1533 
1534  parallel_workers = Max(parallel_workers, path->parallel_workers);
1535  }
1536 
1537  /*
1538  * Same formula here as above. It's even more important in this
1539  * instance because the non-partial paths won't contribute anything to
1540  * the planned number of parallel workers.
1541  */
1542  parallel_workers = Max(parallel_workers,
1543  fls(list_length(live_childrels)));
1544  parallel_workers = Min(parallel_workers,
1546  Assert(parallel_workers > 0);
1547 
1548  appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1549  pa_partial_subpaths,
1550  NIL, NULL, parallel_workers, true,
1551  partial_rows);
1552  add_partial_path(rel, (Path *) appendpath);
1553  }
1554 
1555  /*
1556  * Also build unparameterized ordered append paths based on the collected
1557  * list of child pathkeys.
1558  */
1559  if (subpaths_valid)
1560  generate_orderedappend_paths(root, rel, live_childrels,
1561  all_child_pathkeys);
1562 
1563  /*
1564  * Build Append paths for each parameterization seen among the child rels.
1565  * (This may look pretty expensive, but in most cases of practical
1566  * interest, the child rels will expose mostly the same parameterizations,
1567  * so that not that many cases actually get considered here.)
1568  *
1569  * The Append node itself cannot enforce quals, so all qual checking must
1570  * be done in the child paths. This means that to have a parameterized
1571  * Append path, we must have the exact same parameterization for each
1572  * child path; otherwise some children might be failing to check the
1573  * moved-down quals. To make them match up, we can try to increase the
1574  * parameterization of lesser-parameterized paths.
1575  */
1576  foreach(l, all_child_outers)
1577  {
1578  Relids required_outer = (Relids) lfirst(l);
1579  ListCell *lcr;
1580 
1581  /* Select the child paths for an Append with this parameterization */
1582  subpaths = NIL;
1583  subpaths_valid = true;
1584  foreach(lcr, live_childrels)
1585  {
1586  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1587  Path *subpath;
1588 
1589  if (childrel->pathlist == NIL)
1590  {
1591  /* failed to make a suitable path for this child */
1592  subpaths_valid = false;
1593  break;
1594  }
1595 
1597  childrel,
1598  required_outer);
1599  if (subpath == NULL)
1600  {
1601  /* failed to make a suitable path for this child */
1602  subpaths_valid = false;
1603  break;
1604  }
1605  accumulate_append_subpath(subpath, &subpaths, NULL);
1606  }
1607 
1608  if (subpaths_valid)
1609  add_path(rel, (Path *)
1610  create_append_path(root, rel, subpaths, NIL,
1611  NIL, required_outer, 0, false,
1612  -1));
1613  }
1614 
1615  /*
1616  * When there is only a single child relation, the Append path can inherit
1617  * any ordering available for the child rel's path, so that it's useful to
1618  * consider ordered partial paths. Above we only considered the cheapest
1619  * partial path for each child, but let's also make paths using any
1620  * partial paths that have pathkeys.
1621  */
1622  if (list_length(live_childrels) == 1)
1623  {
1624  RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1625 
1626  /* skip the cheapest partial path, since we already used that above */
1627  for_each_from(l, childrel->partial_pathlist, 1)
1628  {
1629  Path *path = (Path *) lfirst(l);
1630  AppendPath *appendpath;
1631 
1632  /* skip paths with no pathkeys. */
1633  if (path->pathkeys == NIL)
1634  continue;
1635 
1636  appendpath = create_append_path(root, rel, NIL, list_make1(path),
1637  NIL, NULL,
1638  path->parallel_workers, true,
1639  partial_rows);
1640  add_partial_path(rel, (Path *) appendpath);
1641  }
1642  }
1643 }
1644 
1645 /*
1646  * generate_orderedappend_paths
1647  * Generate ordered append paths for an append relation
1648  *
1649  * Usually we generate MergeAppend paths here, but there are some special
1650  * cases where we can generate simple Append paths, because the subpaths
1651  * can provide tuples in the required order already.
1652  *
1653  * We generate a path for each ordering (pathkey list) appearing in
1654  * all_child_pathkeys.
1655  *
1656  * We consider both cheapest-startup and cheapest-total cases, ie, for each
1657  * interesting ordering, collect all the cheapest startup subpaths and all the
1658  * cheapest total paths, and build a suitable path for each case.
1659  *
1660  * We don't currently generate any parameterized ordered paths here. While
1661  * it would not take much more code here to do so, it's very unclear that it
1662  * is worth the planning cycles to investigate such paths: there's little
1663  * use for an ordered path on the inside of a nestloop. In fact, it's likely
1664  * that the current coding of add_path would reject such paths out of hand,
1665  * because add_path gives no credit for sort ordering of parameterized paths,
1666  * and a parameterized MergeAppend is going to be more expensive than the
1667  * corresponding parameterized Append path. If we ever try harder to support
1668  * parameterized mergejoin plans, it might be worth adding support for
1669  * parameterized paths here to feed such joins. (See notes in
1670  * optimizer/README for why that might not ever happen, though.)
1671  */
1672 static void
1674  List *live_childrels,
1675  List *all_child_pathkeys)
1676 {
1677  ListCell *lcp;
1678  List *partition_pathkeys = NIL;
1679  List *partition_pathkeys_desc = NIL;
1680  bool partition_pathkeys_partial = true;
1681  bool partition_pathkeys_desc_partial = true;
1682 
1683  /*
1684  * Some partitioned table setups may allow us to use an Append node
1685  * instead of a MergeAppend. This is possible in cases such as RANGE
1686  * partitioned tables where it's guaranteed that an earlier partition must
1687  * contain rows which come earlier in the sort order. To detect whether
1688  * this is relevant, build pathkey descriptions of the partition ordering,
1689  * for both forward and reverse scans.
1690  */
1691  if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1693  {
1694  partition_pathkeys = build_partition_pathkeys(root, rel,
1696  &partition_pathkeys_partial);
1697 
1698  partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1700  &partition_pathkeys_desc_partial);
1701 
1702  /*
1703  * You might think we should truncate_useless_pathkeys here, but
1704  * allowing partition keys which are a subset of the query's pathkeys
1705  * can often be useful. For example, consider a table partitioned by
1706  * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1707  * paths that can produce the a, b, c ordering (perhaps via indexes on
1708  * (a, b, c)) then it works to consider the appendrel output as
1709  * ordered by a, b, c.
1710  */
1711  }
1712 
1713  /* Now consider each interesting sort ordering */
1714  foreach(lcp, all_child_pathkeys)
1715  {
1716  List *pathkeys = (List *) lfirst(lcp);
1717  List *startup_subpaths = NIL;
1718  List *total_subpaths = NIL;
1719  List *fractional_subpaths = NIL;
1720  bool startup_neq_total = false;
1721  ListCell *lcr;
1722  bool match_partition_order;
1723  bool match_partition_order_desc;
1724 
1725  /*
1726  * Determine if this sort ordering matches any partition pathkeys we
1727  * have, for both ascending and descending partition order. If the
1728  * partition pathkeys happen to be contained in pathkeys then it still
1729  * works, as described above, providing that the partition pathkeys
1730  * are complete and not just a prefix of the partition keys. (In such
1731  * cases we'll be relying on the child paths to have sorted the
1732  * lower-order columns of the required pathkeys.)
1733  */
1734  match_partition_order =
1735  pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1736  (!partition_pathkeys_partial &&
1737  pathkeys_contained_in(partition_pathkeys, pathkeys));
1738 
1739  match_partition_order_desc = !match_partition_order &&
1740  (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1741  (!partition_pathkeys_desc_partial &&
1742  pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1743 
1744  /* Select the child paths for this ordering... */
1745  foreach(lcr, live_childrels)
1746  {
1747  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1748  Path *cheapest_startup,
1749  *cheapest_total,
1750  *cheapest_fractional = NULL;
1751 
1752  /* Locate the right paths, if they are available. */
1753  cheapest_startup =
1755  pathkeys,
1756  NULL,
1757  STARTUP_COST,
1758  false);
1759  cheapest_total =
1761  pathkeys,
1762  NULL,
1763  TOTAL_COST,
1764  false);
1765 
1766  /*
1767  * If we can't find any paths with the right order just use the
1768  * cheapest-total path; we'll have to sort it later.
1769  */
1770  if (cheapest_startup == NULL || cheapest_total == NULL)
1771  {
1772  cheapest_startup = cheapest_total =
1773  childrel->cheapest_total_path;
1774  /* Assert we do have an unparameterized path for this child */
1775  Assert(cheapest_total->param_info == NULL);
1776  }
1777 
1778  /*
1779  * When building a fractional path, determine a cheapest fractional
1780  * path for each child relation too. Looking at startup and total
1781  * costs is not enough, because the cheapest fractional path may be
1782  * dominated by two separate paths (one for startup, one for total).
1783  *
1784  * When needed (building fractional path), determine the cheapest
1785  * fractional path too.
1786  */
1787  if (root->tuple_fraction > 0)
1788  {
1789  double path_fraction = (1.0 / root->tuple_fraction);
1790 
1791  cheapest_fractional =
1793  pathkeys,
1794  NULL,
1795  path_fraction);
1796 
1797  /*
1798  * If we found no path with matching pathkeys, use the cheapest
1799  * total path instead.
1800  *
1801  * XXX We might consider partially sorted paths too (with an
1802  * incremental sort on top). But we'd have to build all the
1803  * incremental paths, do the costing etc.
1804  */
1805  if (!cheapest_fractional)
1806  cheapest_fractional = cheapest_total;
1807  }
1808 
1809  /*
1810  * Notice whether we actually have different paths for the
1811  * "cheapest" and "total" cases; frequently there will be no point
1812  * in two create_merge_append_path() calls.
1813  */
1814  if (cheapest_startup != cheapest_total)
1815  startup_neq_total = true;
1816 
1817  /*
1818  * Collect the appropriate child paths. The required logic varies
1819  * for the Append and MergeAppend cases.
1820  */
1821  if (match_partition_order)
1822  {
1823  /*
1824  * We're going to make a plain Append path. We don't need
1825  * most of what accumulate_append_subpath would do, but we do
1826  * want to cut out child Appends or MergeAppends if they have
1827  * just a single subpath (and hence aren't doing anything
1828  * useful).
1829  */
1830  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1831  cheapest_total = get_singleton_append_subpath(cheapest_total);
1832 
1833  startup_subpaths = lappend(startup_subpaths, cheapest_startup);
1834  total_subpaths = lappend(total_subpaths, cheapest_total);
1835 
1836  if (cheapest_fractional)
1837  {
1838  cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1839  fractional_subpaths = lappend(fractional_subpaths, cheapest_fractional);
1840  }
1841  }
1842  else if (match_partition_order_desc)
1843  {
1844  /*
1845  * As above, but we need to reverse the order of the children,
1846  * because nodeAppend.c doesn't know anything about reverse
1847  * ordering and will scan the children in the order presented.
1848  */
1849  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1850  cheapest_total = get_singleton_append_subpath(cheapest_total);
1851 
1852  startup_subpaths = lcons(cheapest_startup, startup_subpaths);
1853  total_subpaths = lcons(cheapest_total, total_subpaths);
1854 
1855  if (cheapest_fractional)
1856  {
1857  cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1858  fractional_subpaths = lcons(cheapest_fractional, fractional_subpaths);
1859  }
1860  }
1861  else
1862  {
1863  /*
1864  * Otherwise, rely on accumulate_append_subpath to collect the
1865  * child paths for the MergeAppend.
1866  */
1867  accumulate_append_subpath(cheapest_startup,
1868  &startup_subpaths, NULL);
1869  accumulate_append_subpath(cheapest_total,
1870  &total_subpaths, NULL);
1871 
1872  if (cheapest_fractional)
1873  accumulate_append_subpath(cheapest_fractional,
1874  &fractional_subpaths, NULL);
1875  }
1876  }
1877 
1878  /* ... and build the Append or MergeAppend paths */
1879  if (match_partition_order || match_partition_order_desc)
1880  {
1881  /* We only need Append */
1882  add_path(rel, (Path *) create_append_path(root,
1883  rel,
1884  startup_subpaths,
1885  NIL,
1886  pathkeys,
1887  NULL,
1888  0,
1889  false,
1890  -1));
1891  if (startup_neq_total)
1892  add_path(rel, (Path *) create_append_path(root,
1893  rel,
1894  total_subpaths,
1895  NIL,
1896  pathkeys,
1897  NULL,
1898  0,
1899  false,
1900  -1));
1901 
1902  if (fractional_subpaths)
1903  add_path(rel, (Path *) create_append_path(root,
1904  rel,
1905  fractional_subpaths,
1906  NIL,
1907  pathkeys,
1908  NULL,
1909  0,
1910  false,
1911  -1));
1912  }
1913  else
1914  {
1915  /* We need MergeAppend */
1916  add_path(rel, (Path *) create_merge_append_path(root,
1917  rel,
1918  startup_subpaths,
1919  pathkeys,
1920  NULL));
1921  if (startup_neq_total)
1922  add_path(rel, (Path *) create_merge_append_path(root,
1923  rel,
1924  total_subpaths,
1925  pathkeys,
1926  NULL));
1927 
1928  if (fractional_subpaths)
1929  add_path(rel, (Path *) create_merge_append_path(root,
1930  rel,
1931  fractional_subpaths,
1932  pathkeys,
1933  NULL));
1934  }
1935  }
1936 }
1937 
1938 /*
1939  * get_cheapest_parameterized_child_path
1940  * Get cheapest path for this relation that has exactly the requested
1941  * parameterization.
1942  *
1943  * Returns NULL if unable to create such a path.
1944  */
1945 static Path *
1947  Relids required_outer)
1948 {
1949  Path *cheapest;
1950  ListCell *lc;
1951 
1952  /*
1953  * Look up the cheapest existing path with no more than the needed
1954  * parameterization. If it has exactly the needed parameterization, we're
1955  * done.
1956  */
1957  cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
1958  NIL,
1959  required_outer,
1960  TOTAL_COST,
1961  false);
1962  Assert(cheapest != NULL);
1963  if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
1964  return cheapest;
1965 
1966  /*
1967  * Otherwise, we can "reparameterize" an existing path to match the given
1968  * parameterization, which effectively means pushing down additional
1969  * joinquals to be checked within the path's scan. However, some existing
1970  * paths might check the available joinquals already while others don't;
1971  * therefore, it's not clear which existing path will be cheapest after
1972  * reparameterization. We have to go through them all and find out.
1973  */
1974  cheapest = NULL;
1975  foreach(lc, rel->pathlist)
1976  {
1977  Path *path = (Path *) lfirst(lc);
1978 
1979  /* Can't use it if it needs more than requested parameterization */
1980  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
1981  continue;
1982 
1983  /*
1984  * Reparameterization can only increase the path's cost, so if it's
1985  * already more expensive than the current cheapest, forget it.
1986  */
1987  if (cheapest != NULL &&
1988  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
1989  continue;
1990 
1991  /* Reparameterize if needed, then recheck cost */
1992  if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
1993  {
1994  path = reparameterize_path(root, path, required_outer, 1.0);
1995  if (path == NULL)
1996  continue; /* failed to reparameterize this one */
1997  Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
1998 
1999  if (cheapest != NULL &&
2000  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2001  continue;
2002  }
2003 
2004  /* We have a new best path */
2005  cheapest = path;
2006  }
2007 
2008  /* Return the best path, or NULL if we found no suitable candidate */
2009  return cheapest;
2010 }
2011 
2012 /*
2013  * accumulate_append_subpath
2014  * Add a subpath to the list being built for an Append or MergeAppend.
2015  *
2016  * It's possible that the child is itself an Append or MergeAppend path, in
2017  * which case we can "cut out the middleman" and just add its child paths to
2018  * our own list. (We don't try to do this earlier because we need to apply
2019  * both levels of transformation to the quals.)
2020  *
2021  * Note that if we omit a child MergeAppend in this way, we are effectively
2022  * omitting a sort step, which seems fine: if the parent is to be an Append,
2023  * its result would be unsorted anyway, while if the parent is to be a
2024  * MergeAppend, there's no point in a separate sort on a child.
2025  *
2026  * Normally, either path is a partial path and subpaths is a list of partial
2027  * paths, or else path is a non-partial plan and subpaths is a list of those.
2028  * However, if path is a parallel-aware Append, then we add its partial path
2029  * children to subpaths and the rest to special_subpaths. If the latter is
2030  * NULL, we don't flatten the path at all (unless it contains only partial
2031  * paths).
2032  */
2033 static void
2034 accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
2035 {
2036  if (IsA(path, AppendPath))
2037  {
2038  AppendPath *apath = (AppendPath *) path;
2039 
2040  if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2041  {
2042  *subpaths = list_concat(*subpaths, apath->subpaths);
2043  return;
2044  }
2045  else if (special_subpaths != NULL)
2046  {
2047  List *new_special_subpaths;
2048 
2049  /* Split Parallel Append into partial and non-partial subpaths */
2050  *subpaths = list_concat(*subpaths,
2051  list_copy_tail(apath->subpaths,
2052  apath->first_partial_path));
2053  new_special_subpaths =
2055  apath->first_partial_path);
2056  *special_subpaths = list_concat(*special_subpaths,
2057  new_special_subpaths);
2058  return;
2059  }
2060  }
2061  else if (IsA(path, MergeAppendPath))
2062  {
2063  MergeAppendPath *mpath = (MergeAppendPath *) path;
2064 
2065  *subpaths = list_concat(*subpaths, mpath->subpaths);
2066  return;
2067  }
2068 
2069  *subpaths = lappend(*subpaths, path);
2070 }
2071 
2072 /*
2073  * get_singleton_append_subpath
2074  * Returns the single subpath of an Append/MergeAppend, or just
2075  * return 'path' if it's not a single sub-path Append/MergeAppend.
2076  *
2077  * Note: 'path' must not be a parallel-aware path.
2078  */
2079 static Path *
2081 {
2082  Assert(!path->parallel_aware);
2083 
2084  if (IsA(path, AppendPath))
2085  {
2086  AppendPath *apath = (AppendPath *) path;
2087 
2088  if (list_length(apath->subpaths) == 1)
2089  return (Path *) linitial(apath->subpaths);
2090  }
2091  else if (IsA(path, MergeAppendPath))
2092  {
2093  MergeAppendPath *mpath = (MergeAppendPath *) path;
2094 
2095  if (list_length(mpath->subpaths) == 1)
2096  return (Path *) linitial(mpath->subpaths);
2097  }
2098 
2099  return path;
2100 }
2101 
2102 /*
2103  * set_dummy_rel_pathlist
2104  * Build a dummy path for a relation that's been excluded by constraints
2105  *
2106  * Rather than inventing a special "dummy" path type, we represent this as an
2107  * AppendPath with no members (see also IS_DUMMY_APPEND/IS_DUMMY_REL macros).
2108  *
2109  * (See also mark_dummy_rel, which does basically the same thing, but is
2110  * typically used to change a rel into dummy state after we already made
2111  * paths for it.)
2112  */
2113 static void
2115 {
2116  /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2117  rel->rows = 0;
2118  rel->reltarget->width = 0;
2119 
2120  /* Discard any pre-existing paths; no further need for them */
2121  rel->pathlist = NIL;
2122  rel->partial_pathlist = NIL;
2123 
2124  /* Set up the dummy path */
2125  add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2126  NIL, rel->lateral_relids,
2127  0, false, -1));
2128 
2129  /*
2130  * We set the cheapest-path fields immediately, just in case they were
2131  * pointing at some discarded path. This is redundant when we're called
2132  * from set_rel_size(), but not when called from elsewhere, and doing it
2133  * twice is harmless anyway.
2134  */
2135  set_cheapest(rel);
2136 }
2137 
2138 /* quick-and-dirty test to see if any joining is needed */
2139 static bool
2141 {
2142  int num_base_rels = 0;
2143  Index rti;
2144 
2145  for (rti = 1; rti < root->simple_rel_array_size; rti++)
2146  {
2147  RelOptInfo *brel = root->simple_rel_array[rti];
2148 
2149  if (brel == NULL)
2150  continue;
2151 
2152  /* ignore RTEs that are "other rels" */
2153  if (brel->reloptkind == RELOPT_BASEREL)
2154  if (++num_base_rels > 1)
2155  return true;
2156  }
2157  return false;
2158 }
2159 
2160 /*
2161  * set_subquery_pathlist
2162  * Generate SubqueryScan access paths for a subquery RTE
2163  *
2164  * We don't currently support generating parameterized paths for subqueries
2165  * by pushing join clauses down into them; it seems too expensive to re-plan
2166  * the subquery multiple times to consider different alternatives.
2167  * (XXX that could stand to be reconsidered, now that we use Paths.)
2168  * So the paths made here will be parameterized if the subquery contains
2169  * LATERAL references, otherwise not. As long as that's true, there's no need
2170  * for a separate set_subquery_size phase: just make the paths right away.
2171  */
2172 static void
2174  Index rti, RangeTblEntry *rte)
2175 {
2176  Query *parse = root->parse;
2177  Query *subquery = rte->subquery;
2178  Relids required_outer;
2179  pushdown_safety_info safetyInfo;
2180  double tuple_fraction;
2181  RelOptInfo *sub_final_rel;
2182  ListCell *lc;
2183 
2184  /*
2185  * Must copy the Query so that planning doesn't mess up the RTE contents
2186  * (really really need to fix the planner to not scribble on its input,
2187  * someday ... but see remove_unused_subquery_outputs to start with).
2188  */
2189  subquery = copyObject(subquery);
2190 
2191  /*
2192  * If it's a LATERAL subquery, it might contain some Vars of the current
2193  * query level, requiring it to be treated as parameterized, even though
2194  * we don't support pushing down join quals into subqueries.
2195  */
2196  required_outer = rel->lateral_relids;
2197 
2198  /*
2199  * Zero out result area for subquery_is_pushdown_safe, so that it can set
2200  * flags as needed while recursing. In particular, we need a workspace
2201  * for keeping track of unsafe-to-reference columns. unsafeColumns[i]
2202  * will be set true if we find that output column i of the subquery is
2203  * unsafe to use in a pushed-down qual.
2204  */
2205  memset(&safetyInfo, 0, sizeof(safetyInfo));
2206  safetyInfo.unsafeColumns = (bool *)
2207  palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
2208 
2209  /*
2210  * If the subquery has the "security_barrier" flag, it means the subquery
2211  * originated from a view that must enforce row-level security. Then we
2212  * must not push down quals that contain leaky functions. (Ideally this
2213  * would be checked inside subquery_is_pushdown_safe, but since we don't
2214  * currently pass the RTE to that function, we must do it here.)
2215  */
2216  safetyInfo.unsafeLeaky = rte->security_barrier;
2217 
2218  /*
2219  * If there are any restriction clauses that have been attached to the
2220  * subquery relation, consider pushing them down to become WHERE or HAVING
2221  * quals of the subquery itself. This transformation is useful because it
2222  * may allow us to generate a better plan for the subquery than evaluating
2223  * all the subquery output rows and then filtering them.
2224  *
2225  * There are several cases where we cannot push down clauses. Restrictions
2226  * involving the subquery are checked by subquery_is_pushdown_safe().
2227  * Restrictions on individual clauses are checked by
2228  * qual_is_pushdown_safe(). Also, we don't want to push down
2229  * pseudoconstant clauses; better to have the gating node above the
2230  * subquery.
2231  *
2232  * Non-pushed-down clauses will get evaluated as qpquals of the
2233  * SubqueryScan node.
2234  *
2235  * XXX Are there any cases where we want to make a policy decision not to
2236  * push down a pushable qual, because it'd result in a worse plan?
2237  */
2238  if (rel->baserestrictinfo != NIL &&
2239  subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2240  {
2241  /* OK to consider pushing down individual quals */
2242  List *upperrestrictlist = NIL;
2243  ListCell *l;
2244 
2245  foreach(l, rel->baserestrictinfo)
2246  {
2247  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2248 
2249  if (!rinfo->pseudoconstant &&
2250  qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2251  {
2252  Node *clause = (Node *) rinfo->clause;
2253 
2254  /* Push it down */
2255  subquery_push_qual(subquery, rte, rti, clause);
2256  }
2257  else
2258  {
2259  /* Keep it in the upper query */
2260  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2261  }
2262  }
2263  rel->baserestrictinfo = upperrestrictlist;
2264  /* We don't bother recomputing baserestrict_min_security */
2265  }
2266 
2267  pfree(safetyInfo.unsafeColumns);
2268 
2269  /*
2270  * The upper query might not use all the subquery's output columns; if
2271  * not, we can simplify.
2272  */
2273  remove_unused_subquery_outputs(subquery, rel);
2274 
2275  /*
2276  * We can safely pass the outer tuple_fraction down to the subquery if the
2277  * outer level has no joining, aggregation, or sorting to do. Otherwise
2278  * we'd better tell the subquery to plan for full retrieval. (XXX This
2279  * could probably be made more intelligent ...)
2280  */
2281  if (parse->hasAggs ||
2282  parse->groupClause ||
2283  parse->groupingSets ||
2284  parse->havingQual ||
2285  parse->distinctClause ||
2286  parse->sortClause ||
2287  has_multiple_baserels(root))
2288  tuple_fraction = 0.0; /* default case */
2289  else
2290  tuple_fraction = root->tuple_fraction;
2291 
2292  /* plan_params should not be in use in current query level */
2293  Assert(root->plan_params == NIL);
2294 
2295  /* Generate a subroot and Paths for the subquery */
2296  rel->subroot = subquery_planner(root->glob, subquery,
2297  root,
2298  false, tuple_fraction);
2299 
2300  /* Isolate the params needed by this specific subplan */
2301  rel->subplan_params = root->plan_params;
2302  root->plan_params = NIL;
2303 
2304  /*
2305  * It's possible that constraint exclusion proved the subquery empty. If
2306  * so, it's desirable to produce an unadorned dummy path so that we will
2307  * recognize appropriate optimizations at this query level.
2308  */
2309  sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2310 
2311  if (IS_DUMMY_REL(sub_final_rel))
2312  {
2314  return;
2315  }
2316 
2317  /*
2318  * Mark rel with estimated output rows, width, etc. Note that we have to
2319  * do this before generating outer-query paths, else cost_subqueryscan is
2320  * not happy.
2321  */
2322  set_subquery_size_estimates(root, rel);
2323 
2324  /*
2325  * For each Path that subquery_planner produced, make a SubqueryScanPath
2326  * in the outer query.
2327  */
2328  foreach(lc, sub_final_rel->pathlist)
2329  {
2330  Path *subpath = (Path *) lfirst(lc);
2331  List *pathkeys;
2332 
2333  /* Convert subpath's pathkeys to outer representation */
2334  pathkeys = convert_subquery_pathkeys(root,
2335  rel,
2336  subpath->pathkeys,
2337  make_tlist_from_pathtarget(subpath->pathtarget));
2338 
2339  /* Generate outer path using this subpath */
2340  add_path(rel, (Path *)
2341  create_subqueryscan_path(root, rel, subpath,
2342  pathkeys, required_outer));
2343  }
2344 
2345  /* If outer rel allows parallelism, do same for partial paths. */
2346  if (rel->consider_parallel && bms_is_empty(required_outer))
2347  {
2348  /* If consider_parallel is false, there should be no partial paths. */
2349  Assert(sub_final_rel->consider_parallel ||
2350  sub_final_rel->partial_pathlist == NIL);
2351 
2352  /* Same for partial paths. */
2353  foreach(lc, sub_final_rel->partial_pathlist)
2354  {
2355  Path *subpath = (Path *) lfirst(lc);
2356  List *pathkeys;
2357 
2358  /* Convert subpath's pathkeys to outer representation */
2359  pathkeys = convert_subquery_pathkeys(root,
2360  rel,
2361  subpath->pathkeys,
2362  make_tlist_from_pathtarget(subpath->pathtarget));
2363 
2364  /* Generate outer path using this subpath */
2365  add_partial_path(rel, (Path *)
2366  create_subqueryscan_path(root, rel, subpath,
2367  pathkeys,
2368  required_outer));
2369  }
2370  }
2371 }
2372 
2373 /*
2374  * set_function_pathlist
2375  * Build the (single) access path for a function RTE
2376  */
2377 static void
2379 {
2380  Relids required_outer;
2381  List *pathkeys = NIL;
2382 
2383  /*
2384  * We don't support pushing join clauses into the quals of a function
2385  * scan, but it could still have required parameterization due to LATERAL
2386  * refs in the function expression.
2387  */
2388  required_outer = rel->lateral_relids;
2389 
2390  /*
2391  * The result is considered unordered unless ORDINALITY was used, in which
2392  * case it is ordered by the ordinal column (the last one). See if we
2393  * care, by checking for uses of that Var in equivalence classes.
2394  */
2395  if (rte->funcordinality)
2396  {
2397  AttrNumber ordattno = rel->max_attr;
2398  Var *var = NULL;
2399  ListCell *lc;
2400 
2401  /*
2402  * Is there a Var for it in rel's targetlist? If not, the query did
2403  * not reference the ordinality column, or at least not in any way
2404  * that would be interesting for sorting.
2405  */
2406  foreach(lc, rel->reltarget->exprs)
2407  {
2408  Var *node = (Var *) lfirst(lc);
2409 
2410  /* checking varno/varlevelsup is just paranoia */
2411  if (IsA(node, Var) &&
2412  node->varattno == ordattno &&
2413  node->varno == rel->relid &&
2414  node->varlevelsup == 0)
2415  {
2416  var = node;
2417  break;
2418  }
2419  }
2420 
2421  /*
2422  * Try to build pathkeys for this Var with int8 sorting. We tell
2423  * build_expression_pathkey not to build any new equivalence class; if
2424  * the Var isn't already mentioned in some EC, it means that nothing
2425  * cares about the ordering.
2426  */
2427  if (var)
2428  pathkeys = build_expression_pathkey(root,
2429  (Expr *) var,
2430  NULL, /* below outer joins */
2431  Int8LessOperator,
2432  rel->relids,
2433  false);
2434  }
2435 
2436  /* Generate appropriate path */
2437  add_path(rel, create_functionscan_path(root, rel,
2438  pathkeys, required_outer));
2439 }
2440 
2441 /*
2442  * set_values_pathlist
2443  * Build the (single) access path for a VALUES RTE
2444  */
2445 static void
2447 {
2448  Relids required_outer;
2449 
2450  /*
2451  * We don't support pushing join clauses into the quals of a values scan,
2452  * but it could still have required parameterization due to LATERAL refs
2453  * in the values expressions.
2454  */
2455  required_outer = rel->lateral_relids;
2456 
2457  /* Generate appropriate path */
2458  add_path(rel, create_valuesscan_path(root, rel, required_outer));
2459 }
2460 
2461 /*
2462  * set_tablefunc_pathlist
2463  * Build the (single) access path for a table func RTE
2464  */
2465 static void
2467 {
2468  Relids required_outer;
2469 
2470  /*
2471  * We don't support pushing join clauses into the quals of a tablefunc
2472  * scan, but it could still have required parameterization due to LATERAL
2473  * refs in the function expression.
2474  */
2475  required_outer = rel->lateral_relids;
2476 
2477  /* Generate appropriate path */
2478  add_path(rel, create_tablefuncscan_path(root, rel,
2479  required_outer));
2480 }
2481 
2482 /*
2483  * set_cte_pathlist
2484  * Build the (single) access path for a non-self-reference CTE RTE
2485  *
2486  * There's no need for a separate set_cte_size phase, since we don't
2487  * support join-qual-parameterized paths for CTEs.
2488  */
2489 static void
2491 {
2492  Plan *cteplan;
2493  PlannerInfo *cteroot;
2494  Index levelsup;
2495  int ndx;
2496  ListCell *lc;
2497  int plan_id;
2498  Relids required_outer;
2499 
2500  /*
2501  * Find the referenced CTE, and locate the plan previously made for it.
2502  */
2503  levelsup = rte->ctelevelsup;
2504  cteroot = root;
2505  while (levelsup-- > 0)
2506  {
2507  cteroot = cteroot->parent_root;
2508  if (!cteroot) /* shouldn't happen */
2509  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2510  }
2511 
2512  /*
2513  * Note: cte_plan_ids can be shorter than cteList, if we are still working
2514  * on planning the CTEs (ie, this is a side-reference from another CTE).
2515  * So we mustn't use forboth here.
2516  */
2517  ndx = 0;
2518  foreach(lc, cteroot->parse->cteList)
2519  {
2520  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2521 
2522  if (strcmp(cte->ctename, rte->ctename) == 0)
2523  break;
2524  ndx++;
2525  }
2526  if (lc == NULL) /* shouldn't happen */
2527  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2528  if (ndx >= list_length(cteroot->cte_plan_ids))
2529  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2530  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2531  Assert(plan_id > 0);
2532  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2533 
2534  /* Mark rel with estimated output rows, width, etc */
2535  set_cte_size_estimates(root, rel, cteplan->plan_rows);
2536 
2537  /*
2538  * We don't support pushing join clauses into the quals of a CTE scan, but
2539  * it could still have required parameterization due to LATERAL refs in
2540  * its tlist.
2541  */
2542  required_outer = rel->lateral_relids;
2543 
2544  /* Generate appropriate path */
2545  add_path(rel, create_ctescan_path(root, rel, required_outer));
2546 }
2547 
2548 /*
2549  * set_namedtuplestore_pathlist
2550  * Build the (single) access path for a named tuplestore RTE
2551  *
2552  * There's no need for a separate set_namedtuplestore_size phase, since we
2553  * don't support join-qual-parameterized paths for tuplestores.
2554  */
2555 static void
2557  RangeTblEntry *rte)
2558 {
2559  Relids required_outer;
2560 
2561  /* Mark rel with estimated output rows, width, etc */
2563 
2564  /*
2565  * We don't support pushing join clauses into the quals of a tuplestore
2566  * scan, but it could still have required parameterization due to LATERAL
2567  * refs in its tlist.
2568  */
2569  required_outer = rel->lateral_relids;
2570 
2571  /* Generate appropriate path */
2572  add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2573 
2574  /* Select cheapest path (pretty easy in this case...) */
2575  set_cheapest(rel);
2576 }
2577 
2578 /*
2579  * set_result_pathlist
2580  * Build the (single) access path for an RTE_RESULT RTE
2581  *
2582  * There's no need for a separate set_result_size phase, since we
2583  * don't support join-qual-parameterized paths for these RTEs.
2584  */
2585 static void
2587  RangeTblEntry *rte)
2588 {
2589  Relids required_outer;
2590 
2591  /* Mark rel with estimated output rows, width, etc */
2592  set_result_size_estimates(root, rel);
2593 
2594  /*
2595  * We don't support pushing join clauses into the quals of a Result scan,
2596  * but it could still have required parameterization due to LATERAL refs
2597  * in its tlist.
2598  */
2599  required_outer = rel->lateral_relids;
2600 
2601  /* Generate appropriate path */
2602  add_path(rel, create_resultscan_path(root, rel, required_outer));
2603 
2604  /* Select cheapest path (pretty easy in this case...) */
2605  set_cheapest(rel);
2606 }
2607 
2608 /*
2609  * set_worktable_pathlist
2610  * Build the (single) access path for a self-reference CTE RTE
2611  *
2612  * There's no need for a separate set_worktable_size phase, since we don't
2613  * support join-qual-parameterized paths for CTEs.
2614  */
2615 static void
2617 {
2618  Path *ctepath;
2619  PlannerInfo *cteroot;
2620  Index levelsup;
2621  Relids required_outer;
2622 
2623  /*
2624  * We need to find the non-recursive term's path, which is in the plan
2625  * level that's processing the recursive UNION, which is one level *below*
2626  * where the CTE comes from.
2627  */
2628  levelsup = rte->ctelevelsup;
2629  if (levelsup == 0) /* shouldn't happen */
2630  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2631  levelsup--;
2632  cteroot = root;
2633  while (levelsup-- > 0)
2634  {
2635  cteroot = cteroot->parent_root;
2636  if (!cteroot) /* shouldn't happen */
2637  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2638  }
2639  ctepath = cteroot->non_recursive_path;
2640  if (!ctepath) /* shouldn't happen */
2641  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
2642 
2643  /* Mark rel with estimated output rows, width, etc */
2644  set_cte_size_estimates(root, rel, ctepath->rows);
2645 
2646  /*
2647  * We don't support pushing join clauses into the quals of a worktable
2648  * scan, but it could still have required parameterization due to LATERAL
2649  * refs in its tlist. (I'm not sure this is actually possible given the
2650  * restrictions on recursive references, but it's easy enough to support.)
2651  */
2652  required_outer = rel->lateral_relids;
2653 
2654  /* Generate appropriate path */
2655  add_path(rel, create_worktablescan_path(root, rel, required_outer));
2656 }
2657 
2658 /*
2659  * generate_gather_paths
2660  * Generate parallel access paths for a relation by pushing a Gather or
2661  * Gather Merge on top of a partial path.
2662  *
2663  * This must not be called until after we're done creating all partial paths
2664  * for the specified relation. (Otherwise, add_partial_path might delete a
2665  * path that some GatherPath or GatherMergePath has a reference to.)
2666  *
2667  * If we're generating paths for a scan or join relation, override_rows will
2668  * be false, and we'll just use the relation's size estimate. When we're
2669  * being called for a partially-grouped path, though, we need to override
2670  * the rowcount estimate. (It's not clear that the particular value we're
2671  * using here is actually best, but the underlying rel has no estimate so
2672  * we must do something.)
2673  */
2674 void
2675 generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
2676 {
2677  Path *cheapest_partial_path;
2678  Path *simple_gather_path;
2679  ListCell *lc;
2680  double rows;
2681  double *rowsp = NULL;
2682 
2683  /* If there are no partial paths, there's nothing to do here. */
2684  if (rel->partial_pathlist == NIL)
2685  return;
2686 
2687  /* Should we override the rel's rowcount estimate? */
2688  if (override_rows)
2689  rowsp = &rows;
2690 
2691  /*
2692  * The output of Gather is always unsorted, so there's only one partial
2693  * path of interest: the cheapest one. That will be the one at the front
2694  * of partial_pathlist because of the way add_partial_path works.
2695  */
2696  cheapest_partial_path = linitial(rel->partial_pathlist);
2697  rows =
2698  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
2699  simple_gather_path = (Path *)
2700  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
2701  NULL, rowsp);
2702  add_path(rel, simple_gather_path);
2703 
2704  /*
2705  * For each useful ordering, we can consider an order-preserving Gather
2706  * Merge.
2707  */
2708  foreach(lc, rel->partial_pathlist)
2709  {
2710  Path *subpath = (Path *) lfirst(lc);
2711  GatherMergePath *path;
2712 
2713  if (subpath->pathkeys == NIL)
2714  continue;
2715 
2716  rows = subpath->rows * subpath->parallel_workers;
2717  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
2718  subpath->pathkeys, NULL, rowsp);
2719  add_path(rel, &path->path);
2720  }
2721 }
2722 
2723 /*
2724  * get_useful_pathkeys_for_relation
2725  * Determine which orderings of a relation might be useful.
2726  *
2727  * Getting data in sorted order can be useful either because the requested
2728  * order matches the final output ordering for the overall query we're
2729  * planning, or because it enables an efficient merge join. Here, we try
2730  * to figure out which pathkeys to consider.
2731  *
2732  * This allows us to do incremental sort on top of an index scan under a gather
2733  * merge node, i.e. parallelized.
2734  *
2735  * If the require_parallel_safe is true, we also require the expressions to
2736  * be parallel safe (which allows pushing the sort below Gather Merge).
2737  *
2738  * XXX At the moment this can only ever return a list with a single element,
2739  * because it looks at query_pathkeys only. So we might return the pathkeys
2740  * directly, but it seems plausible we'll want to consider other orderings
2741  * in the future. For example, we might want to consider pathkeys useful for
2742  * merge joins.
2743  */
2744 static List *
2746  bool require_parallel_safe)
2747 {
2748  List *useful_pathkeys_list = NIL;
2749 
2750  /*
2751  * Considering query_pathkeys is always worth it, because it might allow
2752  * us to avoid a total sort when we have a partially presorted path
2753  * available or to push the total sort into the parallel portion of the
2754  * query.
2755  */
2756  if (root->query_pathkeys)
2757  {
2758  ListCell *lc;
2759  int npathkeys = 0; /* useful pathkeys */
2760 
2761  foreach(lc, root->query_pathkeys)
2762  {
2763  PathKey *pathkey = (PathKey *) lfirst(lc);
2764  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
2765 
2766  /*
2767  * We can only build a sort for pathkeys that contain a
2768  * safe-to-compute-early EC member computable from the current
2769  * relation's reltarget, so ignore the remainder of the list as
2770  * soon as we find a pathkey without such a member.
2771  *
2772  * It's still worthwhile to return any prefix of the pathkeys list
2773  * that meets this requirement, as we may be able to do an
2774  * incremental sort.
2775  *
2776  * If requested, ensure the sort expression is parallel-safe too.
2777  */
2778  if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
2779  require_parallel_safe))
2780  break;
2781 
2782  npathkeys++;
2783  }
2784 
2785  /*
2786  * The whole query_pathkeys list matches, so append it directly, to
2787  * allow comparing pathkeys easily by comparing list pointer. If we
2788  * have to truncate the pathkeys, we gotta do a copy though.
2789  */
2790  if (npathkeys == list_length(root->query_pathkeys))
2791  useful_pathkeys_list = lappend(useful_pathkeys_list,
2792  root->query_pathkeys);
2793  else if (npathkeys > 0)
2794  useful_pathkeys_list = lappend(useful_pathkeys_list,
2796  npathkeys));
2797  }
2798 
2799  return useful_pathkeys_list;
2800 }
2801 
2802 /*
2803  * generate_useful_gather_paths
2804  * Generate parallel access paths for a relation by pushing a Gather or
2805  * Gather Merge on top of a partial path.
2806  *
2807  * Unlike plain generate_gather_paths, this looks both at pathkeys of input
2808  * paths (aiming to preserve the ordering), but also considers ordering that
2809  * might be useful for nodes above the gather merge node, and tries to add
2810  * a sort (regular or incremental) to provide that.
2811  */
2812 void
2813 generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
2814 {
2815  ListCell *lc;
2816  double rows;
2817  double *rowsp = NULL;
2818  List *useful_pathkeys_list = NIL;
2819  Path *cheapest_partial_path = NULL;
2820 
2821  /* If there are no partial paths, there's nothing to do here. */
2822  if (rel->partial_pathlist == NIL)
2823  return;
2824 
2825  /* Should we override the rel's rowcount estimate? */
2826  if (override_rows)
2827  rowsp = &rows;
2828 
2829  /* generate the regular gather (merge) paths */
2830  generate_gather_paths(root, rel, override_rows);
2831 
2832  /* consider incremental sort for interesting orderings */
2833  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
2834 
2835  /* used for explicit (full) sort paths */
2836  cheapest_partial_path = linitial(rel->partial_pathlist);
2837 
2838  /*
2839  * Consider sorted paths for each interesting ordering. We generate both
2840  * incremental and full sort.
2841  */
2842  foreach(lc, useful_pathkeys_list)
2843  {
2844  List *useful_pathkeys = lfirst(lc);
2845  ListCell *lc2;
2846  bool is_sorted;
2847  int presorted_keys;
2848 
2849  foreach(lc2, rel->partial_pathlist)
2850  {
2851  Path *subpath = (Path *) lfirst(lc2);
2852  GatherMergePath *path;
2853 
2854  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
2855  subpath->pathkeys,
2856  &presorted_keys);
2857 
2858  /*
2859  * We don't need to consider the case where a subpath is already
2860  * fully sorted because generate_gather_paths already creates a
2861  * gather merge path for every subpath that has pathkeys present.
2862  *
2863  * But since the subpath is already sorted, we know we don't need
2864  * to consider adding a sort (full or incremental) on top of it,
2865  * so we can continue here.
2866  */
2867  if (is_sorted)
2868  continue;
2869 
2870  /*
2871  * Consider regular sort for the cheapest partial path (for each
2872  * useful pathkeys). We know the path is not sorted, because we'd
2873  * not get here otherwise.
2874  *
2875  * This is not redundant with the gather paths created in
2876  * generate_gather_paths, because that doesn't generate ordered
2877  * output. Here we add an explicit sort to match the useful
2878  * ordering.
2879  */
2880  if (cheapest_partial_path == subpath)
2881  {
2882  Path *tmp;
2883 
2884  tmp = (Path *) create_sort_path(root,
2885  rel,
2886  subpath,
2887  useful_pathkeys,
2888  -1.0);
2889 
2890  rows = tmp->rows * tmp->parallel_workers;
2891 
2892  path = create_gather_merge_path(root, rel,
2893  tmp,
2894  rel->reltarget,
2895  tmp->pathkeys,
2896  NULL,
2897  rowsp);
2898 
2899  add_path(rel, &path->path);
2900 
2901  /* Fall through */
2902  }
2903 
2904  /*
2905  * Consider incremental sort, but only when the subpath is already
2906  * partially sorted on a pathkey prefix.
2907  */
2908  if (enable_incremental_sort && presorted_keys > 0)
2909  {
2910  Path *tmp;
2911 
2912  /*
2913  * We should have already excluded pathkeys of length 1
2914  * because then presorted_keys > 0 would imply is_sorted was
2915  * true.
2916  */
2917  Assert(list_length(useful_pathkeys) != 1);
2918 
2919  tmp = (Path *) create_incremental_sort_path(root,
2920  rel,
2921  subpath,
2922  useful_pathkeys,
2923  presorted_keys,
2924  -1);
2925 
2926  path = create_gather_merge_path(root, rel,
2927  tmp,
2928  rel->reltarget,
2929  tmp->pathkeys,
2930  NULL,
2931  rowsp);
2932 
2933  add_path(rel, &path->path);
2934  }
2935  }
2936  }
2937 }
2938 
2939 /*
2940  * make_rel_from_joinlist
2941  * Build access paths using a "joinlist" to guide the join path search.
2942  *
2943  * See comments for deconstruct_jointree() for definition of the joinlist
2944  * data structure.
2945  */
2946 static RelOptInfo *
2948 {
2949  int levels_needed;
2950  List *initial_rels;
2951  ListCell *jl;
2952 
2953  /*
2954  * Count the number of child joinlist nodes. This is the depth of the
2955  * dynamic-programming algorithm we must employ to consider all ways of
2956  * joining the child nodes.
2957  */
2958  levels_needed = list_length(joinlist);
2959 
2960  if (levels_needed <= 0)
2961  return NULL; /* nothing to do? */
2962 
2963  /*
2964  * Construct a list of rels corresponding to the child joinlist nodes.
2965  * This may contain both base rels and rels constructed according to
2966  * sub-joinlists.
2967  */
2968  initial_rels = NIL;
2969  foreach(jl, joinlist)
2970  {
2971  Node *jlnode = (Node *) lfirst(jl);
2972  RelOptInfo *thisrel;
2973 
2974  if (IsA(jlnode, RangeTblRef))
2975  {
2976  int varno = ((RangeTblRef *) jlnode)->rtindex;
2977 
2978  thisrel = find_base_rel(root, varno);
2979  }
2980  else if (IsA(jlnode, List))
2981  {
2982  /* Recurse to handle subproblem */
2983  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
2984  }
2985  else
2986  {
2987  elog(ERROR, "unrecognized joinlist node type: %d",
2988  (int) nodeTag(jlnode));
2989  thisrel = NULL; /* keep compiler quiet */
2990  }
2991 
2992  initial_rels = lappend(initial_rels, thisrel);
2993  }
2994 
2995  if (levels_needed == 1)
2996  {
2997  /*
2998  * Single joinlist node, so we're done.
2999  */
3000  return (RelOptInfo *) linitial(initial_rels);
3001  }
3002  else
3003  {
3004  /*
3005  * Consider the different orders in which we could join the rels,
3006  * using a plugin, GEQO, or the regular join search code.
3007  *
3008  * We put the initial_rels list into a PlannerInfo field because
3009  * has_legal_joinclause() needs to look at it (ugly :-().
3010  */
3011  root->initial_rels = initial_rels;
3012 
3013  if (join_search_hook)
3014  return (*join_search_hook) (root, levels_needed, initial_rels);
3015  else if (enable_geqo && levels_needed >= geqo_threshold)
3016  return geqo(root, levels_needed, initial_rels);
3017  else
3018  return standard_join_search(root, levels_needed, initial_rels);
3019  }
3020 }
3021 
3022 /*
3023  * standard_join_search
3024  * Find possible joinpaths for a query by successively finding ways
3025  * to join component relations into join relations.
3026  *
3027  * 'levels_needed' is the number of iterations needed, ie, the number of
3028  * independent jointree items in the query. This is > 1.
3029  *
3030  * 'initial_rels' is a list of RelOptInfo nodes for each independent
3031  * jointree item. These are the components to be joined together.
3032  * Note that levels_needed == list_length(initial_rels).
3033  *
3034  * Returns the final level of join relations, i.e., the relation that is
3035  * the result of joining all the original relations together.
3036  * At least one implementation path must be provided for this relation and
3037  * all required sub-relations.
3038  *
3039  * To support loadable plugins that modify planner behavior by changing the
3040  * join searching algorithm, we provide a hook variable that lets a plugin
3041  * replace or supplement this function. Any such hook must return the same
3042  * final join relation as the standard code would, but it might have a
3043  * different set of implementation paths attached, and only the sub-joinrels
3044  * needed for these paths need have been instantiated.
3045  *
3046  * Note to plugin authors: the functions invoked during standard_join_search()
3047  * modify root->join_rel_list and root->join_rel_hash. If you want to do more
3048  * than one join-order search, you'll probably need to save and restore the
3049  * original states of those data structures. See geqo_eval() for an example.
3050  */
3051 RelOptInfo *
3052 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
3053 {
3054  int lev;
3055  RelOptInfo *rel;
3056 
3057  /*
3058  * This function cannot be invoked recursively within any one planning
3059  * problem, so join_rel_level[] can't be in use already.
3060  */
3061  Assert(root->join_rel_level == NULL);
3062 
3063  /*
3064  * We employ a simple "dynamic programming" algorithm: we first find all
3065  * ways to build joins of two jointree items, then all ways to build joins
3066  * of three items (from two-item joins and single items), then four-item
3067  * joins, and so on until we have considered all ways to join all the
3068  * items into one rel.
3069  *
3070  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3071  * set root->join_rel_level[1] to represent all the single-jointree-item
3072  * relations.
3073  */
3074  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3075 
3076  root->join_rel_level[1] = initial_rels;
3077 
3078  for (lev = 2; lev <= levels_needed; lev++)
3079  {
3080  ListCell *lc;
3081 
3082  /*
3083  * Determine all possible pairs of relations to be joined at this
3084  * level, and build paths for making each one from every available
3085  * pair of lower-level relations.
3086  */
3087  join_search_one_level(root, lev);
3088 
3089  /*
3090  * Run generate_partitionwise_join_paths() and
3091  * generate_useful_gather_paths() for each just-processed joinrel. We
3092  * could not do this earlier because both regular and partial paths
3093  * can get added to a particular joinrel at multiple times within
3094  * join_search_one_level.
3095  *
3096  * After that, we're done creating paths for the joinrel, so run
3097  * set_cheapest().
3098  */
3099  foreach(lc, root->join_rel_level[lev])
3100  {
3101  rel = (RelOptInfo *) lfirst(lc);
3102 
3103  /* Create paths for partitionwise joins. */
3105 
3106  /*
3107  * Except for the topmost scan/join rel, consider gathering
3108  * partial paths. We'll do the same for the topmost scan/join rel
3109  * once we know the final targetlist (see grouping_planner).
3110  */
3111  if (lev < levels_needed)
3112  generate_useful_gather_paths(root, rel, false);
3113 
3114  /* Find and save the cheapest paths for this rel */
3115  set_cheapest(rel);
3116 
3117 #ifdef OPTIMIZER_DEBUG
3118  debug_print_rel(root, rel);
3119 #endif
3120  }
3121  }
3122 
3123  /*
3124  * We should have a single rel at the final level.
3125  */
3126  if (root->join_rel_level[levels_needed] == NIL)
3127  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3128  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3129 
3130  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3131 
3132  root->join_rel_level = NULL;
3133 
3134  return rel;
3135 }
3136 
3137 /*****************************************************************************
3138  * PUSHING QUALS DOWN INTO SUBQUERIES
3139  *****************************************************************************/
3140 
3141 /*
3142  * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
3143  *
3144  * subquery is the particular component query being checked. topquery
3145  * is the top component of a set-operations tree (the same Query if no
3146  * set-op is involved).
3147  *
3148  * Conditions checked here:
3149  *
3150  * 1. If the subquery has a LIMIT clause, we must not push down any quals,
3151  * since that could change the set of rows returned.
3152  *
3153  * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
3154  * quals into it, because that could change the results.
3155  *
3156  * 3. If the subquery uses DISTINCT, we cannot push volatile quals into it.
3157  * This is because upper-level quals should semantically be evaluated only
3158  * once per distinct row, not once per original row, and if the qual is
3159  * volatile then extra evaluations could change the results. (This issue
3160  * does not apply to other forms of aggregation such as GROUP BY, because
3161  * when those are present we push into HAVING not WHERE, so that the quals
3162  * are still applied after aggregation.)
3163  *
3164  * 4. If the subquery contains window functions, we cannot push volatile quals
3165  * into it. The issue here is a bit different from DISTINCT: a volatile qual
3166  * might succeed for some rows of a window partition and fail for others,
3167  * thereby changing the partition contents and thus the window functions'
3168  * results for rows that remain.
3169  *
3170  * 5. If the subquery contains any set-returning functions in its targetlist,
3171  * we cannot push volatile quals into it. That would push them below the SRFs
3172  * and thereby change the number of times they are evaluated. Also, a
3173  * volatile qual could succeed for some SRF output rows and fail for others,
3174  * a behavior that cannot occur if it's evaluated before SRF expansion.
3175  *
3176  * 6. If the subquery has nonempty grouping sets, we cannot push down any
3177  * quals. The concern here is that a qual referencing a "constant" grouping
3178  * column could get constant-folded, which would be improper because the value
3179  * is potentially nullable by grouping-set expansion. This restriction could
3180  * be removed if we had a parsetree representation that shows that such
3181  * grouping columns are not really constant. (There are other ideas that
3182  * could be used to relax this restriction, but that's the approach most
3183  * likely to get taken in the future. Note that there's not much to be gained
3184  * so long as subquery_planner can't move HAVING clauses to WHERE within such
3185  * a subquery.)
3186  *
3187  * In addition, we make several checks on the subquery's output columns to see
3188  * if it is safe to reference them in pushed-down quals. If output column k
3189  * is found to be unsafe to reference, we set safetyInfo->unsafeColumns[k]
3190  * to true, but we don't reject the subquery overall since column k might not
3191  * be referenced by some/all quals. The unsafeColumns[] array will be
3192  * consulted later by qual_is_pushdown_safe(). It's better to do it this way
3193  * than to make the checks directly in qual_is_pushdown_safe(), because when
3194  * the subquery involves set operations we have to check the output
3195  * expressions in each arm of the set op.
3196  *
3197  * Note: pushing quals into a DISTINCT subquery is theoretically dubious:
3198  * we're effectively assuming that the quals cannot distinguish values that
3199  * the DISTINCT's equality operator sees as equal, yet there are many
3200  * counterexamples to that assumption. However use of such a qual with a
3201  * DISTINCT subquery would be unsafe anyway, since there's no guarantee which
3202  * "equal" value will be chosen as the output value by the DISTINCT operation.
3203  * So we don't worry too much about that. Another objection is that if the
3204  * qual is expensive to evaluate, running it for each original row might cost
3205  * more than we save by eliminating rows before the DISTINCT step. But it
3206  * would be very hard to estimate that at this stage, and in practice pushdown
3207  * seldom seems to make things worse, so we ignore that problem too.
3208  *
3209  * Note: likewise, pushing quals into a subquery with window functions is a
3210  * bit dubious: the quals might remove some rows of a window partition while
3211  * leaving others, causing changes in the window functions' results for the
3212  * surviving rows. We insist that such a qual reference only partitioning
3213  * columns, but again that only protects us if the qual does not distinguish
3214  * values that the partitioning equality operator sees as equal. The risks
3215  * here are perhaps larger than for DISTINCT, since no de-duplication of rows
3216  * occurs and thus there is no theoretical problem with such a qual. But
3217  * we'll do this anyway because the potential performance benefits are very
3218  * large, and we've seen no field complaints about the longstanding comparable
3219  * behavior with DISTINCT.
3220  */
3221 static bool
3223  pushdown_safety_info *safetyInfo)
3224 {
3225  SetOperationStmt *topop;
3226 
3227  /* Check point 1 */
3228  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3229  return false;
3230 
3231  /* Check point 6 */
3232  if (subquery->groupClause && subquery->groupingSets)
3233  return false;
3234 
3235  /* Check points 3, 4, and 5 */
3236  if (subquery->distinctClause ||
3237  subquery->hasWindowFuncs ||
3238  subquery->hasTargetSRFs)
3239  safetyInfo->unsafeVolatile = true;
3240 
3241  /*
3242  * If we're at a leaf query, check for unsafe expressions in its target
3243  * list, and mark any unsafe ones in unsafeColumns[]. (Non-leaf nodes in
3244  * setop trees have only simple Vars in their tlists, so no need to check
3245  * them.)
3246  */
3247  if (subquery->setOperations == NULL)
3248  check_output_expressions(subquery, safetyInfo);
3249 
3250  /* Are we at top level, or looking at a setop component? */
3251  if (subquery == topquery)
3252  {
3253  /* Top level, so check any component queries */
3254  if (subquery->setOperations != NULL)
3255  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3256  safetyInfo))
3257  return false;
3258  }
3259  else
3260  {
3261  /* Setop component must not have more components (too weird) */
3262  if (subquery->setOperations != NULL)
3263  return false;
3264  /* Check whether setop component output types match top level */
3265  topop = castNode(SetOperationStmt, topquery->setOperations);
3266  Assert(topop);
3268  topop->colTypes,
3269  safetyInfo);
3270  }
3271  return true;
3272 }
3273 
3274 /*
3275  * Helper routine to recurse through setOperations tree
3276  */
3277 static bool
3279  pushdown_safety_info *safetyInfo)
3280 {
3281  if (IsA(setOp, RangeTblRef))
3282  {
3283  RangeTblRef *rtr = (RangeTblRef *) setOp;
3284  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3285  Query *subquery = rte->subquery;
3286 
3287  Assert(subquery != NULL);
3288  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3289  }
3290  else if (IsA(setOp, SetOperationStmt))
3291  {
3292  SetOperationStmt *op = (SetOperationStmt *) setOp;
3293 
3294  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3295  if (op->op == SETOP_EXCEPT)
3296  return false;
3297  /* Else recurse */
3298  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3299  return false;
3300  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3301  return false;
3302  }
3303  else
3304  {
3305  elog(ERROR, "unrecognized node type: %d",
3306  (int) nodeTag(setOp));
3307  }
3308  return true;
3309 }
3310 
3311 /*
3312  * check_output_expressions - check subquery's output expressions for safety
3313  *
3314  * There are several cases in which it's unsafe to push down an upper-level
3315  * qual if it references a particular output column of a subquery. We check
3316  * each output column of the subquery and set unsafeColumns[k] to true if
3317  * that column is unsafe for a pushed-down qual to reference. The conditions
3318  * checked here are:
3319  *
3320  * 1. We must not push down any quals that refer to subselect outputs that
3321  * return sets, else we'd introduce functions-returning-sets into the
3322  * subquery's WHERE/HAVING quals.
3323  *
3324  * 2. We must not push down any quals that refer to subselect outputs that
3325  * contain volatile functions, for fear of introducing strange results due
3326  * to multiple evaluation of a volatile function.
3327  *
3328  * 3. If the subquery uses DISTINCT ON, we must not push down any quals that
3329  * refer to non-DISTINCT output columns, because that could change the set
3330  * of rows returned. (This condition is vacuous for DISTINCT, because then
3331  * there are no non-DISTINCT output columns, so we needn't check. Note that
3332  * subquery_is_pushdown_safe already reported that we can't use volatile
3333  * quals if there's DISTINCT or DISTINCT ON.)
3334  *
3335  * 4. If the subquery has any window functions, we must not push down quals
3336  * that reference any output columns that are not listed in all the subquery's
3337  * window PARTITION BY clauses. We can push down quals that use only
3338  * partitioning columns because they should succeed or fail identically for
3339  * every row of any one window partition, and totally excluding some
3340  * partitions will not change a window function's results for remaining
3341  * partitions. (Again, this also requires nonvolatile quals, but
3342  * subquery_is_pushdown_safe handles that.)
3343  */
3344 static void
3346 {
3347  ListCell *lc;
3348 
3349  foreach(lc, subquery->targetList)
3350  {
3351  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3352 
3353  if (tle->resjunk)
3354  continue; /* ignore resjunk columns */
3355 
3356  /* We need not check further if output col is already known unsafe */
3357  if (safetyInfo->unsafeColumns[tle->resno])
3358  continue;
3359 
3360  /* Functions returning sets are unsafe (point 1) */
3361  if (subquery->hasTargetSRFs &&
3362  expression_returns_set((Node *) tle->expr))
3363  {
3364  safetyInfo->unsafeColumns[tle->resno] = true;
3365  continue;
3366  }
3367 
3368  /* Volatile functions are unsafe (point 2) */
3369  if (contain_volatile_functions((Node *) tle->expr))
3370  {
3371  safetyInfo->unsafeColumns[tle->resno] = true;
3372  continue;
3373  }
3374 
3375  /* If subquery uses DISTINCT ON, check point 3 */
3376  if (subquery->hasDistinctOn &&
3377  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3378  {
3379  /* non-DISTINCT column, so mark it unsafe */
3380  safetyInfo->unsafeColumns[tle->resno] = true;
3381  continue;
3382  }
3383 
3384  /* If subquery uses window functions, check point 4 */
3385  if (subquery->hasWindowFuncs &&
3386  !targetIsInAllPartitionLists(tle, subquery))
3387  {
3388  /* not present in all PARTITION BY clauses, so mark it unsafe */
3389  safetyInfo->unsafeColumns[tle->resno] = true;
3390  continue;
3391  }
3392  }
3393 }
3394 
3395 /*
3396  * For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
3397  * push quals into each component query, but the quals can only reference
3398  * subquery columns that suffer no type coercions in the set operation.
3399  * Otherwise there are possible semantic gotchas. So, we check the
3400  * component queries to see if any of them have output types different from
3401  * the top-level setop outputs. unsafeColumns[k] is set true if column k
3402  * has different type in any component.
3403  *
3404  * We don't have to care about typmods here: the only allowed difference
3405  * between set-op input and output typmods is input is a specific typmod
3406  * and output is -1, and that does not require a coercion.
3407  *
3408  * tlist is a subquery tlist.
3409  * colTypes is an OID list of the top-level setop's output column types.
3410  * safetyInfo->unsafeColumns[] is the result array.
3411  */
3412 static void
3414  pushdown_safety_info *safetyInfo)
3415 {
3416  ListCell *l;
3417  ListCell *colType = list_head(colTypes);
3418 
3419  foreach(l, tlist)
3420  {
3421  TargetEntry *tle = (TargetEntry *) lfirst(l);
3422 
3423  if (tle->resjunk)
3424  continue; /* ignore resjunk columns */
3425  if (colType == NULL)
3426  elog(ERROR, "wrong number of tlist entries");
3427  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3428  safetyInfo->unsafeColumns[tle->resno] = true;
3429  colType = lnext(colTypes, colType);
3430  }
3431  if (colType != NULL)
3432  elog(ERROR, "wrong number of tlist entries");
3433 }
3434 
3435 /*
3436  * targetIsInAllPartitionLists
3437  * True if the TargetEntry is listed in the PARTITION BY clause
3438  * of every window defined in the query.
3439  *
3440  * It would be safe to ignore windows not actually used by any window
3441  * function, but it's not easy to get that info at this stage; and it's
3442  * unlikely to be useful to spend any extra cycles getting it, since
3443  * unreferenced window definitions are probably infrequent in practice.
3444  */
3445 static bool
3447 {
3448  ListCell *lc;
3449 
3450  foreach(lc, query->windowClause)
3451  {
3452  WindowClause *wc = (WindowClause *) lfirst(lc);
3453 
3455  return false;
3456  }
3457  return true;
3458 }
3459 
3460 /*
3461  * qual_is_pushdown_safe - is a particular rinfo safe to push down?
3462  *
3463  * rinfo is a restriction clause applying to the given subquery (whose RTE
3464  * has index rti in the parent query).
3465  *
3466  * Conditions checked here:
3467  *
3468  * 1. rinfo's clause must not contain any SubPlans (mainly because it's
3469  * unclear that it will work correctly: SubLinks will already have been
3470  * transformed into SubPlans in the qual, but not in the subquery). Note that
3471  * SubLinks that transform to initplans are safe, and will be accepted here
3472  * because what we'll see in the qual is just a Param referencing the initplan
3473  * output.
3474  *
3475  * 2. If unsafeVolatile is set, rinfo's clause must not contain any volatile
3476  * functions.
3477  *
3478  * 3. If unsafeLeaky is set, rinfo's clause must not contain any leaky
3479  * functions that are passed Var nodes, and therefore might reveal values from
3480  * the subquery as side effects.
3481  *
3482  * 4. rinfo's clause must not refer to the whole-row output of the subquery
3483  * (since there is no easy way to name that within the subquery itself).
3484  *
3485  * 5. rinfo's clause must not refer to any subquery output columns that were
3486  * found to be unsafe to reference by subquery_is_pushdown_safe().
3487  */
3488 static bool
3490  pushdown_safety_info *safetyInfo)
3491 {
3492  bool safe = true;
3493  Node *qual = (Node *) rinfo->clause;
3494  List *vars;
3495  ListCell *vl;
3496 
3497  /* Refuse subselects (point 1) */
3498  if (contain_subplans(qual))
3499  return false;
3500 
3501  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3502  if (safetyInfo->unsafeVolatile &&
3503  contain_volatile_functions((Node *) rinfo))
3504  return false;
3505 
3506  /* Refuse leaky quals if told to (point 3) */
3507  if (safetyInfo->unsafeLeaky &&
3508  contain_leaked_vars(qual))
3509  return false;
3510 
3511  /*
3512  * It would be unsafe to push down window function calls, but at least for
3513  * the moment we could never see any in a qual anyhow. (The same applies
3514  * to aggregates, which we check for in pull_var_clause below.)
3515  */
3517 
3518  /*
3519  * Examine all Vars used in clause. Since it's a restriction clause, all
3520  * such Vars must refer to subselect output columns ... unless this is
3521  * part of a LATERAL subquery, in which case there could be lateral
3522  * references.
3523  */
3525  foreach(vl, vars)
3526  {
3527  Var *var = (Var *) lfirst(vl);
3528 
3529  /*
3530  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3531  * It's not clear whether a PHV could safely be pushed down, and even
3532  * less clear whether such a situation could arise in any cases of
3533  * practical interest anyway. So for the moment, just refuse to push
3534  * down.
3535  */
3536  if (!IsA(var, Var))
3537  {
3538  safe = false;
3539  break;
3540  }
3541 
3542  /*
3543  * Punt if we find any lateral references. It would be safe to push
3544  * these down, but we'd have to convert them into outer references,
3545  * which subquery_push_qual lacks the infrastructure to do. The case
3546  * arises so seldom that it doesn't seem worth working hard on.
3547  */
3548  if (var->varno != rti)
3549  {
3550  safe = false;
3551  break;
3552  }
3553 
3554  /* Subqueries have no system columns */
3555  Assert(var->varattno >= 0);
3556 
3557  /* Check point 4 */
3558  if (var->varattno == 0)
3559  {
3560  safe = false;
3561  break;
3562  }
3563 
3564  /* Check point 5 */
3565  if (safetyInfo->unsafeColumns[var->varattno])
3566  {
3567  safe = false;
3568  break;
3569  }
3570  }
3571 
3572  list_free(vars);
3573 
3574  return safe;
3575 }
3576 
3577 /*
3578  * subquery_push_qual - push down a qual that we have determined is safe
3579  */
3580 static void
3581 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
3582 {
3583  if (subquery->setOperations != NULL)
3584  {
3585  /* Recurse to push it separately to each component query */
3586  recurse_push_qual(subquery->setOperations, subquery,
3587  rte, rti, qual);
3588  }
3589  else
3590  {
3591  /*
3592  * We need to replace Vars in the qual (which must refer to outputs of
3593  * the subquery) with copies of the subquery's targetlist expressions.
3594  * Note that at this point, any uplevel Vars in the qual should have
3595  * been replaced with Params, so they need no work.
3596  *
3597  * This step also ensures that when we are pushing into a setop tree,
3598  * each component query gets its own copy of the qual.
3599  */
3600  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3601  subquery->targetList,
3603  &subquery->hasSubLinks);
3604 
3605  /*
3606  * Now attach the qual to the proper place: normally WHERE, but if the
3607  * subquery uses grouping or aggregation, put it in HAVING (since the
3608  * qual really refers to the group-result rows).
3609  */
3610  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
3611  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
3612  else
3613  subquery->jointree->quals =
3614  make_and_qual(subquery->jointree->quals, qual);
3615 
3616  /*
3617  * We need not change the subquery's hasAggs or hasSubLinks flags,
3618  * since we can't be pushing down any aggregates that weren't there
3619  * before, and we don't push down subselects at all.
3620  */
3621  }
3622 }
3623 
3624 /*
3625  * Helper routine to recurse through setOperations tree
3626  */
3627 static void
3628 recurse_push_qual(Node *setOp, Query *topquery,
3629  RangeTblEntry *rte, Index rti, Node *qual)
3630 {
3631  if (IsA(setOp, RangeTblRef))
3632  {
3633  RangeTblRef *rtr = (RangeTblRef *) setOp;
3634  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
3635  Query *subquery = subrte->subquery;
3636 
3637  Assert(subquery != NULL);
3638  subquery_push_qual(subquery, rte, rti, qual);
3639  }
3640  else if (IsA(setOp, SetOperationStmt))
3641  {
3642  SetOperationStmt *op = (SetOperationStmt *) setOp;
3643 
3644  recurse_push_qual(op->larg, topquery, rte, rti, qual);
3645  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
3646  }
3647  else
3648  {
3649  elog(ERROR, "unrecognized node type: %d",
3650  (int) nodeTag(setOp));
3651  }
3652 }
3653 
3654 /*****************************************************************************
3655  * SIMPLIFYING SUBQUERY TARGETLISTS
3656  *****************************************************************************/
3657 
3658 /*
3659  * remove_unused_subquery_outputs
3660  * Remove subquery targetlist items we don't need
3661  *
3662  * It's possible, even likely, that the upper query does not read all the
3663  * output columns of the subquery. We can remove any such outputs that are
3664  * not needed by the subquery itself (e.g., as sort/group columns) and do not
3665  * affect semantics otherwise (e.g., volatile functions can't be removed).
3666  * This is useful not only because we might be able to remove expensive-to-
3667  * compute expressions, but because deletion of output columns might allow
3668  * optimizations such as join removal to occur within the subquery.
3669  *
3670  * To avoid affecting column numbering in the targetlist, we don't physically
3671  * remove unused tlist entries, but rather replace their expressions with NULL
3672  * constants. This is implemented by modifying subquery->targetList.
3673  */
3674 static void
3676 {
3677  Bitmapset *attrs_used = NULL;
3678  ListCell *lc;
3679 
3680  /*
3681  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
3682  * could update all the child SELECTs' tlists, but it seems not worth the
3683  * trouble presently.
3684  */
3685  if (subquery->setOperations)
3686  return;
3687 
3688  /*
3689  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
3690  * time: all its output columns must be used in the distinctClause.
3691  */
3692  if (subquery->distinctClause && !subquery->hasDistinctOn)
3693  return;
3694 
3695  /*
3696  * Collect a bitmap of all the output column numbers used by the upper
3697  * query.
3698  *
3699  * Add all the attributes needed for joins or final output. Note: we must
3700  * look at rel's targetlist, not the attr_needed data, because attr_needed
3701  * isn't computed for inheritance child rels, cf set_append_rel_size().
3702  * (XXX might be worth changing that sometime.)
3703  */
3704  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
3705 
3706  /* Add all the attributes used by un-pushed-down restriction clauses. */
3707  foreach(lc, rel->baserestrictinfo)
3708  {
3709  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3710 
3711  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
3712  }
3713 
3714  /*
3715  * If there's a whole-row reference to the subquery, we can't remove
3716  * anything.
3717  */
3719  return;
3720 
3721  /*
3722  * Run through the tlist and zap entries we don't need. It's okay to
3723  * modify the tlist items in-place because set_subquery_pathlist made a
3724  * copy of the subquery.
3725  */
3726  foreach(lc, subquery->targetList)
3727  {
3728  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3729  Node *texpr = (Node *) tle->expr;
3730 
3731  /*
3732  * If it has a sortgroupref number, it's used in some sort/group
3733  * clause so we'd better not remove it. Also, don't remove any
3734  * resjunk columns, since their reason for being has nothing to do
3735  * with anybody reading the subquery's output. (It's likely that
3736  * resjunk columns in a sub-SELECT would always have ressortgroupref
3737  * set, but even if they don't, it seems imprudent to remove them.)
3738  */
3739  if (tle->ressortgroupref || tle->resjunk)
3740  continue;
3741 
3742  /*
3743  * If it's used by the upper query, we can't remove it.
3744  */
3746  attrs_used))
3747  continue;
3748 
3749  /*
3750  * If it contains a set-returning function, we can't remove it since
3751  * that could change the number of rows returned by the subquery.
3752  */
3753  if (subquery->hasTargetSRFs &&
3754  expression_returns_set(texpr))
3755  continue;
3756 
3757  /*
3758  * If it contains volatile functions, we daren't remove it for fear
3759  * that the user is expecting their side-effects to happen.
3760  */
3761  if (contain_volatile_functions(texpr))
3762  continue;
3763 
3764  /*
3765  * OK, we don't need it. Replace the expression with a NULL constant.
3766  * Preserve the exposed type of the expression, in case something
3767  * looks at the rowtype of the subquery's result.
3768  */
3769  tle->expr = (Expr *) makeNullConst(exprType(texpr),
3770  exprTypmod(texpr),
3771  exprCollation(texpr));
3772  }
3773 }
3774 
3775 /*
3776  * create_partial_bitmap_paths
3777  * Build partial bitmap heap path for the relation
3778  */
3779 void
3781  Path *bitmapqual)
3782 {
3783  int parallel_workers;
3784  double pages_fetched;
3785 
3786  /* Compute heap pages for bitmap heap scan */
3787  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
3788  NULL, NULL);
3789 
3790  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
3792 
3793  if (parallel_workers <= 0)
3794  return;
3795 
3796  add_partial_path(rel, (Path *) create_bitmap_heap_path(root, rel,
3797  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
3798 }
3799 
3800 /*
3801  * Compute the number of parallel workers that should be used to scan a
3802  * relation. We compute the parallel workers based on the size of the heap to
3803  * be scanned and the size of the index to be scanned, then choose a minimum
3804  * of those.
3805  *
3806  * "heap_pages" is the number of pages from the table that we expect to scan, or
3807  * -1 if we don't expect to scan any.
3808  *
3809  * "index_pages" is the number of pages from the index that we expect to scan, or
3810  * -1 if we don't expect to scan any.
3811  *
3812  * "max_workers" is caller's limit on the number of workers. This typically
3813  * comes from a GUC.
3814  */
3815 int
3816 compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages,
3817  int max_workers)
3818 {
3819  int parallel_workers = 0;
3820 
3821  /*
3822  * If the user has set the parallel_workers reloption, use that; otherwise
3823  * select a default number of workers.
3824  */
3825  if (rel->rel_parallel_workers != -1)
3826  parallel_workers = rel->rel_parallel_workers;
3827  else
3828  {
3829  /*
3830  * If the number of pages being scanned is insufficient to justify a
3831  * parallel scan, just return zero ... unless it's an inheritance
3832  * child. In that case, we want to generate a parallel path here
3833  * anyway. It might not be worthwhile just for this relation, but
3834  * when combined with all of its inheritance siblings it may well pay
3835  * off.
3836  */
3837  if (rel->reloptkind == RELOPT_BASEREL &&
3838  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
3839  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
3840  return 0;
3841 
3842  if (heap_pages >= 0)
3843  {
3844  int heap_parallel_threshold;
3845  int heap_parallel_workers = 1;
3846 
3847  /*
3848  * Select the number of workers based on the log of the size of
3849  * the relation. This probably needs to be a good deal more
3850  * sophisticated, but we need something here for now. Note that
3851  * the upper limit of the min_parallel_table_scan_size GUC is
3852  * chosen to prevent overflow here.
3853  */
3854  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
3855  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
3856  {
3857  heap_parallel_workers++;
3858  heap_parallel_threshold *= 3;
3859  if (heap_parallel_threshold > INT_MAX / 3)
3860  break; /* avoid overflow */
3861  }
3862 
3863  parallel_workers = heap_parallel_workers;
3864  }
3865 
3866  if (index_pages >= 0)
3867  {
3868  int index_parallel_workers = 1;
3869  int index_parallel_threshold;
3870 
3871  /* same calculation as for heap_pages above */
3872  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
3873  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
3874  {
3875  index_parallel_workers++;
3876  index_parallel_threshold *= 3;
3877  if (index_parallel_threshold > INT_MAX / 3)
3878  break; /* avoid overflow */
3879  }
3880 
3881  if (parallel_workers > 0)
3882  parallel_workers = Min(parallel_workers, index_parallel_workers);
3883  else
3884  parallel_workers = index_parallel_workers;
3885  }
3886  }
3887 
3888  /* In no case use more than caller supplied maximum number of workers */
3889  parallel_workers = Min(parallel_workers, max_workers);
3890 
3891  return parallel_workers;
3892 }
3893 
3894 /*
3895  * generate_partitionwise_join_paths
3896  * Create paths representing partitionwise join for given partitioned
3897  * join relation.
3898  *
3899  * This must not be called until after we are done adding paths for all
3900  * child-joins. Otherwise, add_path might delete a path to which some path
3901  * generated here has a reference.
3902  */
3903 void
3905 {
3906  List *live_children = NIL;
3907  int cnt_parts;
3908  int num_parts;
3909  RelOptInfo **part_rels;
3910 
3911  /* Handle only join relations here. */
3912  if (!IS_JOIN_REL(rel))
3913  return;
3914 
3915  /* We've nothing to do if the relation is not partitioned. */
3916  if (!IS_PARTITIONED_REL(rel))
3917  return;
3918 
3919  /* The relation should have consider_partitionwise_join set. */
3921 
3922  /* Guard against stack overflow due to overly deep partition hierarchy. */
3924 
3925  num_parts = rel->nparts;
3926  part_rels = rel->part_rels;
3927 
3928  /* Collect non-dummy child-joins. */
3929  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
3930  {
3931  RelOptInfo *child_rel = part_rels[cnt_parts];
3932 
3933  /* If it's been pruned entirely, it's certainly dummy. */
3934  if (child_rel == NULL)
3935  continue;
3936 
3937  /* Add partitionwise join paths for partitioned child-joins. */
3938  generate_partitionwise_join_paths(root, child_rel);
3939 
3940  set_cheapest(child_rel);
3941 
3942  /* Dummy children will not be scanned, so ignore those. */
3943  if (IS_DUMMY_REL(child_rel))
3944  continue;
3945 
3946 #ifdef OPTIMIZER_DEBUG
3947  debug_print_rel(root, child_rel);
3948 #endif
3949 
3950  live_children = lappend(live_children, child_rel);
3951  }
3952 
3953  /* If all child-joins are dummy, parent join is also dummy. */
3954  if (!live_children)
3955  {
3956  mark_dummy_rel(rel);
3957  return;
3958  }
3959 
3960  /* Build additional paths for this rel from child-join paths. */
3961  add_paths_to_append_rel(root, rel, live_children);
3962  list_free(live_children);
3963 }
3964 
3965 
3966 /*****************************************************************************
3967  * DEBUG SUPPORT
3968  *****************************************************************************/
3969 
3970 #ifdef OPTIMIZER_DEBUG
3971 
3972 static void
3973 print_relids(PlannerInfo *root, Relids relids)
3974 {
3975  int x;
3976  bool first = true;
3977 
3978  x = -1;
3979  while ((x = bms_next_member(relids, x)) >= 0)
3980  {
3981  if (!first)
3982  printf(" ");
3983  if (x < root->simple_rel_array_size &&
3984  root->simple_rte_array[x])
3985  printf("%s", root->simple_rte_array[x]->eref->aliasname);
3986  else
3987  printf("%d", x);
3988  first = false;
3989  }
3990 }
3991 
3992 static void
3993 print_restrictclauses(PlannerInfo *root, List *clauses)
3994 {
3995  ListCell *l;
3996 
3997  foreach(l, clauses)
3998  {
3999  RestrictInfo *c = lfirst(l);
4000 
4001  print_expr((Node *) c->clause, root->parse->rtable);
4002  if (lnext(clauses, l))
4003  printf(", ");
4004  }
4005 }
4006 
4007 static void
4008 print_path(PlannerInfo *root, Path *path, int indent)
4009 {
4010  const char *ptype;
4011  bool join = false;
4012  Path *subpath = NULL;
4013  int i;
4014 
4015  switch (nodeTag(path))
4016  {
4017  case T_Path:
4018  switch (path->pathtype)
4019  {
4020  case T_SeqScan:
4021  ptype = "SeqScan";
4022  break;
4023  case T_SampleScan:
4024  ptype = "SampleScan";
4025  break;
4026  case T_FunctionScan:
4027  ptype = "FunctionScan";
4028  break;
4029  case T_TableFuncScan:
4030  ptype = "TableFuncScan";
4031  break;
4032  case T_ValuesScan:
4033  ptype = "ValuesScan";
4034  break;
4035  case T_CteScan:
4036  ptype = "CteScan";
4037  break;
4038  case T_NamedTuplestoreScan:
4039  ptype = "NamedTuplestoreScan";
4040  break;
4041  case T_Result:
4042  ptype = "Result";
4043  break;
4044  case T_WorkTableScan:
4045  ptype = "WorkTableScan";
4046  break;
4047  default:
4048  ptype = "???Path";
4049  break;
4050  }
4051  break;
4052  case T_IndexPath:
4053  ptype = "IdxScan";
4054  break;
4055  case T_BitmapHeapPath:
4056  ptype = "BitmapHeapScan";
4057  break;
4058  case T_BitmapAndPath:
4059  ptype = "BitmapAndPath";
4060  break;
4061  case T_BitmapOrPath:
4062  ptype = "BitmapOrPath";
4063  break;
4064  case T_TidPath:
4065  ptype = "TidScan";
4066  break;
4067  case T_SubqueryScanPath:
4068  ptype = "SubqueryScan";
4069  break;
4070  case T_ForeignPath:
4071  ptype = "ForeignScan";
4072  break;
4073  case T_CustomPath:
4074  ptype = "CustomScan";
4075  break;
4076  case T_NestPath:
4077  ptype = "NestLoop";
4078  join = true;
4079  break;
4080  case T_MergePath:
4081  ptype = "MergeJoin";
4082  join = true;
4083  break;
4084  case T_HashPath:
4085  ptype = "HashJoin";
4086  join = true;
4087  break;
4088  case T_AppendPath:
4089  ptype = "Append";
4090  break;
4091  case T_MergeAppendPath:
4092  ptype = "MergeAppend";
4093  break;
4094  case T_GroupResultPath:
4095  ptype = "GroupResult";
4096  break;
4097  case T_MaterialPath:
4098  ptype = "Material";
4099  subpath = ((MaterialPath *) path)->subpath;
4100  break;
4101  case T_MemoizePath:
4102  ptype = "Memoize";
4103  subpath = ((MemoizePath *) path)->subpath;
4104  break;
4105  case T_UniquePath:
4106  ptype = "Unique";
4107  subpath = ((UniquePath *) path)->subpath;
4108  break;
4109  case T_GatherPath:
4110  ptype = "Gather";
4111  subpath = ((GatherPath *) path)->subpath;
4112  break;
4113  case T_GatherMergePath:
4114  ptype = "GatherMerge";
4115  subpath = ((GatherMergePath *) path)->subpath;
4116  break;
4117  case T_ProjectionPath:
4118  ptype = "Projection";
4119  subpath = ((ProjectionPath *) path)->subpath;
4120  break;
4121  case T_ProjectSetPath:
4122  ptype = "ProjectSet";
4123  subpath = ((ProjectSetPath *) path)->subpath;
4124  break;
4125  case T_SortPath:
4126  ptype = "Sort";
4127  subpath = ((SortPath *) path)->subpath;
4128  break;
4129  case T_IncrementalSortPath:
4130  ptype = "IncrementalSort";
4131  subpath = ((SortPath *) path)->subpath;
4132  break;
4133  case T_GroupPath:
4134  ptype = "Group";
4135  subpath = ((GroupPath *) path)->subpath;
4136  break;
4137  case T_UpperUniquePath:
4138  ptype = "UpperUnique";
4139  subpath = ((UpperUniquePath *) path)->subpath;
4140  break;
4141  case T_AggPath:
4142  ptype = "Agg";
4143  subpath = ((AggPath *) path)->subpath;
4144  break;
4145  case T_GroupingSetsPath:
4146  ptype = "GroupingSets";
4147  subpath = ((GroupingSetsPath *) path)->subpath;
4148  break;
4149  case T_MinMaxAggPath:
4150  ptype = "MinMaxAgg";
4151  break;
4152  case T_WindowAggPath:
4153  ptype = "WindowAgg";
4154  subpath = ((WindowAggPath *) path)->subpath;
4155  break;
4156  case T_SetOpPath:
4157  ptype = "SetOp";
4158  subpath = ((SetOpPath *) path)->subpath;
4159  break;
4160  case T_RecursiveUnionPath:
4161  ptype = "RecursiveUnion";
4162  break;
4163  case T_LockRowsPath:
4164  ptype = "LockRows";
4165  subpath = ((LockRowsPath *) path)->subpath;
4166  break;
4167  case T_ModifyTablePath:
4168  ptype = "ModifyTable";
4169  break;
4170  case T_LimitPath:
4171  ptype = "Limit";
4172  subpath = ((LimitPath *) path)->subpath;
4173  break;
4174  default:
4175  ptype = "???Path";
4176  break;
4177  }
4178 
4179  for (i = 0; i < indent; i++)
4180  printf("\t");
4181  printf("%s", ptype);
4182 
4183  if (path->parent)
4184  {
4185  printf("(");
4186  print_relids(root, path->parent->relids);
4187  printf(")");
4188  }
4189  if (path->param_info)
4190  {
4191  printf(" required_outer (");
4192  print_relids(root, path->param_info->ppi_req_outer);
4193  printf(")");
4194  }
4195  printf(" rows=%.0f cost=%.2f..%.2f\n",
4196  path->rows, path->startup_cost, path->total_cost);
4197 
4198  if (path->pathkeys)
4199  {
4200  for (i = 0; i < indent; i++)
4201  printf("\t");
4202  printf(" pathkeys: ");
4203  print_pathkeys(path->pathkeys, root->parse->rtable);
4204  }
4205 
4206  if (join)
4207  {
4208  JoinPath *jp = (JoinPath *) path;
4209 
4210  for (i = 0; i < indent; i++)
4211  printf("\t");
4212  printf(" clauses: ");
4213  print_restrictclauses(root, jp->joinrestrictinfo);
4214  printf("\n");
4215 
4216  if (IsA(path, MergePath))
4217  {
4218  MergePath *mp = (MergePath *) path;
4219 
4220  for (i = 0; i < indent; i++)
4221  printf("\t");
4222  printf(" sortouter=%d sortinner=%d materializeinner=%d\n",
4223  ((mp->outersortkeys) ? 1 : 0),
4224  ((mp->innersortkeys) ? 1 : 0),
4225  ((mp->materialize_inner) ? 1 : 0));
4226  }
4227 
4228  print_path(root, jp->outerjoinpath, indent + 1);
4229  print_path(root, jp->innerjoinpath, indent + 1);
4230  }
4231 
4232  if (subpath)
4233  print_path(root, subpath, indent + 1);
4234 }
4235 
4236 void
4237 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
4238 {
4239  ListCell *l;
4240 
4241  printf("RELOPTINFO (");
4242  print_relids(root, rel->relids);
4243  printf("): rows=%.0f width=%d\n", rel->rows, rel->reltarget->width);
4244 
4245  if (rel->baserestrictinfo)
4246  {
4247  printf("\tbaserestrictinfo: ");
4248  print_restrictclauses(root, rel->baserestrictinfo);
4249  printf("\n");
4250  }
4251 
4252  if (rel->joininfo)
4253  {
4254  printf("\tjoininfo: ");
4255  print_restrictclauses(root, rel->joininfo);
4256  printf("\n");
4257  }
4258 
4259  printf("\tpath list:\n");
4260  foreach(l, rel->pathlist)
4261  print_path(root, lfirst(l), 1);
4263  {
4264  printf("\n\tcheapest parameterized paths:\n");
4265  foreach(l, rel->cheapest_parameterized_paths)
4266  print_path(root, lfirst(l), 1);
4267  }
4268  if (rel->cheapest_startup_path)
4269  {
4270  printf("\n\tcheapest startup path:\n");
4271  print_path(root, rel->cheapest_startup_path, 1);
4272  }
4273  if (rel->cheapest_total_path)
4274  {
4275  printf("\n\tcheapest total path:\n");
4276  print_path(root, rel->cheapest_total_path, 1);
4277  }
4278  printf("\n");
4279  fflush(stdout);
4280 }
4281 
4282 #endif /* OPTIMIZER_DEBUG */
static void set_base_rel_sizes(PlannerInfo *root)
Definition: allpaths.c:292
static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:2173
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:1946
static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2556
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3581
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:3904
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3052
static void set_base_rel_consider_startup(PlannerInfo *root)
Definition: allpaths.c:249
static bool qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3489
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:471
static Path * get_singleton_append_subpath(Path *path)
Definition: allpaths.c:2080
static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:817
static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:857
static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:929
static void set_base_rel_pathlists(PlannerInfo *root)
Definition: allpaths.c:335
int geqo_threshold
Definition: allpaths.c:63
static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1215
static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2586
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3816
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2675
static void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:2114
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3413
static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2616
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:3446
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:797
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3222
join_search_hook_type join_search_hook
Definition: allpaths.c:71
bool enable_geqo
Definition: allpaths.c:62
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2813
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:2947
static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2378
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3628
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:767
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:2745
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3345
static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2466
static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:905
set_rel_pathlist_hook_type set_rel_pathlist_hook
Definition: allpaths.c:68
static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2446
struct pushdown_safety_info pushdown_safety_info
static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2490
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:592
static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:947
void create_partial_bitmap_paths(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual)
Definition: allpaths.c:3780
static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:575
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1285
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:362
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition: allpaths.c:1673
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:153
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3278
static bool has_multiple_baserels(PlannerInfo *root)
Definition: allpaths.c:2140
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2034
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel)
Definition: allpaths.c:3675
int min_parallel_index_scan_size
Definition: allpaths.c:65
int min_parallel_table_scan_size
Definition: allpaths.c:64
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:195
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
void print_pathkeys(const List *pathkeys, const List *rtable)
Definition: print.c:426
void print_expr(const Node *expr, const List *rtable)
Definition: print.c:321
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1045
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:703
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:674
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:617
@ BMS_SINGLETON
Definition: bitmapset.h:69
uint32 BlockNumber
Definition: block.h:31
#define Min(x, y)
Definition: c.h:986
signed int int32
Definition: c.h:429
#define Max(x, y)
Definition: c.h:980
unsigned char bool
Definition: c.h:391
unsigned int Index
Definition: c.h:549
bool contain_window_function(Node *clause)
Definition: clauses.c:213
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1150
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:640
bool contain_subplans(Node *clause)
Definition: clauses.c:329
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:453
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5687
int max_parallel_workers_per_gather
Definition: costsize.c:131
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4923
void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5558
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:6075
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:5650
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5720
bool enable_partitionwise_join
Definition: costsize.c:147
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5478
bool enable_parallel_append
Definition: costsize.c:149
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5749
double clamp_row_est(double nrows)
Definition: costsize.c:199
void set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5596
void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5618
bool enable_incremental_sort
Definition: costsize.c:139
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
Definition: equivclass.c:2568
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
Definition: equivclass.c:977
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:67
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:3307
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:235
int x
Definition: isn.c:71
int i
Definition: isn.c:73
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:71
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1261
static void const char fflush(stdout)
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_truncate(List *list, int new_size)
Definition: list.c:610
List * lappend(List *list, void *datum)
Definition: list.c:336
List * list_copy(const List *oldlist)
Definition: list.c:1532
void list_free(List *list)
Definition: list.c:1505
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1551
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
List * lcons(void *datum, List *list)
Definition: list.c:474
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2049
char func_parallel(Oid funcid)
Definition: lsyscache.c:1770
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2525
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:689
void pfree(void *pointer)
Definition: mcxt.c:1169
void * palloc0(Size size)
Definition: mcxt.c:1093
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:709
#define IsA(nodeptr, _type_)
Definition: nodes.h:589
#define copyObject(obj)
Definition: nodes.h:654
#define nodeTag(nodeptr)
Definition: nodes.h:543
@ T_ModifyTablePath
Definition: nodes.h:263
@ T_SortPath
Definition: nodes.h:252
@ T_NamedTuplestoreScan
Definition: nodes.h:68
@ T_SubqueryScanPath
Definition: nodes.h:236
@ T_GroupResultPath
Definition: nodes.h:244
@ T_HashPath
Definition: nodes.h:241
@ T_GroupPath
Definition: nodes.h:254
@ T_TableFuncScan
Definition: nodes.h:66
@ T_MinMaxAggPath
Definition: nodes.h:258
@ T_FunctionScan
Definition: nodes.h:64
@ T_NestPath
Definition: nodes.h:239
@ T_CustomPath
Definition: nodes.h:238
@ T_IncrementalSortPath
Definition: nodes.h:253
@ T_TidPath
Definition: nodes.h:234
@ T_AggPath
Definition: nodes.h:256
@ T_MemoizePath
Definition: nodes.h:246
@ T_GatherMergePath
Definition: nodes.h:249
@ T_SetOpPath
Definition: nodes.h:260
@ T_BitmapAndPath
Definition: nodes.h:232
@ T_ProjectionPath
Definition: nodes.h:250
@ T_SeqScan
Definition: nodes.h:55
@ T_MaterialPath
Definition: nodes.h:245
@ T_RecursiveUnionPath
Definition: nodes.h:261
@ T_ForeignPath
Definition: nodes.h:237
@ T_SampleScan
Definition: nodes.h:56
@ T_MergeAppendPath
Definition: nodes.h:243
@ T_ValuesScan
Definition: nodes.h:65
@ T_GroupingSetsPath
Definition: nodes.h:257
@ T_BitmapHeapPath
Definition: nodes.h:231
@ T_UpperUniquePath
Definition: nodes.h:255
@ T_CteScan
Definition: nodes.h:67
@ T_LockRowsPath
Definition: nodes.h:262
@ T_UniquePath
Definition: nodes.h:247
@ T_WindowAggPath
Definition: nodes.h:259
@ T_LimitPath
Definition: nodes.h:264
@ T_MergePath
Definition: nodes.h:240
@ T_ProjectSetPath
Definition: nodes.h:251
@ T_Result
Definition: nodes.h:46
@ T_AppendPath
Definition: nodes.h:242
@ T_BitmapOrPath
Definition: nodes.h:233
@ T_WorkTableScan
Definition: nodes.h:69
@ T_Path
Definition: nodes.h:229
@ T_GatherPath
Definition: nodes.h:248
@ T_IndexPath
Definition: nodes.h:230
#define castNode(_type_, nodeptr)
Definition: nodes.h:607
@ JOIN_SEMI
Definition: nodes.h:726
@ JOIN_ANTI
Definition: nodes.h:727
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
@ SETOP_EXCEPT
Definition: parsenodes.h:1648
@ RTE_JOIN
Definition: parsenodes.h:992
@ RTE_CTE
Definition: parsenodes.h:996
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:997
@ RTE_VALUES
Definition: parsenodes.h:995
@ RTE_SUBQUERY
Definition: parsenodes.h:991
@ RTE_RESULT
Definition: parsenodes.h:998
@ RTE_FUNCTION
Definition: parsenodes.h:993
@ RTE_TABLEFUNC
Definition: parsenodes.h:994
@ RTE_RELATION
Definition: parsenodes.h:990
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2863
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:404
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:1910
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:782
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition: pathkeys.c:482
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:838
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:449
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:285
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:699
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1244
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2942
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1861
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2045
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2122
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1952
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2148
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:954
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1404
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3845
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2097
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1552
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2019
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1991
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2893
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2174
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2071
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:71
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1046
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:654
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1467
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:659
@ TOTAL_COST
Definition: pathnodes.h:36
@ STARTUP_COST
Definition: pathnodes.h:36
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:786
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1202
Bitmapset * Relids
Definition: pathnodes.h:28
@ UPPERREL_FINAL
Definition: pathnodes.h:77
@ RELOPT_BASEREL
Definition: pathnodes.h:641
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:643
RelOptInfo *(* join_search_hook_type)(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: paths.h:45
void(* set_rel_pathlist_hook_type)(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: paths.h:29
@ PATHKEYS_EQUAL
Definition: paths.h:197
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
#define list_make1(x1)
Definition: pg_list.h:206
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
#define linitial(l)
Definition: pg_list.h:174
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define lfirst_oid(lc)
Definition: pg_list.h:171
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:289
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1476
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:596
bool limit_needed(Query *parse)
Definition: planner.c:2489
int fls(int mask)
Definition: fls.c:55
#define printf(...)
Definition: port.h:231
void check_stack_depth(void)
Definition: postgres.c:3470
#define InvalidOid
Definition: postgres_ext.h:36
char * c
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:375
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
@ REPLACEVARS_REPORT_ERROR
Definition: rewriteManip.h:38
@ BackwardScanDirection
Definition: sdir.h:24
@ ForwardScanDirection
Definition: sdir.h:26
char * aliasname
Definition: primnodes.h:42
int first_partial_path
Definition: pathnodes.h:1455
List * subpaths
Definition: pathnodes.h:1453
Index child_relid
Definition: pathnodes.h:2311
Index parent_relid
Definition: pathnodes.h:2310
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:266
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:210
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:209
Node * quals
Definition: primnodes.h:1565
Path * outerjoinpath
Definition: pathnodes.h:1593
Path * innerjoinpath
Definition: pathnodes.h:1594
List * joinrestrictinfo
Definition: pathnodes.h:1596
Definition: pg_list.h:51
List * outersortkeys
Definition: pathnodes.h:1653
List * innersortkeys
Definition: pathnodes.h:1654
bool materialize_inner
Definition: pathnodes.h:1656
Definition: nodes.h:539
Relids ppi_req_outer
Definition: pathnodes.h:1142
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1067
List * exprs
Definition: pathnodes.h:1111
List * pathkeys
Definition: pathnodes.h:1197
NodeTag pathtype
Definition: pathnodes.h:1181
RelOptInfo * parent
Definition: pathnodes.h:1183
Cardinality rows
Definition: pathnodes.h:1193
Cost startup_cost
Definition: pathnodes.h:1194
int parallel_workers
Definition: pathnodes.h:1190
ParamPathInfo * param_info
Definition: pathnodes.h:1186
Cost total_cost
Definition: pathnodes.h:1195
bool parallel_aware
Definition: pathnodes.h:1188
Cardinality plan_rows
Definition: plannodes.h:123
List * subplans
Definition: pathnodes.h:96
bool parallelModeOK
Definition: pathnodes.h:126
List ** join_rel_level
Definition: pathnodes.h:239
int simple_rel_array_size
Definition: pathnodes.h:187
List * cte_plan_ids
Definition: pathnodes.h:244
Index query_level
Definition: pathnodes.h:166
List * append_rel_list
Definition: pathnodes.h:284
struct Path * non_recursive_path
Definition: pathnodes.h:365
PlannerGlobal * glob
Definition: pathnodes.h:164
List * plan_params
Definition: pathnodes.h:176
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:186
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:194
PlannerInfo * parent_root
Definition: pathnodes.h:168
Cardinality total_table_pages
Definition: pathnodes.h:337
Query * parse
Definition: pathnodes.h:162
List * query_pathkeys
Definition: pathnodes.h:294
Selectivity tuple_fraction
Definition: pathnodes.h:340
List * join_info_list
Definition: pathnodes.h:266
List * initial_rels
Definition: pathnodes.h:304
Relids all_baserels
Definition: pathnodes.h:210
bool hasWindowFuncs
Definition: parsenodes.h:133
Node * limitCount
Definition: parsenodes.h:171
FromExpr * jointree
Definition: parsenodes.h:147
Node * setOperations
Definition: parsenodes.h:176
List * cteList
Definition: parsenodes.h:144
bool hasTargetSRFs
Definition: parsenodes.h:134
List * groupClause
Definition: parsenodes.h:157
Node * havingQual
Definition: parsenodes.h:162
List * rtable
Definition: parsenodes.h:146
Node * limitOffset
Definition: parsenodes.h:170
bool hasAggs
Definition: parsenodes.h:132
bool hasDistinctOn
Definition: parsenodes.h:136
List * windowClause
Definition: parsenodes.h:164
List * targetList
Definition: parsenodes.h:149
bool hasSubLinks
Definition: parsenodes.h:135
List * groupingSets
Definition: parsenodes.h:160
List * distinctClause
Definition: parsenodes.h:166
char * ctename
Definition: parsenodes.h:1117
bool self_reference
Definition: parsenodes.h:1119
bool security_barrier
Definition: parsenodes.h:1043
Index ctelevelsup
Definition: parsenodes.h:1118
bool funcordinality
Definition: parsenodes.h:1102
struct TableSampleClause * tablesample
Definition: parsenodes.h:1037
Query * subquery
Definition: parsenodes.h:1042
Alias * eref
Definition: parsenodes.h:1153
List * values_lists
Definition: parsenodes.h:1112
List * functions
Definition: parsenodes.h:1101
RTEKind rtekind
Definition: parsenodes.h:1007
List * baserestrictinfo
Definition: pathnodes.h:745
bool consider_param_startup
Definition: pathnodes.h:688
List * subplan_params
Definition: pathnodes.h:726
List * joininfo
Definition: pathnodes.h:749
Relids relids
Definition: pathnodes.h:681
struct PathTarget * reltarget
Definition: pathnodes.h:692
int32 * attr_widths
Definition: pathnodes.h:715
Relids * attr_needed
Definition: pathnodes.h:714
Index relid
Definition: pathnodes.h:709
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:764
PartitionScheme part_scheme
Definition: pathnodes.h:760
int nparts
Definition: pathnodes.h:761
Cardinality tuples
Definition: pathnodes.h:721
bool consider_parallel
Definition: pathnodes.h:689
BlockNumber pages
Definition: pathnodes.h:720
Relids lateral_relids
Definition: pathnodes.h:706
List * cheapest_parameterized_paths
Definition: pathnodes.h:701
List * pathlist
Definition: pathnodes.h:695
RelOptKind reloptkind
Definition: pathnodes.h:678
struct Path * cheapest_startup_path
Definition: pathnodes.h:698
struct Path * cheapest_total_path
Definition: pathnodes.h:699
struct RelOptInfo ** part_rels
Definition: pathnodes.h:768
bool has_eclass_joins
Definition: pathnodes.h:751
Bitmapset * live_parts
Definition: pathnodes.h:770
int rel_parallel_workers
Definition: pathnodes.h:727
bool consider_partitionwise_join
Definition: pathnodes.h:754
List * partial_pathlist
Definition: pathnodes.h:697
PlannerInfo * subroot
Definition: pathnodes.h:725
AttrNumber max_attr
Definition: pathnodes.h:713
Cardinality rows
Definition: pathnodes.h:684
AttrNumber min_attr
Definition: pathnodes.h:712
RTEKind rtekind
Definition: pathnodes.h:711
bool pseudoconstant
Definition: pathnodes.h:2067
Expr * clause
Definition: pathnodes.h:2059
SetOperation op
Definition: parsenodes.h:1723
JoinType jointype
Definition: pathnodes.h:2260
Relids syn_righthand
Definition: pathnodes.h:2259
Expr * expr
Definition: primnodes.h:1455
AttrNumber resno
Definition: primnodes.h:1456
bool resjunk
Definition: primnodes.h:1462
Index ressortgroupref
Definition: primnodes.h:1458
bool repeatable_across_scans
Definition: tsmapi.h:65
SampleScanGetSampleSize_function SampleScanGetSampleSize
Definition: tsmapi.h:68
Definition: primnodes.h:187
AttrNumber varattno
Definition: primnodes.h:191
int varno
Definition: primnodes.h:189
Index varlevelsup
Definition: primnodes.h:196
List * partitionClause
Definition: parsenodes.h:1391
bool * unsafeColumns
Definition: allpaths.c:56
Definition: regcomp.c:238
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
void create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: tidpath.c:459
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:613
List * pull_var_clause(Node *node, int flags)
Definition: var.c:604
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:288