1 /*-------------------------------------------------------------------------
4 * Routines for managing EquivalenceClasses
6 * See src/backend/optimizer/README for discussion of EquivalenceClasses.
9 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/backend/optimizer/path/equivclass.c
15 *-------------------------------------------------------------------------
19 #include "access/skey.h"
20 #include "catalog/pg_type.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/cost.h"
25 #include "optimizer/paths.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/var.h"
29 #include "utils/lsyscache.h"
32 static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
33 Expr *expr, Relids relids,
34 bool is_child, Oid datatype);
35 static void generate_base_implied_equalities_const(PlannerInfo *root,
36 EquivalenceClass *ec);
37 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
38 EquivalenceClass *ec);
39 static void generate_base_implied_equalities_broken(PlannerInfo *root,
40 EquivalenceClass *ec);
41 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
44 RelOptInfo *outer_rel,
45 RelOptInfo *inner_rel);
46 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
49 RelOptInfo *outer_rel,
50 RelOptInfo *inner_rel);
51 static Oid select_equality_operator(EquivalenceClass *ec,
52 Oid lefttype, Oid righttype);
53 static RestrictInfo *create_join_clause(PlannerInfo *root,
54 EquivalenceClass *ec, Oid opno,
55 EquivalenceMember *leftem,
56 EquivalenceMember *rightem,
57 EquivalenceClass *parent_ec);
58 static bool reconsider_outer_join_clause(PlannerInfo *root,
61 static bool reconsider_full_join_clause(PlannerInfo *root,
67 * The given clause has a mergejoinable operator and can be applied without
68 * any delay by an outer join, so its two sides can be considered equal
69 * anywhere they are both computable; moreover that equality can be
70 * extended transitively. Record this knowledge in the EquivalenceClass
71 * data structure. Returns TRUE if successful, FALSE if not (in which
72 * case caller should treat the clause as ordinary, not an equivalence).
74 * If below_outer_join is true, then the clause was found below the nullable
75 * side of an outer join, so its sides might validly be both NULL rather than
76 * strictly equal. We can still deduce equalities in such cases, but we take
77 * care to mark an EquivalenceClass if it came from any such clauses. Also,
78 * we have to check that both sides are either pseudo-constants or strict
79 * functions of Vars, else they might not both go to NULL above the outer
80 * join. (This is the reason why we need a failure return. It's more
81 * convenient to check this case here than at the call sites...)
83 * On success return, we have also initialized the clause's left_ec/right_ec
84 * fields to point to the EquivalenceClass representing it. This saves lookup
87 * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
88 * problem, for which there exist better data structures than simple lists.
89 * If this code ever proves to be a bottleneck then it could be sped up ---
90 * but for now, simple is beautiful.
92 * Note: this is only called during planner startup, not during GEQO
93 * exploration, so we need not worry about whether we're in the right
97 process_equivalence(PlannerInfo *root, RestrictInfo *restrictinfo,
98 bool below_outer_join)
100 Expr *clause = restrictinfo->clause;
110 EquivalenceClass *ec1,
112 EquivalenceMember *em1,
116 /* Should not already be marked as having generated an eclass */
117 Assert(restrictinfo->left_ec == NULL);
118 Assert(restrictinfo->right_ec == NULL);
120 /* Extract info from given clause */
121 Assert(is_opclause(clause));
122 opno = ((OpExpr *) clause)->opno;
123 collation = ((OpExpr *) clause)->inputcollid;
124 item1 = (Expr *) get_leftop(clause);
125 item2 = (Expr *) get_rightop(clause);
126 item1_relids = restrictinfo->left_relids;
127 item2_relids = restrictinfo->right_relids;
130 * Ensure both input expressions expose the desired collation (their types
131 * should be OK already); see comments for canonicalize_ec_expression.
133 item1 = canonicalize_ec_expression(item1,
134 exprType((Node *) item1),
136 item2 = canonicalize_ec_expression(item2,
137 exprType((Node *) item2),
141 * Reject clauses of the form X=X. These are not as redundant as they
142 * might seem at first glance: assuming the operator is strict, this is
143 * really an expensive way to write X IS NOT NULL. So we must not risk
144 * just losing the clause, which would be possible if there is already a
145 * single-element EquivalenceClass containing X. The case is not common
146 * enough to be worth contorting the EC machinery for, so just reject the
147 * clause and let it be processed as a normal restriction clause.
149 if (equal(item1, item2))
150 return false; /* X=X is not a useful equivalence */
153 * If below outer join, check for strictness, else reject.
155 if (below_outer_join)
157 if (!bms_is_empty(item1_relids) &&
158 contain_nonstrict_functions((Node *) item1))
159 return false; /* LHS is non-strict but not constant */
160 if (!bms_is_empty(item2_relids) &&
161 contain_nonstrict_functions((Node *) item2))
162 return false; /* RHS is non-strict but not constant */
166 * We use the declared input types of the operator, not exprType() of the
167 * inputs, as the nominal datatypes for opfamily lookup. This presumes
168 * that btree operators are always registered with amoplefttype and
169 * amoprighttype equal to their declared input types. We will need this
170 * info anyway to build EquivalenceMember nodes, and by extracting it now
171 * we can use type comparisons to short-circuit some equal() tests.
173 op_input_types(opno, &item1_type, &item2_type);
175 opfamilies = restrictinfo->mergeopfamilies;
178 * Sweep through the existing EquivalenceClasses looking for matches to
179 * item1 and item2. These are the possible outcomes:
181 * 1. We find both in the same EC. The equivalence is already known, so
182 * there's nothing to do.
184 * 2. We find both in different ECs. Merge the two ECs together.
186 * 3. We find just one. Add the other to its EC.
188 * 4. We find neither. Make a new, two-entry EC.
190 * Note: since all ECs are built through this process or the similar
191 * search in get_eclass_for_sort_expr(), it's impossible that we'd match
192 * an item in more than one existing nonvolatile EC. So it's okay to stop
193 * at the first match.
197 foreach(lc1, root->eq_classes)
199 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
202 /* Never match to a volatile EC */
203 if (cur_ec->ec_has_volatile)
207 * The collation has to match; check this first since it's cheaper
208 * than the opfamily comparison.
210 if (collation != cur_ec->ec_collation)
214 * A "match" requires matching sets of btree opfamilies. Use of
215 * equal() for this test has implications discussed in the comments
216 * for get_mergejoin_opfamilies().
218 if (!equal(opfamilies, cur_ec->ec_opfamilies))
221 foreach(lc2, cur_ec->ec_members)
223 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
225 Assert(!cur_em->em_is_child); /* no children yet */
228 * If below an outer join, don't match constants: they're not as
229 * constant as they look.
231 if ((below_outer_join || cur_ec->ec_below_outer_join) &&
236 item1_type == cur_em->em_datatype &&
237 equal(item1, cur_em->em_expr))
246 item2_type == cur_em->em_datatype &&
247 equal(item2, cur_em->em_expr))
260 /* Sweep finished, what did we find? */
264 /* If case 1, nothing to do, except add to sources */
267 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
268 ec1->ec_below_outer_join |= below_outer_join;
269 /* mark the RI as associated with this eclass */
270 restrictinfo->left_ec = ec1;
271 restrictinfo->right_ec = ec1;
272 /* mark the RI as usable with this pair of EMs */
273 restrictinfo->left_em = em1;
274 restrictinfo->right_em = em2;
279 * Case 2: need to merge ec1 and ec2. We add ec2's items to ec1, then
280 * set ec2's ec_merged link to point to ec1 and remove ec2 from the
281 * eq_classes list. We cannot simply delete ec2 because that could
282 * leave dangling pointers in existing PathKeys. We leave it behind
283 * with a link so that the merged EC can be found.
285 ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
286 ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
287 ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
288 ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
289 ec1->ec_has_const |= ec2->ec_has_const;
290 /* can't need to set has_volatile */
291 ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
292 ec2->ec_merged = ec1;
293 root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
294 /* just to avoid debugging confusion w/ dangling pointers: */
295 ec2->ec_members = NIL;
296 ec2->ec_sources = NIL;
297 ec2->ec_derives = NIL;
298 ec2->ec_relids = NULL;
299 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
300 ec1->ec_below_outer_join |= below_outer_join;
301 /* mark the RI as associated with this eclass */
302 restrictinfo->left_ec = ec1;
303 restrictinfo->right_ec = ec1;
304 /* mark the RI as usable with this pair of EMs */
305 restrictinfo->left_em = em1;
306 restrictinfo->right_em = em2;
310 /* Case 3: add item2 to ec1 */
311 em2 = add_eq_member(ec1, item2, item2_relids, false, item2_type);
312 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
313 ec1->ec_below_outer_join |= below_outer_join;
314 /* mark the RI as associated with this eclass */
315 restrictinfo->left_ec = ec1;
316 restrictinfo->right_ec = ec1;
317 /* mark the RI as usable with this pair of EMs */
318 restrictinfo->left_em = em1;
319 restrictinfo->right_em = em2;
323 /* Case 3: add item1 to ec2 */
324 em1 = add_eq_member(ec2, item1, item1_relids, false, item1_type);
325 ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
326 ec2->ec_below_outer_join |= below_outer_join;
327 /* mark the RI as associated with this eclass */
328 restrictinfo->left_ec = ec2;
329 restrictinfo->right_ec = ec2;
330 /* mark the RI as usable with this pair of EMs */
331 restrictinfo->left_em = em1;
332 restrictinfo->right_em = em2;
336 /* Case 4: make a new, two-entry EC */
337 EquivalenceClass *ec = makeNode(EquivalenceClass);
339 ec->ec_opfamilies = opfamilies;
340 ec->ec_collation = collation;
341 ec->ec_members = NIL;
342 ec->ec_sources = list_make1(restrictinfo);
343 ec->ec_derives = NIL;
344 ec->ec_relids = NULL;
345 ec->ec_has_const = false;
346 ec->ec_has_volatile = false;
347 ec->ec_below_outer_join = below_outer_join;
348 ec->ec_broken = false;
350 ec->ec_merged = NULL;
351 em1 = add_eq_member(ec, item1, item1_relids, false, item1_type);
352 em2 = add_eq_member(ec, item2, item2_relids, false, item2_type);
354 root->eq_classes = lappend(root->eq_classes, ec);
356 /* mark the RI as associated with this eclass */
357 restrictinfo->left_ec = ec;
358 restrictinfo->right_ec = ec;
359 /* mark the RI as usable with this pair of EMs */
360 restrictinfo->left_em = em1;
361 restrictinfo->right_em = em2;
368 * canonicalize_ec_expression
370 * This function ensures that the expression exposes the expected type and
371 * collation, so that it will be equal() to other equivalence-class expressions
372 * that it ought to be equal() to.
374 * The rule for datatypes is that the exposed type should match what it would
375 * be for an input to an operator of the EC's opfamilies; which is usually
376 * the declared input type of the operator, but in the case of polymorphic
377 * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
378 * Expressions coming in from quals will generally have the right type
379 * already, but expressions coming from indexkeys may not (because they are
380 * represented without any explicit relabel in pg_index), and the same problem
381 * occurs for sort expressions (because the parser is likewise cavalier about
382 * putting relabels on them). Such cases will be binary-compatible with the
383 * real operators, so adding a RelabelType is sufficient.
385 * Also, the expression's exposed collation must match the EC's collation.
386 * This is important because in comparisons like "foo < bar COLLATE baz",
387 * only one of the expressions has the correct exposed collation as we receive
388 * it from the parser. Forcing both of them to have it ensures that all
389 * variant spellings of such a construct behave the same. Again, we can
390 * stick on a RelabelType to force the right exposed collation. (It might
391 * work to not label the collation at all in EC members, but this is risky
392 * since some parts of the system expect exprCollation() to deliver the
393 * right answer for a sort key.)
395 * Note this code assumes that the expression has already been through
396 * eval_const_expressions, so there are no CollateExprs and no redundant
400 canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
402 Oid expr_type = exprType((Node *) expr);
405 * For a polymorphic-input-type opclass, just keep the same exposed type.
407 if (IsPolymorphicType(req_type))
408 req_type = expr_type;
411 * No work if the expression exposes the right type/collation already.
413 if (expr_type != req_type ||
414 exprCollation((Node *) expr) != req_collation)
417 * Strip any existing RelabelType, then add a new one if needed.
418 * This is to preserve the invariant of no redundant RelabelTypes.
420 * If we have to change the exposed type of the stripped expression,
421 * set typmod to -1 (since the new type may not have the same typmod
422 * interpretation). If we only have to change collation, preserve
423 * the exposed typmod.
425 while (expr && IsA(expr, RelabelType))
426 expr = (Expr *) ((RelabelType *) expr)->arg;
428 if (exprType((Node *) expr) != req_type)
429 expr = (Expr *) makeRelabelType(expr,
434 else if (exprCollation((Node *) expr) != req_collation)
435 expr = (Expr *) makeRelabelType(expr,
437 exprTypmod((Node *) expr),
446 * add_eq_member - build a new EquivalenceMember and add it to an EC
448 static EquivalenceMember *
449 add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
450 bool is_child, Oid datatype)
452 EquivalenceMember *em = makeNode(EquivalenceMember);
455 em->em_relids = relids;
456 em->em_is_const = false;
457 em->em_is_child = is_child;
458 em->em_datatype = datatype;
460 if (bms_is_empty(relids))
463 * No Vars, assume it's a pseudoconstant. This is correct for entries
464 * generated from process_equivalence(), because a WHERE clause can't
465 * contain aggregates or SRFs, and non-volatility was checked before
466 * process_equivalence() ever got called. But
467 * get_eclass_for_sort_expr() has to work harder. We put the tests
468 * there not here to save cycles in the equivalence case.
471 em->em_is_const = true;
472 ec->ec_has_const = true;
473 /* it can't affect ec_relids */
475 else if (!is_child) /* child members don't add to ec_relids */
477 ec->ec_relids = bms_add_members(ec->ec_relids, relids);
479 ec->ec_members = lappend(ec->ec_members, em);
486 * get_eclass_for_sort_expr
487 * Given an expression and opfamily/collation info, find an existing
488 * equivalence class it is a member of; if none, optionally build a new
489 * single-member EquivalenceClass for it.
491 * sortref is the SortGroupRef of the originating SortGroupClause, if any,
492 * or zero if not. (It should never be zero if the expression is volatile!)
494 * If create_it is TRUE, we'll build a new EquivalenceClass when there is no
495 * match. If create_it is FALSE, we just return NULL when no match.
497 * This can be used safely both before and after EquivalenceClass merging;
498 * since it never causes merging it does not invalidate any existing ECs
499 * or PathKeys. However, ECs added after path generation has begun are
500 * of limited usefulness, so usually it's best to create them beforehand.
502 * Note: opfamilies must be chosen consistently with the way
503 * process_equivalence() would do; that is, generated from a mergejoinable
504 * equality operator. Else we might fail to detect valid equivalences,
505 * generating poor (but not incorrect) plans.
508 get_eclass_for_sort_expr(PlannerInfo *root,
516 EquivalenceClass *newec;
517 EquivalenceMember *newem;
519 MemoryContext oldcontext;
522 * Ensure the expression exposes the correct type and collation.
524 expr = canonicalize_ec_expression(expr, opcintype, collation);
527 * Scan through the existing EquivalenceClasses for a match
529 foreach(lc1, root->eq_classes)
531 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
535 * Never match to a volatile EC, except when we are looking at another
536 * reference to the same volatile SortGroupClause.
538 if (cur_ec->ec_has_volatile &&
539 (sortref == 0 || sortref != cur_ec->ec_sortref))
542 if (collation != cur_ec->ec_collation)
544 if (!equal(opfamilies, cur_ec->ec_opfamilies))
547 foreach(lc2, cur_ec->ec_members)
549 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
552 * If below an outer join, don't match constants: they're not as
553 * constant as they look.
555 if (cur_ec->ec_below_outer_join &&
559 if (opcintype == cur_em->em_datatype &&
560 equal(expr, cur_em->em_expr))
561 return cur_ec; /* Match! */
565 /* No match; does caller want a NULL result? */
570 * OK, build a new single-member EC
572 * Here, we must be sure that we construct the EC in the right context.
574 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
576 newec = makeNode(EquivalenceClass);
577 newec->ec_opfamilies = list_copy(opfamilies);
578 newec->ec_collation = collation;
579 newec->ec_members = NIL;
580 newec->ec_sources = NIL;
581 newec->ec_derives = NIL;
582 newec->ec_relids = NULL;
583 newec->ec_has_const = false;
584 newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
585 newec->ec_below_outer_join = false;
586 newec->ec_broken = false;
587 newec->ec_sortref = sortref;
588 newec->ec_merged = NULL;
590 if (newec->ec_has_volatile && sortref == 0) /* should not happen */
591 elog(ERROR, "volatile EquivalenceClass has no sortref");
593 newem = add_eq_member(newec, copyObject(expr), pull_varnos((Node *) expr),
597 * add_eq_member doesn't check for volatile functions, set-returning
598 * functions, aggregates, or window functions, but such could appear in
599 * sort expressions; so we have to check whether its const-marking was
602 if (newec->ec_has_const)
604 if (newec->ec_has_volatile ||
605 expression_returns_set((Node *) expr) ||
606 contain_agg_clause((Node *) expr) ||
607 contain_window_function((Node *) expr))
609 newec->ec_has_const = false;
610 newem->em_is_const = false;
614 root->eq_classes = lappend(root->eq_classes, newec);
616 MemoryContextSwitchTo(oldcontext);
623 * generate_base_implied_equalities
624 * Generate any restriction clauses that we can deduce from equivalence
627 * When an EC contains pseudoconstants, our strategy is to generate
628 * "member = const1" clauses where const1 is the first constant member, for
629 * every other member (including other constants). If we are able to do this
630 * then we don't need any "var = var" comparisons because we've successfully
631 * constrained all the vars at their points of creation. If we fail to
632 * generate any of these clauses due to lack of cross-type operators, we fall
633 * back to the "ec_broken" strategy described below. (XXX if there are
634 * multiple constants of different types, it's possible that we might succeed
635 * in forming all the required clauses if we started from a different const
636 * member; but this seems a sufficiently hokey corner case to not be worth
637 * spending lots of cycles on.)
639 * For ECs that contain no pseudoconstants, we generate derived clauses
640 * "member1 = member2" for each pair of members belonging to the same base
641 * relation (actually, if there are more than two for the same base relation,
642 * we only need enough clauses to link each to each other). This provides
643 * the base case for the recursion: each row emitted by a base relation scan
644 * will constrain all computable members of the EC to be equal. As each
645 * join path is formed, we'll add additional derived clauses on-the-fly
646 * to maintain this invariant (see generate_join_implied_equalities).
648 * If the opfamilies used by the EC do not provide complete sets of cross-type
649 * equality operators, it is possible that we will fail to generate a clause
650 * that must be generated to maintain the invariant. (An example: given
651 * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
652 * generate "a.x = a.z" as a restriction clause for A.) In this case we mark
653 * the EC "ec_broken" and fall back to regurgitating its original source
654 * RestrictInfos at appropriate times. We do not try to retract any derived
655 * clauses already generated from the broken EC, so the resulting plan could
656 * be poor due to bad selectivity estimates caused by redundant clauses. But
657 * the correct solution to that is to fix the opfamilies ...
659 * Equality clauses derived by this function are passed off to
660 * process_implied_equality (in plan/initsplan.c) to be inserted into the
661 * restrictinfo datastructures. Note that this must be called after initial
662 * scanning of the quals and before Path construction begins.
664 * We make no attempt to avoid generating duplicate RestrictInfos here: we
665 * don't search ec_sources for matches, nor put the created RestrictInfos
666 * into ec_derives. Doing so would require some slightly ugly changes in
667 * initsplan.c's API, and there's no real advantage, because the clauses
668 * generated here can't duplicate anything we will generate for joins anyway.
671 generate_base_implied_equalities(PlannerInfo *root)
676 foreach(lc, root->eq_classes)
678 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
680 Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
681 Assert(!ec->ec_broken); /* not yet anyway... */
683 /* Single-member ECs won't generate any deductions */
684 if (list_length(ec->ec_members) <= 1)
687 if (ec->ec_has_const)
688 generate_base_implied_equalities_const(root, ec);
690 generate_base_implied_equalities_no_const(root, ec);
692 /* Recover if we failed to generate required derived clauses */
694 generate_base_implied_equalities_broken(root, ec);
698 * This is also a handy place to mark base rels (which should all exist by
699 * now) with flags showing whether they have pending eclass joins.
701 for (rti = 1; rti < root->simple_rel_array_size; rti++)
703 RelOptInfo *brel = root->simple_rel_array[rti];
708 brel->has_eclass_joins = has_relevant_eclass_joinclause(root, brel);
713 * generate_base_implied_equalities when EC contains pseudoconstant(s)
716 generate_base_implied_equalities_const(PlannerInfo *root,
717 EquivalenceClass *ec)
719 EquivalenceMember *const_em = NULL;
723 * In the trivial case where we just had one "var = const" clause, push
724 * the original clause back into the main planner machinery. There is
725 * nothing to be gained by doing it differently, and we save the effort to
726 * re-build and re-analyze an equality clause that will be exactly
727 * equivalent to the old one.
729 if (list_length(ec->ec_members) == 2 &&
730 list_length(ec->ec_sources) == 1)
732 RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
734 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
736 distribute_restrictinfo_to_rels(root, restrictinfo);
741 /* Find the constant member to use */
742 foreach(lc, ec->ec_members)
744 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
746 if (cur_em->em_is_const)
752 Assert(const_em != NULL);
754 /* Generate a derived equality against each other member */
755 foreach(lc, ec->ec_members)
757 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
760 Assert(!cur_em->em_is_child); /* no children yet */
761 if (cur_em == const_em)
763 eq_op = select_equality_operator(ec,
765 const_em->em_datatype);
766 if (!OidIsValid(eq_op))
769 ec->ec_broken = true;
772 process_implied_equality(root, eq_op, ec->ec_collation,
773 cur_em->em_expr, const_em->em_expr,
775 ec->ec_below_outer_join,
776 cur_em->em_is_const);
781 * generate_base_implied_equalities when EC contains no pseudoconstants
784 generate_base_implied_equalities_no_const(PlannerInfo *root,
785 EquivalenceClass *ec)
787 EquivalenceMember **prev_ems;
791 * We scan the EC members once and track the last-seen member for each
792 * base relation. When we see another member of the same base relation,
793 * we generate "prev_mem = cur_mem". This results in the minimum number
794 * of derived clauses, but it's possible that it will fail when a
795 * different ordering would succeed. XXX FIXME: use a UNION-FIND
796 * algorithm similar to the way we build merged ECs. (Use a list-of-lists
799 prev_ems = (EquivalenceMember **)
800 palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
802 foreach(lc, ec->ec_members)
804 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
807 Assert(!cur_em->em_is_child); /* no children yet */
808 if (bms_membership(cur_em->em_relids) != BMS_SINGLETON)
810 relid = bms_singleton_member(cur_em->em_relids);
811 Assert(relid < root->simple_rel_array_size);
813 if (prev_ems[relid] != NULL)
815 EquivalenceMember *prev_em = prev_ems[relid];
818 eq_op = select_equality_operator(ec,
819 prev_em->em_datatype,
820 cur_em->em_datatype);
821 if (!OidIsValid(eq_op))
824 ec->ec_broken = true;
827 process_implied_equality(root, eq_op, ec->ec_collation,
828 prev_em->em_expr, cur_em->em_expr,
830 ec->ec_below_outer_join,
833 prev_ems[relid] = cur_em;
839 * We also have to make sure that all the Vars used in the member clauses
840 * will be available at any join node we might try to reference them at.
841 * For the moment we force all the Vars to be available at all join nodes
842 * for this eclass. Perhaps this could be improved by doing some
843 * pre-analysis of which members we prefer to join, but it's no worse than
844 * what happened in the pre-8.3 code.
846 foreach(lc, ec->ec_members)
848 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
849 List *vars = pull_var_clause((Node *) cur_em->em_expr,
850 PVC_INCLUDE_PLACEHOLDERS);
852 add_vars_to_targetlist(root, vars, ec->ec_relids);
858 * generate_base_implied_equalities cleanup after failure
860 * What we must do here is push any zero- or one-relation source RestrictInfos
861 * of the EC back into the main restrictinfo datastructures. Multi-relation
862 * clauses will be regurgitated later by generate_join_implied_equalities().
863 * (We do it this way to maintain continuity with the case that ec_broken
864 * becomes set only after we've gone up a join level or two.)
867 generate_base_implied_equalities_broken(PlannerInfo *root,
868 EquivalenceClass *ec)
872 foreach(lc, ec->ec_sources)
874 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
876 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
877 distribute_restrictinfo_to_rels(root, restrictinfo);
883 * generate_join_implied_equalities
884 * Generate any join clauses that we can deduce from equivalence classes.
886 * At a join node, we must enforce restriction clauses sufficient to ensure
887 * that all equivalence-class members computable at that node are equal.
888 * Since the set of clauses to enforce can vary depending on which subset
889 * relations are the inputs, we have to compute this afresh for each join
890 * path pair. Hence a fresh List of RestrictInfo nodes is built and passed
893 * The results are sufficient for use in merge, hash, and plain nestloop join
894 * methods. We do not worry here about selecting clauses that are optimal
895 * for use in a nestloop-with-inner-indexscan join, however. indxpath.c makes
896 * its own selections of clauses to use, and if the ones we pick here are
897 * redundant with those, the extras will be eliminated in createplan.c.
899 * Because the same join clauses are likely to be needed multiple times as
900 * we consider different join paths, we avoid generating multiple copies:
901 * whenever we select a particular pair of EquivalenceMembers to join,
902 * we check to see if the pair matches any original clause (in ec_sources)
903 * or previously-built clause (in ec_derives). This saves memory and allows
904 * re-use of information cached in RestrictInfos.
907 generate_join_implied_equalities(PlannerInfo *root,
909 RelOptInfo *outer_rel,
910 RelOptInfo *inner_rel)
915 foreach(lc, root->eq_classes)
917 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
920 /* ECs containing consts do not need any further enforcement */
921 if (ec->ec_has_const)
924 /* Single-member ECs won't generate any deductions */
925 if (list_length(ec->ec_members) <= 1)
928 /* We can quickly ignore any that don't overlap the join, too */
929 if (!bms_overlap(ec->ec_relids, joinrel->relids))
933 sublist = generate_join_implied_equalities_normal(root,
939 /* Recover if we failed to generate required derived clauses */
941 sublist = generate_join_implied_equalities_broken(root,
947 result = list_concat(result, sublist);
954 * generate_join_implied_equalities for a still-valid EC
957 generate_join_implied_equalities_normal(PlannerInfo *root,
958 EquivalenceClass *ec,
960 RelOptInfo *outer_rel,
961 RelOptInfo *inner_rel)
964 List *new_members = NIL;
965 List *outer_members = NIL;
966 List *inner_members = NIL;
970 * First, scan the EC to identify member values that are computable at the
971 * outer rel, at the inner rel, or at this relation but not in either
972 * input rel. The outer-rel members should already be enforced equal,
973 * likewise for the inner-rel members. We'll need to create clauses to
974 * enforce that any newly computable members are all equal to each other
975 * as well as to at least one input member, plus enforce at least one
976 * outer-rel member equal to at least one inner-rel member.
978 foreach(lc1, ec->ec_members)
980 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
982 if (cur_em->em_is_child)
983 continue; /* ignore children here */
984 if (!bms_is_subset(cur_em->em_relids, joinrel->relids))
985 continue; /* ignore --- not computable yet */
987 if (bms_is_subset(cur_em->em_relids, outer_rel->relids))
988 outer_members = lappend(outer_members, cur_em);
989 else if (bms_is_subset(cur_em->em_relids, inner_rel->relids))
990 inner_members = lappend(inner_members, cur_em);
992 new_members = lappend(new_members, cur_em);
996 * First, select the joinclause if needed. We can equate any one outer
997 * member to any one inner member, but we have to find a datatype
998 * combination for which an opfamily member operator exists. If we have
999 * choices, we prefer simple Var members (possibly with RelabelType) since
1000 * these are (a) cheapest to compute at runtime and (b) most likely to
1001 * have useful statistics. Also, prefer operators that are also
1004 if (outer_members && inner_members)
1006 EquivalenceMember *best_outer_em = NULL;
1007 EquivalenceMember *best_inner_em = NULL;
1008 Oid best_eq_op = InvalidOid;
1009 int best_score = -1;
1010 RestrictInfo *rinfo;
1012 foreach(lc1, outer_members)
1014 EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1017 foreach(lc2, inner_members)
1019 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1023 eq_op = select_equality_operator(ec,
1024 outer_em->em_datatype,
1025 inner_em->em_datatype);
1026 if (!OidIsValid(eq_op))
1029 if (IsA(outer_em->em_expr, Var) ||
1030 (IsA(outer_em->em_expr, RelabelType) &&
1031 IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1033 if (IsA(inner_em->em_expr, Var) ||
1034 (IsA(inner_em->em_expr, RelabelType) &&
1035 IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1037 if (op_hashjoinable(eq_op,
1038 exprType((Node *) outer_em->em_expr)))
1040 if (score > best_score)
1042 best_outer_em = outer_em;
1043 best_inner_em = inner_em;
1046 if (best_score == 3)
1047 break; /* no need to look further */
1050 if (best_score == 3)
1051 break; /* no need to look further */
1056 ec->ec_broken = true;
1061 * Create clause, setting parent_ec to mark it as redundant with other
1064 rinfo = create_join_clause(root, ec, best_eq_op,
1065 best_outer_em, best_inner_em,
1068 result = lappend(result, rinfo);
1072 * Now deal with building restrictions for any expressions that involve
1073 * Vars from both sides of the join. We have to equate all of these to
1074 * each other as well as to at least one old member (if any).
1076 * XXX as in generate_base_implied_equalities_no_const, we could be a lot
1077 * smarter here to avoid unnecessary failures in cross-type situations.
1078 * For now, use the same left-to-right method used there.
1082 List *old_members = list_concat(outer_members, inner_members);
1083 EquivalenceMember *prev_em = NULL;
1084 RestrictInfo *rinfo;
1086 /* For now, arbitrarily take the first old_member as the one to use */
1088 new_members = lappend(new_members, linitial(old_members));
1090 foreach(lc1, new_members)
1092 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
1094 if (prev_em != NULL)
1098 eq_op = select_equality_operator(ec,
1099 prev_em->em_datatype,
1100 cur_em->em_datatype);
1101 if (!OidIsValid(eq_op))
1104 ec->ec_broken = true;
1107 /* do NOT set parent_ec, this qual is not redundant! */
1108 rinfo = create_join_clause(root, ec, eq_op,
1112 result = lappend(result, rinfo);
1122 * generate_join_implied_equalities cleanup after failure
1124 * Return any original RestrictInfos that are enforceable at this join.
1127 generate_join_implied_equalities_broken(PlannerInfo *root,
1128 EquivalenceClass *ec,
1129 RelOptInfo *joinrel,
1130 RelOptInfo *outer_rel,
1131 RelOptInfo *inner_rel)
1136 foreach(lc, ec->ec_sources)
1138 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1140 if (bms_is_subset(restrictinfo->required_relids, joinrel->relids) &&
1141 !bms_is_subset(restrictinfo->required_relids, outer_rel->relids) &&
1142 !bms_is_subset(restrictinfo->required_relids, inner_rel->relids))
1143 result = lappend(result, restrictinfo);
1151 * select_equality_operator
1152 * Select a suitable equality operator for comparing two EC members
1154 * Returns InvalidOid if no operator can be found for this datatype combination
1157 select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
1161 foreach(lc, ec->ec_opfamilies)
1163 Oid opfamily = lfirst_oid(lc);
1166 opno = get_opfamily_member(opfamily, lefttype, righttype,
1167 BTEqualStrategyNumber);
1168 if (OidIsValid(opno))
1176 * create_join_clause
1177 * Find or make a RestrictInfo comparing the two given EC members
1178 * with the given operator.
1180 * parent_ec is either equal to ec (if the clause is a potentially-redundant
1181 * join clause) or NULL (if not). We have to treat this as part of the
1182 * match requirements --- it's possible that a clause comparing the same two
1183 * EMs is a join clause in one join path and a restriction clause in another.
1185 static RestrictInfo *
1186 create_join_clause(PlannerInfo *root,
1187 EquivalenceClass *ec, Oid opno,
1188 EquivalenceMember *leftem,
1189 EquivalenceMember *rightem,
1190 EquivalenceClass *parent_ec)
1192 RestrictInfo *rinfo;
1194 MemoryContext oldcontext;
1197 * Search to see if we already built a RestrictInfo for this pair of
1198 * EquivalenceMembers. We can use either original source clauses or
1199 * previously-derived clauses. The check on opno is probably redundant,
1202 foreach(lc, ec->ec_sources)
1204 rinfo = (RestrictInfo *) lfirst(lc);
1205 if (rinfo->left_em == leftem &&
1206 rinfo->right_em == rightem &&
1207 rinfo->parent_ec == parent_ec &&
1208 opno == ((OpExpr *) rinfo->clause)->opno)
1212 foreach(lc, ec->ec_derives)
1214 rinfo = (RestrictInfo *) lfirst(lc);
1215 if (rinfo->left_em == leftem &&
1216 rinfo->right_em == rightem &&
1217 rinfo->parent_ec == parent_ec &&
1218 opno == ((OpExpr *) rinfo->clause)->opno)
1223 * Not there, so build it, in planner context so we can re-use it. (Not
1224 * important in normal planning, but definitely so in GEQO.)
1226 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1228 rinfo = build_implied_join_equality(opno,
1232 bms_union(leftem->em_relids,
1233 rightem->em_relids));
1235 /* Mark the clause as redundant, or not */
1236 rinfo->parent_ec = parent_ec;
1239 * We know the correct values for left_ec/right_ec, ie this particular EC,
1240 * so we can just set them directly instead of forcing another lookup.
1242 rinfo->left_ec = ec;
1243 rinfo->right_ec = ec;
1245 /* Mark it as usable with these EMs */
1246 rinfo->left_em = leftem;
1247 rinfo->right_em = rightem;
1248 /* and save it for possible re-use */
1249 ec->ec_derives = lappend(ec->ec_derives, rinfo);
1251 MemoryContextSwitchTo(oldcontext);
1258 * reconsider_outer_join_clauses
1259 * Re-examine any outer-join clauses that were set aside by
1260 * distribute_qual_to_rels(), and see if we can derive any
1261 * EquivalenceClasses from them. Then, if they were not made
1262 * redundant, push them out into the regular join-clause lists.
1264 * When we have mergejoinable clauses A = B that are outer-join clauses,
1265 * we can't blindly combine them with other clauses A = C to deduce B = C,
1266 * since in fact the "equality" A = B won't necessarily hold above the
1267 * outer join (one of the variables might be NULL instead). Nonetheless
1268 * there are cases where we can add qual clauses using transitivity.
1270 * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
1271 * for which there is also an equivalence clause OUTERVAR = CONSTANT.
1272 * It is safe and useful to push a clause INNERVAR = CONSTANT into the
1273 * evaluation of the inner (nullable) relation, because any inner rows not
1274 * meeting this condition will not contribute to the outer-join result anyway.
1275 * (Any outer rows they could join to will be eliminated by the pushed-down
1276 * equivalence clause.)
1278 * Note that the above rule does not work for full outer joins; nor is it
1279 * very interesting to consider cases where the generated equivalence clause
1280 * would involve relations outside the outer join, since such clauses couldn't
1281 * be pushed into the inner side's scan anyway. So the restriction to
1282 * outervar = pseudoconstant is not really giving up anything.
1284 * For full-join cases, we can only do something useful if it's a FULL JOIN
1285 * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
1286 * By the time it gets here, the merged column will look like
1287 * COALESCE(LEFTVAR, RIGHTVAR)
1288 * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
1289 * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
1290 * and RIGHTVAR = CONSTANT into the input relations, since any rows not
1291 * meeting these conditions cannot contribute to the join result.
1293 * Again, there isn't any traction to be gained by trying to deal with
1294 * clauses comparing a mergedvar to a non-pseudoconstant. So we can make
1295 * use of the EquivalenceClasses to search for matching variables that were
1296 * equivalenced to constants. The interesting outer-join clauses were
1297 * accumulated for us by distribute_qual_to_rels.
1299 * When we find one of these cases, we implement the changes we want by
1300 * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
1301 * and pushing it into the EquivalenceClass structures. This is because we
1302 * may already know that INNERVAR is equivalenced to some other var(s), and
1303 * we'd like the constant to propagate to them too. Note that it would be
1304 * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
1305 * that could result in propagating constant restrictions from
1306 * INNERVAR to OUTERVAR, which would be very wrong.
1308 * It's possible that the INNERVAR is also an OUTERVAR for some other
1309 * outer-join clause, in which case the process can be repeated. So we repeat
1310 * looping over the lists of clauses until no further deductions can be made.
1311 * Whenever we do make a deduction, we remove the generating clause from the
1312 * lists, since we don't want to make the same deduction twice.
1314 * If we don't find any match for a set-aside outer join clause, we must
1315 * throw it back into the regular joinclause processing by passing it to
1316 * distribute_restrictinfo_to_rels(). If we do generate a derived clause,
1317 * however, the outer-join clause is redundant. We still throw it back,
1318 * because otherwise the join will be seen as a clauseless join and avoided
1319 * during join order searching; but we mark it as redundant to keep from
1320 * messing up the joinrel's size estimate. (This behavior means that the
1321 * API for this routine is uselessly complex: we could have just put all
1322 * the clauses into the regular processing initially. We keep it because
1323 * someday we might want to do something else, such as inserting "dummy"
1324 * joinclauses instead of real ones.)
1326 * Outer join clauses that are marked outerjoin_delayed are special: this
1327 * condition means that one or both VARs might go to null due to a lower
1328 * outer join. We can still push a constant through the clause, but only
1329 * if its operator is strict; and we *have to* throw the clause back into
1330 * regular joinclause processing. By keeping the strict join clause,
1331 * we ensure that any null-extended rows that are mistakenly generated due
1332 * to suppressing rows not matching the constant will be rejected at the
1333 * upper outer join. (This doesn't work for full-join clauses.)
1336 reconsider_outer_join_clauses(PlannerInfo *root)
1343 /* Outer loop repeats until we find no more deductions */
1348 /* Process the LEFT JOIN clauses */
1350 for (cell = list_head(root->left_join_clauses); cell; cell = next)
1352 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1355 if (reconsider_outer_join_clause(root, rinfo, true))
1358 /* remove it from the list */
1359 root->left_join_clauses =
1360 list_delete_cell(root->left_join_clauses, cell, prev);
1361 /* we throw it back anyway (see notes above) */
1362 /* but the thrown-back clause has no extra selectivity */
1363 rinfo->norm_selec = 2.0;
1364 rinfo->outer_selec = 1.0;
1365 distribute_restrictinfo_to_rels(root, rinfo);
1371 /* Process the RIGHT JOIN clauses */
1373 for (cell = list_head(root->right_join_clauses); cell; cell = next)
1375 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1378 if (reconsider_outer_join_clause(root, rinfo, false))
1381 /* remove it from the list */
1382 root->right_join_clauses =
1383 list_delete_cell(root->right_join_clauses, cell, prev);
1384 /* we throw it back anyway (see notes above) */
1385 /* but the thrown-back clause has no extra selectivity */
1386 rinfo->norm_selec = 2.0;
1387 rinfo->outer_selec = 1.0;
1388 distribute_restrictinfo_to_rels(root, rinfo);
1394 /* Process the FULL JOIN clauses */
1396 for (cell = list_head(root->full_join_clauses); cell; cell = next)
1398 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1401 if (reconsider_full_join_clause(root, rinfo))
1404 /* remove it from the list */
1405 root->full_join_clauses =
1406 list_delete_cell(root->full_join_clauses, cell, prev);
1407 /* we throw it back anyway (see notes above) */
1408 /* but the thrown-back clause has no extra selectivity */
1409 rinfo->norm_selec = 2.0;
1410 rinfo->outer_selec = 1.0;
1411 distribute_restrictinfo_to_rels(root, rinfo);
1418 /* Now, any remaining clauses have to be thrown back */
1419 foreach(cell, root->left_join_clauses)
1421 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1423 distribute_restrictinfo_to_rels(root, rinfo);
1425 foreach(cell, root->right_join_clauses)
1427 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1429 distribute_restrictinfo_to_rels(root, rinfo);
1431 foreach(cell, root->full_join_clauses)
1433 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1435 distribute_restrictinfo_to_rels(root, rinfo);
1440 * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
1442 * Returns TRUE if we were able to propagate a constant through the clause.
1445 reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo,
1455 Relids inner_relids;
1458 Assert(is_opclause(rinfo->clause));
1459 opno = ((OpExpr *) rinfo->clause)->opno;
1460 collation = ((OpExpr *) rinfo->clause)->inputcollid;
1462 /* If clause is outerjoin_delayed, operator must be strict */
1463 if (rinfo->outerjoin_delayed && !op_strict(opno))
1466 /* Extract needed info from the clause */
1467 op_input_types(opno, &left_type, &right_type);
1470 outervar = (Expr *) get_leftop(rinfo->clause);
1471 innervar = (Expr *) get_rightop(rinfo->clause);
1472 inner_datatype = right_type;
1473 inner_relids = rinfo->right_relids;
1477 outervar = (Expr *) get_rightop(rinfo->clause);
1478 innervar = (Expr *) get_leftop(rinfo->clause);
1479 inner_datatype = left_type;
1480 inner_relids = rinfo->left_relids;
1483 /* Scan EquivalenceClasses for a match to outervar */
1484 foreach(lc1, root->eq_classes)
1486 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1490 /* Ignore EC unless it contains pseudoconstants */
1491 if (!cur_ec->ec_has_const)
1493 /* Never match to a volatile EC */
1494 if (cur_ec->ec_has_volatile)
1496 /* It has to match the outer-join clause as to semantics, too */
1497 if (collation != cur_ec->ec_collation)
1499 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1501 /* Does it contain a match to outervar? */
1503 foreach(lc2, cur_ec->ec_members)
1505 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1507 if (equal(outervar, cur_em->em_expr))
1514 continue; /* no match, so ignore this EC */
1517 * Yes it does! Try to generate a clause INNERVAR = CONSTANT for each
1518 * CONSTANT in the EC. Note that we must succeed with at least one
1519 * constant before we can decide to throw away the outer-join clause.
1522 foreach(lc2, cur_ec->ec_members)
1524 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1526 RestrictInfo *newrinfo;
1528 if (!cur_em->em_is_const)
1529 continue; /* ignore non-const members */
1530 eq_op = select_equality_operator(cur_ec,
1532 cur_em->em_datatype);
1533 if (!OidIsValid(eq_op))
1534 continue; /* can't generate equality */
1535 newrinfo = build_implied_join_equality(eq_op,
1536 cur_ec->ec_collation,
1540 if (process_equivalence(root, newrinfo, true))
1545 * If we were able to equate INNERVAR to any constant, report success.
1546 * Otherwise, fall out of the search loop, since we know the OUTERVAR
1547 * appears in at most one EC.
1555 return false; /* failed to make any deduction */
1559 * reconsider_outer_join_clauses for a single FULL JOIN clause
1561 * Returns TRUE if we were able to propagate a constant through the clause.
1564 reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
1576 /* Can't use an outerjoin_delayed clause here */
1577 if (rinfo->outerjoin_delayed)
1580 /* Extract needed info from the clause */
1581 Assert(is_opclause(rinfo->clause));
1582 opno = ((OpExpr *) rinfo->clause)->opno;
1583 collation = ((OpExpr *) rinfo->clause)->inputcollid;
1584 op_input_types(opno, &left_type, &right_type);
1585 leftvar = (Expr *) get_leftop(rinfo->clause);
1586 rightvar = (Expr *) get_rightop(rinfo->clause);
1587 left_relids = rinfo->left_relids;
1588 right_relids = rinfo->right_relids;
1590 foreach(lc1, root->eq_classes)
1592 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1593 EquivalenceMember *coal_em = NULL;
1599 /* Ignore EC unless it contains pseudoconstants */
1600 if (!cur_ec->ec_has_const)
1602 /* Never match to a volatile EC */
1603 if (cur_ec->ec_has_volatile)
1605 /* It has to match the outer-join clause as to semantics, too */
1606 if (collation != cur_ec->ec_collation)
1608 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1612 * Does it contain a COALESCE(leftvar, rightvar) construct?
1614 * We can assume the COALESCE() inputs are in the same order as the
1615 * join clause, since both were automatically generated in the cases
1618 * XXX currently this may fail to match in cross-type cases because
1619 * the COALESCE will contain typecast operations while the join clause
1620 * may not (if there is a cross-type mergejoin operator available for
1621 * the two column types). Is it OK to strip implicit coercions from
1622 * the COALESCE arguments?
1625 foreach(lc2, cur_ec->ec_members)
1627 coal_em = (EquivalenceMember *) lfirst(lc2);
1628 if (IsA(coal_em->em_expr, CoalesceExpr))
1630 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
1634 if (list_length(cexpr->args) != 2)
1636 cfirst = (Node *) linitial(cexpr->args);
1637 csecond = (Node *) lsecond(cexpr->args);
1639 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
1647 continue; /* no match, so ignore this EC */
1650 * Yes it does! Try to generate clauses LEFTVAR = CONSTANT and
1651 * RIGHTVAR = CONSTANT for each CONSTANT in the EC. Note that we must
1652 * succeed with at least one constant for each var before we can
1653 * decide to throw away the outer-join clause.
1655 matchleft = matchright = false;
1656 foreach(lc2, cur_ec->ec_members)
1658 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1660 RestrictInfo *newrinfo;
1662 if (!cur_em->em_is_const)
1663 continue; /* ignore non-const members */
1664 eq_op = select_equality_operator(cur_ec,
1666 cur_em->em_datatype);
1667 if (OidIsValid(eq_op))
1669 newrinfo = build_implied_join_equality(eq_op,
1670 cur_ec->ec_collation,
1674 if (process_equivalence(root, newrinfo, true))
1677 eq_op = select_equality_operator(cur_ec,
1679 cur_em->em_datatype);
1680 if (OidIsValid(eq_op))
1682 newrinfo = build_implied_join_equality(eq_op,
1683 cur_ec->ec_collation,
1687 if (process_equivalence(root, newrinfo, true))
1693 * If we were able to equate both vars to constants, we're done, and
1694 * we can throw away the full-join clause as redundant. Moreover, we
1695 * can remove the COALESCE entry from the EC, since the added
1696 * restrictions ensure it will always have the expected value. (We
1697 * don't bother trying to update ec_relids or ec_sources.)
1699 if (matchleft && matchright)
1701 cur_ec->ec_members = list_delete_ptr(cur_ec->ec_members, coal_em);
1706 * Otherwise, fall out of the search loop, since we know the COALESCE
1707 * appears in at most one EC (XXX might stop being true if we allow
1708 * stripping of coercions above?)
1713 return false; /* failed to make any deduction */
1719 * Detect whether two expressions are known equal due to equivalence
1722 * Actually, this only shows that the expressions are equal according
1723 * to some opfamily's notion of equality --- but we only use it for
1724 * selectivity estimation, so a fuzzy idea of equality is OK.
1726 * Note: does not bother to check for "equal(item1, item2)"; caller must
1727 * check that case if it's possible to pass identical items.
1730 exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
1734 foreach(lc1, root->eq_classes)
1736 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1737 bool item1member = false;
1738 bool item2member = false;
1741 /* Never match to a volatile EC */
1742 if (ec->ec_has_volatile)
1745 foreach(lc2, ec->ec_members)
1747 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
1749 if (equal(item1, em->em_expr))
1751 else if (equal(item2, em->em_expr))
1753 /* Exit as soon as equality is proven */
1754 if (item1member && item2member)
1763 * add_child_rel_equivalences
1764 * Search for EC members that reference (only) the parent_rel, and
1765 * add transformed members referencing the child_rel.
1767 * Note that this function won't be called at all unless we have at least some
1768 * reason to believe that the EC members it generates will be useful.
1770 * parent_rel and child_rel could be derived from appinfo, but since the
1771 * caller has already computed them, we might as well just pass them in.
1774 add_child_rel_equivalences(PlannerInfo *root,
1775 AppendRelInfo *appinfo,
1776 RelOptInfo *parent_rel,
1777 RelOptInfo *child_rel)
1781 foreach(lc1, root->eq_classes)
1783 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1787 * If this EC contains a constant, then it's not useful for sorting
1788 * or driving an inner index-scan, so we skip generating child EMs.
1790 * If this EC contains a volatile expression, then generating child
1791 * EMs would be downright dangerous. We rely on a volatile EC having
1794 if (cur_ec->ec_has_const || cur_ec->ec_has_volatile)
1797 /* No point in searching if parent rel not mentioned in eclass */
1798 if (!bms_is_subset(parent_rel->relids, cur_ec->ec_relids))
1801 foreach(lc2, cur_ec->ec_members)
1803 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1805 /* Does it reference (only) parent_rel? */
1806 if (bms_equal(cur_em->em_relids, parent_rel->relids))
1808 /* Yes, generate transformed child version */
1811 child_expr = (Expr *)
1812 adjust_appendrel_attrs((Node *) cur_em->em_expr,
1814 (void) add_eq_member(cur_ec, child_expr, child_rel->relids,
1815 true, cur_em->em_datatype);
1823 * mutate_eclass_expressions
1824 * Apply an expression tree mutator to all expressions stored in
1825 * equivalence classes.
1827 * This is a bit of a hack ... it's currently needed only by planagg.c,
1828 * which needs to do a global search-and-replace of MIN/MAX Aggrefs
1829 * after eclasses are already set up. Without changing the eclasses too,
1830 * subsequent matching of ORDER BY clauses would fail.
1832 * Note that we assume the mutation won't affect relation membership or any
1833 * other properties we keep track of (which is a bit bogus, but by the time
1834 * planagg.c runs, it no longer matters). Also we must be called in the
1835 * main planner memory context.
1838 mutate_eclass_expressions(PlannerInfo *root,
1839 Node *(*mutator) (),
1844 foreach(lc1, root->eq_classes)
1846 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1849 foreach(lc2, cur_ec->ec_members)
1851 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1853 cur_em->em_expr = (Expr *)
1854 mutator((Node *) cur_em->em_expr, context);
1861 * find_eclass_clauses_for_index_join
1862 * Create joinclauses usable for a nestloop-with-inner-indexscan
1863 * scanning the given inner rel with the specified set of outer rels.
1866 find_eclass_clauses_for_index_join(PlannerInfo *root, RelOptInfo *rel,
1867 Relids outer_relids)
1870 bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1873 foreach(lc1, root->eq_classes)
1875 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1879 * Won't generate joinclauses if const or single-member (the latter
1880 * test covers the volatile case too)
1882 if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
1886 * No point in searching if rel not mentioned in eclass (but we can't
1887 * tell that for a child rel).
1889 if (!is_child_rel &&
1890 !bms_is_subset(rel->relids, cur_ec->ec_relids))
1892 /* ... nor if no overlap with outer_relids */
1893 if (!bms_overlap(outer_relids, cur_ec->ec_relids))
1896 /* Scan members, looking for indexable columns */
1897 foreach(lc2, cur_ec->ec_members)
1899 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1900 EquivalenceMember *best_outer_em = NULL;
1901 Oid best_eq_op = InvalidOid;
1904 if (!bms_equal(cur_em->em_relids, rel->relids) ||
1905 !eclass_matches_any_index(cur_ec, cur_em, rel))
1909 * Found one, so try to generate a join clause. This is like
1910 * generate_join_implied_equalities_normal, except simpler since
1911 * our only preference item is to pick a Var on the outer side. We
1912 * only need one join clause per index col.
1914 foreach(lc3, cur_ec->ec_members)
1916 EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc3);
1919 if (!bms_is_subset(outer_em->em_relids, outer_relids))
1921 eq_op = select_equality_operator(cur_ec,
1922 cur_em->em_datatype,
1923 outer_em->em_datatype);
1924 if (!OidIsValid(eq_op))
1926 best_outer_em = outer_em;
1928 if (IsA(outer_em->em_expr, Var) ||
1929 (IsA(outer_em->em_expr, RelabelType) &&
1930 IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1931 break; /* no need to look further */
1936 /* Found a suitable joinclause */
1937 RestrictInfo *rinfo;
1939 /* set parent_ec to mark as redundant with other joinclauses */
1940 rinfo = create_join_clause(root, cur_ec, best_eq_op,
1941 cur_em, best_outer_em,
1944 result = lappend(result, rinfo);
1947 * Note: we keep scanning here because we want to provide a
1948 * clause for every possible indexcol.
1959 * have_relevant_eclass_joinclause
1960 * Detect whether there is an EquivalenceClass that could produce
1961 * a joinclause between the two given relations.
1963 * This is essentially a very cut-down version of
1964 * generate_join_implied_equalities(). Note it's OK to occasionally say "yes"
1965 * incorrectly. Hence we don't bother with details like whether the lack of a
1966 * cross-type operator might prevent the clause from actually being generated.
1969 have_relevant_eclass_joinclause(PlannerInfo *root,
1970 RelOptInfo *rel1, RelOptInfo *rel2)
1974 foreach(lc1, root->eq_classes)
1976 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1982 * Won't generate joinclauses if single-member (this test covers the
1983 * volatile case too)
1985 if (list_length(ec->ec_members) <= 1)
1989 * Note we don't test ec_broken; if we did, we'd need a separate code
1990 * path to look through ec_sources. Checking the members anyway is OK
1991 * as a possibly-overoptimistic heuristic.
1993 * We don't test ec_has_const either, even though a const eclass won't
1994 * generate real join clauses. This is because if we had "WHERE a.x =
1995 * b.y and a.x = 42", it is worth considering a join between a and b,
1996 * since the join result is likely to be small even though it'll end
1997 * up being an unqualified nestloop.
2000 /* Needn't scan if it couldn't contain members from each rel */
2001 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
2002 !bms_overlap(rel2->relids, ec->ec_relids))
2005 /* Scan the EC to see if it has member(s) in each rel */
2006 has_rel1 = has_rel2 = false;
2007 foreach(lc2, ec->ec_members)
2009 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2011 if (cur_em->em_is_const || cur_em->em_is_child)
2012 continue; /* ignore consts and children here */
2013 if (bms_is_subset(cur_em->em_relids, rel1->relids))
2019 if (bms_is_subset(cur_em->em_relids, rel2->relids))
2027 if (has_rel1 && has_rel2)
2036 * has_relevant_eclass_joinclause
2037 * Detect whether there is an EquivalenceClass that could produce
2038 * a joinclause between the given relation and anything else.
2040 * This is the same as have_relevant_eclass_joinclause with the other rel
2041 * implicitly defined as "everything else in the query".
2044 has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
2048 foreach(lc1, root->eq_classes)
2050 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2056 * Won't generate joinclauses if single-member (this test covers the
2057 * volatile case too)
2059 if (list_length(ec->ec_members) <= 1)
2063 * Note we don't test ec_broken; if we did, we'd need a separate code
2064 * path to look through ec_sources. Checking the members anyway is OK
2065 * as a possibly-overoptimistic heuristic.
2067 * We don't test ec_has_const either, even though a const eclass won't
2068 * generate real join clauses. This is because if we had "WHERE a.x =
2069 * b.y and a.x = 42", it is worth considering a join between a and b,
2070 * since the join result is likely to be small even though it'll end
2071 * up being an unqualified nestloop.
2074 /* Needn't scan if it couldn't contain members from each rel */
2075 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
2076 bms_is_subset(ec->ec_relids, rel1->relids))
2079 /* Scan the EC to see if it has member(s) in each rel */
2080 has_rel1 = has_rel2 = false;
2081 foreach(lc2, ec->ec_members)
2083 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2085 if (cur_em->em_is_const || cur_em->em_is_child)
2086 continue; /* ignore consts and children here */
2087 if (bms_is_subset(cur_em->em_relids, rel1->relids))
2093 if (!bms_overlap(cur_em->em_relids, rel1->relids))
2101 if (has_rel1 && has_rel2)
2110 * eclass_useful_for_merging
2111 * Detect whether the EC could produce any mergejoinable join clauses
2112 * against the specified relation.
2114 * This is just a heuristic test and doesn't have to be exact; it's better
2115 * to say "yes" incorrectly than "no". Hence we don't bother with details
2116 * like whether the lack of a cross-type operator might prevent the clause
2117 * from actually being generated.
2120 eclass_useful_for_merging(EquivalenceClass *eclass,
2125 Assert(!eclass->ec_merged);
2128 * Won't generate joinclauses if const or single-member (the latter test
2129 * covers the volatile case too)
2131 if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
2135 * Note we don't test ec_broken; if we did, we'd need a separate code path
2136 * to look through ec_sources. Checking the members anyway is OK as a
2137 * possibly-overoptimistic heuristic.
2140 /* If rel already includes all members of eclass, no point in searching */
2141 if (bms_is_subset(eclass->ec_relids, rel->relids))
2144 /* To join, we need a member not in the given rel */
2145 foreach(lc, eclass->ec_members)
2147 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
2149 if (!cur_em->em_is_child &&
2150 !bms_overlap(cur_em->em_relids, rel->relids))