1 /*-------------------------------------------------------------------------
4 * Routines to find possible search paths for processing a query
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/path/allpaths.c
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_class.h"
21 #include "nodes/nodeFuncs.h"
22 #ifdef OPTIMIZER_DEBUG
23 #include "nodes/print.h"
25 #include "optimizer/clauses.h"
26 #include "optimizer/cost.h"
27 #include "optimizer/geqo.h"
28 #include "optimizer/pathnode.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/plancat.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/prep.h"
33 #include "optimizer/restrictinfo.h"
34 #include "optimizer/var.h"
35 #include "parser/parse_clause.h"
36 #include "parser/parsetree.h"
37 #include "rewrite/rewriteManip.h"
38 #include "utils/lsyscache.h"
41 /* These parameters are set by GUC */
42 bool enable_geqo = false; /* just in case GUC doesn't set it */
45 /* Hook for plugins to replace standard_join_search() */
46 join_search_hook_type join_search_hook = NULL;
49 static void set_base_rel_pathlists(PlannerInfo *root);
50 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
51 Index rti, RangeTblEntry *rte);
52 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
54 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
55 Index rti, RangeTblEntry *rte);
56 static List *accumulate_append_subpath(List *subpaths, Path *path);
57 static void set_dummy_rel_pathlist(RelOptInfo *rel);
58 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
59 Index rti, RangeTblEntry *rte);
60 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
62 static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
64 static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel,
66 static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel,
68 static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel,
70 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
71 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
72 bool *differentTypes);
73 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
74 bool *differentTypes);
75 static void compare_tlist_datatypes(List *tlist, List *colTypes,
76 bool *differentTypes);
77 static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
78 bool *differentTypes);
79 static void subquery_push_qual(Query *subquery,
80 RangeTblEntry *rte, Index rti, Node *qual);
81 static void recurse_push_qual(Node *setOp, Query *topquery,
82 RangeTblEntry *rte, Index rti, Node *qual);
87 * Finds all possible access paths for executing a query, returning a
88 * single rel that represents the join of all base rels in the query.
91 make_one_rel(PlannerInfo *root, List *joinlist)
96 * Generate access paths for the base rels.
98 set_base_rel_pathlists(root);
101 * Generate access paths for the entire join tree.
103 rel = make_rel_from_joinlist(root, joinlist);
106 * The result should join all and only the query's base rels.
108 #ifdef USE_ASSERT_CHECKING
110 int num_base_rels = 0;
113 for (rti = 1; rti < root->simple_rel_array_size; rti++)
115 RelOptInfo *brel = root->simple_rel_array[rti];
120 Assert(brel->relid == rti); /* sanity check on array */
122 /* ignore RTEs that are "other rels" */
123 if (brel->reloptkind != RELOPT_BASEREL)
126 Assert(bms_is_member(rti, rel->relids));
130 Assert(bms_num_members(rel->relids) == num_base_rels);
138 * set_base_rel_pathlists
139 * Finds all paths available for scanning each base-relation entry.
140 * Sequential scan and any available indices are considered.
141 * Each useful path is attached to its relation's 'pathlist' field.
144 set_base_rel_pathlists(PlannerInfo *root)
148 for (rti = 1; rti < root->simple_rel_array_size; rti++)
150 RelOptInfo *rel = root->simple_rel_array[rti];
152 /* there may be empty slots corresponding to non-baserel RTEs */
156 Assert(rel->relid == rti); /* sanity check on array */
158 /* ignore RTEs that are "other rels" */
159 if (rel->reloptkind != RELOPT_BASEREL)
162 set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
168 * Build access paths for a base relation
171 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
172 Index rti, RangeTblEntry *rte)
174 if (rel->reloptkind == RELOPT_BASEREL &&
175 relation_excluded_by_constraints(root, rel, rte))
178 * We proved we don't need to scan the rel via constraint exclusion,
179 * so set up a single dummy path for it. Here we only check this for
180 * regular baserels; if it's an otherrel, CE was already checked in
181 * set_append_rel_pathlist().
183 set_dummy_rel_pathlist(rel);
187 /* It's an "append relation", process accordingly */
188 set_append_rel_pathlist(root, rel, rti, rte);
192 switch (rel->rtekind)
195 if (rte->relkind == RELKIND_FOREIGN_TABLE)
198 set_foreign_pathlist(root, rel, rte);
203 set_plain_rel_pathlist(root, rel, rte);
207 /* Subquery --- generate a separate plan for it */
208 set_subquery_pathlist(root, rel, rti, rte);
211 /* RangeFunction --- generate a suitable path for it */
212 set_function_pathlist(root, rel, rte);
215 /* Values list --- generate a suitable path for it */
216 set_values_pathlist(root, rel, rte);
219 /* CTE reference --- generate a suitable path for it */
220 if (rte->self_reference)
221 set_worktable_pathlist(root, rel, rte);
223 set_cte_pathlist(root, rel, rte);
226 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
231 #ifdef OPTIMIZER_DEBUG
232 debug_print_rel(root, rel);
237 * set_plain_rel_pathlist
238 * Build access paths for a plain relation (no subquery, no inheritance)
241 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
244 * Test any partial indexes of rel for applicability. We must do this
245 * first since partial unique indexes can affect size estimates.
247 check_partial_indexes(root, rel);
249 /* Mark rel with estimated output rows, width, etc */
250 set_baserel_size_estimates(root, rel);
253 * Check to see if we can extract any restriction conditions from join
254 * quals that are OR-of-AND structures. If so, add them to the rel's
255 * restriction list, and redo the above steps.
257 if (create_or_index_quals(root, rel))
259 check_partial_indexes(root, rel);
260 set_baserel_size_estimates(root, rel);
264 * Generate paths and add them to the rel's pathlist.
266 * Note: add_path() will discard any paths that are dominated by another
267 * available path, keeping only those paths that are superior along at
268 * least one dimension of cost or sortedness.
271 /* Consider sequential scan */
272 add_path(rel, create_seqscan_path(root, rel));
274 /* Consider index scans */
275 create_index_paths(root, rel);
277 /* Consider TID scans */
278 create_tidscan_paths(root, rel);
280 /* Now find the cheapest of the paths for this rel */
285 * set_append_rel_pathlist
286 * Build access paths for an "append relation"
288 * The passed-in rel and RTE represent the entire append relation. The
289 * relation's contents are computed by appending together the output of
290 * the individual member relations. Note that in the inheritance case,
291 * the first member relation is actually the same table as is mentioned in
292 * the parent RTE ... but it has a different RTE and RelOptInfo. This is
293 * a good thing because their outputs are not the same size.
296 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
297 Index rti, RangeTblEntry *rte)
299 int parentRTindex = rti;
300 List *live_childrels = NIL;
301 List *subpaths = NIL;
302 List *all_child_pathkeys = NIL;
305 double *parent_attrsizes;
310 * Initialize to compute size estimates for whole append relation.
312 * We handle width estimates by weighting the widths of different child
313 * rels proportionally to their number of rows. This is sensible because
314 * the use of width estimates is mainly to compute the total relation
315 * "footprint" if we have to sort or hash it. To do this, we sum the
316 * total equivalent size (in "double" arithmetic) and then divide by the
317 * total rowcount estimate. This is done separately for the total rel
318 * width and each attribute.
320 * Note: if you consider changing this logic, beware that child rels could
321 * have zero rows and/or width, if they were excluded by constraints.
325 nattrs = rel->max_attr - rel->min_attr + 1;
326 parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
329 * Generate access paths for each member relation, and pick the cheapest
332 foreach(l, root->append_rel_list)
334 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
336 RangeTblEntry *childRTE;
337 RelOptInfo *childrel;
341 ListCell *parentvars;
344 /* append_rel_list contains all append rels; ignore others */
345 if (appinfo->parent_relid != parentRTindex)
348 childRTindex = appinfo->child_relid;
349 childRTE = root->simple_rte_array[childRTindex];
352 * The child rel's RelOptInfo was already created during
353 * add_base_rels_to_query.
355 childrel = find_base_rel(root, childRTindex);
356 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
359 * We have to copy the parent's targetlist and quals to the child,
360 * with appropriate substitution of variables. However, only the
361 * baserestrictinfo quals are needed before we can check for
362 * constraint exclusion; so do that first and then check to see if we
363 * can disregard this child.
365 * As of 8.4, the child rel's targetlist might contain non-Var
366 * expressions, which means that substitution into the quals could
367 * produce opportunities for const-simplification, and perhaps even
368 * pseudoconstant quals. To deal with this, we strip the RestrictInfo
369 * nodes, do the substitution, do const-simplification, and then
370 * reconstitute the RestrictInfo layer.
372 childquals = get_all_actual_clauses(rel->baserestrictinfo);
373 childquals = (List *) adjust_appendrel_attrs((Node *) childquals,
375 childqual = eval_const_expressions(root, (Node *)
376 make_ands_explicit(childquals));
377 if (childqual && IsA(childqual, Const) &&
378 (((Const *) childqual)->constisnull ||
379 !DatumGetBool(((Const *) childqual)->constvalue)))
382 * Restriction reduces to constant FALSE or constant NULL after
383 * substitution, so this child need not be scanned.
385 set_dummy_rel_pathlist(childrel);
388 childquals = make_ands_implicit((Expr *) childqual);
389 childquals = make_restrictinfos_from_actual_clauses(root,
391 childrel->baserestrictinfo = childquals;
393 if (relation_excluded_by_constraints(root, childrel, childRTE))
396 * This child need not be scanned, so we can omit it from the
397 * appendrel. Mark it with a dummy cheapest-path though, in case
398 * best_appendrel_indexscan() looks at it later.
400 set_dummy_rel_pathlist(childrel);
405 * CE failed, so finish copying/modifying targetlist and join quals.
407 * Note: the resulting childrel->reltargetlist may contain arbitrary
408 * expressions, which normally would not occur in a reltargetlist.
409 * That is okay because nothing outside of this routine will look at
410 * the child rel's reltargetlist. We do have to cope with the case
411 * while constructing attr_widths estimates below, though.
413 childrel->joininfo = (List *)
414 adjust_appendrel_attrs((Node *) rel->joininfo,
416 childrel->reltargetlist = (List *)
417 adjust_appendrel_attrs((Node *) rel->reltargetlist,
421 * We have to make child entries in the EquivalenceClass data
422 * structures as well. This is needed either if the parent
423 * participates in some eclass joins (because we will want to consider
424 * inner-indexscan joins on the individual children) or if the parent
425 * has useful pathkeys (because we should try to build MergeAppend
426 * paths that produce those sort orderings).
428 if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
429 add_child_rel_equivalences(root, appinfo, rel, childrel);
430 childrel->has_eclass_joins = rel->has_eclass_joins;
433 * Note: we could compute appropriate attr_needed data for the child's
434 * variables, by transforming the parent's attr_needed through the
435 * translated_vars mapping. However, currently there's no need
436 * because attr_needed is only examined for base relations not
437 * otherrels. So we just leave the child's attr_needed empty.
441 * Compute the child's access paths.
443 set_rel_pathlist(root, childrel, childRTindex, childRTE);
446 * It is possible that constraint exclusion detected a contradiction
447 * within a child subquery, even though we didn't prove one above.
448 * If what we got back was a dummy path, we can skip this child.
450 if (IS_DUMMY_PATH(childrel->cheapest_total_path))
454 * Child is live, so add its cheapest access path to the Append path
455 * we are constructing for the parent.
457 subpaths = accumulate_append_subpath(subpaths,
458 childrel->cheapest_total_path);
460 /* Remember which childrels are live, for MergeAppend logic below */
461 live_childrels = lappend(live_childrels, childrel);
464 * Collect a list of all the available path orderings for all the
465 * children. We use this as a heuristic to indicate which sort
466 * orderings we should build MergeAppend paths for.
468 foreach(lcp, childrel->pathlist)
470 Path *childpath = (Path *) lfirst(lcp);
471 List *childkeys = childpath->pathkeys;
475 /* Ignore unsorted paths */
476 if (childkeys == NIL)
479 /* Have we already seen this ordering? */
480 foreach(lpk, all_child_pathkeys)
482 List *existing_pathkeys = (List *) lfirst(lpk);
484 if (compare_pathkeys(existing_pathkeys,
485 childkeys) == PATHKEYS_EQUAL)
493 /* No, so add it to all_child_pathkeys */
494 all_child_pathkeys = lappend(all_child_pathkeys, childkeys);
499 * Accumulate size information from each child.
501 if (childrel->rows > 0)
503 parent_rows += childrel->rows;
504 parent_size += childrel->width * childrel->rows;
507 * Accumulate per-column estimates too. We need not do anything
508 * for PlaceHolderVars in the parent list. If child expression
509 * isn't a Var, or we didn't record a width estimate for it, we
510 * have to fall back on a datatype-based estimate.
512 * By construction, child's reltargetlist is 1-to-1 with parent's.
514 forboth(parentvars, rel->reltargetlist,
515 childvars, childrel->reltargetlist)
517 Var *parentvar = (Var *) lfirst(parentvars);
518 Node *childvar = (Node *) lfirst(childvars);
520 if (IsA(parentvar, Var))
522 int pndx = parentvar->varattno - rel->min_attr;
523 int32 child_width = 0;
525 if (IsA(childvar, Var))
527 int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
529 child_width = childrel->attr_widths[cndx];
531 if (child_width <= 0)
532 child_width = get_typavgwidth(exprType(childvar),
533 exprTypmod(childvar));
534 Assert(child_width > 0);
535 parent_attrsizes[pndx] += child_width * childrel->rows;
542 * Save the finished size estimates.
544 rel->rows = parent_rows;
549 rel->width = rint(parent_size / parent_rows);
550 for (i = 0; i < nattrs; i++)
551 rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
554 rel->width = 0; /* attr_widths should be zero already */
557 * Set "raw tuples" count equal to "rows" for the appendrel; needed
558 * because some places assume rel->tuples is valid for any baserel.
560 rel->tuples = parent_rows;
562 pfree(parent_attrsizes);
565 * Next, build an unordered Append path for the rel. (Note: this is
566 * correct even if we have zero or one live subpath due to constraint
569 add_path(rel, (Path *) create_append_path(rel, subpaths));
572 * Next, build MergeAppend paths based on the collected list of child
573 * pathkeys. We consider both cheapest-startup and cheapest-total cases,
574 * ie, for each interesting ordering, collect all the cheapest startup
575 * subpaths and all the cheapest total paths, and build a MergeAppend path
578 foreach(l, all_child_pathkeys)
580 List *pathkeys = (List *) lfirst(l);
581 List *startup_subpaths = NIL;
582 List *total_subpaths = NIL;
583 bool startup_neq_total = false;
586 /* Select the child paths for this ordering... */
587 foreach(lcr, live_childrels)
589 RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
590 Path *cheapest_startup,
593 /* Locate the right paths, if they are available. */
595 get_cheapest_path_for_pathkeys(childrel->pathlist,
599 get_cheapest_path_for_pathkeys(childrel->pathlist,
604 * If we can't find any paths with the right order just add the
605 * cheapest-total path; we'll have to sort it.
607 if (cheapest_startup == NULL)
608 cheapest_startup = childrel->cheapest_total_path;
609 if (cheapest_total == NULL)
610 cheapest_total = childrel->cheapest_total_path;
613 * Notice whether we actually have different paths for the
614 * "cheapest" and "total" cases; frequently there will be no point
615 * in two create_merge_append_path() calls.
617 if (cheapest_startup != cheapest_total)
618 startup_neq_total = true;
621 accumulate_append_subpath(startup_subpaths, cheapest_startup);
623 accumulate_append_subpath(total_subpaths, cheapest_total);
626 /* ... and build the MergeAppend paths */
627 add_path(rel, (Path *) create_merge_append_path(root,
631 if (startup_neq_total)
632 add_path(rel, (Path *) create_merge_append_path(root,
638 /* Select cheapest path */
643 * accumulate_append_subpath
644 * Add a subpath to the list being built for an Append or MergeAppend
646 * It's possible that the child is itself an Append path, in which case
647 * we can "cut out the middleman" and just add its child paths to our
648 * own list. (We don't try to do this earlier because we need to
649 * apply both levels of transformation to the quals.)
652 accumulate_append_subpath(List *subpaths, Path *path)
654 if (IsA(path, AppendPath))
656 AppendPath *apath = (AppendPath *) path;
658 /* list_copy is important here to avoid sharing list substructure */
659 return list_concat(subpaths, list_copy(apath->subpaths));
662 return lappend(subpaths, path);
666 * set_dummy_rel_pathlist
667 * Build a dummy path for a relation that's been excluded by constraints
669 * Rather than inventing a special "dummy" path type, we represent this as an
670 * AppendPath with no members (see also IS_DUMMY_PATH macro).
673 set_dummy_rel_pathlist(RelOptInfo *rel)
675 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
679 add_path(rel, (Path *) create_append_path(rel, NIL));
681 /* Select cheapest path (pretty easy in this case...) */
685 /* quick-and-dirty test to see if any joining is needed */
687 has_multiple_baserels(PlannerInfo *root)
689 int num_base_rels = 0;
692 for (rti = 1; rti < root->simple_rel_array_size; rti++)
694 RelOptInfo *brel = root->simple_rel_array[rti];
699 /* ignore RTEs that are "other rels" */
700 if (brel->reloptkind == RELOPT_BASEREL)
701 if (++num_base_rels > 1)
708 * set_subquery_pathlist
709 * Build the (single) access path for a subquery RTE
712 set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
713 Index rti, RangeTblEntry *rte)
715 Query *parse = root->parse;
716 Query *subquery = rte->subquery;
717 bool *differentTypes;
718 double tuple_fraction;
719 PlannerInfo *subroot;
723 * Must copy the Query so that planning doesn't mess up the RTE contents
724 * (really really need to fix the planner to not scribble on its input,
727 subquery = copyObject(subquery);
729 /* We need a workspace for keeping track of set-op type coercions */
730 differentTypes = (bool *)
731 palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
734 * If there are any restriction clauses that have been attached to the
735 * subquery relation, consider pushing them down to become WHERE or HAVING
736 * quals of the subquery itself. This transformation is useful because it
737 * may allow us to generate a better plan for the subquery than evaluating
738 * all the subquery output rows and then filtering them.
740 * There are several cases where we cannot push down clauses. Restrictions
741 * involving the subquery are checked by subquery_is_pushdown_safe().
742 * Restrictions on individual clauses are checked by
743 * qual_is_pushdown_safe(). Also, we don't want to push down
744 * pseudoconstant clauses; better to have the gating node above the
747 * Non-pushed-down clauses will get evaluated as qpquals of the
750 * XXX Are there any cases where we want to make a policy decision not to
751 * push down a pushable qual, because it'd result in a worse plan?
753 if (rel->baserestrictinfo != NIL &&
754 subquery_is_pushdown_safe(subquery, subquery, differentTypes))
756 /* OK to consider pushing down individual quals */
757 List *upperrestrictlist = NIL;
760 foreach(l, rel->baserestrictinfo)
762 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
763 Node *clause = (Node *) rinfo->clause;
765 if (!rinfo->pseudoconstant &&
766 qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
769 subquery_push_qual(subquery, rte, rti, clause);
773 /* Keep it in the upper query */
774 upperrestrictlist = lappend(upperrestrictlist, rinfo);
777 rel->baserestrictinfo = upperrestrictlist;
780 pfree(differentTypes);
783 * We can safely pass the outer tuple_fraction down to the subquery if the
784 * outer level has no joining, aggregation, or sorting to do. Otherwise
785 * we'd better tell the subquery to plan for full retrieval. (XXX This
786 * could probably be made more intelligent ...)
788 if (parse->hasAggs ||
789 parse->groupClause ||
791 parse->distinctClause ||
793 has_multiple_baserels(root))
794 tuple_fraction = 0.0; /* default case */
796 tuple_fraction = root->tuple_fraction;
798 /* Generate the plan for the subquery */
799 rel->subplan = subquery_planner(root->glob, subquery,
801 false, tuple_fraction,
803 rel->subroot = subroot;
806 * It's possible that constraint exclusion proved the subquery empty.
807 * If so, it's convenient to turn it back into a dummy path so that we
808 * will recognize appropriate optimizations at this level.
810 if (is_dummy_plan(rel->subplan))
812 set_dummy_rel_pathlist(rel);
816 /* Mark rel with estimated output rows, width, etc */
817 set_subquery_size_estimates(root, rel);
819 /* Convert subquery pathkeys to outer representation */
820 pathkeys = convert_subquery_pathkeys(root, rel, subroot->query_pathkeys);
822 /* Generate appropriate path */
823 add_path(rel, create_subqueryscan_path(rel, pathkeys));
825 /* Select cheapest path (pretty easy in this case...) */
830 * set_function_pathlist
831 * Build the (single) access path for a function RTE
834 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
836 /* Mark rel with estimated output rows, width, etc */
837 set_function_size_estimates(root, rel);
839 /* Generate appropriate path */
840 add_path(rel, create_functionscan_path(root, rel));
842 /* Select cheapest path (pretty easy in this case...) */
847 * set_values_pathlist
848 * Build the (single) access path for a VALUES RTE
851 set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
853 /* Mark rel with estimated output rows, width, etc */
854 set_values_size_estimates(root, rel);
856 /* Generate appropriate path */
857 add_path(rel, create_valuesscan_path(root, rel));
859 /* Select cheapest path (pretty easy in this case...) */
865 * Build the (single) access path for a non-self-reference CTE RTE
868 set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
871 PlannerInfo *cteroot;
878 * Find the referenced CTE, and locate the plan previously made for it.
880 levelsup = rte->ctelevelsup;
882 while (levelsup-- > 0)
884 cteroot = cteroot->parent_root;
885 if (!cteroot) /* shouldn't happen */
886 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
890 * Note: cte_plan_ids can be shorter than cteList, if we are still working
891 * on planning the CTEs (ie, this is a side-reference from another CTE).
892 * So we mustn't use forboth here.
895 foreach(lc, cteroot->parse->cteList)
897 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
899 if (strcmp(cte->ctename, rte->ctename) == 0)
903 if (lc == NULL) /* shouldn't happen */
904 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
905 if (ndx >= list_length(cteroot->cte_plan_ids))
906 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
907 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
909 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
911 /* Mark rel with estimated output rows, width, etc */
912 set_cte_size_estimates(root, rel, cteplan);
914 /* Generate appropriate path */
915 add_path(rel, create_ctescan_path(root, rel));
917 /* Select cheapest path (pretty easy in this case...) */
922 * set_worktable_pathlist
923 * Build the (single) access path for a self-reference CTE RTE
926 set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
929 PlannerInfo *cteroot;
933 * We need to find the non-recursive term's plan, which is in the plan
934 * level that's processing the recursive UNION, which is one level *below*
935 * where the CTE comes from.
937 levelsup = rte->ctelevelsup;
938 if (levelsup == 0) /* shouldn't happen */
939 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
942 while (levelsup-- > 0)
944 cteroot = cteroot->parent_root;
945 if (!cteroot) /* shouldn't happen */
946 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
948 cteplan = cteroot->non_recursive_plan;
949 if (!cteplan) /* shouldn't happen */
950 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
952 /* Mark rel with estimated output rows, width, etc */
953 set_cte_size_estimates(root, rel, cteplan);
955 /* Generate appropriate path */
956 add_path(rel, create_worktablescan_path(root, rel));
958 /* Select cheapest path (pretty easy in this case...) */
963 * set_foreign_pathlist
964 * Build the (single) access path for a foreign table RTE
967 set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
969 /* Mark rel with estimated output rows, width, etc */
970 set_foreign_size_estimates(root, rel);
972 /* Generate appropriate path */
973 add_path(rel, (Path *) create_foreignscan_path(root, rel));
975 /* Select cheapest path (pretty easy in this case...) */
980 * make_rel_from_joinlist
981 * Build access paths using a "joinlist" to guide the join path search.
983 * See comments for deconstruct_jointree() for definition of the joinlist
987 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
994 * Count the number of child joinlist nodes. This is the depth of the
995 * dynamic-programming algorithm we must employ to consider all ways of
996 * joining the child nodes.
998 levels_needed = list_length(joinlist);
1000 if (levels_needed <= 0)
1001 return NULL; /* nothing to do? */
1004 * Construct a list of rels corresponding to the child joinlist nodes.
1005 * This may contain both base rels and rels constructed according to
1009 foreach(jl, joinlist)
1011 Node *jlnode = (Node *) lfirst(jl);
1012 RelOptInfo *thisrel;
1014 if (IsA(jlnode, RangeTblRef))
1016 int varno = ((RangeTblRef *) jlnode)->rtindex;
1018 thisrel = find_base_rel(root, varno);
1020 else if (IsA(jlnode, List))
1022 /* Recurse to handle subproblem */
1023 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
1027 elog(ERROR, "unrecognized joinlist node type: %d",
1028 (int) nodeTag(jlnode));
1029 thisrel = NULL; /* keep compiler quiet */
1032 initial_rels = lappend(initial_rels, thisrel);
1035 if (levels_needed == 1)
1038 * Single joinlist node, so we're done.
1040 return (RelOptInfo *) linitial(initial_rels);
1045 * Consider the different orders in which we could join the rels,
1046 * using a plugin, GEQO, or the regular join search code.
1048 * We put the initial_rels list into a PlannerInfo field because
1049 * has_legal_joinclause() needs to look at it (ugly :-().
1051 root->initial_rels = initial_rels;
1053 if (join_search_hook)
1054 return (*join_search_hook) (root, levels_needed, initial_rels);
1055 else if (enable_geqo && levels_needed >= geqo_threshold)
1056 return geqo(root, levels_needed, initial_rels);
1058 return standard_join_search(root, levels_needed, initial_rels);
1063 * standard_join_search
1064 * Find possible joinpaths for a query by successively finding ways
1065 * to join component relations into join relations.
1067 * 'levels_needed' is the number of iterations needed, ie, the number of
1068 * independent jointree items in the query. This is > 1.
1070 * 'initial_rels' is a list of RelOptInfo nodes for each independent
1071 * jointree item. These are the components to be joined together.
1072 * Note that levels_needed == list_length(initial_rels).
1074 * Returns the final level of join relations, i.e., the relation that is
1075 * the result of joining all the original relations together.
1076 * At least one implementation path must be provided for this relation and
1077 * all required sub-relations.
1079 * To support loadable plugins that modify planner behavior by changing the
1080 * join searching algorithm, we provide a hook variable that lets a plugin
1081 * replace or supplement this function. Any such hook must return the same
1082 * final join relation as the standard code would, but it might have a
1083 * different set of implementation paths attached, and only the sub-joinrels
1084 * needed for these paths need have been instantiated.
1086 * Note to plugin authors: the functions invoked during standard_join_search()
1087 * modify root->join_rel_list and root->join_rel_hash. If you want to do more
1088 * than one join-order search, you'll probably need to save and restore the
1089 * original states of those data structures. See geqo_eval() for an example.
1092 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
1098 * This function cannot be invoked recursively within any one planning
1099 * problem, so join_rel_level[] can't be in use already.
1101 Assert(root->join_rel_level == NULL);
1104 * We employ a simple "dynamic programming" algorithm: we first find all
1105 * ways to build joins of two jointree items, then all ways to build joins
1106 * of three items (from two-item joins and single items), then four-item
1107 * joins, and so on until we have considered all ways to join all the
1108 * items into one rel.
1110 * root->join_rel_level[j] is a list of all the j-item rels. Initially we
1111 * set root->join_rel_level[1] to represent all the single-jointree-item
1114 root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
1116 root->join_rel_level[1] = initial_rels;
1118 for (lev = 2; lev <= levels_needed; lev++)
1123 * Determine all possible pairs of relations to be joined at this
1124 * level, and build paths for making each one from every available
1125 * pair of lower-level relations.
1127 join_search_one_level(root, lev);
1130 * Do cleanup work on each just-processed rel.
1132 foreach(lc, root->join_rel_level[lev])
1134 rel = (RelOptInfo *) lfirst(lc);
1136 /* Find and save the cheapest paths for this rel */
1139 #ifdef OPTIMIZER_DEBUG
1140 debug_print_rel(root, rel);
1146 * We should have a single rel at the final level.
1148 if (root->join_rel_level[levels_needed] == NIL)
1149 elog(ERROR, "failed to build any %d-way joins", levels_needed);
1150 Assert(list_length(root->join_rel_level[levels_needed]) == 1);
1152 rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
1154 root->join_rel_level = NULL;
1159 /*****************************************************************************
1160 * PUSHING QUALS DOWN INTO SUBQUERIES
1161 *****************************************************************************/
1164 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
1166 * subquery is the particular component query being checked. topquery
1167 * is the top component of a set-operations tree (the same Query if no
1168 * set-op is involved).
1170 * Conditions checked here:
1172 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
1173 * since that could change the set of rows returned.
1175 * 2. If the subquery contains any window functions, we can't push quals
1176 * into it, because that could change the results.
1178 * 3. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
1179 * quals into it, because that could change the results.
1181 * 4. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
1182 * push quals into each component query, but the quals can only reference
1183 * subquery columns that suffer no type coercions in the set operation.
1184 * Otherwise there are possible semantic gotchas. So, we check the
1185 * component queries to see if any of them have different output types;
1186 * differentTypes[k] is set true if column k has different type in any
1190 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
1191 bool *differentTypes)
1193 SetOperationStmt *topop;
1196 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
1200 if (subquery->hasWindowFuncs)
1203 /* Are we at top level, or looking at a setop component? */
1204 if (subquery == topquery)
1206 /* Top level, so check any component queries */
1207 if (subquery->setOperations != NULL)
1208 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
1214 /* Setop component must not have more components (too weird) */
1215 if (subquery->setOperations != NULL)
1217 /* Check whether setop component output types match top level */
1218 topop = (SetOperationStmt *) topquery->setOperations;
1219 Assert(topop && IsA(topop, SetOperationStmt));
1220 compare_tlist_datatypes(subquery->targetList,
1228 * Helper routine to recurse through setOperations tree
1231 recurse_pushdown_safe(Node *setOp, Query *topquery,
1232 bool *differentTypes)
1234 if (IsA(setOp, RangeTblRef))
1236 RangeTblRef *rtr = (RangeTblRef *) setOp;
1237 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
1238 Query *subquery = rte->subquery;
1240 Assert(subquery != NULL);
1241 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
1243 else if (IsA(setOp, SetOperationStmt))
1245 SetOperationStmt *op = (SetOperationStmt *) setOp;
1247 /* EXCEPT is no good */
1248 if (op->op == SETOP_EXCEPT)
1251 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
1253 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
1258 elog(ERROR, "unrecognized node type: %d",
1259 (int) nodeTag(setOp));
1265 * Compare tlist's datatypes against the list of set-operation result types.
1266 * For any items that are different, mark the appropriate element of
1267 * differentTypes[] to show that this column will have type conversions.
1269 * We don't have to care about typmods here: the only allowed difference
1270 * between set-op input and output typmods is input is a specific typmod
1271 * and output is -1, and that does not require a coercion.
1274 compare_tlist_datatypes(List *tlist, List *colTypes,
1275 bool *differentTypes)
1278 ListCell *colType = list_head(colTypes);
1282 TargetEntry *tle = (TargetEntry *) lfirst(l);
1285 continue; /* ignore resjunk columns */
1286 if (colType == NULL)
1287 elog(ERROR, "wrong number of tlist entries");
1288 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
1289 differentTypes[tle->resno] = true;
1290 colType = lnext(colType);
1292 if (colType != NULL)
1293 elog(ERROR, "wrong number of tlist entries");
1297 * qual_is_pushdown_safe - is a particular qual safe to push down?
1299 * qual is a restriction clause applying to the given subquery (whose RTE
1300 * has index rti in the parent query).
1302 * Conditions checked here:
1304 * 1. The qual must not contain any subselects (mainly because I'm not sure
1305 * it will work correctly: sublinks will already have been transformed into
1306 * subplans in the qual, but not in the subquery).
1308 * 2. The qual must not refer to the whole-row output of the subquery
1309 * (since there is no easy way to name that within the subquery itself).
1311 * 3. The qual must not refer to any subquery output columns that were
1312 * found to have inconsistent types across a set operation tree by
1313 * subquery_is_pushdown_safe().
1315 * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
1316 * refer to non-DISTINCT output columns, because that could change the set
1317 * of rows returned. (This condition is vacuous for DISTINCT, because then
1318 * there are no non-DISTINCT output columns, so we needn't check. But note
1319 * we are assuming that the qual can't distinguish values that the DISTINCT
1320 * operator sees as equal. This is a bit shaky but we have no way to test
1321 * for the case, and it's unlikely enough that we shouldn't refuse the
1322 * optimization just because it could theoretically happen.)
1324 * 5. We must not push down any quals that refer to subselect outputs that
1325 * return sets, else we'd introduce functions-returning-sets into the
1326 * subquery's WHERE/HAVING quals.
1328 * 6. We must not push down any quals that refer to subselect outputs that
1329 * contain volatile functions, for fear of introducing strange results due
1330 * to multiple evaluation of a volatile function.
1333 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
1334 bool *differentTypes)
1339 Bitmapset *tested = NULL;
1341 /* Refuse subselects (point 1) */
1342 if (contain_subplans(qual))
1346 * It would be unsafe to push down window function calls, but at least for
1347 * the moment we could never see any in a qual anyhow. (The same applies
1348 * to aggregates, which we check for in pull_var_clause below.)
1350 Assert(!contain_window_function(qual));
1353 * Examine all Vars used in clause; since it's a restriction clause, all
1354 * such Vars must refer to subselect output columns.
1356 vars = pull_var_clause(qual,
1357 PVC_REJECT_AGGREGATES,
1358 PVC_INCLUDE_PLACEHOLDERS);
1361 Var *var = (Var *) lfirst(vl);
1365 * XXX Punt if we find any PlaceHolderVars in the restriction clause.
1366 * It's not clear whether a PHV could safely be pushed down, and even
1367 * less clear whether such a situation could arise in any cases of
1368 * practical interest anyway. So for the moment, just refuse to push
1377 Assert(var->varno == rti);
1380 if (var->varattno == 0)
1387 * We use a bitmapset to avoid testing the same attno more than once.
1388 * (NB: this only works because subquery outputs can't have negative
1391 if (bms_is_member(var->varattno, tested))
1393 tested = bms_add_member(tested, var->varattno);
1396 if (differentTypes[var->varattno])
1402 /* Must find the tlist element referenced by the Var */
1403 tle = get_tle_by_resno(subquery->targetList, var->varattno);
1404 Assert(tle != NULL);
1405 Assert(!tle->resjunk);
1407 /* If subquery uses DISTINCT ON, check point 4 */
1408 if (subquery->hasDistinctOn &&
1409 !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
1411 /* non-DISTINCT column, so fail */
1416 /* Refuse functions returning sets (point 5) */
1417 if (expression_returns_set((Node *) tle->expr))
1423 /* Refuse volatile functions (point 6) */
1424 if (contain_volatile_functions((Node *) tle->expr))
1438 * subquery_push_qual - push down a qual that we have determined is safe
1441 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
1443 if (subquery->setOperations != NULL)
1445 /* Recurse to push it separately to each component query */
1446 recurse_push_qual(subquery->setOperations, subquery,
1452 * We need to replace Vars in the qual (which must refer to outputs of
1453 * the subquery) with copies of the subquery's targetlist expressions.
1454 * Note that at this point, any uplevel Vars in the qual should have
1455 * been replaced with Params, so they need no work.
1457 * This step also ensures that when we are pushing into a setop tree,
1458 * each component query gets its own copy of the qual.
1460 qual = ResolveNew(qual, rti, 0, rte,
1461 subquery->targetList,
1463 &subquery->hasSubLinks);
1466 * Now attach the qual to the proper place: normally WHERE, but if the
1467 * subquery uses grouping or aggregation, put it in HAVING (since the
1468 * qual really refers to the group-result rows).
1470 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
1471 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
1473 subquery->jointree->quals =
1474 make_and_qual(subquery->jointree->quals, qual);
1477 * We need not change the subquery's hasAggs or hasSublinks flags,
1478 * since we can't be pushing down any aggregates that weren't there
1479 * before, and we don't push down subselects at all.
1485 * Helper routine to recurse through setOperations tree
1488 recurse_push_qual(Node *setOp, Query *topquery,
1489 RangeTblEntry *rte, Index rti, Node *qual)
1491 if (IsA(setOp, RangeTblRef))
1493 RangeTblRef *rtr = (RangeTblRef *) setOp;
1494 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
1495 Query *subquery = subrte->subquery;
1497 Assert(subquery != NULL);
1498 subquery_push_qual(subquery, rte, rti, qual);
1500 else if (IsA(setOp, SetOperationStmt))
1502 SetOperationStmt *op = (SetOperationStmt *) setOp;
1504 recurse_push_qual(op->larg, topquery, rte, rti, qual);
1505 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
1509 elog(ERROR, "unrecognized node type: %d",
1510 (int) nodeTag(setOp));
1514 /*****************************************************************************
1516 *****************************************************************************/
1518 #ifdef OPTIMIZER_DEBUG
1521 print_relids(Relids relids)
1527 tmprelids = bms_copy(relids);
1528 while ((x = bms_first_member(tmprelids)) >= 0)
1535 bms_free(tmprelids);
1539 print_restrictclauses(PlannerInfo *root, List *clauses)
1545 RestrictInfo *c = lfirst(l);
1547 print_expr((Node *) c->clause, root->parse->rtable);
1554 print_path(PlannerInfo *root, Path *path, int indent)
1558 Path *subpath = NULL;
1561 switch (nodeTag(path))
1569 case T_BitmapHeapPath:
1570 ptype = "BitmapHeapScan";
1572 case T_BitmapAndPath:
1573 ptype = "BitmapAndPath";
1575 case T_BitmapOrPath:
1576 ptype = "BitmapOrPath";
1582 ptype = "ForeignScan";
1587 case T_MergeAppendPath:
1588 ptype = "MergeAppend";
1593 case T_MaterialPath:
1595 subpath = ((MaterialPath *) path)->subpath;
1599 subpath = ((UniquePath *) path)->subpath;
1606 ptype = "MergeJoin";
1618 for (i = 0; i < indent; i++)
1620 printf("%s", ptype);
1625 print_relids(path->parent->relids);
1626 printf(") rows=%.0f", path->parent->rows);
1628 printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
1632 for (i = 0; i < indent; i++)
1634 printf(" pathkeys: ");
1635 print_pathkeys(path->pathkeys, root->parse->rtable);
1640 JoinPath *jp = (JoinPath *) path;
1642 for (i = 0; i < indent; i++)
1644 printf(" clauses: ");
1645 print_restrictclauses(root, jp->joinrestrictinfo);
1648 if (IsA(path, MergePath))
1650 MergePath *mp = (MergePath *) path;
1652 for (i = 0; i < indent; i++)
1654 printf(" sortouter=%d sortinner=%d materializeinner=%d\n",
1655 ((mp->outersortkeys) ? 1 : 0),
1656 ((mp->innersortkeys) ? 1 : 0),
1657 ((mp->materialize_inner) ? 1 : 0));
1660 print_path(root, jp->outerjoinpath, indent + 1);
1661 print_path(root, jp->innerjoinpath, indent + 1);
1665 print_path(root, subpath, indent + 1);
1669 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
1673 printf("RELOPTINFO (");
1674 print_relids(rel->relids);
1675 printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
1677 if (rel->baserestrictinfo)
1679 printf("\tbaserestrictinfo: ");
1680 print_restrictclauses(root, rel->baserestrictinfo);
1686 printf("\tjoininfo: ");
1687 print_restrictclauses(root, rel->joininfo);
1691 printf("\tpath list:\n");
1692 foreach(l, rel->pathlist)
1693 print_path(root, lfirst(l), 1);
1694 printf("\n\tcheapest startup path:\n");
1695 print_path(root, rel->cheapest_startup_path, 1);
1696 printf("\n\tcheapest total path:\n");
1697 print_path(root, rel->cheapest_total_path, 1);
1702 #endif /* OPTIMIZER_DEBUG */