1 /*-------------------------------------------------------------------------
4 * Routines for managing EquivalenceClasses
6 * See src/backend/optimizer/README for discussion of EquivalenceClasses.
9 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/backend/optimizer/path/equivclass.c,v 1.11 2008/08/02 21:31:59 tgl Exp $
15 *-------------------------------------------------------------------------
19 #include "access/skey.h"
20 #include "optimizer/clauses.h"
21 #include "optimizer/cost.h"
22 #include "optimizer/paths.h"
23 #include "optimizer/planmain.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/var.h"
26 #include "utils/lsyscache.h"
29 static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
30 Expr *expr, Relids relids,
31 bool is_child, Oid datatype);
32 static void generate_base_implied_equalities_const(PlannerInfo *root,
33 EquivalenceClass *ec);
34 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
35 EquivalenceClass *ec);
36 static void generate_base_implied_equalities_broken(PlannerInfo *root,
37 EquivalenceClass *ec);
38 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
41 RelOptInfo *outer_rel,
42 RelOptInfo *inner_rel);
43 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
46 RelOptInfo *outer_rel,
47 RelOptInfo *inner_rel);
48 static Oid select_equality_operator(EquivalenceClass *ec,
49 Oid lefttype, Oid righttype);
50 static RestrictInfo *create_join_clause(PlannerInfo *root,
51 EquivalenceClass *ec, Oid opno,
52 EquivalenceMember *leftem,
53 EquivalenceMember *rightem,
54 EquivalenceClass *parent_ec);
55 static bool reconsider_outer_join_clause(PlannerInfo *root,
58 static bool reconsider_full_join_clause(PlannerInfo *root,
64 * The given clause has a mergejoinable operator and can be applied without
65 * any delay by an outer join, so its two sides can be considered equal
66 * anywhere they are both computable; moreover that equality can be
67 * extended transitively. Record this knowledge in the EquivalenceClass
68 * data structure. Returns TRUE if successful, FALSE if not (in which
69 * case caller should treat the clause as ordinary, not an equivalence).
71 * If below_outer_join is true, then the clause was found below the nullable
72 * side of an outer join, so its sides might validly be both NULL rather than
73 * strictly equal. We can still deduce equalities in such cases, but we take
74 * care to mark an EquivalenceClass if it came from any such clauses. Also,
75 * we have to check that both sides are either pseudo-constants or strict
76 * functions of Vars, else they might not both go to NULL above the outer
77 * join. (This is the reason why we need a failure return. It's more
78 * convenient to check this case here than at the call sites...)
80 * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
81 * problem, for which there exist better data structures than simple lists.
82 * If this code ever proves to be a bottleneck then it could be sped up ---
83 * but for now, simple is beautiful.
85 * Note: this is only called during planner startup, not during GEQO
86 * exploration, so we need not worry about whether we're in the right
90 process_equivalence(PlannerInfo *root, RestrictInfo *restrictinfo,
91 bool below_outer_join)
93 Expr *clause = restrictinfo->clause;
102 EquivalenceClass *ec1,
104 EquivalenceMember *em1,
108 /* Extract info from given clause */
109 Assert(is_opclause(clause));
110 opno = ((OpExpr *) clause)->opno;
111 item1 = (Expr *) get_leftop(clause);
112 item2 = (Expr *) get_rightop(clause);
113 item1_relids = restrictinfo->left_relids;
114 item2_relids = restrictinfo->right_relids;
117 * If below outer join, check for strictness, else reject.
119 if (below_outer_join)
121 if (!bms_is_empty(item1_relids) &&
122 contain_nonstrict_functions((Node *) item1))
123 return false; /* LHS is non-strict but not constant */
124 if (!bms_is_empty(item2_relids) &&
125 contain_nonstrict_functions((Node *) item2))
126 return false; /* RHS is non-strict but not constant */
130 * We use the declared input types of the operator, not exprType() of the
131 * inputs, as the nominal datatypes for opfamily lookup. This presumes
132 * that btree operators are always registered with amoplefttype and
133 * amoprighttype equal to their declared input types. We will need this
134 * info anyway to build EquivalenceMember nodes, and by extracting it now
135 * we can use type comparisons to short-circuit some equal() tests.
137 op_input_types(opno, &item1_type, &item2_type);
139 opfamilies = restrictinfo->mergeopfamilies;
142 * Sweep through the existing EquivalenceClasses looking for matches to
143 * item1 and item2. These are the possible outcomes:
145 * 1. We find both in the same EC. The equivalence is already known, so
146 * there's nothing to do.
148 * 2. We find both in different ECs. Merge the two ECs together.
150 * 3. We find just one. Add the other to its EC.
152 * 4. We find neither. Make a new, two-entry EC.
154 * Note: since all ECs are built through this process, it's impossible
155 * that we'd match an item in more than one existing EC. It is possible
156 * to match more than once within an EC, if someone fed us something silly
157 * like "WHERE X=X". (However, we can't simply discard such clauses,
158 * since they should fail when X is null; so we will build a 2-member EC
159 * to ensure the correct restriction clause gets generated. Hence there
160 * is no shortcut here for item1 and item2 equal.)
164 foreach(lc1, root->eq_classes)
166 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
169 /* Never match to a volatile EC */
170 if (cur_ec->ec_has_volatile)
174 * A "match" requires matching sets of btree opfamilies. Use of
175 * equal() for this test has implications discussed in the comments
176 * for get_mergejoin_opfamilies().
178 if (!equal(opfamilies, cur_ec->ec_opfamilies))
181 foreach(lc2, cur_ec->ec_members)
183 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
185 Assert(!cur_em->em_is_child); /* no children yet */
188 * If below an outer join, don't match constants: they're not as
189 * constant as they look.
191 if ((below_outer_join || cur_ec->ec_below_outer_join) &&
196 item1_type == cur_em->em_datatype &&
197 equal(item1, cur_em->em_expr))
206 item2_type == cur_em->em_datatype &&
207 equal(item2, cur_em->em_expr))
220 /* Sweep finished, what did we find? */
224 /* If case 1, nothing to do, except add to sources */
227 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
228 ec1->ec_below_outer_join |= below_outer_join;
229 /* mark the RI as usable with this pair of EMs */
230 /* NB: can't set left_ec/right_ec until merging is finished */
231 restrictinfo->left_em = em1;
232 restrictinfo->right_em = em2;
237 * Case 2: need to merge ec1 and ec2. We add ec2's items to ec1, then
238 * set ec2's ec_merged link to point to ec1 and remove ec2 from the
239 * eq_classes list. We cannot simply delete ec2 because that could
240 * leave dangling pointers in existing PathKeys. We leave it behind
241 * with a link so that the merged EC can be found.
243 ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
244 ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
245 ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
246 ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
247 ec1->ec_has_const |= ec2->ec_has_const;
248 /* can't need to set has_volatile */
249 ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
250 ec2->ec_merged = ec1;
251 root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
252 /* just to avoid debugging confusion w/ dangling pointers: */
253 ec2->ec_members = NIL;
254 ec2->ec_sources = NIL;
255 ec2->ec_derives = NIL;
256 ec2->ec_relids = NULL;
257 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
258 ec1->ec_below_outer_join |= below_outer_join;
259 /* mark the RI as usable with this pair of EMs */
260 restrictinfo->left_em = em1;
261 restrictinfo->right_em = em2;
265 /* Case 3: add item2 to ec1 */
266 em2 = add_eq_member(ec1, item2, item2_relids, false, item2_type);
267 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
268 ec1->ec_below_outer_join |= below_outer_join;
269 /* mark the RI as usable with this pair of EMs */
270 restrictinfo->left_em = em1;
271 restrictinfo->right_em = em2;
275 /* Case 3: add item1 to ec2 */
276 em1 = add_eq_member(ec2, item1, item1_relids, false, item1_type);
277 ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
278 ec2->ec_below_outer_join |= below_outer_join;
279 /* mark the RI as usable with this pair of EMs */
280 restrictinfo->left_em = em1;
281 restrictinfo->right_em = em2;
285 /* Case 4: make a new, two-entry EC */
286 EquivalenceClass *ec = makeNode(EquivalenceClass);
288 ec->ec_opfamilies = opfamilies;
289 ec->ec_members = NIL;
290 ec->ec_sources = list_make1(restrictinfo);
291 ec->ec_derives = NIL;
292 ec->ec_relids = NULL;
293 ec->ec_has_const = false;
294 ec->ec_has_volatile = false;
295 ec->ec_below_outer_join = below_outer_join;
296 ec->ec_broken = false;
298 ec->ec_merged = NULL;
299 em1 = add_eq_member(ec, item1, item1_relids, false, item1_type);
300 em2 = add_eq_member(ec, item2, item2_relids, false, item2_type);
302 root->eq_classes = lappend(root->eq_classes, ec);
304 /* mark the RI as usable with this pair of EMs */
305 restrictinfo->left_em = em1;
306 restrictinfo->right_em = em2;
313 * add_eq_member - build a new EquivalenceMember and add it to an EC
315 static EquivalenceMember *
316 add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
317 bool is_child, Oid datatype)
319 EquivalenceMember *em = makeNode(EquivalenceMember);
322 em->em_relids = relids;
323 em->em_is_const = false;
324 em->em_is_child = is_child;
325 em->em_datatype = datatype;
327 if (bms_is_empty(relids))
330 * No Vars, assume it's a pseudoconstant. This is correct for entries
331 * generated from process_equivalence(), because a WHERE clause can't
332 * contain aggregates or SRFs, and non-volatility was checked before
333 * process_equivalence() ever got called. But
334 * get_eclass_for_sort_expr() has to work harder. We put the tests
335 * there not here to save cycles in the equivalence case.
338 em->em_is_const = true;
339 ec->ec_has_const = true;
340 /* it can't affect ec_relids */
342 else if (!is_child) /* child members don't add to ec_relids */
344 ec->ec_relids = bms_add_members(ec->ec_relids, relids);
346 ec->ec_members = lappend(ec->ec_members, em);
353 * get_eclass_for_sort_expr
354 * Given an expression and opfamily info, find an existing equivalence
355 * class it is a member of; if none, build a new single-member
356 * EquivalenceClass for it.
358 * sortref is the SortGroupRef of the originating SortGroupClause, if any,
361 * This can be used safely both before and after EquivalenceClass merging;
362 * since it never causes merging it does not invalidate any existing ECs
365 * Note: opfamilies must be chosen consistently with the way
366 * process_equivalence() would do; that is, generated from a mergejoinable
367 * equality operator. Else we might fail to detect valid equivalences,
368 * generating poor (but not incorrect) plans.
371 get_eclass_for_sort_expr(PlannerInfo *root,
377 EquivalenceClass *newec;
378 EquivalenceMember *newem;
380 MemoryContext oldcontext;
383 * Scan through the existing EquivalenceClasses for a match
385 foreach(lc1, root->eq_classes)
387 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
390 /* Never match to a volatile EC */
391 if (cur_ec->ec_has_volatile)
394 if (!equal(opfamilies, cur_ec->ec_opfamilies))
397 foreach(lc2, cur_ec->ec_members)
399 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
402 * If below an outer join, don't match constants: they're not as
403 * constant as they look.
405 if (cur_ec->ec_below_outer_join &&
409 if (expr_datatype == cur_em->em_datatype &&
410 equal(expr, cur_em->em_expr))
411 return cur_ec; /* Match! */
416 * No match, so build a new single-member EC
418 * Here, we must be sure that we construct the EC in the right context. We
419 * can assume, however, that the passed expr is long-lived.
421 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
423 newec = makeNode(EquivalenceClass);
424 newec->ec_opfamilies = list_copy(opfamilies);
425 newec->ec_members = NIL;
426 newec->ec_sources = NIL;
427 newec->ec_derives = NIL;
428 newec->ec_relids = NULL;
429 newec->ec_has_const = false;
430 newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
431 newec->ec_below_outer_join = false;
432 newec->ec_broken = false;
433 newec->ec_sortref = sortref;
434 newec->ec_merged = NULL;
435 newem = add_eq_member(newec, expr, pull_varnos((Node *) expr),
436 false, expr_datatype);
439 * add_eq_member doesn't check for volatile functions, set-returning
440 * functions, or aggregates, but such could appear in sort expressions; so
441 * we have to check whether its const-marking was correct.
443 if (newec->ec_has_const)
445 if (newec->ec_has_volatile ||
446 expression_returns_set((Node *) expr) ||
447 contain_agg_clause((Node *) expr))
449 newec->ec_has_const = false;
450 newem->em_is_const = false;
454 root->eq_classes = lappend(root->eq_classes, newec);
456 MemoryContextSwitchTo(oldcontext);
463 * generate_base_implied_equalities
464 * Generate any restriction clauses that we can deduce from equivalence
467 * When an EC contains pseudoconstants, our strategy is to generate
468 * "member = const1" clauses where const1 is the first constant member, for
469 * every other member (including other constants). If we are able to do this
470 * then we don't need any "var = var" comparisons because we've successfully
471 * constrained all the vars at their points of creation. If we fail to
472 * generate any of these clauses due to lack of cross-type operators, we fall
473 * back to the "ec_broken" strategy described below. (XXX if there are
474 * multiple constants of different types, it's possible that we might succeed
475 * in forming all the required clauses if we started from a different const
476 * member; but this seems a sufficiently hokey corner case to not be worth
477 * spending lots of cycles on.)
479 * For ECs that contain no pseudoconstants, we generate derived clauses
480 * "member1 = member2" for each pair of members belonging to the same base
481 * relation (actually, if there are more than two for the same base relation,
482 * we only need enough clauses to link each to each other). This provides
483 * the base case for the recursion: each row emitted by a base relation scan
484 * will constrain all computable members of the EC to be equal. As each
485 * join path is formed, we'll add additional derived clauses on-the-fly
486 * to maintain this invariant (see generate_join_implied_equalities).
488 * If the opfamilies used by the EC do not provide complete sets of cross-type
489 * equality operators, it is possible that we will fail to generate a clause
490 * that must be generated to maintain the invariant. (An example: given
491 * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
492 * generate "a.x = a.z" as a restriction clause for A.) In this case we mark
493 * the EC "ec_broken" and fall back to regurgitating its original source
494 * RestrictInfos at appropriate times. We do not try to retract any derived
495 * clauses already generated from the broken EC, so the resulting plan could
496 * be poor due to bad selectivity estimates caused by redundant clauses. But
497 * the correct solution to that is to fix the opfamilies ...
499 * Equality clauses derived by this function are passed off to
500 * process_implied_equality (in plan/initsplan.c) to be inserted into the
501 * restrictinfo datastructures. Note that this must be called after initial
502 * scanning of the quals and before Path construction begins.
504 * We make no attempt to avoid generating duplicate RestrictInfos here: we
505 * don't search ec_sources for matches, nor put the created RestrictInfos
506 * into ec_derives. Doing so would require some slightly ugly changes in
507 * initsplan.c's API, and there's no real advantage, because the clauses
508 * generated here can't duplicate anything we will generate for joins anyway.
511 generate_base_implied_equalities(PlannerInfo *root)
516 foreach(lc, root->eq_classes)
518 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
520 Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
521 Assert(!ec->ec_broken); /* not yet anyway... */
523 /* Single-member ECs won't generate any deductions */
524 if (list_length(ec->ec_members) <= 1)
527 if (ec->ec_has_const)
528 generate_base_implied_equalities_const(root, ec);
530 generate_base_implied_equalities_no_const(root, ec);
532 /* Recover if we failed to generate required derived clauses */
534 generate_base_implied_equalities_broken(root, ec);
538 * This is also a handy place to mark base rels (which should all exist by
539 * now) with flags showing whether they have pending eclass joins.
541 for (rti = 1; rti < root->simple_rel_array_size; rti++)
543 RelOptInfo *brel = root->simple_rel_array[rti];
548 brel->has_eclass_joins = has_relevant_eclass_joinclause(root, brel);
553 * generate_base_implied_equalities when EC contains pseudoconstant(s)
556 generate_base_implied_equalities_const(PlannerInfo *root,
557 EquivalenceClass *ec)
559 EquivalenceMember *const_em = NULL;
563 * In the trivial case where we just had one "var = const" clause,
564 * push the original clause back into the main planner machinery. There
565 * is nothing to be gained by doing it differently, and we save the
566 * effort to re-build and re-analyze an equality clause that will be
567 * exactly equivalent to the old one.
569 if (list_length(ec->ec_members) == 2 &&
570 list_length(ec->ec_sources) == 1)
572 RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
574 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
576 distribute_restrictinfo_to_rels(root, restrictinfo);
581 /* Find the constant member to use */
582 foreach(lc, ec->ec_members)
584 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
586 if (cur_em->em_is_const)
592 Assert(const_em != NULL);
594 /* Generate a derived equality against each other member */
595 foreach(lc, ec->ec_members)
597 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
600 Assert(!cur_em->em_is_child); /* no children yet */
601 if (cur_em == const_em)
603 eq_op = select_equality_operator(ec,
605 const_em->em_datatype);
606 if (!OidIsValid(eq_op))
609 ec->ec_broken = true;
612 process_implied_equality(root, eq_op,
613 cur_em->em_expr, const_em->em_expr,
615 ec->ec_below_outer_join,
616 cur_em->em_is_const);
621 * generate_base_implied_equalities when EC contains no pseudoconstants
624 generate_base_implied_equalities_no_const(PlannerInfo *root,
625 EquivalenceClass *ec)
627 EquivalenceMember **prev_ems;
631 * We scan the EC members once and track the last-seen member for each
632 * base relation. When we see another member of the same base relation,
633 * we generate "prev_mem = cur_mem". This results in the minimum number
634 * of derived clauses, but it's possible that it will fail when a
635 * different ordering would succeed. XXX FIXME: use a UNION-FIND
636 * algorithm similar to the way we build merged ECs. (Use a list-of-lists
639 prev_ems = (EquivalenceMember **)
640 palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
642 foreach(lc, ec->ec_members)
644 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
647 Assert(!cur_em->em_is_child); /* no children yet */
648 if (bms_membership(cur_em->em_relids) != BMS_SINGLETON)
650 relid = bms_singleton_member(cur_em->em_relids);
651 Assert(relid < root->simple_rel_array_size);
653 if (prev_ems[relid] != NULL)
655 EquivalenceMember *prev_em = prev_ems[relid];
658 eq_op = select_equality_operator(ec,
659 prev_em->em_datatype,
660 cur_em->em_datatype);
661 if (!OidIsValid(eq_op))
664 ec->ec_broken = true;
667 process_implied_equality(root, eq_op,
668 prev_em->em_expr, cur_em->em_expr,
670 ec->ec_below_outer_join,
673 prev_ems[relid] = cur_em;
679 * We also have to make sure that all the Vars used in the member clauses
680 * will be available at any join node we might try to reference them at.
681 * For the moment we force all the Vars to be available at all join nodes
682 * for this eclass. Perhaps this could be improved by doing some
683 * pre-analysis of which members we prefer to join, but it's no worse than
684 * what happened in the pre-8.3 code.
686 foreach(lc, ec->ec_members)
688 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
689 List *vars = pull_var_clause((Node *) cur_em->em_expr, false);
691 add_vars_to_targetlist(root, vars, ec->ec_relids);
697 * generate_base_implied_equalities cleanup after failure
699 * What we must do here is push any zero- or one-relation source RestrictInfos
700 * of the EC back into the main restrictinfo datastructures. Multi-relation
701 * clauses will be regurgitated later by generate_join_implied_equalities().
702 * (We do it this way to maintain continuity with the case that ec_broken
703 * becomes set only after we've gone up a join level or two.)
706 generate_base_implied_equalities_broken(PlannerInfo *root,
707 EquivalenceClass *ec)
711 foreach(lc, ec->ec_sources)
713 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
715 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
716 distribute_restrictinfo_to_rels(root, restrictinfo);
722 * generate_join_implied_equalities
723 * Generate any join clauses that we can deduce from equivalence classes.
725 * At a join node, we must enforce restriction clauses sufficient to ensure
726 * that all equivalence-class members computable at that node are equal.
727 * Since the set of clauses to enforce can vary depending on which subset
728 * relations are the inputs, we have to compute this afresh for each join
729 * path pair. Hence a fresh List of RestrictInfo nodes is built and passed
732 * The results are sufficient for use in merge, hash, and plain nestloop join
733 * methods. We do not worry here about selecting clauses that are optimal
734 * for use in a nestloop-with-inner-indexscan join, however. indxpath.c makes
735 * its own selections of clauses to use, and if the ones we pick here are
736 * redundant with those, the extras will be eliminated in createplan.c.
738 * Because the same join clauses are likely to be needed multiple times as
739 * we consider different join paths, we avoid generating multiple copies:
740 * whenever we select a particular pair of EquivalenceMembers to join,
741 * we check to see if the pair matches any original clause (in ec_sources)
742 * or previously-built clause (in ec_derives). This saves memory and allows
743 * re-use of information cached in RestrictInfos.
746 generate_join_implied_equalities(PlannerInfo *root,
748 RelOptInfo *outer_rel,
749 RelOptInfo *inner_rel)
754 foreach(lc, root->eq_classes)
756 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
759 /* ECs containing consts do not need any further enforcement */
760 if (ec->ec_has_const)
763 /* Single-member ECs won't generate any deductions */
764 if (list_length(ec->ec_members) <= 1)
767 /* We can quickly ignore any that don't overlap the join, too */
768 if (!bms_overlap(ec->ec_relids, joinrel->relids))
772 sublist = generate_join_implied_equalities_normal(root,
778 /* Recover if we failed to generate required derived clauses */
780 sublist = generate_join_implied_equalities_broken(root,
786 result = list_concat(result, sublist);
793 * generate_join_implied_equalities for a still-valid EC
796 generate_join_implied_equalities_normal(PlannerInfo *root,
797 EquivalenceClass *ec,
799 RelOptInfo *outer_rel,
800 RelOptInfo *inner_rel)
803 List *new_members = NIL;
804 List *outer_members = NIL;
805 List *inner_members = NIL;
809 * First, scan the EC to identify member values that are computable at the
810 * outer rel, at the inner rel, or at this relation but not in either
811 * input rel. The outer-rel members should already be enforced equal,
812 * likewise for the inner-rel members. We'll need to create clauses to
813 * enforce that any newly computable members are all equal to each other
814 * as well as to at least one input member, plus enforce at least one
815 * outer-rel member equal to at least one inner-rel member.
817 foreach(lc1, ec->ec_members)
819 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
821 if (cur_em->em_is_child)
822 continue; /* ignore children here */
823 if (!bms_is_subset(cur_em->em_relids, joinrel->relids))
824 continue; /* ignore --- not computable yet */
826 if (bms_is_subset(cur_em->em_relids, outer_rel->relids))
827 outer_members = lappend(outer_members, cur_em);
828 else if (bms_is_subset(cur_em->em_relids, inner_rel->relids))
829 inner_members = lappend(inner_members, cur_em);
831 new_members = lappend(new_members, cur_em);
835 * First, select the joinclause if needed. We can equate any one outer
836 * member to any one inner member, but we have to find a datatype
837 * combination for which an opfamily member operator exists. If we have
838 * choices, we prefer simple Var members (possibly with RelabelType) since
839 * these are (a) cheapest to compute at runtime and (b) most likely to
840 * have useful statistics. Also, if enable_hashjoin is on, we prefer
841 * operators that are also hashjoinable.
843 if (outer_members && inner_members)
845 EquivalenceMember *best_outer_em = NULL;
846 EquivalenceMember *best_inner_em = NULL;
847 Oid best_eq_op = InvalidOid;
851 foreach(lc1, outer_members)
853 EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
856 foreach(lc2, inner_members)
858 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
862 eq_op = select_equality_operator(ec,
863 outer_em->em_datatype,
864 inner_em->em_datatype);
865 if (!OidIsValid(eq_op))
868 if (IsA(outer_em->em_expr, Var) ||
869 (IsA(outer_em->em_expr, RelabelType) &&
870 IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
872 if (IsA(inner_em->em_expr, Var) ||
873 (IsA(inner_em->em_expr, RelabelType) &&
874 IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
876 if (!enable_hashjoin || op_hashjoinable(eq_op))
878 if (score > best_score)
880 best_outer_em = outer_em;
881 best_inner_em = inner_em;
885 break; /* no need to look further */
889 break; /* no need to look further */
894 ec->ec_broken = true;
899 * Create clause, setting parent_ec to mark it as redundant with other
902 rinfo = create_join_clause(root, ec, best_eq_op,
903 best_outer_em, best_inner_em,
906 result = lappend(result, rinfo);
910 * Now deal with building restrictions for any expressions that involve
911 * Vars from both sides of the join. We have to equate all of these to
912 * each other as well as to at least one old member (if any).
914 * XXX as in generate_base_implied_equalities_no_const, we could be a lot
915 * smarter here to avoid unnecessary failures in cross-type situations.
916 * For now, use the same left-to-right method used there.
920 List *old_members = list_concat(outer_members, inner_members);
921 EquivalenceMember *prev_em = NULL;
924 /* For now, arbitrarily take the first old_member as the one to use */
926 new_members = lappend(new_members, linitial(old_members));
928 foreach(lc1, new_members)
930 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
936 eq_op = select_equality_operator(ec,
937 prev_em->em_datatype,
938 cur_em->em_datatype);
939 if (!OidIsValid(eq_op))
942 ec->ec_broken = true;
945 /* do NOT set parent_ec, this qual is not redundant! */
946 rinfo = create_join_clause(root, ec, eq_op,
950 result = lappend(result, rinfo);
960 * generate_join_implied_equalities cleanup after failure
962 * Return any original RestrictInfos that are enforceable at this join.
965 generate_join_implied_equalities_broken(PlannerInfo *root,
966 EquivalenceClass *ec,
968 RelOptInfo *outer_rel,
969 RelOptInfo *inner_rel)
974 foreach(lc, ec->ec_sources)
976 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
978 if (bms_is_subset(restrictinfo->required_relids, joinrel->relids) &&
979 !bms_is_subset(restrictinfo->required_relids, outer_rel->relids) &&
980 !bms_is_subset(restrictinfo->required_relids, inner_rel->relids))
981 result = lappend(result, restrictinfo);
989 * select_equality_operator
990 * Select a suitable equality operator for comparing two EC members
992 * Returns InvalidOid if no operator can be found for this datatype combination
995 select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
999 foreach(lc, ec->ec_opfamilies)
1001 Oid opfamily = lfirst_oid(lc);
1004 opno = get_opfamily_member(opfamily, lefttype, righttype,
1005 BTEqualStrategyNumber);
1006 if (OidIsValid(opno))
1014 * create_join_clause
1015 * Find or make a RestrictInfo comparing the two given EC members
1016 * with the given operator.
1018 * parent_ec is either equal to ec (if the clause is a potentially-redundant
1019 * join clause) or NULL (if not). We have to treat this as part of the
1020 * match requirements --- it's possible that a clause comparing the same two
1021 * EMs is a join clause in one join path and a restriction clause in another.
1023 static RestrictInfo *
1024 create_join_clause(PlannerInfo *root,
1025 EquivalenceClass *ec, Oid opno,
1026 EquivalenceMember *leftem,
1027 EquivalenceMember *rightem,
1028 EquivalenceClass *parent_ec)
1030 RestrictInfo *rinfo;
1032 MemoryContext oldcontext;
1035 * Search to see if we already built a RestrictInfo for this pair of
1036 * EquivalenceMembers. We can use either original source clauses or
1037 * previously-derived clauses. The check on opno is probably redundant,
1040 foreach(lc, ec->ec_sources)
1042 rinfo = (RestrictInfo *) lfirst(lc);
1043 if (rinfo->left_em == leftem &&
1044 rinfo->right_em == rightem &&
1045 rinfo->parent_ec == parent_ec &&
1046 opno == ((OpExpr *) rinfo->clause)->opno)
1050 foreach(lc, ec->ec_derives)
1052 rinfo = (RestrictInfo *) lfirst(lc);
1053 if (rinfo->left_em == leftem &&
1054 rinfo->right_em == rightem &&
1055 rinfo->parent_ec == parent_ec &&
1056 opno == ((OpExpr *) rinfo->clause)->opno)
1061 * Not there, so build it, in planner context so we can re-use it. (Not
1062 * important in normal planning, but definitely so in GEQO.)
1064 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1066 rinfo = build_implied_join_equality(opno,
1069 bms_union(leftem->em_relids,
1070 rightem->em_relids));
1072 /* Mark the clause as redundant, or not */
1073 rinfo->parent_ec = parent_ec;
1076 * We can set these now, rather than letting them be looked up later,
1077 * since this is only used after EC merging is complete.
1079 rinfo->left_ec = ec;
1080 rinfo->right_ec = ec;
1082 /* Mark it as usable with these EMs */
1083 rinfo->left_em = leftem;
1084 rinfo->right_em = rightem;
1085 /* and save it for possible re-use */
1086 ec->ec_derives = lappend(ec->ec_derives, rinfo);
1088 MemoryContextSwitchTo(oldcontext);
1095 * reconsider_outer_join_clauses
1096 * Re-examine any outer-join clauses that were set aside by
1097 * distribute_qual_to_rels(), and see if we can derive any
1098 * EquivalenceClasses from them. Then, if they were not made
1099 * redundant, push them out into the regular join-clause lists.
1101 * When we have mergejoinable clauses A = B that are outer-join clauses,
1102 * we can't blindly combine them with other clauses A = C to deduce B = C,
1103 * since in fact the "equality" A = B won't necessarily hold above the
1104 * outer join (one of the variables might be NULL instead). Nonetheless
1105 * there are cases where we can add qual clauses using transitivity.
1107 * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
1108 * for which there is also an equivalence clause OUTERVAR = CONSTANT.
1109 * It is safe and useful to push a clause INNERVAR = CONSTANT into the
1110 * evaluation of the inner (nullable) relation, because any inner rows not
1111 * meeting this condition will not contribute to the outer-join result anyway.
1112 * (Any outer rows they could join to will be eliminated by the pushed-down
1113 * equivalence clause.)
1115 * Note that the above rule does not work for full outer joins; nor is it
1116 * very interesting to consider cases where the generated equivalence clause
1117 * would involve relations outside the outer join, since such clauses couldn't
1118 * be pushed into the inner side's scan anyway. So the restriction to
1119 * outervar = pseudoconstant is not really giving up anything.
1121 * For full-join cases, we can only do something useful if it's a FULL JOIN
1122 * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
1123 * By the time it gets here, the merged column will look like
1124 * COALESCE(LEFTVAR, RIGHTVAR)
1125 * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
1126 * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
1127 * and RIGHTVAR = CONSTANT into the input relations, since any rows not
1128 * meeting these conditions cannot contribute to the join result.
1130 * Again, there isn't any traction to be gained by trying to deal with
1131 * clauses comparing a mergedvar to a non-pseudoconstant. So we can make
1132 * use of the EquivalenceClasses to search for matching variables that were
1133 * equivalenced to constants. The interesting outer-join clauses were
1134 * accumulated for us by distribute_qual_to_rels.
1136 * When we find one of these cases, we implement the changes we want by
1137 * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
1138 * and pushing it into the EquivalenceClass structures. This is because we
1139 * may already know that INNERVAR is equivalenced to some other var(s), and
1140 * we'd like the constant to propagate to them too. Note that it would be
1141 * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
1142 * that could result in propagating constant restrictions from
1143 * INNERVAR to OUTERVAR, which would be very wrong.
1145 * It's possible that the INNERVAR is also an OUTERVAR for some other
1146 * outer-join clause, in which case the process can be repeated. So we repeat
1147 * looping over the lists of clauses until no further deductions can be made.
1148 * Whenever we do make a deduction, we remove the generating clause from the
1149 * lists, since we don't want to make the same deduction twice.
1151 * If we don't find any match for a set-aside outer join clause, we must
1152 * throw it back into the regular joinclause processing by passing it to
1153 * distribute_restrictinfo_to_rels(). If we do generate a derived clause,
1154 * however, the outer-join clause is redundant. We still throw it back,
1155 * because otherwise the join will be seen as a clauseless join and avoided
1156 * during join order searching; but we mark it as redundant to keep from
1157 * messing up the joinrel's size estimate. (This behavior means that the
1158 * API for this routine is uselessly complex: we could have just put all
1159 * the clauses into the regular processing initially. We keep it because
1160 * someday we might want to do something else, such as inserting "dummy"
1161 * joinclauses instead of real ones.)
1163 * Outer join clauses that are marked outerjoin_delayed are special: this
1164 * condition means that one or both VARs might go to null due to a lower
1165 * outer join. We can still push a constant through the clause, but only
1166 * if its operator is strict; and we *have to* throw the clause back into
1167 * regular joinclause processing. By keeping the strict join clause,
1168 * we ensure that any null-extended rows that are mistakenly generated due
1169 * to suppressing rows not matching the constant will be rejected at the
1170 * upper outer join. (This doesn't work for full-join clauses.)
1173 reconsider_outer_join_clauses(PlannerInfo *root)
1180 /* Outer loop repeats until we find no more deductions */
1185 /* Process the LEFT JOIN clauses */
1187 for (cell = list_head(root->left_join_clauses); cell; cell = next)
1189 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1192 if (reconsider_outer_join_clause(root, rinfo, true))
1195 /* remove it from the list */
1196 root->left_join_clauses =
1197 list_delete_cell(root->left_join_clauses, cell, prev);
1198 /* we throw it back anyway (see notes above) */
1199 /* but the thrown-back clause has no extra selectivity */
1200 rinfo->this_selec = 1.0;
1201 distribute_restrictinfo_to_rels(root, rinfo);
1207 /* Process the RIGHT JOIN clauses */
1209 for (cell = list_head(root->right_join_clauses); cell; cell = next)
1211 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1214 if (reconsider_outer_join_clause(root, rinfo, false))
1217 /* remove it from the list */
1218 root->right_join_clauses =
1219 list_delete_cell(root->right_join_clauses, cell, prev);
1220 /* we throw it back anyway (see notes above) */
1221 /* but the thrown-back clause has no extra selectivity */
1222 rinfo->this_selec = 1.0;
1223 distribute_restrictinfo_to_rels(root, rinfo);
1229 /* Process the FULL JOIN clauses */
1231 for (cell = list_head(root->full_join_clauses); cell; cell = next)
1233 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1236 if (reconsider_full_join_clause(root, rinfo))
1239 /* remove it from the list */
1240 root->full_join_clauses =
1241 list_delete_cell(root->full_join_clauses, cell, prev);
1242 /* we throw it back anyway (see notes above) */
1243 /* but the thrown-back clause has no extra selectivity */
1244 rinfo->this_selec = 1.0;
1245 distribute_restrictinfo_to_rels(root, rinfo);
1252 /* Now, any remaining clauses have to be thrown back */
1253 foreach(cell, root->left_join_clauses)
1255 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1257 distribute_restrictinfo_to_rels(root, rinfo);
1259 foreach(cell, root->right_join_clauses)
1261 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1263 distribute_restrictinfo_to_rels(root, rinfo);
1265 foreach(cell, root->full_join_clauses)
1267 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1269 distribute_restrictinfo_to_rels(root, rinfo);
1274 * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
1276 * Returns TRUE if we were able to propagate a constant through the clause.
1279 reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo,
1288 Relids inner_relids;
1291 Assert(is_opclause(rinfo->clause));
1292 opno = ((OpExpr *) rinfo->clause)->opno;
1294 /* If clause is outerjoin_delayed, operator must be strict */
1295 if (rinfo->outerjoin_delayed && !op_strict(opno))
1298 /* Extract needed info from the clause */
1299 op_input_types(opno, &left_type, &right_type);
1302 outervar = (Expr *) get_leftop(rinfo->clause);
1303 innervar = (Expr *) get_rightop(rinfo->clause);
1304 inner_datatype = right_type;
1305 inner_relids = rinfo->right_relids;
1309 outervar = (Expr *) get_rightop(rinfo->clause);
1310 innervar = (Expr *) get_leftop(rinfo->clause);
1311 inner_datatype = left_type;
1312 inner_relids = rinfo->left_relids;
1315 /* Scan EquivalenceClasses for a match to outervar */
1316 foreach(lc1, root->eq_classes)
1318 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1322 /* Ignore EC unless it contains pseudoconstants */
1323 if (!cur_ec->ec_has_const)
1325 /* Never match to a volatile EC */
1326 if (cur_ec->ec_has_volatile)
1328 /* It has to match the outer-join clause as to opfamilies, too */
1329 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1331 /* Does it contain a match to outervar? */
1333 foreach(lc2, cur_ec->ec_members)
1335 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1337 if (equal(outervar, cur_em->em_expr))
1344 continue; /* no match, so ignore this EC */
1347 * Yes it does! Try to generate a clause INNERVAR = CONSTANT for each
1348 * CONSTANT in the EC. Note that we must succeed with at least one
1349 * constant before we can decide to throw away the outer-join clause.
1352 foreach(lc2, cur_ec->ec_members)
1354 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1356 RestrictInfo *newrinfo;
1358 if (!cur_em->em_is_const)
1359 continue; /* ignore non-const members */
1360 eq_op = select_equality_operator(cur_ec,
1362 cur_em->em_datatype);
1363 if (!OidIsValid(eq_op))
1364 continue; /* can't generate equality */
1365 newrinfo = build_implied_join_equality(eq_op,
1369 if (process_equivalence(root, newrinfo, true))
1374 * If we were able to equate INNERVAR to any constant, report success.
1375 * Otherwise, fall out of the search loop, since we know the OUTERVAR
1376 * appears in at most one EC.
1384 return false; /* failed to make any deduction */
1388 * reconsider_outer_join_clauses for a single FULL JOIN clause
1390 * Returns TRUE if we were able to propagate a constant through the clause.
1393 reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
1404 /* Can't use an outerjoin_delayed clause here */
1405 if (rinfo->outerjoin_delayed)
1408 /* Extract needed info from the clause */
1409 Assert(is_opclause(rinfo->clause));
1410 opno = ((OpExpr *) rinfo->clause)->opno;
1411 op_input_types(opno, &left_type, &right_type);
1412 leftvar = (Expr *) get_leftop(rinfo->clause);
1413 rightvar = (Expr *) get_rightop(rinfo->clause);
1414 left_relids = rinfo->left_relids;
1415 right_relids = rinfo->right_relids;
1417 foreach(lc1, root->eq_classes)
1419 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1420 EquivalenceMember *coal_em = NULL;
1426 /* Ignore EC unless it contains pseudoconstants */
1427 if (!cur_ec->ec_has_const)
1429 /* Never match to a volatile EC */
1430 if (cur_ec->ec_has_volatile)
1432 /* It has to match the outer-join clause as to opfamilies, too */
1433 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1437 * Does it contain a COALESCE(leftvar, rightvar) construct?
1439 * We can assume the COALESCE() inputs are in the same order as the
1440 * join clause, since both were automatically generated in the cases
1443 * XXX currently this may fail to match in cross-type cases because
1444 * the COALESCE will contain typecast operations while the join clause
1445 * may not (if there is a cross-type mergejoin operator available for
1446 * the two column types). Is it OK to strip implicit coercions from
1447 * the COALESCE arguments?
1450 foreach(lc2, cur_ec->ec_members)
1452 coal_em = (EquivalenceMember *) lfirst(lc2);
1453 if (IsA(coal_em->em_expr, CoalesceExpr))
1455 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
1459 if (list_length(cexpr->args) != 2)
1461 cfirst = (Node *) linitial(cexpr->args);
1462 csecond = (Node *) lsecond(cexpr->args);
1464 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
1472 continue; /* no match, so ignore this EC */
1475 * Yes it does! Try to generate clauses LEFTVAR = CONSTANT and
1476 * RIGHTVAR = CONSTANT for each CONSTANT in the EC. Note that we must
1477 * succeed with at least one constant for each var before we can
1478 * decide to throw away the outer-join clause.
1480 matchleft = matchright = false;
1481 foreach(lc2, cur_ec->ec_members)
1483 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1485 RestrictInfo *newrinfo;
1487 if (!cur_em->em_is_const)
1488 continue; /* ignore non-const members */
1489 eq_op = select_equality_operator(cur_ec,
1491 cur_em->em_datatype);
1492 if (OidIsValid(eq_op))
1494 newrinfo = build_implied_join_equality(eq_op,
1498 if (process_equivalence(root, newrinfo, true))
1501 eq_op = select_equality_operator(cur_ec,
1503 cur_em->em_datatype);
1504 if (OidIsValid(eq_op))
1506 newrinfo = build_implied_join_equality(eq_op,
1510 if (process_equivalence(root, newrinfo, true))
1516 * If we were able to equate both vars to constants, we're done, and
1517 * we can throw away the full-join clause as redundant. Moreover, we
1518 * can remove the COALESCE entry from the EC, since the added
1519 * restrictions ensure it will always have the expected value. (We
1520 * don't bother trying to update ec_relids or ec_sources.)
1522 if (matchleft && matchright)
1524 cur_ec->ec_members = list_delete_ptr(cur_ec->ec_members, coal_em);
1529 * Otherwise, fall out of the search loop, since we know the COALESCE
1530 * appears in at most one EC (XXX might stop being true if we allow
1531 * stripping of coercions above?)
1536 return false; /* failed to make any deduction */
1542 * Detect whether two expressions are known equal due to equivalence
1545 * Actually, this only shows that the expressions are equal according
1546 * to some opfamily's notion of equality --- but we only use it for
1547 * selectivity estimation, so a fuzzy idea of equality is OK.
1549 * Note: does not bother to check for "equal(item1, item2)"; caller must
1550 * check that case if it's possible to pass identical items.
1553 exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
1557 foreach(lc1, root->eq_classes)
1559 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1560 bool item1member = false;
1561 bool item2member = false;
1564 /* Never match to a volatile EC */
1565 if (ec->ec_has_volatile)
1568 foreach(lc2, ec->ec_members)
1570 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
1572 if (equal(item1, em->em_expr))
1574 else if (equal(item2, em->em_expr))
1576 /* Exit as soon as equality is proven */
1577 if (item1member && item2member)
1586 * add_child_rel_equivalences
1587 * Search for EC members that reference (only) the parent_rel, and
1588 * add transformed members referencing the child_rel.
1590 * We only need to do this for ECs that could generate join conditions,
1591 * since the child members are only used for creating inner-indexscan paths.
1593 * parent_rel and child_rel could be derived from appinfo, but since the
1594 * caller has already computed them, we might as well just pass them in.
1597 add_child_rel_equivalences(PlannerInfo *root,
1598 AppendRelInfo *appinfo,
1599 RelOptInfo *parent_rel,
1600 RelOptInfo *child_rel)
1604 foreach(lc1, root->eq_classes)
1606 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1610 * Won't generate joinclauses if const or single-member (the latter
1611 * test covers the volatile case too)
1613 if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
1616 /* No point in searching if parent rel not mentioned in eclass */
1617 if (!bms_is_subset(parent_rel->relids, cur_ec->ec_relids))
1620 foreach(lc2, cur_ec->ec_members)
1622 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1624 /* Does it reference (only) parent_rel? */
1625 if (bms_equal(cur_em->em_relids, parent_rel->relids))
1627 /* Yes, generate transformed child version */
1630 child_expr = (Expr *)
1631 adjust_appendrel_attrs((Node *) cur_em->em_expr,
1633 (void) add_eq_member(cur_ec, child_expr, child_rel->relids,
1634 true, cur_em->em_datatype);
1642 * mutate_eclass_expressions
1643 * Apply an expression tree mutator to all expressions stored in
1644 * equivalence classes.
1646 * This is a bit of a hack ... it's currently needed only by planagg.c,
1647 * which needs to do a global search-and-replace of MIN/MAX Aggrefs
1648 * after eclasses are already set up. Without changing the eclasses too,
1649 * subsequent matching of ORDER BY clauses would fail.
1651 * Note that we assume the mutation won't affect relation membership or any
1652 * other properties we keep track of (which is a bit bogus, but by the time
1653 * planagg.c runs, it no longer matters). Also we must be called in the
1654 * main planner memory context.
1657 mutate_eclass_expressions(PlannerInfo *root,
1658 Node *(*mutator) (),
1663 foreach(lc1, root->eq_classes)
1665 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1668 foreach(lc2, cur_ec->ec_members)
1670 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1672 cur_em->em_expr = (Expr *)
1673 mutator((Node *) cur_em->em_expr, context);
1680 * find_eclass_clauses_for_index_join
1681 * Create joinclauses usable for a nestloop-with-inner-indexscan
1682 * scanning the given inner rel with the specified set of outer rels.
1685 find_eclass_clauses_for_index_join(PlannerInfo *root, RelOptInfo *rel,
1686 Relids outer_relids)
1689 bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1692 foreach(lc1, root->eq_classes)
1694 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1698 * Won't generate joinclauses if const or single-member (the latter
1699 * test covers the volatile case too)
1701 if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
1705 * No point in searching if rel not mentioned in eclass (but we can't
1706 * tell that for a child rel).
1708 if (!is_child_rel &&
1709 !bms_is_subset(rel->relids, cur_ec->ec_relids))
1711 /* ... nor if no overlap with outer_relids */
1712 if (!bms_overlap(outer_relids, cur_ec->ec_relids))
1715 /* Scan members, looking for indexable columns */
1716 foreach(lc2, cur_ec->ec_members)
1718 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1719 EquivalenceMember *best_outer_em = NULL;
1720 Oid best_eq_op = InvalidOid;
1723 if (!bms_equal(cur_em->em_relids, rel->relids) ||
1724 !eclass_matches_any_index(cur_ec, cur_em, rel))
1728 * Found one, so try to generate a join clause. This is like
1729 * generate_join_implied_equalities_normal, except simpler since
1730 * our only preference item is to pick a Var on the outer side. We
1731 * only need one join clause per index col.
1733 foreach(lc3, cur_ec->ec_members)
1735 EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc3);
1738 if (!bms_is_subset(outer_em->em_relids, outer_relids))
1740 eq_op = select_equality_operator(cur_ec,
1741 cur_em->em_datatype,
1742 outer_em->em_datatype);
1743 if (!OidIsValid(eq_op))
1745 best_outer_em = outer_em;
1747 if (IsA(outer_em->em_expr, Var) ||
1748 (IsA(outer_em->em_expr, RelabelType) &&
1749 IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1750 break; /* no need to look further */
1755 /* Found a suitable joinclause */
1756 RestrictInfo *rinfo;
1758 /* set parent_ec to mark as redundant with other joinclauses */
1759 rinfo = create_join_clause(root, cur_ec, best_eq_op,
1760 cur_em, best_outer_em,
1763 result = lappend(result, rinfo);
1766 * Note: we keep scanning here because we want to provide a
1767 * clause for every possible indexcol.
1778 * have_relevant_eclass_joinclause
1779 * Detect whether there is an EquivalenceClass that could produce
1780 * a joinclause between the two given relations.
1782 * This is essentially a very cut-down version of
1783 * generate_join_implied_equalities(). Note it's OK to occasionally say "yes"
1784 * incorrectly. Hence we don't bother with details like whether the lack of a
1785 * cross-type operator might prevent the clause from actually being generated.
1788 have_relevant_eclass_joinclause(PlannerInfo *root,
1789 RelOptInfo *rel1, RelOptInfo *rel2)
1793 foreach(lc1, root->eq_classes)
1795 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1801 * Won't generate joinclauses if single-member (this test covers the
1802 * volatile case too)
1804 if (list_length(ec->ec_members) <= 1)
1808 * Note we don't test ec_broken; if we did, we'd need a separate code
1809 * path to look through ec_sources. Checking the members anyway is OK
1810 * as a possibly-overoptimistic heuristic.
1812 * We don't test ec_has_const either, even though a const eclass
1813 * won't generate real join clauses. This is because if we had
1814 * "WHERE a.x = b.y and a.x = 42", it is worth considering a join
1815 * between a and b, since the join result is likely to be small even
1816 * though it'll end up being an unqualified nestloop.
1819 /* Needn't scan if it couldn't contain members from each rel */
1820 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
1821 !bms_overlap(rel2->relids, ec->ec_relids))
1824 /* Scan the EC to see if it has member(s) in each rel */
1825 has_rel1 = has_rel2 = false;
1826 foreach(lc2, ec->ec_members)
1828 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1830 if (cur_em->em_is_const || cur_em->em_is_child)
1831 continue; /* ignore consts and children here */
1832 if (bms_is_subset(cur_em->em_relids, rel1->relids))
1838 if (bms_is_subset(cur_em->em_relids, rel2->relids))
1846 if (has_rel1 && has_rel2)
1855 * has_relevant_eclass_joinclause
1856 * Detect whether there is an EquivalenceClass that could produce
1857 * a joinclause between the given relation and anything else.
1859 * This is the same as have_relevant_eclass_joinclause with the other rel
1860 * implicitly defined as "everything else in the query".
1863 has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
1867 foreach(lc1, root->eq_classes)
1869 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1875 * Won't generate joinclauses if single-member (this test covers the
1876 * volatile case too)
1878 if (list_length(ec->ec_members) <= 1)
1882 * Note we don't test ec_broken; if we did, we'd need a separate code
1883 * path to look through ec_sources. Checking the members anyway is OK
1884 * as a possibly-overoptimistic heuristic.
1886 * We don't test ec_has_const either, even though a const eclass
1887 * won't generate real join clauses. This is because if we had
1888 * "WHERE a.x = b.y and a.x = 42", it is worth considering a join
1889 * between a and b, since the join result is likely to be small even
1890 * though it'll end up being an unqualified nestloop.
1893 /* Needn't scan if it couldn't contain members from each rel */
1894 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
1895 bms_is_subset(ec->ec_relids, rel1->relids))
1898 /* Scan the EC to see if it has member(s) in each rel */
1899 has_rel1 = has_rel2 = false;
1900 foreach(lc2, ec->ec_members)
1902 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1904 if (cur_em->em_is_const || cur_em->em_is_child)
1905 continue; /* ignore consts and children here */
1906 if (bms_is_subset(cur_em->em_relids, rel1->relids))
1912 if (!bms_overlap(cur_em->em_relids, rel1->relids))
1920 if (has_rel1 && has_rel2)
1929 * eclass_useful_for_merging
1930 * Detect whether the EC could produce any mergejoinable join clauses
1931 * against the specified relation.
1933 * This is just a heuristic test and doesn't have to be exact; it's better
1934 * to say "yes" incorrectly than "no". Hence we don't bother with details
1935 * like whether the lack of a cross-type operator might prevent the clause
1936 * from actually being generated.
1939 eclass_useful_for_merging(EquivalenceClass *eclass,
1944 Assert(!eclass->ec_merged);
1947 * Won't generate joinclauses if const or single-member (the latter test
1948 * covers the volatile case too)
1950 if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
1954 * Note we don't test ec_broken; if we did, we'd need a separate code path
1955 * to look through ec_sources. Checking the members anyway is OK as a
1956 * possibly-overoptimistic heuristic.
1959 /* If rel already includes all members of eclass, no point in searching */
1960 if (bms_is_subset(eclass->ec_relids, rel->relids))
1963 /* To join, we need a member not in the given rel */
1964 foreach(lc, eclass->ec_members)
1966 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1968 if (!cur_em->em_is_child &&
1969 !bms_overlap(cur_em->em_relids, rel->relids))