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/paths.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/var.h"
28 #include "utils/lsyscache.h"
31 static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
32 Expr *expr, Relids relids,
33 bool is_child, Oid datatype);
34 static void generate_base_implied_equalities_const(PlannerInfo *root,
35 EquivalenceClass *ec);
36 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
37 EquivalenceClass *ec);
38 static void generate_base_implied_equalities_broken(PlannerInfo *root,
39 EquivalenceClass *ec);
40 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
43 RelOptInfo *outer_rel,
44 RelOptInfo *inner_rel);
45 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
48 RelOptInfo *outer_rel,
49 RelOptInfo *inner_rel);
50 static Oid select_equality_operator(EquivalenceClass *ec,
51 Oid lefttype, Oid righttype);
52 static RestrictInfo *create_join_clause(PlannerInfo *root,
53 EquivalenceClass *ec, Oid opno,
54 EquivalenceMember *leftem,
55 EquivalenceMember *rightem,
56 EquivalenceClass *parent_ec);
57 static bool reconsider_outer_join_clause(PlannerInfo *root,
60 static bool reconsider_full_join_clause(PlannerInfo *root,
66 * The given clause has a mergejoinable operator and can be applied without
67 * any delay by an outer join, so its two sides can be considered equal
68 * anywhere they are both computable; moreover that equality can be
69 * extended transitively. Record this knowledge in the EquivalenceClass
70 * data structure. Returns TRUE if successful, FALSE if not (in which
71 * case caller should treat the clause as ordinary, not an equivalence).
73 * If below_outer_join is true, then the clause was found below the nullable
74 * side of an outer join, so its sides might validly be both NULL rather than
75 * strictly equal. We can still deduce equalities in such cases, but we take
76 * care to mark an EquivalenceClass if it came from any such clauses. Also,
77 * we have to check that both sides are either pseudo-constants or strict
78 * functions of Vars, else they might not both go to NULL above the outer
79 * join. (This is the reason why we need a failure return. It's more
80 * convenient to check this case here than at the call sites...)
82 * On success return, we have also initialized the clause's left_ec/right_ec
83 * fields to point to the EquivalenceClass representing it. This saves lookup
86 * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
87 * problem, for which there exist better data structures than simple lists.
88 * If this code ever proves to be a bottleneck then it could be sped up ---
89 * but for now, simple is beautiful.
91 * Note: this is only called during planner startup, not during GEQO
92 * exploration, so we need not worry about whether we're in the right
96 process_equivalence(PlannerInfo *root, RestrictInfo *restrictinfo,
97 bool below_outer_join)
99 Expr *clause = restrictinfo->clause;
109 EquivalenceClass *ec1,
111 EquivalenceMember *em1,
115 /* Should not already be marked as having generated an eclass */
116 Assert(restrictinfo->left_ec == NULL);
117 Assert(restrictinfo->right_ec == NULL);
119 /* Extract info from given clause */
120 Assert(is_opclause(clause));
121 opno = ((OpExpr *) clause)->opno;
122 collation = ((OpExpr *) clause)->inputcollid;
123 item1 = (Expr *) get_leftop(clause);
124 item2 = (Expr *) get_rightop(clause);
125 item1_relids = restrictinfo->left_relids;
126 item2_relids = restrictinfo->right_relids;
129 * Ensure both input expressions expose the desired collation (their types
130 * should be OK already); see comments for canonicalize_ec_expression.
132 item1 = canonicalize_ec_expression(item1,
133 exprType((Node *) item1),
135 item2 = canonicalize_ec_expression(item2,
136 exprType((Node *) item2),
140 * Reject clauses of the form X=X. These are not as redundant as they
141 * might seem at first glance: assuming the operator is strict, this is
142 * really an expensive way to write X IS NOT NULL. So we must not risk
143 * just losing the clause, which would be possible if there is already a
144 * single-element EquivalenceClass containing X. The case is not common
145 * enough to be worth contorting the EC machinery for, so just reject the
146 * clause and let it be processed as a normal restriction clause.
148 if (equal(item1, item2))
149 return false; /* X=X is not a useful equivalence */
152 * If below outer join, check for strictness, else reject.
154 if (below_outer_join)
156 if (!bms_is_empty(item1_relids) &&
157 contain_nonstrict_functions((Node *) item1))
158 return false; /* LHS is non-strict but not constant */
159 if (!bms_is_empty(item2_relids) &&
160 contain_nonstrict_functions((Node *) item2))
161 return false; /* RHS is non-strict but not constant */
165 * We use the declared input types of the operator, not exprType() of the
166 * inputs, as the nominal datatypes for opfamily lookup. This presumes
167 * that btree operators are always registered with amoplefttype and
168 * amoprighttype equal to their declared input types. We will need this
169 * info anyway to build EquivalenceMember nodes, and by extracting it now
170 * we can use type comparisons to short-circuit some equal() tests.
172 op_input_types(opno, &item1_type, &item2_type);
174 opfamilies = restrictinfo->mergeopfamilies;
177 * Sweep through the existing EquivalenceClasses looking for matches to
178 * item1 and item2. These are the possible outcomes:
180 * 1. We find both in the same EC. The equivalence is already known, so
181 * there's nothing to do.
183 * 2. We find both in different ECs. Merge the two ECs together.
185 * 3. We find just one. Add the other to its EC.
187 * 4. We find neither. Make a new, two-entry EC.
189 * Note: since all ECs are built through this process or the similar
190 * search in get_eclass_for_sort_expr(), it's impossible that we'd match
191 * an item in more than one existing nonvolatile EC. So it's okay to stop
192 * at the first match.
196 foreach(lc1, root->eq_classes)
198 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
201 /* Never match to a volatile EC */
202 if (cur_ec->ec_has_volatile)
206 * The collation has to match; check this first since it's cheaper
207 * than the opfamily comparison.
209 if (collation != cur_ec->ec_collation)
213 * A "match" requires matching sets of btree opfamilies. Use of
214 * equal() for this test has implications discussed in the comments
215 * for get_mergejoin_opfamilies().
217 if (!equal(opfamilies, cur_ec->ec_opfamilies))
220 foreach(lc2, cur_ec->ec_members)
222 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
224 Assert(!cur_em->em_is_child); /* no children yet */
227 * If below an outer join, don't match constants: they're not as
228 * constant as they look.
230 if ((below_outer_join || cur_ec->ec_below_outer_join) &&
235 item1_type == cur_em->em_datatype &&
236 equal(item1, cur_em->em_expr))
245 item2_type == cur_em->em_datatype &&
246 equal(item2, cur_em->em_expr))
259 /* Sweep finished, what did we find? */
263 /* If case 1, nothing to do, except add to sources */
266 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
267 ec1->ec_below_outer_join |= below_outer_join;
268 /* mark the RI as associated with this eclass */
269 restrictinfo->left_ec = ec1;
270 restrictinfo->right_ec = ec1;
271 /* mark the RI as usable with this pair of EMs */
272 restrictinfo->left_em = em1;
273 restrictinfo->right_em = em2;
278 * Case 2: need to merge ec1 and ec2. We add ec2's items to ec1, then
279 * set ec2's ec_merged link to point to ec1 and remove ec2 from the
280 * eq_classes list. We cannot simply delete ec2 because that could
281 * leave dangling pointers in existing PathKeys. We leave it behind
282 * with a link so that the merged EC can be found.
284 ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
285 ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
286 ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
287 ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
288 ec1->ec_has_const |= ec2->ec_has_const;
289 /* can't need to set has_volatile */
290 ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
291 ec2->ec_merged = ec1;
292 root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
293 /* just to avoid debugging confusion w/ dangling pointers: */
294 ec2->ec_members = NIL;
295 ec2->ec_sources = NIL;
296 ec2->ec_derives = NIL;
297 ec2->ec_relids = NULL;
298 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
299 ec1->ec_below_outer_join |= below_outer_join;
300 /* mark the RI as associated with this eclass */
301 restrictinfo->left_ec = ec1;
302 restrictinfo->right_ec = ec1;
303 /* mark the RI as usable with this pair of EMs */
304 restrictinfo->left_em = em1;
305 restrictinfo->right_em = em2;
309 /* Case 3: add item2 to ec1 */
310 em2 = add_eq_member(ec1, item2, item2_relids, false, item2_type);
311 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
312 ec1->ec_below_outer_join |= below_outer_join;
313 /* mark the RI as associated with this eclass */
314 restrictinfo->left_ec = ec1;
315 restrictinfo->right_ec = ec1;
316 /* mark the RI as usable with this pair of EMs */
317 restrictinfo->left_em = em1;
318 restrictinfo->right_em = em2;
322 /* Case 3: add item1 to ec2 */
323 em1 = add_eq_member(ec2, item1, item1_relids, false, item1_type);
324 ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
325 ec2->ec_below_outer_join |= below_outer_join;
326 /* mark the RI as associated with this eclass */
327 restrictinfo->left_ec = ec2;
328 restrictinfo->right_ec = ec2;
329 /* mark the RI as usable with this pair of EMs */
330 restrictinfo->left_em = em1;
331 restrictinfo->right_em = em2;
335 /* Case 4: make a new, two-entry EC */
336 EquivalenceClass *ec = makeNode(EquivalenceClass);
338 ec->ec_opfamilies = opfamilies;
339 ec->ec_collation = collation;
340 ec->ec_members = NIL;
341 ec->ec_sources = list_make1(restrictinfo);
342 ec->ec_derives = NIL;
343 ec->ec_relids = NULL;
344 ec->ec_has_const = false;
345 ec->ec_has_volatile = false;
346 ec->ec_below_outer_join = below_outer_join;
347 ec->ec_broken = false;
349 ec->ec_merged = NULL;
350 em1 = add_eq_member(ec, item1, item1_relids, false, item1_type);
351 em2 = add_eq_member(ec, item2, item2_relids, false, item2_type);
353 root->eq_classes = lappend(root->eq_classes, ec);
355 /* mark the RI as associated with this eclass */
356 restrictinfo->left_ec = ec;
357 restrictinfo->right_ec = ec;
358 /* mark the RI as usable with this pair of EMs */
359 restrictinfo->left_em = em1;
360 restrictinfo->right_em = em2;
367 * canonicalize_ec_expression
369 * This function ensures that the expression exposes the expected type and
370 * collation, so that it will be equal() to other equivalence-class expressions
371 * that it ought to be equal() to.
373 * The rule for datatypes is that the exposed type should match what it would
374 * be for an input to an operator of the EC's opfamilies; which is usually
375 * the declared input type of the operator, but in the case of polymorphic
376 * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
377 * Expressions coming in from quals will generally have the right type
378 * already, but expressions coming from indexkeys may not (because they are
379 * represented without any explicit relabel in pg_index), and the same problem
380 * occurs for sort expressions (because the parser is likewise cavalier about
381 * putting relabels on them). Such cases will be binary-compatible with the
382 * real operators, so adding a RelabelType is sufficient.
384 * Also, the expression's exposed collation must match the EC's collation.
385 * This is important because in comparisons like "foo < bar COLLATE baz",
386 * only one of the expressions has the correct exposed collation as we receive
387 * it from the parser. Forcing both of them to have it ensures that all
388 * variant spellings of such a construct behave the same. Again, we can
389 * stick on a RelabelType to force the right exposed collation. (It might
390 * work to not label the collation at all in EC members, but this is risky
391 * since some parts of the system expect exprCollation() to deliver the
392 * right answer for a sort key.)
394 * Note this code assumes that the expression has already been through
395 * eval_const_expressions, so there are no CollateExprs and no redundant
399 canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
401 Oid expr_type = exprType((Node *) expr);
404 * For a polymorphic-input-type opclass, just keep the same exposed type.
406 if (IsPolymorphicType(req_type))
407 req_type = expr_type;
410 * No work if the expression exposes the right type/collation already.
412 if (expr_type != req_type ||
413 exprCollation((Node *) expr) != req_collation)
416 * Strip any existing RelabelType, then add a new one if needed. This
417 * is to preserve the invariant of no redundant RelabelTypes.
419 * If we have to change the exposed type of the stripped expression,
420 * set typmod to -1 (since the new type may not have the same typmod
421 * interpretation). If we only have to change collation, preserve the
424 while (expr && IsA(expr, RelabelType))
425 expr = (Expr *) ((RelabelType *) expr)->arg;
427 if (exprType((Node *) expr) != req_type)
428 expr = (Expr *) makeRelabelType(expr,
433 else if (exprCollation((Node *) expr) != req_collation)
434 expr = (Expr *) makeRelabelType(expr,
436 exprTypmod((Node *) expr),
445 * add_eq_member - build a new EquivalenceMember and add it to an EC
447 static EquivalenceMember *
448 add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
449 bool is_child, Oid datatype)
451 EquivalenceMember *em = makeNode(EquivalenceMember);
454 em->em_relids = relids;
455 em->em_is_const = false;
456 em->em_is_child = is_child;
457 em->em_datatype = datatype;
459 if (bms_is_empty(relids))
462 * No Vars, assume it's a pseudoconstant. This is correct for entries
463 * generated from process_equivalence(), because a WHERE clause can't
464 * contain aggregates or SRFs, and non-volatility was checked before
465 * process_equivalence() ever got called. But
466 * get_eclass_for_sort_expr() has to work harder. We put the tests
467 * there not here to save cycles in the equivalence case.
470 em->em_is_const = true;
471 ec->ec_has_const = true;
472 /* it can't affect ec_relids */
474 else if (!is_child) /* child members don't add to ec_relids */
476 ec->ec_relids = bms_add_members(ec->ec_relids, relids);
478 ec->ec_members = lappend(ec->ec_members, em);
485 * get_eclass_for_sort_expr
486 * Given an expression and opfamily/collation info, find an existing
487 * equivalence class it is a member of; if none, optionally build a new
488 * single-member EquivalenceClass for it.
490 * sortref is the SortGroupRef of the originating SortGroupClause, if any,
491 * or zero if not. (It should never be zero if the expression is volatile!)
493 * If create_it is TRUE, we'll build a new EquivalenceClass when there is no
494 * match. If create_it is FALSE, we just return NULL when no match.
496 * This can be used safely both before and after EquivalenceClass merging;
497 * since it never causes merging it does not invalidate any existing ECs
498 * or PathKeys. However, ECs added after path generation has begun are
499 * of limited usefulness, so usually it's best to create them beforehand.
501 * Note: opfamilies must be chosen consistently with the way
502 * process_equivalence() would do; that is, generated from a mergejoinable
503 * equality operator. Else we might fail to detect valid equivalences,
504 * generating poor (but not incorrect) plans.
507 get_eclass_for_sort_expr(PlannerInfo *root,
515 EquivalenceClass *newec;
516 EquivalenceMember *newem;
518 MemoryContext oldcontext;
521 * Ensure the expression exposes the correct type and collation.
523 expr = canonicalize_ec_expression(expr, opcintype, collation);
526 * Scan through the existing EquivalenceClasses for a match
528 foreach(lc1, root->eq_classes)
530 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
534 * Never match to a volatile EC, except when we are looking at another
535 * reference to the same volatile SortGroupClause.
537 if (cur_ec->ec_has_volatile &&
538 (sortref == 0 || sortref != cur_ec->ec_sortref))
541 if (collation != cur_ec->ec_collation)
543 if (!equal(opfamilies, cur_ec->ec_opfamilies))
546 foreach(lc2, cur_ec->ec_members)
548 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
551 * If below an outer join, don't match constants: they're not as
552 * constant as they look.
554 if (cur_ec->ec_below_outer_join &&
558 if (opcintype == cur_em->em_datatype &&
559 equal(expr, cur_em->em_expr))
560 return cur_ec; /* Match! */
564 /* No match; does caller want a NULL result? */
569 * OK, build a new single-member EC
571 * Here, we must be sure that we construct the EC in the right context.
573 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
575 newec = makeNode(EquivalenceClass);
576 newec->ec_opfamilies = list_copy(opfamilies);
577 newec->ec_collation = collation;
578 newec->ec_members = NIL;
579 newec->ec_sources = NIL;
580 newec->ec_derives = NIL;
581 newec->ec_relids = NULL;
582 newec->ec_has_const = false;
583 newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
584 newec->ec_below_outer_join = false;
585 newec->ec_broken = false;
586 newec->ec_sortref = sortref;
587 newec->ec_merged = NULL;
589 if (newec->ec_has_volatile && sortref == 0) /* should not happen */
590 elog(ERROR, "volatile EquivalenceClass has no sortref");
592 newem = add_eq_member(newec, copyObject(expr), pull_varnos((Node *) expr),
596 * add_eq_member doesn't check for volatile functions, set-returning
597 * functions, aggregates, or window functions, but such could appear in
598 * sort expressions; so we have to check whether its const-marking was
601 if (newec->ec_has_const)
603 if (newec->ec_has_volatile ||
604 expression_returns_set((Node *) expr) ||
605 contain_agg_clause((Node *) expr) ||
606 contain_window_function((Node *) expr))
608 newec->ec_has_const = false;
609 newem->em_is_const = false;
613 root->eq_classes = lappend(root->eq_classes, newec);
615 MemoryContextSwitchTo(oldcontext);
622 * generate_base_implied_equalities
623 * Generate any restriction clauses that we can deduce from equivalence
626 * When an EC contains pseudoconstants, our strategy is to generate
627 * "member = const1" clauses where const1 is the first constant member, for
628 * every other member (including other constants). If we are able to do this
629 * then we don't need any "var = var" comparisons because we've successfully
630 * constrained all the vars at their points of creation. If we fail to
631 * generate any of these clauses due to lack of cross-type operators, we fall
632 * back to the "ec_broken" strategy described below. (XXX if there are
633 * multiple constants of different types, it's possible that we might succeed
634 * in forming all the required clauses if we started from a different const
635 * member; but this seems a sufficiently hokey corner case to not be worth
636 * spending lots of cycles on.)
638 * For ECs that contain no pseudoconstants, we generate derived clauses
639 * "member1 = member2" for each pair of members belonging to the same base
640 * relation (actually, if there are more than two for the same base relation,
641 * we only need enough clauses to link each to each other). This provides
642 * the base case for the recursion: each row emitted by a base relation scan
643 * will constrain all computable members of the EC to be equal. As each
644 * join path is formed, we'll add additional derived clauses on-the-fly
645 * to maintain this invariant (see generate_join_implied_equalities).
647 * If the opfamilies used by the EC do not provide complete sets of cross-type
648 * equality operators, it is possible that we will fail to generate a clause
649 * that must be generated to maintain the invariant. (An example: given
650 * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
651 * generate "a.x = a.z" as a restriction clause for A.) In this case we mark
652 * the EC "ec_broken" and fall back to regurgitating its original source
653 * RestrictInfos at appropriate times. We do not try to retract any derived
654 * clauses already generated from the broken EC, so the resulting plan could
655 * be poor due to bad selectivity estimates caused by redundant clauses. But
656 * the correct solution to that is to fix the opfamilies ...
658 * Equality clauses derived by this function are passed off to
659 * process_implied_equality (in plan/initsplan.c) to be inserted into the
660 * restrictinfo datastructures. Note that this must be called after initial
661 * scanning of the quals and before Path construction begins.
663 * We make no attempt to avoid generating duplicate RestrictInfos here: we
664 * don't search ec_sources for matches, nor put the created RestrictInfos
665 * into ec_derives. Doing so would require some slightly ugly changes in
666 * initsplan.c's API, and there's no real advantage, because the clauses
667 * generated here can't duplicate anything we will generate for joins anyway.
670 generate_base_implied_equalities(PlannerInfo *root)
675 foreach(lc, root->eq_classes)
677 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
679 Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
680 Assert(!ec->ec_broken); /* not yet anyway... */
682 /* Single-member ECs won't generate any deductions */
683 if (list_length(ec->ec_members) <= 1)
686 if (ec->ec_has_const)
687 generate_base_implied_equalities_const(root, ec);
689 generate_base_implied_equalities_no_const(root, ec);
691 /* Recover if we failed to generate required derived clauses */
693 generate_base_implied_equalities_broken(root, ec);
697 * This is also a handy place to mark base rels (which should all exist by
698 * now) with flags showing whether they have pending eclass joins.
700 for (rti = 1; rti < root->simple_rel_array_size; rti++)
702 RelOptInfo *brel = root->simple_rel_array[rti];
707 brel->has_eclass_joins = has_relevant_eclass_joinclause(root, brel);
712 * generate_base_implied_equalities when EC contains pseudoconstant(s)
715 generate_base_implied_equalities_const(PlannerInfo *root,
716 EquivalenceClass *ec)
718 EquivalenceMember *const_em = NULL;
722 * In the trivial case where we just had one "var = const" clause, push
723 * the original clause back into the main planner machinery. There is
724 * nothing to be gained by doing it differently, and we save the effort to
725 * re-build and re-analyze an equality clause that will be exactly
726 * equivalent to the old one.
728 if (list_length(ec->ec_members) == 2 &&
729 list_length(ec->ec_sources) == 1)
731 RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
733 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
735 distribute_restrictinfo_to_rels(root, restrictinfo);
740 /* Find the constant member to use */
741 foreach(lc, ec->ec_members)
743 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
745 if (cur_em->em_is_const)
751 Assert(const_em != NULL);
753 /* Generate a derived equality against each other member */
754 foreach(lc, ec->ec_members)
756 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
759 Assert(!cur_em->em_is_child); /* no children yet */
760 if (cur_em == const_em)
762 eq_op = select_equality_operator(ec,
764 const_em->em_datatype);
765 if (!OidIsValid(eq_op))
768 ec->ec_broken = true;
771 process_implied_equality(root, eq_op, ec->ec_collation,
772 cur_em->em_expr, const_em->em_expr,
774 ec->ec_below_outer_join,
775 cur_em->em_is_const);
780 * generate_base_implied_equalities when EC contains no pseudoconstants
783 generate_base_implied_equalities_no_const(PlannerInfo *root,
784 EquivalenceClass *ec)
786 EquivalenceMember **prev_ems;
790 * We scan the EC members once and track the last-seen member for each
791 * base relation. When we see another member of the same base relation,
792 * we generate "prev_mem = cur_mem". This results in the minimum number
793 * of derived clauses, but it's possible that it will fail when a
794 * different ordering would succeed. XXX FIXME: use a UNION-FIND
795 * algorithm similar to the way we build merged ECs. (Use a list-of-lists
798 prev_ems = (EquivalenceMember **)
799 palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
801 foreach(lc, ec->ec_members)
803 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
806 Assert(!cur_em->em_is_child); /* no children yet */
807 if (bms_membership(cur_em->em_relids) != BMS_SINGLETON)
809 relid = bms_singleton_member(cur_em->em_relids);
810 Assert(relid < root->simple_rel_array_size);
812 if (prev_ems[relid] != NULL)
814 EquivalenceMember *prev_em = prev_ems[relid];
817 eq_op = select_equality_operator(ec,
818 prev_em->em_datatype,
819 cur_em->em_datatype);
820 if (!OidIsValid(eq_op))
823 ec->ec_broken = true;
826 process_implied_equality(root, eq_op, ec->ec_collation,
827 prev_em->em_expr, cur_em->em_expr,
829 ec->ec_below_outer_join,
832 prev_ems[relid] = cur_em;
838 * We also have to make sure that all the Vars used in the member clauses
839 * will be available at any join node we might try to reference them at.
840 * For the moment we force all the Vars to be available at all join nodes
841 * for this eclass. Perhaps this could be improved by doing some
842 * pre-analysis of which members we prefer to join, but it's no worse than
843 * what happened in the pre-8.3 code.
845 foreach(lc, ec->ec_members)
847 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
848 List *vars = pull_var_clause((Node *) cur_em->em_expr,
849 PVC_RECURSE_AGGREGATES,
850 PVC_INCLUDE_PLACEHOLDERS);
852 add_vars_to_targetlist(root, vars, ec->ec_relids, false);
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 or
1788 * 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))