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