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