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