1 /*-------------------------------------------------------------------------
4 * Routines copied from PostgreSQL core distribution.
6 * src/backend/optimizer/path/allpaths.c
7 * standard_join_search()
8 * set_plain_rel_pathlist()
9 * set_append_rel_pathlist()
10 * accumulate_append_subpath()
11 * set_dummy_rel_pathlist()
13 * src/backend/optimizer/path/joinrels.c:
14 * join_search_one_level()
15 * make_rels_by_clause_joins()
16 * make_rels_by_clauseless_joins()
18 * has_join_restriction()
21 * restriction_is_constant_false()
23 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
24 * Portions Copyright (c) 1994, Regents of the University of California
26 *-------------------------------------------------------------------------
30 * standard_join_search
31 * Find possible joinpaths for a query by successively finding ways
32 * to join component relations into join relations.
34 * 'levels_needed' is the number of iterations needed, ie, the number of
35 * independent jointree items in the query. This is > 1.
37 * 'initial_rels' is a list of RelOptInfo nodes for each independent
38 * jointree item. These are the components to be joined together.
39 * Note that levels_needed == list_length(initial_rels).
41 * Returns the final level of join relations, i.e., the relation that is
42 * the result of joining all the original relations together.
43 * At least one implementation path must be provided for this relation and
44 * all required sub-relations.
46 * To support loadable plugins that modify planner behavior by changing the
47 * join searching algorithm, we provide a hook variable that lets a plugin
48 * replace or supplement this function. Any such hook must return the same
49 * final join relation as the standard code would, but it might have a
50 * different set of implementation paths attached, and only the sub-joinrels
51 * needed for these paths need have been instantiated.
53 * Note to plugin authors: the functions invoked during standard_join_search()
54 * modify root->join_rel_list and root->join_rel_hash. If you want to do more
55 * than one join-order search, you'll probably need to save and restore the
56 * original states of those data structures. See geqo_eval() for an example.
59 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
65 * This function cannot be invoked recursively within any one planning
66 * problem, so join_rel_level[] can't be in use already.
68 Assert(root->join_rel_level == NULL);
71 * We employ a simple "dynamic programming" algorithm: we first find all
72 * ways to build joins of two jointree items, then all ways to build joins
73 * of three items (from two-item joins and single items), then four-item
74 * joins, and so on until we have considered all ways to join all the
77 * root->join_rel_level[j] is a list of all the j-item rels. Initially we
78 * set root->join_rel_level[1] to represent all the single-jointree-item
81 root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
83 root->join_rel_level[1] = initial_rels;
85 for (lev = 2; lev <= levels_needed; lev++)
90 * Determine all possible pairs of relations to be joined at this
91 * level, and build paths for making each one from every available
92 * pair of lower-level relations.
94 join_search_one_level(root, lev);
97 * Do cleanup work on each just-processed rel.
99 foreach(lc, root->join_rel_level[lev])
101 rel = (RelOptInfo *) lfirst(lc);
103 /* Find and save the cheapest paths for this rel */
106 #ifdef OPTIMIZER_DEBUG
107 debug_print_rel(root, rel);
113 * We should have a single rel at the final level.
115 if (root->join_rel_level[levels_needed] == NIL)
116 elog(ERROR, "failed to build any %d-way joins", levels_needed);
117 Assert(list_length(root->join_rel_level[levels_needed]) == 1);
119 rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
121 root->join_rel_level = NULL;
127 * set_plain_rel_pathlist
128 * Build access paths for a plain relation (no subquery, no inheritance)
131 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
133 /* Consider sequential scan */
134 add_path(rel, create_seqscan_path(root, rel));
136 /* Consider index scans */
137 create_index_paths(root, rel);
139 /* Consider TID scans */
140 create_tidscan_paths(root, rel);
142 /* Now find the cheapest of the paths for this rel */
147 * set_append_rel_pathlist
148 * Build access paths for an "append relation"
150 * The passed-in rel and RTE represent the entire append relation. The
151 * relation's contents are computed by appending together the output of
152 * the individual member relations. Note that in the inheritance case,
153 * the first member relation is actually the same table as is mentioned in
154 * the parent RTE ... but it has a different RTE and RelOptInfo. This is
155 * a good thing because their outputs are not the same size.
158 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
159 Index rti, RangeTblEntry *rte)
161 int parentRTindex = rti;
162 List *live_childrels = NIL;
163 List *subpaths = NIL;
164 List *all_child_pathkeys = NIL;
167 double *parent_attrsizes;
172 * Initialize to compute size estimates for whole append relation.
174 * We handle width estimates by weighting the widths of different child
175 * rels proportionally to their number of rows. This is sensible because
176 * the use of width estimates is mainly to compute the total relation
177 * "footprint" if we have to sort or hash it. To do this, we sum the
178 * total equivalent size (in "double" arithmetic) and then divide by the
179 * total rowcount estimate. This is done separately for the total rel
180 * width and each attribute.
182 * Note: if you consider changing this logic, beware that child rels could
183 * have zero rows and/or width, if they were excluded by constraints.
187 nattrs = rel->max_attr - rel->min_attr + 1;
188 parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
191 * Generate access paths for each member relation, and pick the cheapest
194 foreach(l, root->append_rel_list)
196 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
198 RangeTblEntry *childRTE;
199 RelOptInfo *childrel;
203 ListCell *parentvars;
206 /* append_rel_list contains all append rels; ignore others */
207 if (appinfo->parent_relid != parentRTindex)
210 childRTindex = appinfo->child_relid;
211 childRTE = root->simple_rte_array[childRTindex];
214 * The child rel's RelOptInfo was already created during
215 * add_base_rels_to_query.
217 childrel = find_base_rel(root, childRTindex);
218 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
221 * We have to copy the parent's targetlist and quals to the child,
222 * with appropriate substitution of variables. However, only the
223 * baserestrictinfo quals are needed before we can check for
224 * constraint exclusion; so do that first and then check to see if we
225 * can disregard this child.
227 * As of 8.4, the child rel's targetlist might contain non-Var
228 * expressions, which means that substitution into the quals could
229 * produce opportunities for const-simplification, and perhaps even
230 * pseudoconstant quals. To deal with this, we strip the RestrictInfo
231 * nodes, do the substitution, do const-simplification, and then
232 * reconstitute the RestrictInfo layer.
234 childquals = get_all_actual_clauses(rel->baserestrictinfo);
235 childquals = (List *) adjust_appendrel_attrs((Node *) childquals,
237 childqual = eval_const_expressions(root, (Node *)
238 make_ands_explicit(childquals));
239 if (childqual && IsA(childqual, Const) &&
240 (((Const *) childqual)->constisnull ||
241 !DatumGetBool(((Const *) childqual)->constvalue)))
244 * Restriction reduces to constant FALSE or constant NULL after
245 * substitution, so this child need not be scanned.
247 set_dummy_rel_pathlist(childrel);
250 childquals = make_ands_implicit((Expr *) childqual);
251 childquals = make_restrictinfos_from_actual_clauses(root,
253 childrel->baserestrictinfo = childquals;
255 if (relation_excluded_by_constraints(root, childrel, childRTE))
258 * This child need not be scanned, so we can omit it from the
259 * appendrel. Mark it with a dummy cheapest-path though, in case
260 * best_appendrel_indexscan() looks at it later.
262 set_dummy_rel_pathlist(childrel);
267 * CE failed, so finish copying/modifying targetlist and join quals.
269 * Note: the resulting childrel->reltargetlist may contain arbitrary
270 * expressions, which normally would not occur in a reltargetlist.
271 * That is okay because nothing outside of this routine will look at
272 * the child rel's reltargetlist. We do have to cope with the case
273 * while constructing attr_widths estimates below, though.
275 childrel->joininfo = (List *)
276 adjust_appendrel_attrs((Node *) rel->joininfo,
278 childrel->reltargetlist = (List *)
279 adjust_appendrel_attrs((Node *) rel->reltargetlist,
283 * We have to make child entries in the EquivalenceClass data
284 * structures as well. This is needed either if the parent
285 * participates in some eclass joins (because we will want to consider
286 * inner-indexscan joins on the individual children) or if the parent
287 * has useful pathkeys (because we should try to build MergeAppend
288 * paths that produce those sort orderings).
290 if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
291 add_child_rel_equivalences(root, appinfo, rel, childrel);
292 childrel->has_eclass_joins = rel->has_eclass_joins;
295 * Note: we could compute appropriate attr_needed data for the child's
296 * variables, by transforming the parent's attr_needed through the
297 * translated_vars mapping. However, currently there's no need
298 * because attr_needed is only examined for base relations not
299 * otherrels. So we just leave the child's attr_needed empty.
302 /* Remember which childrels are live, for MergeAppend logic below */
303 live_childrels = lappend(live_childrels, childrel);
306 * Compute the child's access paths, and add the cheapest one to the
307 * Append path we are constructing for the parent.
309 set_rel_pathlist(root, childrel, childRTindex, childRTE);
311 subpaths = accumulate_append_subpath(subpaths,
312 childrel->cheapest_total_path);
315 * Collect a list of all the available path orderings for all the
316 * children. We use this as a heuristic to indicate which sort
317 * orderings we should build MergeAppend paths for.
319 foreach(lcp, childrel->pathlist)
321 Path *childpath = (Path *) lfirst(lcp);
322 List *childkeys = childpath->pathkeys;
326 /* Ignore unsorted paths */
327 if (childkeys == NIL)
330 /* Have we already seen this ordering? */
331 foreach(lpk, all_child_pathkeys)
333 List *existing_pathkeys = (List *) lfirst(lpk);
335 if (compare_pathkeys(existing_pathkeys,
336 childkeys) == PATHKEYS_EQUAL)
344 /* No, so add it to all_child_pathkeys */
345 all_child_pathkeys = lappend(all_child_pathkeys, childkeys);
350 * Accumulate size information from each child.
352 if (childrel->rows > 0)
354 parent_rows += childrel->rows;
355 parent_size += childrel->width * childrel->rows;
358 * Accumulate per-column estimates too. We need not do anything
359 * for PlaceHolderVars in the parent list. If child expression
360 * isn't a Var, or we didn't record a width estimate for it, we
361 * have to fall back on a datatype-based estimate.
363 * By construction, child's reltargetlist is 1-to-1 with parent's.
365 forboth(parentvars, rel->reltargetlist,
366 childvars, childrel->reltargetlist)
368 Var *parentvar = (Var *) lfirst(parentvars);
369 Node *childvar = (Node *) lfirst(childvars);
371 if (IsA(parentvar, Var))
373 int pndx = parentvar->varattno - rel->min_attr;
374 int32 child_width = 0;
376 if (IsA(childvar, Var))
378 int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
380 child_width = childrel->attr_widths[cndx];
382 if (child_width <= 0)
383 child_width = get_typavgwidth(exprType(childvar),
384 exprTypmod(childvar));
385 Assert(child_width > 0);
386 parent_attrsizes[pndx] += child_width * childrel->rows;
393 * Save the finished size estimates.
395 rel->rows = parent_rows;
400 rel->width = rint(parent_size / parent_rows);
401 for (i = 0; i < nattrs; i++)
402 rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
405 rel->width = 0; /* attr_widths should be zero already */
408 * Set "raw tuples" count equal to "rows" for the appendrel; needed
409 * because some places assume rel->tuples is valid for any baserel.
411 rel->tuples = parent_rows;
413 pfree(parent_attrsizes);
416 * Next, build an unordered Append path for the rel. (Note: this is
417 * correct even if we have zero or one live subpath due to constraint
420 add_path(rel, (Path *) create_append_path(rel, subpaths));
423 * Next, build MergeAppend paths based on the collected list of child
424 * pathkeys. We consider both cheapest-startup and cheapest-total cases,
425 * ie, for each interesting ordering, collect all the cheapest startup
426 * subpaths and all the cheapest total paths, and build a MergeAppend path
429 foreach(l, all_child_pathkeys)
431 List *pathkeys = (List *) lfirst(l);
432 List *startup_subpaths = NIL;
433 List *total_subpaths = NIL;
434 bool startup_neq_total = false;
437 /* Select the child paths for this ordering... */
438 foreach(lcr, live_childrels)
440 RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
441 Path *cheapest_startup,
444 /* Locate the right paths, if they are available. */
446 get_cheapest_path_for_pathkeys(childrel->pathlist,
450 get_cheapest_path_for_pathkeys(childrel->pathlist,
455 * If we can't find any paths with the right order just add the
456 * cheapest-total path; we'll have to sort it.
458 if (cheapest_startup == NULL)
459 cheapest_startup = childrel->cheapest_total_path;
460 if (cheapest_total == NULL)
461 cheapest_total = childrel->cheapest_total_path;
464 * Notice whether we actually have different paths for the
465 * "cheapest" and "total" cases; frequently there will be no point
466 * in two create_merge_append_path() calls.
468 if (cheapest_startup != cheapest_total)
469 startup_neq_total = true;
472 accumulate_append_subpath(startup_subpaths, cheapest_startup);
474 accumulate_append_subpath(total_subpaths, cheapest_total);
477 /* ... and build the MergeAppend paths */
478 add_path(rel, (Path *) create_merge_append_path(root,
482 if (startup_neq_total)
483 add_path(rel, (Path *) create_merge_append_path(root,
489 /* Select cheapest path */
494 * accumulate_append_subpath
495 * Add a subpath to the list being built for an Append or MergeAppend
497 * It's possible that the child is itself an Append path, in which case
498 * we can "cut out the middleman" and just add its child paths to our
499 * own list. (We don't try to do this earlier because we need to
500 * apply both levels of transformation to the quals.)
503 accumulate_append_subpath(List *subpaths, Path *path)
505 if (IsA(path, AppendPath))
507 AppendPath *apath = (AppendPath *) path;
509 /* list_copy is important here to avoid sharing list substructure */
510 return list_concat(subpaths, list_copy(apath->subpaths));
513 return lappend(subpaths, path);
517 * set_dummy_rel_pathlist
518 * Build a dummy path for a relation that's been excluded by constraints
520 * Rather than inventing a special "dummy" path type, we represent this as an
521 * AppendPath with no members (see also IS_DUMMY_PATH macro).
524 set_dummy_rel_pathlist(RelOptInfo *rel)
526 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
530 add_path(rel, (Path *) create_append_path(rel, NIL));
532 /* Select cheapest path (pretty easy in this case...) */
537 * join_search_one_level
538 * Consider ways to produce join relations containing exactly 'level'
539 * jointree items. (This is one step of the dynamic-programming method
540 * embodied in standard_join_search.) Join rel nodes for each feasible
541 * combination of lower-level rels are created and returned in a list.
542 * Implementation paths are created for each such joinrel, too.
544 * level: level of rels we want to make this time
545 * root->join_rel_level[j], 1 <= j < level, is a list of rels containing j items
547 * The result is returned in root->join_rel_level[level].
550 join_search_one_level(PlannerInfo *root, int level)
552 List **joinrels = root->join_rel_level;
556 Assert(joinrels[level] == NIL);
558 /* Set join_cur_level so that new joinrels are added to proper list */
559 root->join_cur_level = level;
562 * First, consider left-sided and right-sided plans, in which rels of
563 * exactly level-1 member relations are joined against initial relations.
564 * We prefer to join using join clauses, but if we find a rel of level-1
565 * members that has no join clauses, we will generate Cartesian-product
566 * joins against all initial rels not already contained in it.
568 * In the first pass (level == 2), we try to join each initial rel to each
569 * initial rel that appears later in joinrels[1]. (The mirror-image joins
570 * are handled automatically by make_join_rel.) In later passes, we try
571 * to join rels of size level-1 from joinrels[level-1] to each initial rel
574 foreach(r, joinrels[level - 1])
576 RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
577 ListCell *other_rels;
580 other_rels = lnext(r); /* only consider remaining initial
583 other_rels = list_head(joinrels[1]); /* consider all initial
586 if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
587 has_join_restriction(root, old_rel))
590 * Note that if all available join clauses for this rel require
591 * more than one other rel, we will fail to make any joins against
592 * it here. In most cases that's OK; it'll be considered by
593 * "bushy plan" join code in a higher-level pass where we have
594 * those other rels collected into a join rel.
596 * See also the last-ditch case below.
598 make_rels_by_clause_joins(root,
605 * Oops, we have a relation that is not joined to any other
606 * relation, either directly or by join-order restrictions.
607 * Cartesian product time.
609 make_rels_by_clauseless_joins(root,
616 * Now, consider "bushy plans" in which relations of k initial rels are
617 * joined to relations of level-k initial rels, for 2 <= k <= level-2.
619 * We only consider bushy-plan joins for pairs of rels where there is a
620 * suitable join clause (or join order restriction), in order to avoid
621 * unreasonable growth of planning time.
625 int other_level = level - k;
628 * Since make_join_rel(x, y) handles both x,y and y,x cases, we only
629 * need to go as far as the halfway point.
634 foreach(r, joinrels[k])
636 RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
637 ListCell *other_rels;
641 * We can ignore clauseless joins here, *except* when they
642 * participate in join-order restrictions --- then we might have
643 * to force a bushy join plan.
645 if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
646 !has_join_restriction(root, old_rel))
649 if (k == other_level)
650 other_rels = lnext(r); /* only consider remaining rels */
652 other_rels = list_head(joinrels[other_level]);
654 for_each_cell(r2, other_rels)
656 RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
658 if (!bms_overlap(old_rel->relids, new_rel->relids))
661 * OK, we can build a rel of the right level from this
662 * pair of rels. Do so if there is at least one usable
663 * join clause or a relevant join restriction.
665 if (have_relevant_joinclause(root, old_rel, new_rel) ||
666 have_join_order_restriction(root, old_rel, new_rel))
668 (void) make_join_rel(root, old_rel, new_rel);
676 * Last-ditch effort: if we failed to find any usable joins so far, force
677 * a set of cartesian-product joins to be generated. This handles the
678 * special case where all the available rels have join clauses but we
679 * cannot use any of those clauses yet. An example is
681 * SELECT * FROM a,b,c WHERE (a.f1 + b.f2 + c.f3) = 0;
683 * The join clause will be usable at level 3, but at level 2 we have no
684 * choice but to make cartesian joins. We consider only left-sided and
685 * right-sided cartesian joins in this case (no bushy).
687 if (joinrels[level] == NIL)
690 * This loop is just like the first one, except we always call
691 * make_rels_by_clauseless_joins().
693 foreach(r, joinrels[level - 1])
695 RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
696 ListCell *other_rels;
699 other_rels = lnext(r); /* only consider remaining initial
702 other_rels = list_head(joinrels[1]); /* consider all initial
705 make_rels_by_clauseless_joins(root,
711 * When special joins are involved, there may be no legal way
712 * to make an N-way join for some values of N. For example consider
714 * SELECT ... FROM t1 WHERE
715 * x IN (SELECT ... FROM t2,t3 WHERE ...) AND
716 * y IN (SELECT ... FROM t4,t5 WHERE ...)
718 * We will flatten this query to a 5-way join problem, but there are
719 * no 4-way joins that join_is_legal() will consider legal. We have
720 * to accept failure at level 4 and go on to discover a workable
721 * bushy plan at level 5.
723 * However, if there are no special joins then join_is_legal() should
724 * never fail, and so the following sanity check is useful.
727 if (joinrels[level] == NIL && root->join_info_list == NIL)
728 elog(ERROR, "failed to build any %d-way joins", level);
733 * make_rels_by_clause_joins
734 * Build joins between the given relation 'old_rel' and other relations
735 * that participate in join clauses that 'old_rel' also participates in
736 * (or participate in join-order restrictions with it).
737 * The join rels are returned in root->join_rel_level[join_cur_level].
739 * Note: at levels above 2 we will generate the same joined relation in
740 * multiple ways --- for example (a join b) join c is the same RelOptInfo as
741 * (b join c) join a, though the second case will add a different set of Paths
742 * to it. This is the reason for using the join_rel_level mechanism, which
743 * automatically ensures that each new joinrel is only added to the list once.
745 * 'old_rel' is the relation entry for the relation to be joined
746 * 'other_rels': the first cell in a linked list containing the other
747 * rels to be considered for joining
749 * Currently, this is only used with initial rels in other_rels, but it
750 * will work for joining to joinrels too.
753 make_rels_by_clause_joins(PlannerInfo *root,
755 ListCell *other_rels)
759 for_each_cell(l, other_rels)
761 RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
763 if (!bms_overlap(old_rel->relids, other_rel->relids) &&
764 (have_relevant_joinclause(root, old_rel, other_rel) ||
765 have_join_order_restriction(root, old_rel, other_rel)))
767 (void) make_join_rel(root, old_rel, other_rel);
773 * make_rels_by_clauseless_joins
774 * Given a relation 'old_rel' and a list of other relations
775 * 'other_rels', create a join relation between 'old_rel' and each
776 * member of 'other_rels' that isn't already included in 'old_rel'.
777 * The join rels are returned in root->join_rel_level[join_cur_level].
779 * 'old_rel' is the relation entry for the relation to be joined
780 * 'other_rels': the first cell of a linked list containing the
781 * other rels to be considered for joining
783 * Currently, this is only used with initial rels in other_rels, but it would
784 * work for joining to joinrels too.
787 make_rels_by_clauseless_joins(PlannerInfo *root,
789 ListCell *other_rels)
793 for_each_cell(l, other_rels)
795 RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
797 if (!bms_overlap(other_rel->relids, old_rel->relids))
799 (void) make_join_rel(root, old_rel, other_rel);
806 * Determine whether a proposed join is legal given the query's
807 * join order constraints; and if it is, determine the join type.
809 * Caller must supply not only the two rels, but the union of their relids.
810 * (We could simplify the API by computing joinrelids locally, but this
811 * would be redundant work in the normal path through make_join_rel.)
813 * On success, *sjinfo_p is set to NULL if this is to be a plain inner join,
814 * else it's set to point to the associated SpecialJoinInfo node. Also,
815 * *reversed_p is set TRUE if the given relations need to be swapped to
816 * match the SpecialJoinInfo node.
819 join_is_legal(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
821 SpecialJoinInfo **sjinfo_p, bool *reversed_p)
823 SpecialJoinInfo *match_sjinfo;
830 * Ensure output params are set on failure return. This is just to
831 * suppress uninitialized-variable warnings from overly anal compilers.
837 * If we have any special joins, the proposed join might be illegal; and
838 * in any case we have to determine its join type. Scan the join info
839 * list for conflicts.
843 unique_ified = false;
844 is_valid_inner = true;
846 foreach(l, root->join_info_list)
848 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
851 * This special join is not relevant unless its RHS overlaps the
852 * proposed join. (Check this first as a fast path for dismissing
853 * most irrelevant SJs quickly.)
855 if (!bms_overlap(sjinfo->min_righthand, joinrelids))
859 * Also, not relevant if proposed join is fully contained within RHS
860 * (ie, we're still building up the RHS).
862 if (bms_is_subset(joinrelids, sjinfo->min_righthand))
866 * Also, not relevant if SJ is already done within either input.
868 if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
869 bms_is_subset(sjinfo->min_righthand, rel1->relids))
871 if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
872 bms_is_subset(sjinfo->min_righthand, rel2->relids))
876 * If it's a semijoin and we already joined the RHS to any other rels
877 * within either input, then we must have unique-ified the RHS at that
878 * point (see below). Therefore the semijoin is no longer relevant in
881 if (sjinfo->jointype == JOIN_SEMI)
883 if (bms_is_subset(sjinfo->syn_righthand, rel1->relids) &&
884 !bms_equal(sjinfo->syn_righthand, rel1->relids))
886 if (bms_is_subset(sjinfo->syn_righthand, rel2->relids) &&
887 !bms_equal(sjinfo->syn_righthand, rel2->relids))
892 * If one input contains min_lefthand and the other contains
893 * min_righthand, then we can perform the SJ at this join.
895 * Barf if we get matches to more than one SJ (is that possible?)
897 if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
898 bms_is_subset(sjinfo->min_righthand, rel2->relids))
901 return false; /* invalid join path */
902 match_sjinfo = sjinfo;
905 else if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
906 bms_is_subset(sjinfo->min_righthand, rel1->relids))
909 return false; /* invalid join path */
910 match_sjinfo = sjinfo;
913 else if (sjinfo->jointype == JOIN_SEMI &&
914 bms_equal(sjinfo->syn_righthand, rel2->relids) &&
915 create_unique_path(root, rel2, rel2->cheapest_total_path,
919 * For a semijoin, we can join the RHS to anything else by
920 * unique-ifying the RHS (if the RHS can be unique-ified).
921 * We will only get here if we have the full RHS but less
922 * than min_lefthand on the LHS.
924 * The reason to consider such a join path is exemplified by
925 * SELECT ... FROM a,b WHERE (a.x,b.y) IN (SELECT c1,c2 FROM c)
926 * If we insist on doing this as a semijoin we will first have
927 * to form the cartesian product of A*B. But if we unique-ify
928 * C then the semijoin becomes a plain innerjoin and we can join
929 * in any order, eg C to A and then to B. When C is much smaller
930 * than A and B this can be a huge win. So we allow C to be
931 * joined to just A or just B here, and then make_join_rel has
932 * to handle the case properly.
934 * Note that actually we'll allow unique-ified C to be joined to
935 * some other relation D here, too. That is legal, if usually not
936 * very sane, and this routine is only concerned with legality not
937 * with whether the join is good strategy.
941 return false; /* invalid join path */
942 match_sjinfo = sjinfo;
946 else if (sjinfo->jointype == JOIN_SEMI &&
947 bms_equal(sjinfo->syn_righthand, rel1->relids) &&
948 create_unique_path(root, rel1, rel1->cheapest_total_path,
951 /* Reversed semijoin case */
953 return false; /* invalid join path */
954 match_sjinfo = sjinfo;
961 * Otherwise, the proposed join overlaps the RHS but isn't
962 * a valid implementation of this SJ. It might still be
963 * a legal join, however. If both inputs overlap the RHS,
964 * assume that it's OK. Since the inputs presumably got past
965 * this function's checks previously, they can't overlap the
966 * LHS and their violations of the RHS boundary must represent
967 * SJs that have been determined to commute with this one.
968 * We have to allow this to work correctly in cases like
969 * (a LEFT JOIN (b JOIN (c LEFT JOIN d)))
970 * when the c/d join has been determined to commute with the join
971 * to a, and hence d is not part of min_righthand for the upper
972 * join. It should be legal to join b to c/d but this will appear
973 * as a violation of the upper join's RHS.
974 * Furthermore, if one input overlaps the RHS and the other does
975 * not, we should still allow the join if it is a valid
976 * implementation of some other SJ. We have to allow this to
977 * support the associative identity
978 * (a LJ b on Pab) LJ c ON Pbc = a LJ (b LJ c ON Pbc) on Pab
979 * since joining B directly to C violates the lower SJ's RHS.
980 * We assume that make_outerjoininfo() set things up correctly
981 * so that we'll only match to some SJ if the join is valid.
982 * Set flag here to check at bottom of loop.
985 if (sjinfo->jointype != JOIN_SEMI &&
986 bms_overlap(rel1->relids, sjinfo->min_righthand) &&
987 bms_overlap(rel2->relids, sjinfo->min_righthand))
990 Assert(!bms_overlap(joinrelids, sjinfo->min_lefthand));
993 is_valid_inner = false;
998 * Fail if violated some SJ's RHS and didn't match to another SJ. However,
999 * "matching" to a semijoin we are implementing by unique-ification
1000 * doesn't count (think: it's really an inner join).
1002 if (!is_valid_inner &&
1003 (match_sjinfo == NULL || unique_ified))
1004 return false; /* invalid join path */
1006 /* Otherwise, it's a valid join */
1007 *sjinfo_p = match_sjinfo;
1008 *reversed_p = reversed;
1013 * has_join_restriction
1014 * Detect whether the specified relation has join-order restrictions
1015 * due to being inside an outer join or an IN (sub-SELECT).
1017 * Essentially, this tests whether have_join_order_restriction() could
1018 * succeed with this rel and some other one. It's OK if we sometimes
1019 * say "true" incorrectly. (Therefore, we don't bother with the relatively
1020 * expensive has_legal_joinclause test.)
1023 has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
1027 foreach(l, root->join_info_list)
1029 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
1031 /* ignore full joins --- other mechanisms preserve their ordering */
1032 if (sjinfo->jointype == JOIN_FULL)
1035 /* ignore if SJ is already contained in rel */
1036 if (bms_is_subset(sjinfo->min_lefthand, rel->relids) &&
1037 bms_is_subset(sjinfo->min_righthand, rel->relids))
1040 /* restricted if it overlaps LHS or RHS, but doesn't contain SJ */
1041 if (bms_overlap(sjinfo->min_lefthand, rel->relids) ||
1042 bms_overlap(sjinfo->min_righthand, rel->relids))
1050 * is_dummy_rel --- has relation been proven empty?
1052 * If so, it will have a single path that is dummy.
1055 is_dummy_rel(RelOptInfo *rel)
1057 return (rel->cheapest_total_path != NULL &&
1058 IS_DUMMY_PATH(rel->cheapest_total_path));
1062 * Mark a relation as proven empty.
1064 * During GEQO planning, this can get invoked more than once on the same
1065 * baserel struct, so it's worth checking to see if the rel is already marked
1068 * Also, when called during GEQO join planning, we are in a short-lived
1069 * memory context. We must make sure that the dummy path attached to a
1070 * baserel survives the GEQO cycle, else the baserel is trashed for future
1071 * GEQO cycles. On the other hand, when we are marking a joinrel during GEQO,
1072 * we don't want the dummy path to clutter the main planning context. Upshot
1073 * is that the best solution is to explicitly make the dummy path in the same
1074 * context the given RelOptInfo is in.
1077 mark_dummy_rel(RelOptInfo *rel)
1079 MemoryContext oldcontext;
1081 /* Already marked? */
1082 if (is_dummy_rel(rel))
1085 /* No, so choose correct context to make the dummy path in */
1086 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1088 /* Set dummy size estimate */
1091 /* Evict any previously chosen paths */
1092 rel->pathlist = NIL;
1094 /* Set up the dummy path */
1095 add_path(rel, (Path *) create_append_path(rel, NIL));
1097 /* Set or update cheapest_total_path */
1100 MemoryContextSwitchTo(oldcontext);
1104 * restriction_is_constant_false --- is a restrictlist just FALSE?
1106 * In cases where a qual is provably constant FALSE, eval_const_expressions
1107 * will generally have thrown away anything that's ANDed with it. In outer
1108 * join situations this will leave us computing cartesian products only to
1109 * decide there's no match for an outer row, which is pretty stupid. So,
1110 * we need to detect the case.
1112 * If only_pushed_down is TRUE, then consider only pushed-down quals.
1115 restriction_is_constant_false(List *restrictlist, bool only_pushed_down)
1120 * Despite the above comment, the restriction list we see here might
1121 * possibly have other members besides the FALSE constant, since other
1122 * quals could get "pushed down" to the outer join level. So we check
1123 * each member of the list.
1125 foreach(lc, restrictlist)
1127 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1129 Assert(IsA(rinfo, RestrictInfo));
1130 if (only_pushed_down && !rinfo->is_pushed_down)
1133 if (rinfo->clause && IsA(rinfo->clause, Const))
1135 Const *con = (Const *) rinfo->clause;
1137 /* constant NULL is as good as constant FALSE for our purposes */
1138 if (con->constisnull)
1140 if (!DatumGetBool(con->constvalue))