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