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