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