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